版本比较
3D Dice Roll
正文
增加 1332 行删除 1332 行
27 行未改动2829303132323334353620 行未改动5758596061616263646530 行未改动969798991001001011021031041051061071081091101101111121131141151161171181191191201211221234 行未改动1281291301311321321331341351361371381391401401411421431441451461471481491491501511521521531541551551561571581591591601611621631641641651661671681691701701711721731741751761771771781791801811811821831841851851861871881891901901911921931941951951961971981992002002012022032042052062072072082092102112 行未改动2142152162172182182192202212223 行未改动2262272282292302302312322332346 行未改动2412422432442452452462472482492502512522532532542552562572 行未改动2602612622632642642652662672682 行未改动2712722732742752752762772782797 行未改动2872882892902912912922932942952 行未改动2982993003013023023033043053062 行未改动3093103113123133133143153163173183193203213213223233243253263273273283293303313323333343353363363373383393403403413423433443453463463473483493503513523533543543553563573583583593603613623633643643653663673683683693703713723733733743753763773783793803803813823833843853863873883893893903913923933933943953963979 行未改动4074084094104114114124134144154164164174184194203 行未改动4244254264274284284294304314322 行未改动4354364374384394394404414424434444454464474474484494504514524534544554564564574584594607 行未改动4684694704714724724734744754764774784794804814814824834844854864874884894904904914924934944954964974984984995005015025035045055065065075085095095105115125132 行未改动5165175185195205205215225235245255255265275285295305315315325335345355365365375385395405415415425435445454 行未改动5505515525535545545555565575575585595605619 行未改动5715725735745755755765775785797 行未改动5875885895905915915925935945958 行未改动60460560660760860860961061161261361461561661661761861962062162262362462562562662762862948 行未改动6786796806816826826836846856866876886896906916916926936946956966976986997007007017027037047057067077077087097107117127137147157167177177187197207218 行未改动7307317327337347347357367377382 行未改动7417427437447457457467477487497507517517527537547557567577587597607617617627637647655 行未改动77177277377477577577677777877978078178178278378478578578678778878979079179279279379479579679679779879879980080180280280380480580680780780880981081181181281381481481581681781881982082182182282382482521 行未改动8478488498508518518528538548558568568578588598608608618628638638648658668678688688698708718718728738748758768768778788798808818828838838848858868878888898908918918928938948948958968978982 行未改动9019029039049059059069079089099109109119129139139149159169179179189199199209219229229239249259269269279289299309319319329339349349359369379387 行未改动9469479489499509509519529539549559569569579589599609609619629639639649659669679689699709709719729739749759759769779789789799809819829829839849859859869879889899909919929929939949959969979989991000100010011002100310041004100510061007100810091010101110121012101310141015101610171018101810191020102110221022102310241025102612 行未改动10391040104110421043104310441045104610471048104810491050105110521053105410551056105610571058105910601061106210621063106410651066106710671068106910701071107210721073107410751075107610771078107910801081108210831083108410851086108710871088108910901091109110921093109310941095109610972 行未改动110011011102110311041104110511061107110811091110111011111112111311141114111511161117111811181119112011211122112311241124112511261127112811291129113011311132113211331134113511361136113711381139114011401141114211431143114411451146114711481149115011501151115211531154115511551156115711581159116011611162116211631164116511661167116711681169117011711172117211731174117411751176117711781179117911801181118211831184118411851186118711886 行未改动11951196119711981199119912001201120212031204120512051206120712081209121012111212121312131214121512161217121812191220122112211222122312241225122612261227122812291230123012311232123312331234123512361237123812391240124112411242124312441245124612471248124912501251125112521253125412551255125612571258125812591260126112621263126412641265126612671268126912691270127112721273127412751276127712781278127912801281128212831284128412851286128712881289129012911292129212931294129512963 行未改动130013011302130313041304130513061307130713081309131013112 行未改动1314131513161317131813181319132013211322132313231324132513261327132713281329133013301331133213331333133413351336133613371338133913391340134113421342134313441345134513461347134813491349135013511352135213531354135513563 行未改动1360136113621363136413641365136613671367136813691370137013711372137313741375137613771377137813791380138013811382138313841385138613871388138913891390139113921393139313941395139613971398139813991400140114021403140314041405140614075 行未改动14131414141514161417141714181419142014211422142314231424142514261427142814291430143114311432143314341435143614361437143814391440144114421443144314441445144614471448144914501450145114521453145414551455145614571458145814591460146114621463146414651465146614671468146914701470147114721473147414741475147614771478147914801481148214831484148414851486148714882 行未改动14911492149314941495149514961497149814991500150115011502150315041505150515061507150815091510151015111512151315141515151615161517151815191520152015211522152315241525152515261527152815291530153115311532153315341534153515361537153715381539154015411542154215431544154515461547154715481549155015511552155315531554155515561557155715581559156015612 行未改动15641565156615671568156815691570157115722 行未改动157515761577157815791579158015811582158315841584158515861587158815891590159115921593159315941595159615971598159815991600160116021603160416041605160616071608160916101610161116121613161416141615161616171617161816191620162116211622162316241624162516261627162824 行未改动16531654165516561657165716581659166016611662166216631664166516661667166716681669167016701671167216731673167416751676167716781679168016811681168216831684168516861686168716881689169016911692169216931694169516961697169716981699170017011702170217031704170517068 行未改动17151716171717181719171917201721172117221723172417251726172617271728172917301731173217331734173517351736173717381739173917401741174217432 行未改动1746174717481749175017501751175217531754175517561756175717581759176017611762176317631764176517651766176717681769177017711771177217731774177517761777177717781779178017811782178217831784178517861787178717881789179017911791179217931794179517961796179717981799179918001801180218031804180518051806180718081809181018111812181218131814181518161817181818191820182018211822182318241825182518261827182818291830183118311832183318341834183518361837183718381839184018411842184318431844184518461846184718481849185018511852185218531854185518561857185818591859186018611862186318641864186518661867186818661867186818691870187018711872187318731874187518761877187818791880188018811882188318846 行未改动18911892189318941895189518961897189818991899190019011902190219031904190519061907190819091910191119121912191319141915191619171918191919201920192119221923192319241925192619261927192819291930193119311932193319341935193619371938193919391940194119421943194419451946194619471948194919501951195219521953195419551955195619571958195919591960196119621963196419651966196619671968196919701971197119721973197419751976197719781978197919801981198119821983198419841985198619871987198819891990199019911992199319941995199619961997199819992000200120022003200420052006200620072008200920102011201220132014201520152016201720182019202020212022202320232024202520262027202820292030203120322033203320342035203620372038203920392040204120422042204320442045204620462047204820492050205120512052205320542055205520562057205820592060206120612062206320642065206620662067206820692070207120712072207320742074207520762077207820792080208120812082208320842085208620872087208820892090209120922092209320942095209620972098209820992100210121022102210321042105210616 行未改动212321242125212621272127212821292130213120 行未改动215221532154215521562156215721582159216036 行未改动2197219821992200220122012202220322042205220622072207220822092210221122122213221322142215221622172218221922202221222222232223222422252226222722282229223022312232223222332234223522364 行未改动2241224222432244224522452246224722482249225022512252225322532254225522562257225822592260226122622262226322642265226522662267226822682269227022712272227222732274227522762277227722782279228022812282228322832284228522862287228822892290229022912292229322942294229522962297229822982299230023012302230323032304230523062307230823082309231023112312231323132314231523162317231823192320232023212322232323242 行未改动23272328232923302331233123322333233423353 行未改动23392340234123422343234323442345234623476 行未改动23542355235623572358235823592360236123622363236423652366236623672368236923702 行未改动23732374237523762377237723782379238023812 行未改动23842385238623872388238823892390239123927 行未改动24002401240224032404240424052406240724082 行未改动24112412241324142415241524162417241824192 行未改动242224232424242524262426242724282429243024312432243324342434243524362437243824392440244024412442244324442445244624472448244924492450245124522453245324542455245624572458245924592460246124622463246424652466246724672468246924702471247124722473247424752476247724772478247924802481248124822483248424852486248624872488248924902491249224932493249424952496249724982499250025012502250325032504250525062507250725082509251025119 行未改动25212522252325242525252525262527252825292530253025312532253325343 行未改动25382539254025412542254225432544254525462 行未改动254925502551255225532553255425552556255725582559256025612561256225632564256525662567256825692570257025712572257325747 行未改动25822583258425852586258625872588258925902591259225932594259525952596259725982599260026012602260326042604260526062607260826092610261126122612261326142615261626172618261926202620262126222623262326242625262626272 行未改动263026312632263326342634263526362637263826392639264026412642264326442645264526462647264826492650265026512652265326542655265526562657265826594 行未改动266426652666266726682668266926702671267126722673267426759 行未改动26852686268726882689268926902691269226937 行未改动27012702270327042705270527062707270827098 行未改动2718271927202721272227222723272427252726272727282729273027302731273227332734273527362737273827392739274027412742274348 行未改动27922793279427952796279627972798279928002801280228032804280528052806280728082809281028112812281328142814281528162817281828192820282128212822282328242825282628272828282928302831283128322833283428358 行未改动28442845284628472848284828492850285128522 行未改动285528562857285828592859286028612862286328642865286628662867286828692870287128722873287428752876287628772878287928805 行未改动28862887288828892890289028912892289328942895289628962897289828992900290029012902290329042905290629072907290829092910291129112912291329132914291529162917291729182919292029212922292229232924292529262926292729282929292929302931293229332934293529362936293729382939294021 行未改动2962296329642965296629662967296829692970297129712972297329742975297529762977297829782979298029812982298329832984298529862986298729882989299029912991299229932994299529962997299829982999300030013002300330043005300630063007300830093009301030113012301230133014301530162 行未改动301930203021302230233023302430253026302730283028302930303031303130323033303430353035303630373037303830393040304030413042304330443044304530463047304830493049305030513052305230533054305530566 行未改动30633064306530663067306730683069307030713072307330733074307530763077307730783079308030803081308230833084308530863087308730883089309030913092309230933094309530953096309730983099309931003101310231023103310431053106310731083109310931103111311231133 行未改动31173118311931203121312131223123312431253125312631273128312931303131313231333133313431353136313731383139313931403141314231433143314431453146314712 行未改动31603161316231633164316431653166316731683169316931703171317231733174317531763177317731783179318031813182318331833184318531863187318831883189319031913192319331933194319531963196319731983199320032013202320332043204320532063207320832083209321032113212321232133214321432153216321732182 行未改动3221322232233224322532253226322732283229323032313232323232333234323532363236323732383239324032403241324232433244324532453246324732483249325032513251325232533254325532563256325732583259325932603261326232633263326432653266326732673268326932703270327132723273327432753276327732773278327932803281328232823283328432853286328732873288328932903291329232923293329432953296329632973298329932993300330133023303330433053306330733073308330933103311331233123313331433153316331733183319331933203321332233233324332433253326332733283329332933303331333133323333333433353336333633373338333933403341334133423343334433456 行未改动33523353335433553356335633573358335933603361336233623363336433653366336733683369337033703371337233733374337533763377337833783379338033813382338333833384338533863387338733883389339033903391339233933394339533963397339833983399340034013402340334043405340634073408340834093410341134123412341334143415341534163417341834193420342134213422342334243425342634263427342834293430343134323433343434353435343634373438343934393440344134423442344334443445344534463447344834493450345134523453345334543455345634573 行未改动346134623463346434653465346634673468346834693470347134722 行未改动3475347634773478347934793480348134823483348434843485348634873488348834893490349134913492349334943494349534963497349734983499350035003501350235033503350435053506350635073508350935103510351135123513351335143515351635173 行未改动3521352235233524352535253526352735283528352935303531353135323533353435353536353735383538353935403541354235433543354435453546354735483548354935503551355235533553355435553556355735573558355935603560356135623563356435653566356735683568356935703571357135723573357435753576357735783579358035803581358235833584358435853586358735883589358935903591359235933594359435953596359735985 行未改动360436053606360736083608360936103611361236133614361436153616361736183619362036213622362236233624362536263627362736283629363036313632363336343634363536363637363836393640364036413642364336443645364636463647364836493650365136513652365336543654365536563657365836593660366136613662366336643665366636663667366836693669367036713672367336733674367536763677367836793680368136823683368336843685368636872 行未改动36903691369236933694369436953696369736982 行未改动370137023703370437053705370637073708370937103711371137123713371437153715371637173718371937203720372137223723372437253726372637273728372937303730373137323733373437353735373637373738373937403741374137423743374437453745374637473748374837493750375137523753375337543755375637573758375937603761376237633763376437653766376710 行未改动37783779378037813782378237833784378537863787378837893790379037913792379337942 行未改动37973798379938003801380138023803380438053806380638073808380938103811381238123813381438153816381638173818381938202 行未改动38233824382538263827382738283829383038312 行未改动38343835383638373838383838393840384138423843384338443845384638473848384938503851385238523853385438553856385738573858385938603861386238633863386438653866386738683869386938703871387238733874387438753876387738783879388038813881388238833884388538853886388738883888388938903891389224 行未改动39173918391939203921392139223923392439253926392639273928392939303931393139323933393439343935393639373937393839393940394139423943394439453945394639473948394939503950395139523953395439553956395639573958395939603961396139623963396439653966396639673968396939708 行未改动39793980398139823983398339843985398539863987398839893990399039913992399339943995399539963997399839994000400140024003400440044005400640074008400840094010401140122 行未改动40154016401740184019401940204021402240234024402540254026402740284029403040314032403240334034403440354036403740384039404040404041404240434044404540464046404740484049405040514051405240534054405540564056405740584059406040604061406240634064406540654066406740684068406940704071407240734074407540764074407540764077407840794080408140824083408340844085408640874088408940904091409140924093409440954096409640974098409941004101410241024103410441054105410641074108410841094110411141124113411441144115411641174117411841194120412141224123412341244125412641274128412941304130413141324133413441354135413641374138413941374138413941404141414141424143414441444145414641474148414941504151415141524153415441556 行未改动41624163416441654166416641674168416941704170417141724173417341744175417641774178417941804181418241834183418441854186418741884189419041914191419241934194419441954196419741974198419942004201420242024203420442054206420742084209421042104211421242134214421542164217421742184219422042214222422342234224422542264226422742284229423042304231423242334234423542364237423742384239424042414241424242434244424542464246424742484249424942504251425242534254425542564256425742584259425942604261426242624263426442654265426642674268426842694270427142724273427442744275427642774278427942804281428242834284428442854286428742884289429042914292429342934294429542964297429842994300430143014302430343044305430643074308430943104311431143124313431443154316431743174318431943204320432143224323432443244325432643274328432943294330433143324333433343344335433643374338433943394340434143424343434443444345434643474348434943494350435143524352435343544355435643574358435943594360436143624363436443654365436643674368436943704370437143724373437443754376437643774378437943804380438143824383438415 行未改动440044014402440344044404440544064407440820 行未改动442944304431443244334433443444354436443736 行未改动4474447544764477447844784479448044814482448344844484448544864487448844894490449044914492449344944495449644974498449945004500450145024503450445054506450745084509450945104511451245134 行未改动4518451945204521452245224523452445254526452745284529453045304531453245334534453545364537453845394539454045414542454245434544454545454546454745484549454945504551455245534554455445554556455745584559456045604561456245634564456545664567456745684569457045714571457245734574457545764577457845794579458045814582458345834584458545864587458845884589459045914592459345934594459545964597459845984599460046014602460346044605460546064607460846092 行未改动46124613461446154616461646174618461946203 行未改动46244625462646274628462846294630463146326 行未改动46394640464146424643464346444645464646474648464946504651465146524653465446552 行未改动46584659466046614662466246634664466546662 行未改动46694670467146724673467346744675467646777 行未改动46854686468746884689468946904691469246932 行未改动46964697469846994700470047014702470347042 行未改动470747084709471047114711471247134714471547164717471847194719472047214722472347244725472547264727472847294730473147324733473447344735473647374738473847394740474147424743474447444745474647474748474947504751475247524753475447554756475647574758475947604761476247624763476447654766476647674768476947704771477147724773477447754776477747784778477947804781478247834784478547864787478847884789479047914792479247934794479547969 行未改动48064807480848094810481048114812481348144815481548164817481848193 行未改动48234824482548264827482748284829483048312 行未改动483448354836483748384838483948404841484248434844484548464846484748484849485048514852485348544855485548564857485848597 行未改动48674868486948704871487148724873487448754876487748784879488048804881488248834884488548864887488848894889489048914892489348944895489648974897489848994900490149024903490449054905490649074908490849094910491149122 行未改动491549164917491849194919492049214922492349244924492549264927492849294930493049314932493349344935493549364937493849394940494049414942494349444 行未改动494949504951495249534953495449554956495649574958495949609 行未改动49704971497249734974497449754976497749787 行未改动49864987498849894990499049914992499349948 行未改动5003500450055006500750075008500950105011501250135014501550155016501750185019502050215022502350245024502550265027502848 行未改动50775078507950805081508150825083508450857 行未改动5093509450955096509750975098509951005101510251035104510551065106510751085109511051115112511351135114511551165117511851195120512151225123512351245125512651278 行未改动51365137513851395140514051415142514351442 行未改动5147514851495150515151515152515351545155515651575158515951595160516151625163516451655166516751685169516951705171517251735 行未改动51795180518151825183518351845185518651875188518951895190519151925193519351945195519651975198519952005200520152025203520452045205520652065207520852095210521052115212521352145215521552165217521852195219522052215222522252235224522552265227522852295229523052315232523321 行未改动5255525652575258525952595260526152625263526452645265526652675268526852695270527152715272527352745275527652765277527852795279528052815282528352845284528552865287528852895290529152915292529352945295529652975298529952995300530153025302530353045305530553065307530853092 行未改动53125313531453155316531653175318531953205321532153225323532453245325532653275328532953295330533153325333533453355336533653375338533953405341534153425343534353445345534653465347534853495350535153525353535353545355535653575357535853595360536153625362536353645365536553665367536853696 行未改动537653775378537953805380538153825383538453855386538753875388538953905391539153925393539453945395539653975398539954005401540154025403540454055406540654075408540954095410541154125413541354145415541654165417541854195420542154225423542354245425542654273 行未改动54315432543354345435543554365437543854395439544054415442544354445445544654475447544854495450545154525453545354545455545654575457545854595460546112 行未改动5474547554765477547854785479548054815482548354835484548554865487548854895490549154915492549354945495549654975497549854995500550155025502550355045505550655075507550855095510551055115512551355145515551655175518551855195520552155225522552355245525552655265527552855295530553055315532553255335534553555362 行未改动553955405541554255435543554455455546554755485549555055505551555255535554555455555556555755585558555955605561556255625563556455655566556755675568556955705571557255735573557455755576557755785578557955805581558155825583558455855585558655875588558955895590559155925592559355945595559655975598559955995600560156025603560456045605560656075608560956095610561156125613561456145615561656175618561856195620562156215622562356245625562656275628562956295630563156325633563456345635563656375638563956405641564156425643564456455646564656475648564956505651565156525653565356545655565656575658565856595660566156625663566356645665566656676 行未改动56745675567656775678567856795680568156825683568456845685568656875688568956905691569256925693569456955696569756985699570057005701570257035704570557055706570757085709570957105711571257125713571457155716571757185719572057205721572257235724572557265727572857295730573057315732573357345734573557365737573757385739574057415742574357435744574557465747574857485749575057515752575357545755575657575757575857595760576157615762576357645764576557665767576757685769577057715772577357745775577557765777577857793 行未改动578357845785578657875787578857895790579057915792579357942 行未改动5797579857995800580158015802580358045805580658065807580858095810581058115812581358135814581558165816581758185819581958205821582258225823582458255825582658275828582858295830583158325832583358345835583558365837583858393 行未改动5843584458455846584758475848584958505850585158525853585358545855585658575858585958605860586158625863586458655865586658675868586958705870587158725873587458755875587658775878587958795880588158825882588358845885588658875888588958905890589158925893589358945895589658975898589959005901590259025903590459055906590659075908590959105911591159125913591459155916591659175918591959205 行未改动592659275928592959305930593159325933593459355936593659375938593959405941594259435944594459455946594759485949594959505951595259535954595559565956595759585959596059615962596259635964596559665967596859685969597059715972597359735974597559765976597759785979598059815982598359835984598559865987598859885989599059915991599259935994599559955996599759985999600060016002600360046005600560066007600860092 行未改动60126013601460156016601660176018601960202 行未改动602360246025602660276027602860296030603160326033603360346035603660376037603860396040604160426042604360446045604660476048604860496050605160526052605360546055605660576057605860596060606160626063606360646065606660676067606860696070607060716072607360746075607560766077607860796080608160826083608460856085608660876088608910 行未改动61006101610261036104610461056106610761086109611061116112611261136114611561162 行未改动61196120612161226123612361246125612661276128612861296130613161326133613461346135613661376138613861396140614161422 行未改动61456146614761486149614961506151615261532 行未改动61566157615861596160616061616162616361646165616561666167616861696170617161726173617461746175617661776178617961796180618161826183618461856185618661876188618961906191619161926193619461956196619661976198619962006201620262036203620462056206620762076208620962106210621162126213621424 行未改动62396240624162426243624362446245624662476248624862496250625162526253625362546255625662566257625862596259626062616262626362646265626662676267626862696270627162726272627362746275627662776278627862796280628162826283628362846285628662876288628862896290629162928 行未改动63016302630363046305630563066307630763086309631063116312631263136314631563166317631763186319632063216322632363246325632663266327632863296330633063316332633363342 行未改动6337633863396340634163416342634363446345634663476347634863496350635163526353635463556355635663576357635863596360636163626362636363646365636663676368636963696370637163726373637463756375637663776378637963806380638163826383638463856385638663876388638963896390639163926393639463946395639663976397639863996400640164026403640464056403640464056406640764086409641064116412641264136414641564166417641864196420642064216422642364246425642564266427642864296430643164316432643364346434643564366437643764386439644064416442644364436444644564466446644764486449645064516452645264536454645564566457645864596459646064616462646364646464646564666467646864666467646864696470647064716472647364736474647564766477647864796480648064816482648364846 行未改动64916492649364946495649564966497649864996499650065016502650265036504650565066507650865096510651165126512651365146515651665176518651965206520652165226523652365246525652665266527652865296530653165316532653365346535653665376538653965396540654165426543654465456546654665476548654965506551655265526553655465556555655665576558655965596560656165626563656465656566656665676568656965706570657165726573657465756575657665776578657865796580658165826583658465856585658665876588658865896590659165916592659365946594659565966597659765986599660066016602660366036604660566066607660866096610661166126613661366146615661666176618661966206621662266226623662466256626662766286629663066306631663266336634663566366637663866396640664066416642664366446645664666466647664866496649665066516652665366536654665566566657665866586659666066616662666266636664666566666667666866686669667066716672667366736674667566766677667866786679668066816681668266836684668566866687668866886689669066916692669366946694669566966697669866996699670067016702670367046705670567066707670867096709671067116712671316 行未改动673067316732673367346734673567366737673820 行未改动675967606761676267636763676467656766676736 行未改动6804680568066807680868086809681068116812681368146814681568166817681868196820682068216822682368246825682668276828682968306830683168326833683468356836683768386839683968406841684268434 行未改动6848684968506851685268526853685468556856685768586859686068606861686268636864686568666867686868696869687068716872687268736874687568756876687768786879687968806881688268836884688468856886688768886889689068906891689268936894689568966897689768986899690069016901690269036904690569066907690869096909691069116912691369136914691569166917691869186919692069216922692369236924692569266927692869286929693069316932693369346935693569366937693869392 行未改动69426943694469456946694669476948694969503 行未改动69546955695669576958695869596960696169626 行未改动69696970697169726973697369746975697669776978697969806981698169826983698469852 行未改动69886989699069916992699269936994699569962 行未改动69997000700170027003700370047005700670077 行未改动70157016701770187019701970207021702270232 行未改动70267027702870297030703070317032703370342 行未改动703770387039704070417041704270437044704570467047704870497049705070517052705370547055705570567057705870597060706170627063706470647065706670677068706870697070707170727073707470747075707670777078707970807081708270827083708470857086708670877088708970907091709270927093709470957096709670977098709971007101710171027103710471057106710771087108710971107111711271137114711571167117711871187119712071217122712271237124712571269 行未改动71367137713871397140714071417142714371447145714571467147714871493 行未改动71537154715571567157715771587159716071612 行未改动716471657166716771687168716971707171717271737174717571767176717771787179718071817182718371847185718571867187718871897 行未改动71977198719972007201720172027203720472057206720772087209721072107211721272137214721572167217721872197219722072217222722372247225722672277227722872297230723172327233723472357235723672377238723872397240724172422 行未改动724572467247724872497249725072517252725372547254725572567257725872597260726072617262726372647265726572667267726872697270727072717272727372744 行未改动727972807281728272837283728472857286728672877288728972909 行未改动73007301730273037304730473057306730773087 行未改动73167317731873197320732073217322732373248 行未改动7333733473357336733773377338733973407341734273437344734573457346734773487349735073517352735373547354735573567357735848 行未改动74077408740974107411741174127413741474157 行未改动7423742474257426742774277428742974307431743274337434743574367436743774387439744074417442744374437444744574467447744874497450745174527453745374547455745674578 行未改动74667467746874697470747074717472747374742 行未改动7477747874797480748174817482748374847485748674877488748974897490749174927493749474957496749774987499749975007501750275035 行未改动75097510751175127513751375147515751675177518751975197520752175227523752375247525752675277528752975307530753175327533753475347535753675367537753875397540754075417542754375447545754575467547754875497549755075517552755275537554755575567557755875597559756075617562756321 行未改动7585758675877588758975897590759175927593759475947595759675977598759875997600760176017602760376047605760676067607760876097609761076117612761376147614761576167617761876197620762176217622762376247625762676277628762976297630763176327632763376347635763576367637763876392 行未改动76427643764476457646764676477648764976507651765176527653765476547655765676577658765976597660766176627663766476657666766676677668766976707671767176727673767376747675767676767677767876797680768176827683768376847685768676877687768876897690769176927692769376947695769576967697769876996 行未改动770677077708770977107710771177127713771477157716771777177718771977207721772177227723772477247725772677277728772977307731773177327733773477357736773677377738773977397740774177427743774377447745774677467747774877497750775177527753775377547755775677573 行未改动77617762776377647765776577667767776877697769777077717772777377747775777677777777777877797780778177827783778377847785778677877787778877897790779112 行未改动7804780578067807780878087809781078117812781378137814781578167817781878197820782178217822782378247825782678277827782878297830783178327832783378347835783678377837783878397840784078417842784378447845784678477848784878497850785178527852785378547855785678567857785878597860786078617862786278637864786578662 行未改动786978707871787278737873787478757876787778787879788078807881788278837884788478857886788778887888788978907891789278927893789478957896789778977898789979007901790279037903790479057906790779087908790979107911791179127913791479157915791679177918791979197920792179227922792379247925792679277928792979297930793179327933793479347935793679377938793979397940794179427943794479447945794679477948794879497950795179517952795379547955795679577958795979597960796179627963796479647965796679677968796979707971797179727973797479757976797679777978797979807981798179827983798379847985798679877988798879897990799179927993799379947995799679976 行未改动80048005800680078008800880098010801180128013801480148015801680178018801980208021802280228023802480258026802780288029803080308031803280338034803580358036803780388039803980408041804280428043804480458046804780488049805080508051805280538054805580568057805880598060806080618062806380648064806580668067806780688069807080718072807380738074807580768077807880788079808080818082808380848085808680878087808880898090809180918092809380948094809580968097809780988099810081018102810381048105810581068107810881093 行未改动811381148115811681178117811881198120812081218122812381242 行未改动8127812881298130813181318132813381348135813681368137813881398140814081418142814381438144814581468146814781488149814981508151815281528153815481558155815681578158815881598160816181628162816381648165816581668167816881693 行未改动8173817481758176817781778178817981808180818181828183818381848185818681878188818981908190819181928193819481958195819681978198819982008200820182028203820482058205820682078208820982098210821182128212821382148215821682178218821982208220822182228223822382248225822682278228822982308231823282328233823482358236823682378238823982408241824182428243824482458246824682478248824982505 行未改动825682578258825982608260826182628263826482658266826682678268826982708271827282738274827482758276827782788279827982808281828282838284828582868286828782888289829082918292829282938294829582968297829882988299830083018302830383038304830583068306830783088309831083118312831383138314831583168317831883188319832083218321832283238324832583258326832783288329833083318332833383348335833583368337833883392 行未改动83428343834483458346834683478348834983502 行未改动835383548355835683578357835883598360836183628363836383648365836683678367836883698370837183728372837383748375837683778378837883798380838183828382838383848385838683878387838883898390839183928393839383948395839683978397839883998400840084018402840384048405840584068407840884098410841184128413841484158415841684178418841910 行未改动84308431843284338434843484358436843784388439844084418442844284438444844584462 行未改动84498450845184528453845384548455845684578458845884598460846184628463846484648465846684678468846884698470847184722 行未改动84758476847784788479847984808481848284832 行未改动84868487848884898490849084918492849384948495849584968497849884998500850185028503850485048505850685078508850985098510851185128513851485158515851685178518851985208521852185228523852485258526852685278528852985308531853285338533853485358536853785378538853985408540854185428543854424 行未改动85698570857185728573857385748575857685778578857885798580858185828583858385848585858685868587858885898589859085918592859385948595859685978597859885998600860186028602860386048605860686078608860886098610861186128613861386148615861686178618861886198620862186228 行未改动86318632863386348635863586368637863786388639864086418642864286438644864586468647864786488649865086518652865386548655865686568657865886598660866086618662866386642 行未改动8667866886698670867186718672867386748675867686778677867886798680868186828683868486858685868686878687868886898690869186928692869386948695869686978698869986998700870187028703870487058705870687078708870987108710871187128713871487158715871687178718871987198720872187228723872487248725872687278727872887298730873187328733873487358733873487358736873787388739874087418742874287438744874587468747874887498750875087518752875387548755875587568757875887598760876187618762876387648764876587668767876787688769877087718772877387738774877587768776877787788779878087818782878287838784878587868787878887898789879087918792879387948794879587968797879887968797879887998800880088018802880388038804880588068807880888098810881088118812881388146 行未改动8821882288238824882588258826882788288829882988308831883288328833883488358836883788388839884088418842884288438844884588468847884888498850885088518852885388538854885588568856885788588859886088618861886288638864886588668867886888698869887088718872887388748875887688768877887888798880888188828882888388848885888588868887888888898889889088918892889388948895889688968897889888998900890089018902890389048905890589068907890889088909891089118912891389148915891589168917891889188919892089218921892289238924892489258926892789278928892989308931893289338933893489358936893789388939894089418942894389438944894589468947894889498950895189528952895389548955895689578958895989608960896189628963896489658966896789688969897089708971897289738974897589768976897789788979897989808981898289838983898489858986898789888988898989908991899289928993899489958996899789988998899990009001900290039003900490059006900790089008900990109011901190129013901490159016901790189018901990209021902290239024902490259026902790289029902990309031903290339034903590359036903790389039903990409041904290439 行未改动27 行未改动 <!-- Tailwind CSS v3 --> <script src="https://cdn.tailwindcss.com"></script> <!-- Font Awesome --> <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script> tailwind.config = { theme: { extend: {20 行未改动 } } } </script>
<style type="text/tailwindcss"> @layer utilities { .preserve-3d { transform-style: preserve-3d;30 行未改动 opacity: 1; visibility: visible; } }
/* Custom styles for 3D dice */ .dice-scene { perspective: 1500px; width: 120px; height: 120px; display: flex; align-items: center; justify-content: center; }
.dice-container { position: relative; width: 100px; height: 100px; transform-style: preserve-3d; transition: transform 1s ease-out; transform: rotateX(20deg) rotateY(20deg); }
.dice-face { position: absolute; width: 100px; height: 100px;4 行未改动 align-items: center; justify-content: center; box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1); }
/* Dice face positions */ .face-1 { transform: translateZ(50px); } .face-2 { transform: rotateY(90deg) translateZ(50px); } .face-3 { transform: rotateY(180deg) translateZ(50px); } .face-4 { transform: rotateY(-90deg) translateZ(50px); } .face-5 { transform: rotateX(90deg) translateZ(50px); } .face-6 { transform: rotateX(-90deg) translateZ(50px); }
/* Dots on dice faces */ .dot { position: absolute; width: 20px; height: 20px; border-radius: 50%; background-color: black; }
/* Dot positions for each face */ .face-1 .dot { top: 40px; left: 40px; }
.face-2 .dot:nth-child(1) { top: 20px; left: 20px; } .face-2 .dot:nth-child(2) { top: 60px; left: 60px; }
.face-3 .dot:nth-child(1) { top: 20px; left: 20px; } .face-3 .dot:nth-child(2) { top: 40px; left: 40px; } .face-3 .dot:nth-child(3) { top: 60px; left: 60px; }
.face-4 .dot:nth-child(1) { top: 20px; left: 20px; } .face-4 .dot:nth-child(2) { top: 20px; left: 60px; } .face-4 .dot:nth-child(3) { top: 60px; left: 20px; } .face-4 .dot:nth-child(4) { top: 60px; left: 60px; }
.face-5 .dot:nth-child(1) { top: 20px; left: 20px; } .face-5 .dot:nth-child(2) { top: 20px; left: 60px; } .face-5 .dot:nth-child(3) { top: 40px; left: 40px; } .face-5 .dot:nth-child(4) { top: 60px; left: 20px; } .face-5 .dot:nth-child(5) { top: 60px; left: 60px; }
.face-6 .dot:nth-child(1) { top: 20px; left: 20px; } .face-6 .dot:nth-child(2) { top: 20px; left: 60px; } .face-6 .dot:nth-child(3) { top: 40px; left: 20px; } .face-6 .dot:nth-child(4) { top: 40px; left: 60px; } .face-6 .dot:nth-child(5) { top: 60px; left: 20px; } .face-6 .dot:nth-child(6) { top: 60px; left: 60px; }
.dice-result { transition: all 0.5s ease-out; }
.result-shine { animation: shine 0.5s ease-out; }
.score-increase { color: #10b981; animation: scorePopup 1s ease-out; }
.score-decrease { color: #ef4444; animation: scorePopup 1s ease-out; }
.score-neutral { color: #6b7280; animation: scorePopup 1s ease-out; }
/* Locked color option styles */ .color-option.locked { position: relative; opacity: 0.5; cursor: not-allowed; }
.color-option.locked::after { content: '\f023'; /* Lock icon from Font Awesome */ font-family: 'FontAwesome'; position: absolute;2 行未改动 transform: translate(-50%, -50%); color: rgba(0, 0, 0, 0.5); font-size: 16px; }
@keyframes shine { 0% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4); }3 行未改动 100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); } }
@keyframes scorePopup { 0% { transform: translateY(0); opacity: 0;6 行未改动 transform: translateY(-20px); opacity: 0; } }
.confetti { position: absolute; width: 10px; height: 10px; background-color: #f97316; animation: confetti-fall 3s ease-in-out infinite; }
@keyframes confetti-fall { 0% { transform: translateY(-100vh) rotate(0deg); opacity: 1;2 行未改动 transform: translateY(100vh) rotate(720deg); opacity: 0; } }
@keyframes lock-particle { 0% { transform: translate(0, 0); opacity: 1;2 行未改动 transform: translate(var(--tx), var(--ty)); opacity: 0; } }
/* Game Rules Modal Styles */ .game-rules-modal { position: fixed; top: 0;7 行未改动 padding: 1rem; visibility: hidden; box-sizing: border-box; }
.game-rules-modal .modal-backdrop { position: absolute; top: 0; left: 0;2 行未改动 opacity: 0; visibility: hidden; transition: all 0.3s ease-out; }
.game-rules-modal .modal-content { position: relative; background-color: white; border-radius: 1rem;2 行未改动 width: 500px; overflow-y: auto; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); }
.game-rules-modal .modal-header { padding: 1.5rem; border-bottom: 1px solid #e5e7eb; display: flex; justify-content: space-between; align-items: center; }
.game-rules-modal .modal-title { font-size: 1.25rem; font-weight: 600; color: #1e293b; }
.game-rules-modal .close-button { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; transition: color 0.2s ease-in-out; }
.game-rules-modal .close-button:hover { color: #1e293b; }
.game-rules-modal .modal-body { padding: 1.5rem; line-height: 1.6; color: #374151; }
.game-rules-modal .modal-body h3 { font-size: 1.1rem; font-weight: 600; margin-top: 1.5rem; margin-bottom: 0.75rem; color: #1e293b; }
.game-rules-modal .modal-body p { margin-bottom: 1rem; }
.game-rules-modal .modal-body ul { margin-bottom: 1rem; padding-left: 1.5rem; list-style-type: disc; }
.game-rules-modal .modal-body li { margin-bottom: 0.5rem; }
.game-rules-modal .modal-body strong { font-weight: 600; color: #1e293b; }
.game-rules-modal .modal-footer { padding: 1rem 1.5rem; border-top: 1px solid #e5e7eb; display: flex; justify-content: flex-end; }
.game-rules-modal .modal-footer button { padding: 0.5rem 1rem; border-radius: 0.5rem; background-color: #3b82f6; color: white; font-weight: 500; transition: background-color 0.2s ease-in-out; }
.game-rules-modal .modal-footer button:hover { background-color: #2563eb; }
/* Game Rules Button Styles */ .game-rules-button { position: fixed; top: 1rem;9 行未改动 gap: 0.5rem; transition: all 0.2s ease-in-out; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); }
.game-rules-button:hover { background-color: #2563eb; transform: translateY(-2px); }
.game-rules-button i { font-size: 1.1rem; } </style>3 行未改动 <button id="game-rules-button" class="game-rules-button"> <i class="fa fa-book"></i> <span>Game Rules</span> </button>
<!-- Game Rules Modal --> <div id="game-rules-modal" class="game-rules-modal"> <div class="modal-backdrop"></div> <div class="modal-content">2 行未改动 <button class="close-button">×</button> </div> <div class="modal-body"> <p>Welcome to the 3D Dice Game! This is an exciting game that combines luck, strategy, and upgrading mechanics. Below is the complete game rules explanation:</p>
<h3>Basic Gameplay</h3> <ul> <li>Click the "Roll Dice" button to roll the dice</li> <li>The dice will randomly show a number between 1-6</li> <li>Gain or lose points based on the number rolled</li> <li>The goal is to obtain the highest tier "Unique" dice</li> </ul>
<h3>Score System</h3> <ul> <li>Rolling 1 or 2: Lose 1 point (multiplier not applied)</li> <li>Rolling 3: No points gained or lost</li> <li>Rolling 4: Gain 1 point</li> <li>Rolling 5: Gain 2 points</li> <li>Rolling 6: Gain 3 points</li> </ul>
<h3>Dice Upgrade System</h3> <p>There are 10 different tiers of dice in the game, from common to rare:</p> <ul> <li><strong>Empty</strong> (Initial) - Score Multiplier ×1.0</li>7 行未改动 <li><strong>Super</strong> - Score Multiplier ×1.8</li> <li><strong>Unique</strong> - Score Multiplier ×1.9</li> </ul> <p>Each upgrade costs 5 points. After upgrading, you can choose to use the new dice or continue using the old one.</p>
<h3>Item System</h3> <p>When upgrading, you have a chance to obtain item cards that can be used at critical moments:</p> <ul> <li><strong>Double Points Card</strong>: Doubles the points from one roll</li> <li><strong>No Penalty Card</strong>: Prevents point loss when rolling 1 or 2</li> <li><strong>Lucky Streak Card</strong>: Gives you 3 free dice rolls that don't count towards your total</li> </ul> <p>Items can be stockpiled and each card can only be used once. Double Points Cards and No Penalty Cards can be used simultaneously. Lucky Streak Cards give you 3 free rolls that don't count towards your total roll count.</p>
<h3>Game Rules</h3> <ul> <li>Initial score is 10 points</li> <li>Score multiplier changes based on the current dice tier being used</li> <li>Game over when score is less than 0</li> <li>Game victory when obtaining the Unique dice</li> <li>Unlocked dice colors can be switched at any time</li> </ul>
<h3>Operation Tips</h3> <ul> <li>Click on dice color options to switch the dice being used</li> <li>Click the "Upgrade Dice" button to upgrade your dice (requires 5 points)</li> <li>Click the "Use" button next to item cards to use them</li> <li>Press the ESC key to close the rules window</li> </ul>
<p>Good luck, and may you successfully obtain the highest tier Unique dice!</p> </div> <div class="modal-footer"> <button class="close-button">Got it</button> </div> </div> </div>
<div class="w-full max-w-md mx-auto glass-effect rounded-2xl p-6 dice-shadow relative z-10"> <h1 class="text-3xl font-bold text-center text-dark mb-8">3D Dice Roll</h1>
<div class="flex flex-col items-center justify-center mb-8"> <!-- Dice display area --> <div id="dice-display" class="w-48 h-48 flex items-center justify-center mb-4 bg-gray-100 rounded-lg"> <!-- Dice scene for 3D perspective -->2 行未改动 <!-- Dice faces will be inserted here by JavaScript --> </div> </div> </div>
<!-- Result display --> <div id="result-display" class="text-2xl font-bold text-center mb-4 hidden"> Result: <span id="result-value" class="text-primary">0</span> </div>
<!-- Score display --> <div id="score-display" class="text-xl font-bold text-center mb-2"> Score: <span id="score-value" class="text-secondary">10</span> <span id="score-change" class="ml-2 text-sm font-normal"></span> </div>
<!-- Roll count display --> <div id="roll-count-display" class="text-lg font-medium text-center mb-4"> Rolls: <span id="roll-count-value" class="text-gray-700">0</span> </div>
<!-- Roll button --> <button id="roll-button" class="bg-primary hover:bg-blue-600 text-white font-bold py-3 px-6 rounded-full transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-blue-300 focus:ring-opacity-50"> <i class="fa fa-random mr-2"></i> Roll Dice </button>
<!-- Upgrade button and current tier display --> <div class="flex flex-col items-center mt-4"> <div id="current-tier" class="text-sm text-gray-600 mb-2"> Current Dice: <span class="font-semibold text-primary">Empty</span>4 行未改动 <button id="upgrade-button" class="bg-secondary hover:bg-orange-600 text-white font-bold py-2 px-4 rounded-full transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-orange-300 focus:ring-opacity-50"> <i class="fa fa-arrow-up mr-1"></i> Upgrade Dice <span id="upgrade-cost">(Cost: 5)</span> </button> </div>
<!-- Game message display --> <div id="game-message" class="mt-4 text-center font-semibold hidden"></div>
<!-- Items display --> <div id="items-display" class="mt-6 grid grid-cols-2 gap-4"> <div class="bg-white rounded-lg p-3 dice-shadow"> <div class="flex items-center justify-between">9 行未改动 </div> </div> <p class="text-xs text-gray-500 mt-1">Doubles your score change for one roll</p> </div>
<div class="bg-white rounded-lg p-3 dice-shadow"> <div class="flex items-center justify-between"> <div class="flex items-center"> <i class="fa fa-shield text-blue-500 text-xl mr-2"></i>7 行未改动 </div> </div> <p class="text-xs text-gray-500 mt-1">Prevents score loss when rolling 1 or 2</p> </div>
<div class="bg-white rounded-lg p-3 dice-shadow"> <div class="flex items-center justify-between"> <div class="flex items-center"> <i class="fa fa-star text-yellow-500 text-xl mr-2"></i>8 行未改动 </div> <p class="text-xs text-gray-500 mt-1">Get 3 free dice rolls (not counted in total)</p> </div> </div>
<!-- Free rolls indicator --> <div id="free-rolls-indicator" class="mt-3 text-center hidden"> <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800"> <i class="fa fa-star mr-1" style="color: #f59e0b;"></i> <span>Free Rolls: <span id="free-rolls-count">0</span></span> </span> </div>
<!-- Active item indicator --> <div id="active-item-indicator" class="mt-3 text-center hidden"> <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"> <i id="active-item-icon" class="mr-1"></i> <span id="active-item-text">Active Item: None</span> </span> </div> </div>
<!-- Dice color selection --> <div class="mb-8"> <label class="block text-sm font-medium text-gray-700 mb-2">Dice Rarity</label> <div class="grid grid-cols-5 gap-4">48 行未改动 <span class="text-xs text-center text-gray-600">Unique</span> </div> </div> </div>
<!-- History log --> <div class="bg-white rounded-lg p-4 h-32 overflow-y-auto"> <h2 class="text-lg font-semibold text-center mb-2">Roll History</h2> <ul id="history-list" class="text-sm"> <!-- History items will be inserted here by JavaScript --> </ul> </div> </div>
<footer class="mt-8 text-center text-gray-600 text-sm"> <p>Click the button to roll the dice and see the result!</p> </footer>
<script> // Set up global error handler window.addEventListener('error', function(event) { console.error('Global error caught:', event.error);
// Try to get roll button element const rollButton = document.getElementById('roll-button'); if (rollButton && rollButton.disabled) { console.warn('Error during dice roll, re-enabling button'); rollButton.disabled = false; rollButton.classList.remove('opacity-70', 'cursor-not-allowed');
// Try to show error message const gameMessage = document.getElementById('game-message'); if (gameMessage) { gameMessage.textContent = 'An error occurred. Please try again.'; gameMessage.className = 'mt-4 text-center font-semibold text-red-500'; gameMessage.classList.remove('hidden'); } } });
// DOM elements const diceElement = document.getElementById('dice'); const rollButton = document.getElementById('roll-button'); const resultDisplay = document.getElementById('result-display');8 行未改动 const gameMessageDisplay = document.getElementById('game-message'); const rollCountDisplay = document.getElementById('roll-count-display'); const rollCountValue = document.getElementById('roll-count-value'); const upgradeCost = document.getElementById('upgrade-cost');
// Item related DOM elements const doublePointsCount = document.getElementById('double-points-count'); const noPenaltyCount = document.getElementById('no-penalty-count'); const luckyStreakCount = document.getElementById('lucky-streak-count');2 行未改动 const useLuckyStreakButton = document.getElementById('use-lucky-streak'); const activeItemIndicator = document.getElementById('active-item-indicator'); const freeRollsIndicator = document.getElementById('free-rolls-indicator'); const freeRollsCountElement = document.getElementById('free-rolls-count');
// Game state let currentScore = 10; // Initial score let currentTier = 0; // Initial dice tier (0 = Empty) let gameOver = false; // Game over flag let rollCount = 0; // Number of dice rolls
// Item system let doublePointsCards = 0; // Number of double points cards let noPenaltyCards = 0; // Number of no penalty cards let luckyStreakCards = 0; // Number of lucky streak cards let freeRolls = 0; // Number of free rolls available let activeItems = { // Currently active items double: 0, // Number of active double points cards noPenalty: false // Whether no penalty card is active };
// Dice tiers configuration const diceTiers = [ { name: 'Empty', color: '#FFFFFF' }, { name: 'Common', color: '#7EEF6D' },5 行未改动 { name: 'Ultra', color: '#ff2b75' }, { name: 'Super', color: '#2bffa3' }, { name: 'Unique', color: '#555555' } ];
// Initialize 3D dice function initializeDice() { console.log('Initializing dice...'); // Create 6 faces for the dice const faces = [1, 2, 3, 4, 5, 6];
faces.forEach(faceNumber => { const face = document.createElement('div'); face.className = `dice-face face-${faceNumber}`;
// Add dots to the face based on the number for (let i = 0; i < faceNumber; i++) { const dot = document.createElement('div'); dot.className = 'dot'; face.appendChild(dot); }
diceElement.appendChild(face); console.log(`Added face ${faceNumber}`); });
console.log('Dice initialized with faces:', diceElement.children.length);
// Set initial position to show face 1 clearly diceElement.style.transform = 'rotateX(0deg) rotateY(0deg)'; }
// Get random rotation values for the dice function getRandomRotation() { // Determine which face we want to show const targetFace = Math.floor(Math.random() * 6) + 1;
// Get current rotation from dice element const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); const matrix = new DOMMatrix(currentTransform);
// Extract current rotation angles let currentX = 0, currentY = 0;
// If transform is not identity matrix, extract rotation if (currentTransform !== 'none') { // Calculate rotation from matrix currentX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI); currentY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI); }
// Set target rotation based on target face // These values are precisely calibrated to show the correct face let targetX = 0, targetY = 0; switch(targetFace) {21 行未改动 targetX = 90; targetY = 0; break; }
// Calculate the shortest path to the target rotation // This prevents large rotation values from accumulating let diffX = targetX - currentX; let diffY = targetY - currentY;
// Normalize the difference to the range [-180, 180] to find the shortest path diffX = ((diffX + 180) % 360) - 180; diffY = ((diffY + 180) % 360) - 180;
// Add multiple full rotations for spinning effect (2-4 full rotations) const fullRotations = 2 + Math.floor(Math.random() * 3);
// Calculate final rotation with full spins // We add full rotations in the direction of the shortest path const spinDirectionX = diffX >= 0 ? 1 : -1; const spinDirectionY = diffY >= 0 ? 1 : -1;
const finalX = currentX + diffX + spinDirectionX * fullRotations * 360; const finalY = currentY + diffY + spinDirectionY * fullRotations * 360;
// Add a tiny bit of randomness to make it look more natural // But not enough to change which face is visible const randomX = (Math.random() - 0.5) * 2; const randomY = (Math.random() - 0.5) * 2;
return { x: finalX + randomX, y: finalY + randomY, targetFace: targetFace // Return the target face so we don't have to recalculate it }; }
// Roll the dice function function rollDice() { // Check if game is over if (gameOver) { showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500'); return; }
// Check if there are free rolls available const isFreeRoll = freeRolls > 0;
// Increment roll count only if not a free roll if (!isFreeRoll) { rollCount++; console.log(`Roll count: ${rollCount}`);2 行未改动 freeRolls--; updateFreeRollsDisplay(); console.log(`Free roll used. Remaining free rolls: ${freeRolls}`); }
// Update roll count display if (rollCountValue) { rollCountValue.textContent = rollCount; }
console.log('Rolling dice...'); console.log('Button state before disable:', rollButton.disabled);
// Disable button during animation rollButton.disabled = true; rollButton.classList.add('opacity-70', 'cursor-not-allowed');
console.log('Button state after disable:', rollButton.disabled);
// Hide result display resultDisplay.classList.add('hidden');
try { // Set animation duration const duration = 2000; // Fixed duration for consistent experience
// Get random rotation values for the final position const rotationData = getRandomRotation(); console.log('Rotation data:', rotationData); console.log('Target face:', rotationData.targetFace);
// Animate the dice using JavaScript for more control animateDice(duration, rotationData);
// Set a safety timeout to ensure button is re-enabled even if something goes wrong setTimeout(() => { if (rollButton.disabled) { console.warn('Safety timeout: Re-enabling roll button');7 行未改动 enableRollButton(); showGameMessage('An error occurred during the dice roll. Please try again.', 'text-red-500'); } }
// Animate the dice with spin animation function animateDice(duration, rotationData) { console.log('Animate dice called with rotationData:', rotationData); const startTime = performance.now(); const finalRotation = rotationData;
// Get current rotation from dice element const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); const matrix = new DOMMatrix(currentTransform);
// Extract current rotation angles let startX = 0, startY = 0;
// If transform is not identity matrix, extract rotation if (currentTransform !== 'none') { // Calculate rotation from matrix startX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI); startY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI); }
// Function to handle each animation frame function animate(currentTime) { const elapsedTime = currentTime - startTime; const progress = Math.min(elapsedTime / duration, 1);
// Apply easing function for smooth, natural animation const easedProgress = easeOutCubic(progress);
// Calculate current rotation - smooth continuous rotation const currentX = startX + (finalRotation.x - startX) * easedProgress; const currentY = startY + (finalRotation.y - startY) * easedProgress;
// Spin animation: rotate in place diceElement.style.transform = `rotateX(${currentX}deg) rotateY(${currentY}deg)`;
// Continue animation if not complete if (progress < 1) { requestAnimationFrame(animate); } else { // Animation complete - ensure we're at the exact target rotation diceElement.style.transform = `rotateX(${finalRotation.x}deg) rotateY(${finalRotation.y}deg)`;
// Show result after a short delay to ensure rotation is complete console.log('Animation complete, calling finalizeAnimation...'); setTimeout(() => { finalizeAnimation(finalRotation); }, 50); } }
// Start the animation requestAnimationFrame(animate); }
// Helper function to normalize angles to the range [-180, 180] function normalizeAngle(angle) { angle = angle % 360; if (angle > 180) angle -= 360; if (angle < -180) angle += 360; return angle; }
// Easing function for smooth, natural animation with gentle acceleration and deceleration // Uses a cubic easing function that starts slow, accelerates, then slows down at the end function easeOutCubic(t) { return 1 - Math.pow(1 - t, 3); }
// Calculate score change based on dice roll result function calculateScoreChange(result) { let baseChange = 0;
switch(result) { case 1: case 2: baseChange = -1;12 行未改动 break; default: baseChange = 0; }
// Apply current tier multiplier // If losing points (baseChange < 0), use multiplier of 1 instead of tier multiplier const tierMultiplier = 1 + currentTier / 10; let finalChange;
if (baseChange < 0) { // For point loss, use multiplier of 1 regardless of tier finalChange = baseChange * 1; } else { // For point gain or neutral, use tier multiplier finalChange = baseChange * tierMultiplier; }
// Apply active item effects const itemsUsed = { double: activeItems.double, noPenalty: activeItems.noPenalty };
// Apply no penalty card first if (activeItems.noPenalty && baseChange < 0) { finalChange = 0; }
// Apply double points cards if (activeItems.double > 0) { finalChange = finalChange * Math.pow(2, activeItems.double); }
// Round to 2 decimal places to avoid floating point precision issues finalChange = Math.round(finalChange * 100) / 100;
return { baseChange: baseChange, finalChange: finalChange, itemsUsed: itemsUsed, tierMultiplier: tierMultiplier }; }
// Enable roll button function enableRollButton() { console.log('Button state before enable:', rollButton.disabled);
// Directly enable the button rollButton.disabled = false; rollButton.classList.remove('opacity-70', 'cursor-not-allowed');
console.log('Button state after enable:', rollButton.disabled);
// Double-check and force enable if needed if (rollButton.disabled) { console.warn('Forcing button enable'); setTimeout(() => {2 行未改动 console.log('Button state after forced enable:', rollButton.disabled); }, 100); } }
// Finalize the animation and show result function finalizeAnimation(rotationData) { console.log('=== Finalize animation called ==='); console.log('Rotation data:', rotationData); const finalRotation = rotationData;
// Use the target face directly instead of recalculating const result = finalRotation.targetFace; console.log(`Final result: ${result} (should show face ${result})`);
// Show result display resultValue.textContent = result; resultDisplay.classList.remove('hidden');
// Add shine effect to result resultDisplay.classList.add('result-shine'); setTimeout(() => { resultDisplay.classList.remove('result-shine'); }, 500);
// Calculate and update score console.log('Calculating score change...'); const scoreChangeData = calculateScoreChange(result); console.log('Score change data:', scoreChangeData);
currentScore += scoreChangeData.finalChange; console.log('Updated score:', currentScore);
// Update score display with animation console.log('Updating score display...'); updateScoreDisplay(scoreChangeData);
// Enable button console.log('Enabling roll button...'); enableRollButton();
// Add to history - include whether it was a free roll addToHistory(result, scoreChangeData, isFreeRoll);
// Check if reached the Unique dice if (currentTier === diceTiers.length - 1) { showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500'); gameOver = true; createConfetti(); }
// Create confetti effect if result is 6 if (result === 6) { createConfetti(); }
// Debug: log final state console.log(`Final precise rotation: X=${finalRotation.x}°, Y=${finalRotation.y}°`); console.log(`Displayed result: ${result}`); console.log(`Score change: ${scoreChangeData.finalChange}, Current score: ${currentScore}`); console.log('=== finalizeAnimation completed ==='); }
// Update score display with animation function updateScoreDisplay(scoreChangeData) { console.log('=== updateScoreDisplay called ==='); console.log('Score change data:', scoreChangeData);
const change = scoreChangeData.finalChange; const baseChange = scoreChangeData.baseChange; const itemsUsed = scoreChangeData.itemsUsed; const tierMultiplier = scoreChangeData.tierMultiplier;
console.log('Change:', change, 'Base change:', baseChange, 'Items used:', itemsUsed);
// Update the score value - round to 2 decimal places currentScore = Math.round(currentScore * 100) / 100; scoreValue.textContent = currentScore; console.log('Score value updated to:', currentScore);
// Clear previous score change display scoreChange.textContent = ''; scoreChange.className = 'ml-2 text-sm font-normal'; console.log('Cleared previous score change display');
// Show score change with appropriate styling if (change > 0) { scoreChange.textContent = `+${change}`; scoreChange.classList.add('score-increase');6 行未改动 scoreChange.textContent = `±0`; scoreChange.classList.add('score-neutral'); console.log('Score neutral'); }
// Show item effect message if items were used if (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) { // Create container for item effects const itemEffectsContainer = document.createElement('div'); itemEffectsContainer.className = 'flex flex-wrap gap-2 mt-1';
// Add tier multiplier effect if applicable if (tierMultiplier !== 1) { const tierEffect = document.createElement('div'); tierEffect.className = 'text-xs text-purple-500'; tierEffect.textContent = `Tier Multiplier ×${tierMultiplier.toFixed(1)}!`; itemEffectsContainer.appendChild(tierEffect); }
// Add no penalty effect if (itemsUsed.noPenalty) { const noPenaltyEffect = document.createElement('div'); noPenaltyEffect.className = 'text-xs text-blue-500'; noPenaltyEffect.textContent = `No Penalty! (Score protected from ${baseChange < 0 ? baseChange : 0} loss)`; itemEffectsContainer.appendChild(noPenaltyEffect); }
// Add double points effect if (itemsUsed.double > 0) { const doublePointsEffect = document.createElement('div'); doublePointsEffect.className = 'text-xs text-green-500';
// Calculate multiplier const multiplier = Math.pow(2, itemsUsed.double); let calculationText = `${baseChange}`;
// Apply tier multiplier for display let displayChange = baseChange * tierMultiplier;
// Apply no penalty first for display if (itemsUsed.noPenalty && baseChange < 0) { displayChange = 0; calculationText = `(${baseChange} × ${tierMultiplier.toFixed(1)} → 0)`; } else if (tierMultiplier !== 1) { calculationText = `(${baseChange} × ${tierMultiplier.toFixed(1)} = ${displayChange.toFixed(2)})`; }
// Show multiplication steps if multiple double cards used if (itemsUsed.double > 1) { for (let i = 0; i < itemsUsed.double; i++) { calculationText += ` × 2`; } calculationText += ` = ${(displayChange * multiplier).toFixed(2)}`; } else { calculationText += ` × 2 = ${(displayChange * multiplier).toFixed(2)}`; }
doublePointsEffect.textContent = `Double Points ×${itemsUsed.double}! (${calculationText})`; itemEffectsContainer.appendChild(doublePointsEffect); }
// Add to score display scoreDisplay.appendChild(itemEffectsContainer);
// Remove after animation setTimeout(() => { scoreDisplay.removeChild(itemEffectsContainer); }, 1000); }
// Reset score change display after animation completes setTimeout(() => { scoreChange.textContent = ''; }, 1000);
// Clear active items after score update console.log('Checking if items need to be cleared...'); if (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) { console.log('Clearing active items...'); clearActiveItems(); console.log('Updating items display...'); updateItemsDisplay(); }
// Check game state after score update console.log('Checking game state...'); checkGameState(); console.log('=== updateScoreDisplay completed ==='); }
// Handle dice upgrade function upgradeDice() { // Check if game is already over if (gameOver) { showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500'); return; }
// Check if already at maximum tier if (currentTier >= diceTiers.length - 1) { // If not already game over, end the game with win condition if (!gameOver) {3 行未改动 showGameMessage('Congratulations! You already have the Unique dice!', 'text-green-500'); } return; }
// Calculate required score for upgrade (5 + currentTier) const requiredScore = 5 + currentTier;
// Check if enough score to upgrade if (currentScore < requiredScore) { showGameMessage(`Not enough score to upgrade! Need ${requiredScore} points.`, 'text-orange-500'); // Add shake animation to score display2 行未改动 scoreDisplay.classList.remove('animate-shake'); }, 500); return; }
// Deduct score for upgrade currentScore -= requiredScore; // Round to 2 decimal places currentScore = Math.round(currentScore * 100) / 100;
// Update score display scoreValue.textContent = currentScore; showScoreChange(-5);
// Increase tier currentTier++;
// Update current tier display currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;
// Update tier multiplier display updateTierMultiplierDisplay();
// Unlock the new dice color unlockDiceColor(currentTier);
// Update color selection UI updateColorSelection(currentTier);
// Update upgrade cost display updateUpgradeCostDisplay();
// Change to the new dice color console.log(`Changing dice color to ${diceTiers[currentTier].color} (${diceTiers[currentTier].name})`); changeDiceColor(diceTiers[currentTier].color);
// Check if this upgrade reached the maximum tier checkGameState();
// Randomly get an item const itemChance = Math.random(); if (itemChance < 0.32) { // 32% chance to get double points card doublePointsCards++;3 行未改动 // Do nothing } else { // 2% chance to get lucky streak card luckyStreakCards++; }
// Update items display to show new counts updateItemsDisplay();
// Update items display updateItemsDisplay();
// Check if reached the Unique dice if (currentTier === diceTiers.length - 1) { showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500'); gameOver = true; createConfetti(); }
// Add to history addToHistory('UPGRADE', -5);
// Add item to history if obtained if (itemChance < 0.32) { addToHistory('ITEM', 'Double Points Card'); } else if (itemChance < 0.64) { addToHistory('ITEM', 'No Penalty Card'); } else if (itemChance >= 0.98) { addToHistory('ITEM', 'Lucky Streak Card'); }
// Check game state after upgrade checkGameState(); }
// Show score change temporarily function showScoreChange(change) { scoreChange.textContent = change > 0 ? `+${change}` : change; scoreChange.className = `ml-2 text-sm font-normal ${change > 0 ? 'score-increase' : 'score-decrease'}`;
setTimeout(() => { scoreChange.textContent = ''; }, 1000); }
// Unlock a dice color option function unlockDiceColor(tierIndex) { if (tierIndex >= 0 && tierIndex < colorOptions.length) { const option = colorOptions[tierIndex];5 行未改动 option.classList.remove('locked'); }, 300); } }
// Show game message function showGameMessage(message, className) { gameMessageDisplay.textContent = message; gameMessageDisplay.className = `mt-4 text-center font-semibold ${className}`; gameMessageDisplay.classList.remove('hidden');
// Hide message after 3 seconds setTimeout(() => { if (!gameOver) { gameMessageDisplay.classList.add('hidden'); } }, 3000); }
// Check game state (win/lose conditions) function checkGameState() { console.log('=== checkGameState called ==='); console.log('Current score:', currentScore, 'Game over:', gameOver);
// Check if score is negative (lose condition) if (currentScore < 0 && !gameOver) { console.log('Score is negative, ending game...'); gameOver = true; endGame(false); }
// Check if reached Unique dice (win condition) if (currentTier === diceTiers.length - 1 && !gameOver) { console.log('Reached Unique dice, ending game...'); gameOver = true; endGame(true); }
// Check if score is low (warning) if (currentScore >= 0 && currentScore <= 5 && !gameOver) { showLowScoreWarning(); }
console.log('=== checkGameState completed ==='); }
// Update items display function updateItemsDisplay() { // Update counts doublePointsCount.textContent = doublePointsCards; noPenaltyCount.textContent = noPenaltyCards; luckyStreakCount.textContent = luckyStreakCards;
// Enable/disable buttons based on available items useDoublePointsButton.disabled = doublePointsCards <= 0 || gameOver; useNoPenaltyButton.disabled = noPenaltyCards <= 0 || activeItems.noPenalty || gameOver; useLuckyStreakButton.disabled = luckyStreakCards <= 0 || gameOver;
// Update free rolls display updateFreeRollsDisplay(); }
// Update free rolls display function updateFreeRollsDisplay() { if (freeRolls > 0) { freeRollsCountElement.textContent = freeRolls; freeRollsIndicator.classList.remove('hidden'); } else { freeRollsIndicator.classList.add('hidden'); } }
// Update upgrade cost display function updateUpgradeCostDisplay() { if (currentTier >= diceTiers.length - 1) { // Already at maximum tier2 行未改动 const requiredScore = 5 + currentTier; upgradeCost.textContent = `(Cost: ${requiredScore})`; } }
// Use double points card function useDoublePointsCard() { if (doublePointsCards > 0 && !gameOver) { activeItems.double++; doublePointsCards--;
// Update UI updateItemsDisplay(); showActiveItemIndicator();
// Show message showGameMessage('Double Points Card activated! Next roll will double your score change.', 'text-green-500'); } }
// Use no penalty card function useNoPenaltyCard() { if (noPenaltyCards > 0 && !activeItems.noPenalty && !gameOver) { activeItems.noPenalty = true; noPenaltyCards--;
// Update UI updateItemsDisplay(); showActiveItemIndicator();
// Show message showGameMessage('No Penalty Card activated! Next roll won\'t lose points.', 'text-blue-500'); } }
// Use lucky streak card function useLuckyStreakCard() { if (luckyStreakCards > 0 && !gameOver) { freeRolls += 3; luckyStreakCards--;
// Update UI updateItemsDisplay();
// Show message showGameMessage('Lucky Streak Card activated! You have 3 free rolls!', 'text-yellow-500');
// Add to history addToHistory('ITEM USE', 'Lucky Streak Card'); } }
// Show active item indicator function showActiveItemIndicator() { // Clear previous content activeItemIndicator.innerHTML = '';
// Check if any items are active if (activeItems.double === 0 && !activeItems.noPenalty) { activeItemIndicator.className = 'mt-3 text-center hidden'; return; }
// Create container for active items const itemsContainer = document.createElement('div'); itemsContainer.className = 'flex flex-wrap justify-center gap-2';
// Add double points cards indicator if (activeItems.double > 0) { const doublePointsIndicator = document.createElement('span'); doublePointsIndicator.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800';2 行未改动 <span>Double Points ×${activeItems.double}</span> `; itemsContainer.appendChild(doublePointsIndicator); }
// Add no penalty card indicator if (activeItems.noPenalty) { const noPenaltyIndicator = document.createElement('span'); noPenaltyIndicator.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800';2 行未改动 <span>No Penalty</span> `; itemsContainer.appendChild(noPenaltyIndicator); }
// Add indicators to container activeItemIndicator.appendChild(itemsContainer); activeItemIndicator.className = 'mt-3 text-center'; }
// Clear active items function clearActiveItems() { activeItems = { double: 0, noPenalty: false }; showActiveItemIndicator(); }
// End the game and display appropriate message function endGame(isWin) { console.log('=== endGame called ==='); console.log('Is win:', isWin, 'Current score:', currentScore);
// Disable all interactive elements rollButton.disabled = true; upgradeButton.disabled = true; rollButton.classList.add('opacity-70', 'cursor-not-allowed'); upgradeButton.classList.add('opacity-70', 'cursor-not-allowed');
// Disable all interactive elements colorOptions.forEach(option => { option.disabled = true; option.classList.add('opacity-50', 'cursor-not-allowed'); });
// Disable item buttons useDoublePointsButton.disabled = true; useNoPenaltyButton.disabled = true;
// Hide active item indicator activeItemIndicator.classList.add('hidden');
// Create game over message element const gameOverMessage = document.createElement('div'); gameOverMessage.className = `mt-4 p-4 rounded-lg text-center font-bold ${isWin ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`;
// Format final score to 2 decimal places const formattedScore = currentScore.toFixed(2);
if (isWin) { gameOverMessage.innerHTML = ` <div class="text-2xl mb-2">Congratulations!</div> <p>You won the game!</p>24 行未改动 <i class="fa fa-refresh mr-1"></i> Play Again </button> `; }
// Add restart button event listener gameOverMessage.querySelector('#play-again').addEventListener('click', () => { window.location.reload(); });
// Replace game message display with game over message const gameMessageContainer = gameMessageDisplay.parentElement; gameMessageContainer.replaceChild(gameOverMessage, gameMessageDisplay); gameMessageDisplay = gameOverMessage;
// Add game end to history addToHistory(isWin ? 'GAME WIN' : 'GAME OVER', 0);
console.log('=== endGame completed ==='); }
// Show warning when score is low function showLowScoreWarning() { // Only show warning if not already showing if (gameMessageDisplay.classList.contains('hidden')) { showGameMessage('Warning: Low score! Risk of game over.', 'text-orange-500'); } }
// Update color selection UI to show the currently selected color function updateColorSelection(selectedIndex) { // Remove active state from all color options colorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary'));
// Add active state to the selected color option if (selectedIndex >= 0 && selectedIndex < colorOptions.length) { colorOptions[selectedIndex].classList.add('ring-2', 'ring-offset-2', 'ring-primary'); } }
// Add result to history function addToHistory(result, scoreChangeData, isFreeRoll = false) { const now = new Date(); const timeString = now.toLocaleTimeString();
// Determine score change display and color let scoreChangeText = ''; let scoreChangeClass = ''; let actionText = '';
if (result === 'UPGRADE') { actionText = 'Upgraded dice'; scoreChangeText = `${scoreChangeData}`; scoreChangeClass = 'text-red-500';8 行未改动 } else { const scoreChange = scoreChangeData.finalChange; const baseChange = scoreChangeData.baseChange; const itemsUsed = scoreChangeData.itemsUsed;
actionText = `Rolled a <span class="font-bold text-primary">${result}</span>`;
// Add free roll indicator if applicable if (isFreeRoll) { actionText += ` <span class="text-yellow-500">(Free Roll)</span>`; }
// Add item effect indicators if applicable const activeItemsText = []; if (itemsUsed && itemsUsed.double > 0) { activeItemsText.push(`<span class="text-green-500">(Double Points ×${itemsUsed.double})</span>`); } if (itemsUsed && itemsUsed.noPenalty) { activeItemsText.push(`<span class="text-blue-500">(No Penalty)</span>`); }
if (activeItemsText.length > 0) { actionText += ` ${activeItemsText.join(' ')}`; }
if (scoreChange > 0) { scoreChangeText = `+${scoreChange}`; scoreChangeClass = 'text-green-500'; } else if (scoreChange < 0) {2 行未改动 } else { scoreChangeText = '±0'; scoreChangeClass = 'text-gray-500'; }
// Show base change if different from final change (items were used) if ((itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) && baseChange !== scoreChange) { scoreChangeText += ` <span class="text-xs">(Base: ${baseChange > 0 ? '+' : ''}${baseChange})</span>`; } }
const listItem = document.createElement('li'); listItem.className = 'py-1 border-b border-gray-100 flex justify-between items-center'; listItem.innerHTML = ` <span><span class="text-gray-500">${timeString}</span>: ${actionText}</span> <span class="font-medium ${scoreChangeClass}">${scoreChangeText}</span> `;
historyList.prepend(listItem);
// Keep only last 5 history items if (historyList.children.length > 5) { historyList.removeChild(historyList.lastChild); } }
// Create confetti effect function createConfetti() { const confettiContainer = document.createElement('div'); confettiContainer.className = 'fixed inset-0 pointer-events-none overflow-hidden'; document.body.appendChild(confettiContainer);
// Create 50 confetti pieces for (let i = 0; i < 50; i++) { const confetti = document.createElement('div'); confetti.className = 'confetti';
// Random position const posX = Math.random() * 100; const delay = Math.random() * 3; const duration = 3 + Math.random() * 2;
// Random colors const colors = ['#3b82f6', '#f97316', '#10b981', '#ef4444', '#8b5cf6']; const color = colors[Math.floor(Math.random() * colors.length)];
confetti.style.left = `${posX}%`; confetti.style.backgroundColor = color; confetti.style.animationDelay = `${delay}s`; confetti.style.animationDuration = `${duration}s`;
confettiContainer.appendChild(confetti); }
// Remove confetti container after animation completes setTimeout(() => { document.body.removeChild(confettiContainer); }, 5000); }
// Create particle effect on lock function createLockParticles(lockElement) { // Get lock element position const rect = lockElement.getBoundingClientRect(); const centerX = rect.left + rect.width / 2; const centerY = rect.top + rect.height / 2;
// Create particle container const particleContainer = document.createElement('div'); particleContainer.className = 'absolute pointer-events-none'; particleContainer.style.left = `${centerX}px`; particleContainer.style.top = `${centerY}px`; particleContainer.style.transform = 'translate(-50%, -50%)'; document.body.appendChild(particleContainer);
// Create 15 particles for (let i = 0; i < 15; i++) { const particle = document.createElement('div'); particle.className = 'lock-particle';
// Random direction and distance const angle = Math.random() * Math.PI * 2; const distance = 10 + Math.random() * 20; const tx = Math.cos(angle) * distance; const ty = Math.sin(angle) * distance;
// Random color (use the color of the unlocked dice) const color = lockElement.style.backgroundColor;
// Random animation duration const duration = 0.5 + Math.random() * 0.5;
// Set particle styles particle.style.backgroundColor = color; particle.style.setProperty('--tx', `${tx}px`); particle.style.setProperty('--ty', `${ty}px`); particle.style.animation = `lock-particle ${duration}s ease-out forwards`;
particleContainer.appendChild(particle); }
// Remove particle container after animation completes setTimeout(() => { document.body.removeChild(particleContainer); }, 1000); }
// Function to darken a color by a certain percentage function darkenColor(color, percent) { const hex = color.replace('#', ''); let r = parseInt(hex.substr(0, 2), 16); let g = parseInt(hex.substr(2, 2), 16); let b = parseInt(hex.substr(4, 2), 16);
// Darken each channel by the percentage r = Math.max(0, Math.floor(r * (1 - percent / 100))); g = Math.max(0, Math.floor(g * (1 - percent / 100))); b = Math.max(0, Math.floor(b * (1 - percent / 100)));
// Convert back to hex const darkenedHex = '#' + r.toString(16).padStart(2, '0') + g.toString(16).padStart(2, '0') + const darkenedHex = '#' + r.toString(16).padStart(2, '0') + g.toString(16).padStart(2, '0') + b.toString(16).padStart(2, '0');
return darkenedHex; }
// Change dice color function function changeDiceColor(color) { console.log(`changeDiceColor called with color: ${color}`); const faces = document.querySelectorAll('.dice-face'); console.log(`Found ${faces.length} dice faces`); let dotColor, borderColor;
// Special cases for high contrast if (color.toUpperCase() === '#FFFFFF') { // White dice - use black dots and light gray borders dotColor = '#000000';6 行未改动 // Calculate darker color for dots and borders (40% darker for more contrast) dotColor = darkenColor(color, 40); borderColor = darkenColor(color, 30); // Slightly lighter border than dots }
faces.forEach(face => { // Set face background color face.style.backgroundColor = color;
// Set face border color face.style.border = `3px solid ${borderColor}`;
// Set dots color const dots = face.querySelectorAll('.dot'); dots.forEach(dot => { dot.style.backgroundColor = dotColor; // Add slight border to dots for better definition dot.style.border = color.toUpperCase() === '#FFFFFF' ? '1px solid rgba(0, 0, 0, 0.2)' : '1px solid rgba(0, 0, 0, 0.1)'; }); }); }
// Update tier multiplier display function updateTierMultiplierDisplay() { const display = document.getElementById('tier-multiplier-display'); if (display) { display.innerHTML = `Tier Multiplier: <span class="font-semibold text-purple-500">×${(1 + currentTier / 10).toFixed(1)}</span>`; } }
// Event listener for roll button rollButton.addEventListener('click', rollDice);
// Event listener for upgrade button upgradeButton.addEventListener('click', upgradeDice);
// Event listeners for item buttons useDoublePointsButton.addEventListener('click', useDoublePointsCard); useNoPenaltyButton.addEventListener('click', useNoPenaltyCard); useLuckyStreakButton.addEventListener('click', useLuckyStreakCard);
// Event listeners for color options colorOptions.forEach((option, index) => { // Disable all color options except the first one initially if (index !== 0) { option.disabled = true; option.classList.add('locked'); }
option.addEventListener('click', () => { // Check if game is over if (gameOver) { showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500'); return; }
// Check if color is unlocked if (option.disabled) { showGameMessage('You need to upgrade to unlock this dice color!', 'text-orange-500'); return; }
const color = option.getAttribute('data-color'); changeDiceColor(color);
// Add active state to selected color colorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary')); option.classList.add('ring-2', 'ring-offset-2', 'ring-primary');
// Update current tier to the selected color's tier currentTier = index; currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`; updateTierMultiplierDisplay(); }); });
// Initialize dice on page load window.addEventListener('DOMContentLoaded', () => { console.log('DOM fully loaded'); initializeDice();
// Set default color (first option) if (colorOptions.length > 0) { const defaultColor = colorOptions[0].getAttribute('data-color'); changeDiceColor(defaultColor); colorOptions[0].classList.add('ring-2', 'ring-offset-2', 'ring-primary'); }
// Initialize current tier display currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;
// Initialize tier multiplier display updateTierMultiplierDisplay();
// Initialize items display updateItemsDisplay();
// Initialize upgrade cost display updateUpgradeCostDisplay();
// Show welcome message setTimeout(() => { showGameMessage('Welcome! Roll the dice to earn points and upgrade your dice!', 'text-blue-500'); }, 1000); });
// Also try initializing on window load window.addEventListener('load', () => { console.log('Window loaded'); // If dice not already initialized, try again if (diceElement.children.length === 0) { console.log('Dice not initialized, trying again...'); initializeDice(); } });
// Game Rules Modal Functionality (function() { // Get elements const rulesButton = document.getElementById('game-rules-button'); const rulesModal = document.getElementById('game-rules-modal'); const closeButtons = rulesModal.querySelectorAll('.close-button'); const modalBackdrop = rulesModal.querySelector('.modal-backdrop'); const modalContent = rulesModal.querySelector('.modal-content');
// Function to prevent background scrolling function preventBackgroundScroll(event) { // Allow scrolling inside the modal content if (modalContent.contains(event.target)) { // Check if we're at the top or bottom of the modal content const isAtTop = modalContent.scrollTop === 0; const isAtBottom = modalContent.scrollTop + modalContent.clientHeight >= modalContent.scrollHeight;
// Prevent scrolling if at the top and scrolling up, or at the bottom and scrolling down if ((isAtTop && event.deltaY < 0) || (isAtBottom && event.deltaY > 0)) { event.preventDefault(); } } else { // Prevent scrolling outside the modal content event.preventDefault(); } }
// Function to open modal function openModal() { // Add event listeners to prevent background scrolling document.addEventListener('wheel', preventBackgroundScroll, { passive: false }); document.addEventListener('touchmove', preventBackgroundScroll, { passive: false });
// Add open class to trigger animations rulesModal.classList.add('modal-open');
// Show the modal rulesModal.style.visibility = 'visible'; }
// Function to close modal function closeModal() { // Remove open class to trigger animations rulesModal.classList.remove('modal-open');
// Remove event listeners that prevent background scrolling document.removeEventListener('wheel', preventBackgroundScroll); document.removeEventListener('touchmove', preventBackgroundScroll);
// Hide the modal after animation completes setTimeout(() => { rulesModal.style.visibility = 'hidden'; }, 300); }
// Add event listeners if (rulesButton) { rulesButton.addEventListener('click', openModal); }
// Close buttons closeButtons.forEach(button => { button.addEventListener('click', closeModal); });
// Close when clicking outside the modal content modalBackdrop.addEventListener('click', closeModal);
// Close when pressing Escape key document.addEventListener('keydown', (event) => { if (event.key === 'Escape' && rulesModal.classList.contains('modal-open')) { closeModal(); } });
// Add hover effect to rules button if (rulesButton) { rulesButton.addEventListener('mouseenter', () => { rulesButton.classList.add('scale-105'); });
rulesButton.addEventListener('mouseleave', () => { rulesButton.classList.remove('scale-105'); }); }
// Add click effect to close buttons closeButtons.forEach(button => { button.addEventListener('mousedown', () => { button.classList.add('scale-95'); });
button.addEventListener('mouseup', () => { button.classList.remove('scale-95'); });
button.addEventListener('mouseleave', () => { button.classList.remove('scale-95'); }); });16 行未改动 <!-- Tailwind CSS v3 --> <script src="https://cdn.tailwindcss.com"></script> <!-- Font Awesome --> <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script> tailwind.config = { theme: { extend: {20 行未改动 } } } </script>
<style type="text/tailwindcss"> @layer utilities { .preserve-3d { transform-style: preserve-3d;36 行未改动 .record-animation { animation: record-shine 2s ease-in-out; } }
@keyframes trophy-pulse { 0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(1); } }
@keyframes record-shine { 0% { box-shadow: 0 0 0 0 rgba(251, 191, 36, 0.7); } 70% { box-shadow: 0 0 0 15px rgba(251, 191, 36, 0); } 100% { box-shadow: 0 0 0 0 rgba(251, 191, 36, 0); } }
/* Custom styles for 3D dice */ .dice-scene { perspective: 1500px; width: 120px; height: 120px; display: flex; align-items: center; justify-content: center; }
.dice-container { position: relative; width: 100px; height: 100px; transform-style: preserve-3d; transition: transform 1s ease-out; transform: rotateX(20deg) rotateY(20deg); }
.dice-face { position: absolute; width: 100px; height: 100px;4 行未改动 align-items: center; justify-content: center; box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1); }
/* Dice face positions */ .face-1 { transform: translateZ(50px); } .face-2 { transform: rotateY(90deg) translateZ(50px); } .face-3 { transform: rotateY(180deg) translateZ(50px); } .face-4 { transform: rotateY(-90deg) translateZ(50px); } .face-5 { transform: rotateX(90deg) translateZ(50px); } .face-6 { transform: rotateX(-90deg) translateZ(50px); }
/* Dots on dice faces */ .dot { position: absolute; width: 20px; height: 20px; border-radius: 50%; background-color: black; }
/* Dot positions for each face */ .face-1 .dot { top: 40px; left: 40px; }
.face-2 .dot:nth-child(1) { top: 20px; left: 20px; } .face-2 .dot:nth-child(2) { top: 60px; left: 60px; }
.face-3 .dot:nth-child(1) { top: 20px; left: 20px; } .face-3 .dot:nth-child(2) { top: 40px; left: 40px; } .face-3 .dot:nth-child(3) { top: 60px; left: 60px; }
.face-4 .dot:nth-child(1) { top: 20px; left: 20px; } .face-4 .dot:nth-child(2) { top: 20px; left: 60px; } .face-4 .dot:nth-child(3) { top: 60px; left: 20px; } .face-4 .dot:nth-child(4) { top: 60px; left: 60px; }
.face-5 .dot:nth-child(1) { top: 20px; left: 20px; } .face-5 .dot:nth-child(2) { top: 20px; left: 60px; } .face-5 .dot:nth-child(3) { top: 40px; left: 40px; } .face-5 .dot:nth-child(4) { top: 60px; left: 20px; } .face-5 .dot:nth-child(5) { top: 60px; left: 60px; }
.face-6 .dot:nth-child(1) { top: 20px; left: 20px; } .face-6 .dot:nth-child(2) { top: 20px; left: 60px; } .face-6 .dot:nth-child(3) { top: 40px; left: 20px; } .face-6 .dot:nth-child(4) { top: 40px; left: 60px; } .face-6 .dot:nth-child(5) { top: 60px; left: 20px; } .face-6 .dot:nth-child(6) { top: 60px; left: 60px; }
.dice-result { transition: all 0.5s ease-out; }
.result-shine { animation: shine 0.5s ease-out; }
.score-increase { color: #10b981; animation: scorePopup 1s ease-out; }
.score-decrease { color: #ef4444; animation: scorePopup 1s ease-out; }
.score-neutral { color: #6b7280; animation: scorePopup 1s ease-out; }
/* Locked color option styles */ .color-option.locked { position: relative; opacity: 0.5; cursor: not-allowed; }
.color-option.locked::after { content: '\f023'; /* Lock icon from Font Awesome */ font-family: 'FontAwesome'; position: absolute;2 行未改动 transform: translate(-50%, -50%); color: rgba(0, 0, 0, 0.5); font-size: 16px; }
@keyframes shine { 0% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4); }3 行未改动 100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); } }
@keyframes scorePopup { 0% { transform: translateY(0); opacity: 0;6 行未改动 transform: translateY(-20px); opacity: 0; } }
.confetti { position: absolute; width: 10px; height: 10px; background-color: #f97316; animation: confetti-fall 3s ease-in-out infinite; }
@keyframes confetti-fall { 0% { transform: translateY(-100vh) rotate(0deg); opacity: 1;2 行未改动 transform: translateY(100vh) rotate(720deg); opacity: 0; } }
@keyframes lock-particle { 0% { transform: translate(0, 0); opacity: 1;2 行未改动 transform: translate(var(--tx), var(--ty)); opacity: 0; } }
/* Game Rules Modal Styles */ .game-rules-modal { position: fixed; top: 0;7 行未改动 padding: 1rem; visibility: hidden; box-sizing: border-box; }
.game-rules-modal .modal-backdrop { position: absolute; top: 0; left: 0;2 行未改动 opacity: 0; visibility: hidden; transition: all 0.3s ease-out; }
.game-rules-modal .modal-content { position: relative; background-color: white; border-radius: 1rem;2 行未改动 width: 500px; overflow-y: auto; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); }
.game-rules-modal .modal-header { padding: 1.5rem; border-bottom: 1px solid #e5e7eb; display: flex; justify-content: space-between; align-items: center; }
.game-rules-modal .modal-title { font-size: 1.25rem; font-weight: 600; color: #1e293b; }
.game-rules-modal .close-button { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; transition: color 0.2s ease-in-out; }
.game-rules-modal .close-button:hover { color: #1e293b; }
.game-rules-modal .modal-body { padding: 1.5rem; line-height: 1.6; color: #374151; }
.game-rules-modal .modal-body h3 { font-size: 1.1rem; font-weight: 600; margin-top: 1.5rem; margin-bottom: 0.75rem; color: #1e293b; }
.game-rules-modal .modal-body p { margin-bottom: 1rem; }
.game-rules-modal .modal-body ul { margin-bottom: 1rem; padding-left: 1.5rem; list-style-type: disc; }
.game-rules-modal .modal-body li { margin-bottom: 0.5rem; }
.game-rules-modal .modal-body strong { font-weight: 600; color: #1e293b; }
.game-rules-modal .modal-footer { padding: 1rem 1.5rem; border-top: 1px solid #e5e7eb; display: flex; justify-content: flex-end; }
.game-rules-modal .modal-footer button { padding: 0.5rem 1rem; border-radius: 0.5rem; background-color: #3b82f6; color: white; font-size: 1.25rem; font-weight: 500; transition: background-color 0.2s ease-in-out; }
.game-rules-modal .modal-footer button:hover { background-color: #2563eb; }
/* Game Rules Button Styles */ .game-rules-button { position: fixed; top: 1rem;9 行未改动 gap: 0.5rem; transition: all 0.2s ease-in-out; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); }
.game-rules-button:hover { background-color: #2563eb; transform: translateY(-2px); }
.game-rules-button i { font-size: 1.1rem; } </style>3 行未改动 <button id="game-rules-button" class="game-rules-button"> <i class="fa fa-book"></i> <span>Game Rules</span> </button>
<!-- Game Rules Modal --> <div id="game-rules-modal" class="game-rules-modal"> <div class="modal-backdrop"></div> <div class="modal-content">2 行未改动 <button class="close-button">×</button> </div> <div class="modal-body"> <p>Welcome to the 3D Dice Game! This is an exciting game that combines luck, strategy, and upgrading mechanics. Below is the complete game rules explanation:</p>
<h3>Basic Gameplay</h3> <ul> <li>Click the "Roll Dice" button to roll the dice</li> <li>The dice will randomly show a number between 1-6</li> <li>Gain or lose points based on the number rolled</li> <li>The goal is to obtain the highest tier "Unique" dice</li> </ul>
<h3>Score System</h3> <ul> <li>Rolling 1 or 2: Lose 1 point (multiplier not applied)</li> <li>Rolling 3: No points gained or lost</li> <li>Rolling 4: Gain 1 point</li> <li>Rolling 5: Gain 2 points</li> <li>Rolling 6: Gain 3 points</li> </ul>
<h3>Dice Upgrade System</h3> <p>There are 10 different tiers of dice in the game, from common to rare:</p> <ul> <li><strong>Empty</strong> (Initial) - Score Multiplier ×1.0</li>7 行未改动 <li><strong>Super</strong> - Score Multiplier ×1.8</li> <li><strong>Unique</strong> - Score Multiplier ×1.9</li> </ul> <p>Each upgrade costs (5 + current tier) points. For example, upgrading from Empty (tier 0) costs 5 points, upgrading from Common (tier 1) costs 6 points, and so on. After upgrading, you can choose to use the new dice or continue using the old one.</p>
<h3>Item System</h3> <p>When upgrading, you have a chance to obtain item cards that can be used at critical moments:</p> <ul> <li><strong>Double Points Card</strong>: Doubles the points from one roll</li> <li><strong>No Penalty Card</strong>: Prevents point loss when rolling 1 or 2</li> <li><strong>Lucky Streak Card</strong>: Next 3 rolls of 1 or 2 won't count towards your total roll count</li> </ul> <p>Items can be stockpiled and each card can only be used once. Double Points Cards and No Penalty Cards can be used simultaneously. Lucky Streak Cards make your next 3 rolls of 1 or 2 not count towards your total roll count, giving you a chance to recover from bad luck.</p>
<h3>Game Rules</h3> <ul> <li>Initial score is 10 points</li> <li>Score multiplier changes based on the current dice tier being used</li> <li>Game over when score is less than 0</li> <li>Game victory when obtaining the Unique dice</li> <li>Unlocked dice colors can be switched at any time</li> </ul>
<h3>Operation Tips</h3> <ul> <li>Click on dice color options to switch the dice being used</li> <li>Click the "Upgrade Dice" button to upgrade your dice (requires 5 points)</li> <li>Click the "Use" button next to item cards to use them</li> <li>Press the ESC key to close the rules window</li> </ul>
<p>Good luck, and may you successfully obtain the highest tier Unique dice!</p> </div> <div class="modal-footer"> <button class="close-button">Got it</button> </div> </div> </div>
<div class="w-full max-w-md mx-auto glass-effect rounded-2xl p-6 dice-shadow relative z-10"> <h1 class="text-3xl font-bold text-center text-dark mb-8">3D Dice Roll</h1>
<div class="flex flex-col items-center justify-center mb-8"> <!-- Dice display area --> <div id="dice-display" class="w-48 h-48 flex items-center justify-center mb-4 bg-gray-100 rounded-lg"> <!-- Dice scene for 3D perspective -->2 行未改动 <!-- Dice faces will be inserted here by JavaScript --> </div> </div> </div>
<!-- Result display --> <div id="result-display" class="text-2xl font-bold text-center mb-4 hidden"> Result: <span id="result-value" class="text-primary">0</span> </div>
<!-- Score display --> <div id="score-display" class="text-xl font-bold text-center mb-2"> Score: <span id="score-value" class="text-secondary">10</span> <span id="score-change" class="ml-2 text-sm font-normal"></span> </div>
<!-- Roll count display --> <div id="roll-count-display" class="text-lg font-medium text-center mb-4"> Rolls: <span id="roll-count-value" class="text-gray-700">0</span> </div>
<!-- Roll button --> <button id="roll-button" class="bg-primary hover:bg-blue-600 text-white font-bold py-3 px-6 rounded-full transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-blue-300 focus:ring-opacity-50"> <i class="fa fa-random mr-2"></i> Roll Dice </button>
<!-- Upgrade button and current tier display --> <div class="flex flex-col items-center mt-4"> <div id="current-tier" class="text-sm text-gray-600 mb-2"> Current Dice: <span class="font-semibold text-primary">Empty</span>4 行未改动 <button id="upgrade-button" class="bg-secondary hover:bg-orange-600 text-white font-bold py-2 px-4 rounded-full transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-orange-300 focus:ring-opacity-50"> <i class="fa fa-arrow-up mr-1"></i> Upgrade Dice <span id="upgrade-cost">(Cost: 5)</span> </button> </div>
<!-- Game message display --> <div id="game-message" class="mt-4 text-center font-semibold hidden"></div>
<!-- Items display --> <div id="items-display" class="mt-6 grid grid-cols-2 gap-4"> <div class="bg-white rounded-lg p-3 dice-shadow"> <div class="flex items-center justify-between">9 行未改动 </div> </div> <p class="text-xs text-gray-500 mt-1">Doubles your score change for one roll</p> </div>
<div class="bg-white rounded-lg p-3 dice-shadow"> <div class="flex items-center justify-between"> <div class="flex items-center"> <i class="fa fa-shield text-blue-500 text-xl mr-2"></i>7 行未改动 </div> </div> <p class="text-xs text-gray-500 mt-1">Prevents score loss when rolling 1 or 2</p> </div>
<div class="bg-white rounded-lg p-3 dice-shadow"> <div class="flex items-center justify-between"> <div class="flex items-center"> <i class="fa fa-star text-yellow-500 text-xl mr-2"></i>8 行未改动 </div> <p class="text-xs text-gray-500 mt-1">Next 3 rolls of 1 or 2 won't count towards your total roll count</p> </div> </div>
<!-- Free rolls indicator --> <div id="free-rolls-indicator" class="mt-3 text-center hidden"> <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800"> <i class="fa fa-star mr-1" style="color: #f59e0b;"></i> <span>Free Rolls: <span id="free-rolls-count">0</span></span> </span> </div>
<!-- Active item indicator --> <div id="active-item-indicator" class="mt-3 text-center hidden"> <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"> <i id="active-item-icon" class="mr-1"></i> <span id="active-item-text">Active Item: None</span> </span> </div> </div>
<!-- Dice color selection --> <div class="mb-8"> <label class="block text-sm font-medium text-gray-700 mb-2">Dice Rarity</label> <div class="grid grid-cols-5 gap-4">48 行未改动 <span class="text-xs text-center text-gray-600">Unique</span> </div> </div> </div>
<!-- History log --> <div class="bg-white rounded-lg p-4 h-32 overflow-y-auto"> <h2 class="text-lg font-semibold text-center mb-2">Roll History</h2> <ul id="history-list" class="text-sm"> <!-- History items will be inserted here by JavaScript --> </ul> </div> </div>
<footer class="mt-8 text-center text-gray-600 text-sm"> <p>Click the button to roll the dice and see the result!</p> </footer>
<script> // Set up global error handler window.addEventListener('error', function(event) { console.error('Global error caught:', event.error);
// Try to get roll button element const rollButton = document.getElementById('roll-button'); if (rollButton && rollButton.disabled) { console.warn('Error during dice roll, re-enabling button'); rollButton.disabled = false; rollButton.classList.remove('opacity-70', 'cursor-not-allowed');
// Try to show error message const gameMessage = document.getElementById('game-message'); if (gameMessage) { gameMessage.textContent = 'An error occurred. Please try again.'; gameMessage.className = 'mt-4 text-center font-semibold text-red-500'; gameMessage.classList.remove('hidden'); } } });
// DOM elements const diceElement = document.getElementById('dice'); const rollButton = document.getElementById('roll-button'); const resultDisplay = document.getElementById('result-display');8 行未改动 const gameMessageDisplay = document.getElementById('game-message'); const rollCountDisplay = document.getElementById('roll-count-display'); const rollCountValue = document.getElementById('roll-count-value'); const upgradeCost = document.getElementById('upgrade-cost');
// Item related DOM elements const doublePointsCount = document.getElementById('double-points-count'); const noPenaltyCount = document.getElementById('no-penalty-count'); const luckyStreakCount = document.getElementById('lucky-streak-count');2 行未改动 const useLuckyStreakButton = document.getElementById('use-lucky-streak'); const activeItemIndicator = document.getElementById('active-item-indicator'); const freeRollsIndicator = document.getElementById('free-rolls-indicator'); const freeRollsCountElement = document.getElementById('free-rolls-count');
// Game state let currentScore = 10; // Initial score let currentTier = 0; // Initial dice tier (0 = Empty) let gameOver = false; // Game over flag let rollCount = 0; // Number of dice rolls let luckyRollsRemaining = 0; // Number of lucky rolls remaining
// Item system let doublePointsCards = 0; // Number of double points cards let noPenaltyCards = 0; // Number of no penalty cards let luckyStreakCards = 0; // Number of lucky streak cards let freeRolls = 0; // Number of free rolls available let activeItems = { // Currently active items double: 0, // Number of active double points cards noPenalty: false // Whether no penalty card is active };
// Dice tiers configuration const diceTiers = [ { name: 'Empty', color: '#FFFFFF' }, { name: 'Common', color: '#7EEF6D' },5 行未改动 { name: 'Ultra', color: '#ff2b75' }, { name: 'Super', color: '#2bffa3' }, { name: 'Unique', color: '#555555' } ];
// Initialize 3D dice function initializeDice() { console.log('Initializing dice...'); // Create 6 faces for the dice const faces = [1, 2, 3, 4, 5, 6];
faces.forEach(faceNumber => { const face = document.createElement('div'); face.className = `dice-face face-${faceNumber}`;
// Add dots to the face based on the number for (let i = 0; i < faceNumber; i++) { const dot = document.createElement('div'); dot.className = 'dot'; face.appendChild(dot); }
diceElement.appendChild(face); console.log(`Added face ${faceNumber}`); });
console.log('Dice initialized with faces:', diceElement.children.length);
// Set initial position to show face 1 clearly diceElement.style.transform = 'rotateX(0deg) rotateY(0deg)'; }
// Get random rotation values for the dice function getRandomRotation() { // Determine which face we want to show const targetFace = Math.floor(Math.random() * 6) + 1;
// Get current rotation from dice element const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); const matrix = new DOMMatrix(currentTransform);
// Extract current rotation angles let currentX = 0, currentY = 0;
// If transform is not identity matrix, extract rotation if (currentTransform !== 'none') { // Calculate rotation from matrix currentX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI); currentY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI); }
// Set target rotation based on target face // These values are precisely calibrated to show the correct face let targetX = 0, targetY = 0; switch(targetFace) {21 行未改动 targetX = 90; targetY = 0; break; }
// Calculate the shortest path to the target rotation // This prevents large rotation values from accumulating let diffX = targetX - currentX; let diffY = targetY - currentY;
// Normalize the difference to the range [-180, 180] to find the shortest path diffX = ((diffX + 180) % 360) - 180; diffY = ((diffY + 180) % 360) - 180;
// Add multiple full rotations for spinning effect (2-4 full rotations) const fullRotations = 2 + Math.floor(Math.random() * 3);
// Calculate final rotation with full spins // We add full rotations in the direction of the shortest path const spinDirectionX = diffX >= 0 ? 1 : -1; const spinDirectionY = diffY >= 0 ? 1 : -1;
const finalX = currentX + diffX + spinDirectionX * fullRotations * 360; const finalY = currentY + diffY + spinDirectionY * fullRotations * 360;
// Add a tiny bit of randomness to make it look more natural // But not enough to change which face is visible const randomX = (Math.random() - 0.5) * 2; const randomY = (Math.random() - 0.5) * 2;
return { x: finalX + randomX, y: finalY + randomY, targetFace: targetFace // Return the target face so we don't have to recalculate it }; }
// Roll the dice function function rollDice() { // Check if game is over if (gameOver) { showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500'); return; }
// Check if there are free rolls available const isFreeRoll = freeRolls > 0;
// Check if in lucky streak mode const isLuckyRoll = luckyRollsRemaining > 0;
// Increment roll count only if not a free roll and not a lucky roll that will be reverted if (!isFreeRoll && !isLuckyRoll) { rollCount++; console.log(`Roll count: ${rollCount}`);2 行未改动 freeRolls--; updateFreeRollsDisplay(); console.log(`Free roll used. Remaining free rolls: ${freeRolls}`); }
// Update roll count display if (rollCountValue) { rollCountValue.textContent = rollCount; }
console.log('Rolling dice...'); console.log('Button state before disable:', rollButton.disabled);
// Disable button during animation rollButton.disabled = true; rollButton.classList.add('opacity-70', 'cursor-not-allowed');
console.log('Button state after disable:', rollButton.disabled);
// Hide result display resultDisplay.classList.add('hidden');
try { // Set animation duration const duration = 2000; // Fixed duration for consistent experience
// Get random rotation values for the final position const rotationData = getRandomRotation(); console.log('Rotation data:', rotationData); console.log('Target face:', rotationData.targetFace);
// Animate the dice using JavaScript for more control animateDice(duration, rotationData);
// Set a safety timeout to ensure button is re-enabled even if something goes wrong setTimeout(() => { if (rollButton.disabled) { console.warn('Safety timeout: Re-enabling roll button');6 行未改动 enableRollButton(); showGameMessage('An error occurred during the dice roll. Please try again.', 'text-red-500'); } }
// Animate the dice with spin animation function animateDice(duration, rotationData) { console.log('Animate dice called with rotationData:', rotationData); const startTime = performance.now(); const finalRotation = rotationData;
// Get current rotation from dice element const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); const matrix = new DOMMatrix(currentTransform);
// Extract current rotation angles let startX = 0, startY = 0;
// If transform is not identity matrix, extract rotation if (currentTransform !== 'none') { // Calculate rotation from matrix startX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI); startY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI); }
// Function to handle each animation frame function animate(currentTime) { const elapsedTime = currentTime - startTime; const progress = Math.min(elapsedTime / duration, 1);
// Apply easing function for smooth, natural animation const easedProgress = easeOutCubic(progress);
// Calculate current rotation - smooth continuous rotation const currentX = startX + (finalRotation.x - startX) * easedProgress; const currentY = startY + (finalRotation.y - startY) * easedProgress;
// Spin animation: rotate in place diceElement.style.transform = `rotateX(${currentX}deg) rotateY(${currentY}deg)`;
// Continue animation if not complete if (progress < 1) { requestAnimationFrame(animate); } else { // Animation complete - ensure we're at the exact target rotation diceElement.style.transform = `rotateX(${finalRotation.x}deg) rotateY(${finalRotation.y}deg)`;
// Show result after a delay to ensure rotation is complete and CSS has applied console.log('Animation complete, waiting before finalizing...'); setTimeout(() => { // Double-check that the transform has been applied3 行未改动 finalizeAnimation(finalRotation); }, 600); } }
// Start the animation requestAnimationFrame(animate); }
// Helper function to normalize angles to the range [-180, 180] function normalizeAngle(angle) { angle = angle % 360; if (angle > 180) angle -= 360; if (angle < -180) angle += 360; return angle; }
// Easing function for smooth, natural animation with gentle acceleration and deceleration // Uses a cubic easing function that starts slow, accelerates, then slows down at the end function easeOutCubic(t) { return 1 - Math.pow(1 - t, 3); }
// Calculate score change based on dice roll result function calculateScoreChange(result) { let baseChange = 0;
switch(result) { case 1: case 2: baseChange = -1;12 行未改动 break; default: baseChange = 0; }
// Apply current tier multiplier // If losing points (baseChange < 0), use multiplier of 1 instead of tier multiplier const tierMultiplier = 1 + currentTier / 10; let finalChange;
if (baseChange < 0) { // For point loss, use multiplier of 1 regardless of tier finalChange = baseChange * 1; } else { // For point gain or neutral, use tier multiplier finalChange = baseChange * tierMultiplier; }
// Apply active item effects const itemsUsed = { double: activeItems.double, noPenalty: activeItems.noPenalty };
// Apply no penalty card first if (activeItems.noPenalty && baseChange < 0) { finalChange = 0; }
// Apply double points cards if (activeItems.double > 0) { finalChange = finalChange * Math.pow(2, activeItems.double); }
// Round to 2 decimal places to avoid floating point precision issues finalChange = Math.round(finalChange * 100) / 100;
return { baseChange: baseChange, finalChange: finalChange, itemsUsed: itemsUsed, tierMultiplier: tierMultiplier }; }
// Enable roll button function enableRollButton() { console.log('Button state before enable:', rollButton.disabled);
// Directly enable the button rollButton.disabled = false; rollButton.classList.remove('opacity-70', 'cursor-not-allowed');
console.log('Button state after enable:', rollButton.disabled);
// Double-check and force enable if needed if (rollButton.disabled) { console.warn('Forcing button enable'); setTimeout(() => {2 行未改动 console.log('Button state after forced enable:', rollButton.disabled); }, 100); } }
// Finalize the animation and show result function finalizeAnimation(rotationData) { console.log('=== Finalize animation called ==='); console.log('Current time:', new Date().toISOString().split('T')[1]); console.log('Rotation data:', rotationData); const finalRotation = rotationData;
// Use the target face directly instead of recalculating const result = finalRotation.targetFace; console.log(`Final result: ${result} (should show face ${result})`);
// Verify dice is in the correct position const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); console.log('Current dice transform:', currentTransform);
// Show result display console.log('Showing result display...'); resultValue.textContent = result; resultDisplay.classList.remove('hidden');
// Add shine effect to result resultDisplay.classList.add('result-shine'); setTimeout(() => { resultDisplay.classList.remove('result-shine'); }, 500);
// Calculate and update score console.log('Calculating score change...'); const scoreChangeData = calculateScoreChange(result); console.log('Score change data:', scoreChangeData);
currentScore += scoreChangeData.finalChange; console.log('Updated score:', currentScore);
// Update score display with animation console.log('Updating score display...'); updateScoreDisplay(scoreChangeData);
// Enable button console.log('Enabling roll button...'); enableRollButton();
// Add to history - include whether it was a free roll or lucky roll addToHistory(result, scoreChangeData, isFreeRoll, isLuckyRoll);
// Check if reached the Unique dice if (currentTier === diceTiers.length - 1) { showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500'); gameOver = true; createConfetti(); }
// Handle lucky roll logic if (luckyRollsRemaining > 0) { // Decrement remaining lucky rolls luckyRollsRemaining--;
// If rolled 1 or 2, decrement roll count if (result === 1 || result === 2) { rollCount--; console.log(`Lucky roll: Reverted roll count to ${rollCount}`);
// Update roll count display if (rollCountValue) { rollCountValue.textContent = rollCount; }
// Show message showGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500'); }
// Update lucky rolls display updateLuckyRollsDisplay();
// If no more lucky rolls, show message if (luckyRollsRemaining === 0) { setTimeout(() => { showGameMessage('Lucky Streak ended!', 'text-yellow-500'); }, 1000); } }
// Create confetti effect if result is 6 if (result === 6) { createConfetti(); }
// Debug: log final state console.log(`Final precise rotation: X=${finalRotation.x}°, Y=${finalRotation.y}°`); console.log(`Displayed result: ${result}`); console.log(`Score change: ${scoreChangeData.finalChange}, Current score: ${currentScore}`); console.log('=== finalizeAnimation completed ==='); }
// Update score display with animation function updateScoreDisplay(scoreChangeData) { console.log('=== updateScoreDisplay called ==='); console.log('Score change data:', scoreChangeData);
const change = scoreChangeData.finalChange; const baseChange = scoreChangeData.baseChange; const itemsUsed = scoreChangeData.itemsUsed; const tierMultiplier = scoreChangeData.tierMultiplier;
console.log('Change:', change, 'Base change:', baseChange, 'Items used:', itemsUsed);
// Update the score value - round to 2 decimal places currentScore = Math.round(currentScore * 100) / 100; scoreValue.textContent = currentScore; console.log('Score value updated to:', currentScore);
// Clear previous score change display scoreChange.textContent = ''; scoreChange.className = 'ml-2 text-sm font-normal'; console.log('Cleared previous score change display');
// Show score change with appropriate styling if (change > 0) { scoreChange.textContent = `+${change}`; scoreChange.classList.add('score-increase');6 行未改动 scoreChange.textContent = `±0`; scoreChange.classList.add('score-neutral'); console.log('Score neutral'); }
// Show item effect message if items were used if (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) { // Create container for item effects const itemEffectsContainer = document.createElement('div'); itemEffectsContainer.className = 'flex flex-wrap gap-2 mt-1';
// Add tier multiplier effect if applicable if (tierMultiplier !== 1) { const tierEffect = document.createElement('div'); tierEffect.className = 'text-xs text-purple-500'; tierEffect.textContent = `Tier Multiplier ×${tierMultiplier.toFixed(1)}!`; itemEffectsContainer.appendChild(tierEffect); }
// Add no penalty effect if (itemsUsed.noPenalty) { const noPenaltyEffect = document.createElement('div'); noPenaltyEffect.className = 'text-xs text-blue-500'; noPenaltyEffect.textContent = `No Penalty! (Score protected from ${baseChange < 0 ? baseChange : 0} loss)`; itemEffectsContainer.appendChild(noPenaltyEffect); }
// Add double points effect if (itemsUsed.double > 0) { const doublePointsEffect = document.createElement('div'); doublePointsEffect.className = 'text-xs text-green-500';
// Calculate multiplier const multiplier = Math.pow(2, itemsUsed.double); let calculationText = `${baseChange}`;
// Apply tier multiplier for display let displayChange = baseChange * tierMultiplier;
// Apply no penalty first for display if (itemsUsed.noPenalty && baseChange < 0) { displayChange = 0; calculationText = `(${baseChange} × ${tierMultiplier.toFixed(1)} → 0)`; } else if (tierMultiplier !== 1) { calculationText = `(${baseChange} × ${tierMultiplier.toFixed(1)} = ${displayChange.toFixed(2)})`; }
// Show multiplication steps if multiple double cards used if (itemsUsed.double > 1) { for (let i = 0; i < itemsUsed.double; i++) { calculationText += ` × 2`; } calculationText += ` = ${(displayChange * multiplier).toFixed(2)}`; } else { calculationText += ` × 2 = ${(displayChange * multiplier).toFixed(2)}`; }
doublePointsEffect.textContent = `Double Points ×${itemsUsed.double}! (${calculationText})`; itemEffectsContainer.appendChild(doublePointsEffect); }
// Add to score display scoreDisplay.appendChild(itemEffectsContainer);
// Remove after animation setTimeout(() => { scoreDisplay.removeChild(itemEffectsContainer); }, 1000); }
// Reset score change display after animation completes setTimeout(() => { scoreChange.textContent = ''; }, 1000);
// Clear active items after score update console.log('Checking if items need to be cleared...'); if (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) { console.log('Clearing active items...'); clearActiveItems(); console.log('Updating items display...'); updateItemsDisplay(); }
// Check game state after score update console.log('Checking game state...'); checkGameState();
// Update upgrade button state updateUpgradeCostDisplay();
console.log('=== updateScoreDisplay completed ==='); }
// Handle dice upgrade function upgradeDice() { // Check if game is already over if (gameOver) { showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500'); return; }
// Check if already at maximum tier if (currentTier >= diceTiers.length - 1) { // If not already game over, end the game with win condition if (!gameOver) {3 行未改动 showGameMessage('Congratulations! You already have the Unique dice!', 'text-green-500'); } return; }
// Calculate required score for upgrade (5 + currentTier) const requiredScore = 5 + currentTier;
// Check if enough score to upgrade if (currentScore < requiredScore) { showGameMessage(`Not enough score to upgrade! Need ${requiredScore} points.`, 'text-orange-500'); // Add shake animation to score display2 行未改动 scoreDisplay.classList.remove('animate-shake'); }, 500); return; }
// Deduct score for upgrade currentScore -= requiredScore; // Round to 2 decimal places currentScore = Math.round(currentScore * 100) / 100;
// Update score display scoreValue.textContent = currentScore; showScoreChange(-requiredScore);
// Increase tier currentTier++;
// Update current tier display currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;
// Update tier multiplier display updateTierMultiplierDisplay();
// Unlock the new dice color unlockDiceColor(currentTier);
// Update color selection UI updateColorSelection(currentTier);
// Update upgrade cost display updateUpgradeCostDisplay();
// Change to the new dice color console.log(`Changing dice color to ${diceTiers[currentTier].color} (${diceTiers[currentTier].name})`); changeDiceColor(diceTiers[currentTier].color);
// Check if this upgrade reached the maximum tier checkGameState();
// Randomly get an item const itemChance = Math.random(); if (itemChance < 0.30) { // 30% chance to get double points card doublePointsCards++;3 行未改动 luckyStreakCards++; } else { // 30% chance to get nothing // Do nothing }
// Update items display to show new counts updateItemsDisplay();
// Update items display updateItemsDisplay();
// Check if reached the Unique dice if (currentTier === diceTiers.length - 1) { showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500'); gameOver = true; createConfetti(); }
// Handle lucky roll logic if (luckyRollsRemaining > 0) { // Decrement remaining lucky rolls luckyRollsRemaining--;
// If rolled 1 or 2, decrement roll count if (result === 1 || result === 2) { rollCount--; console.log(`Lucky roll: Reverted roll count to ${rollCount}`);
// Update roll count display if (rollCountValue) { rollCountValue.textContent = rollCount; }
// Show message showGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500'); }
// Update lucky rolls display updateLuckyRollsDisplay();
// If no more lucky rolls, show message if (luckyRollsRemaining === 0) { setTimeout(() => { showGameMessage('Lucky Streak ended!', 'text-yellow-500'); }, 1000); } }
// Add to history addToHistory('UPGRADE', -5);
// Add item to history if obtained if (itemChance < 0.30) { addToHistory('ITEM', 'Double Points Card'); } else if (itemChance < 0.60) { addToHistory('ITEM', 'No Penalty Card'); } else if (itemChance < 0.70) { addToHistory('ITEM', 'Lucky Streak Card'); }
// Check game state after upgrade checkGameState(); }
// Show score change temporarily function showScoreChange(change) { scoreChange.textContent = change > 0 ? `+${change}` : change; scoreChange.className = `ml-2 text-sm font-normal ${change > 0 ? 'score-increase' : 'score-decrease'}`;
setTimeout(() => { scoreChange.textContent = ''; }, 1000); }
// Unlock a dice color option function unlockDiceColor(tierIndex) { if (tierIndex >= 0 && tierIndex < colorOptions.length) { const option = colorOptions[tierIndex];5 行未改动 option.classList.remove('locked'); }, 300); } }
// Show game message function showGameMessage(message, className) { gameMessageDisplay.textContent = message; gameMessageDisplay.className = `mt-4 text-center font-semibold ${className}`; gameMessageDisplay.classList.remove('hidden');
// Hide message after 3 seconds setTimeout(() => { if (!gameOver) { gameMessageDisplay.classList.add('hidden'); } }, 3000); }
// Check game state (win/lose conditions) function checkGameState() { console.log('=== checkGameState called ==='); console.log('Current score:', currentScore, 'Game over:', gameOver);
// Check if score is negative (lose condition) if (currentScore < 0 && !gameOver) { console.log('Score is negative, ending game...'); gameOver = true; endGame(false); }
// Check if reached Unique dice (win condition) if (currentTier === diceTiers.length - 1 && !gameOver) { console.log('Reached Unique dice, ending game...'); gameOver = true; endGame(true);
// Check if this is a new record setTimeout(() => { checkWinRecord(); }, 1000); }
// Check if score is low (warning) if (currentScore >= 0 && currentScore <= 5 && !gameOver) { showLowScoreWarning(); }
console.log('=== checkGameState completed ==='); }
// Update items display function updateItemsDisplay() { // Update counts doublePointsCount.textContent = doublePointsCards; noPenaltyCount.textContent = noPenaltyCards; luckyStreakCount.textContent = luckyStreakCards;
// Enable/disable buttons based on available items useDoublePointsButton.disabled = doublePointsCards <= 0 || gameOver; useNoPenaltyButton.disabled = noPenaltyCards <= 0 || activeItems.noPenalty || gameOver; useLuckyStreakButton.disabled = luckyStreakCards <= 0 || gameOver;
// Update free rolls display updateFreeRollsDisplay();
// Update lucky rolls display updateLuckyRollsDisplay(); }
// Update free rolls display function updateFreeRollsDisplay() { if (freeRolls > 0) { freeRollsCountElement.textContent = freeRolls; freeRollsIndicator.classList.remove('hidden'); } else { freeRollsIndicator.classList.add('hidden'); } }
// Update upgrade cost display and button state function updateUpgradeCostDisplay() { if (currentTier >= diceTiers.length - 1) { // Already at maximum tier2 行未改动 upgradeButton.classList.add('opacity-70', 'cursor-not-allowed'); } else { const requiredScore = 5 + currentTier; upgradeCost.textContent = `(Cost: ${requiredScore})`;
// Update button state based on available score if (currentScore >= requiredScore && !gameOver) { upgradeButton.disabled = false; upgradeButton.classList.remove('opacity-70', 'cursor-not-allowed');2 行未改动 upgradeButton.classList.add('opacity-70', 'cursor-not-allowed'); } } }
// Use double points card function useDoublePointsCard() { if (doublePointsCards > 0 && !gameOver) { activeItems.double++; doublePointsCards--;
// Update UI updateItemsDisplay(); showActiveItemIndicator();
// Show message showGameMessage('Double Points Card activated! Next roll will double your score change.', 'text-green-500'); } }
// Use no penalty card function useNoPenaltyCard() { if (noPenaltyCards > 0 && !activeItems.noPenalty && !gameOver) { activeItems.noPenalty = true; noPenaltyCards--;
// Update UI updateItemsDisplay(); showActiveItemIndicator();
// Show message showGameMessage('No Penalty Card activated! Next roll won\'t lose points.', 'text-blue-500'); } }
// Use lucky streak card function useLuckyStreakCard() { if (luckyStreakCards > 0 && !gameOver) { luckyRollsRemaining = 3; luckyStreakCards--;
// Update UI updateItemsDisplay(); updateLuckyRollsDisplay();
// Show message showGameMessage('Lucky Streak Card activated! Next 3 rolls of 1 or 2 won\'t count!', 'text-yellow-500');
// Add to history addToHistory('ITEM USE', 'Lucky Streak Card'); } }
// Update lucky rolls display function updateLuckyRollsDisplay() { if (luckyRollsRemaining > 0) { // Check if indicator exists, if not create it let luckyRollsIndicator = document.getElementById('lucky-rolls-indicator'); if (!luckyRollsIndicator) { luckyRollsIndicator = document.createElement('div'); luckyRollsIndicator.id = 'lucky-rolls-indicator'; luckyRollsIndicator.className = 'mt-3 text-center';
// Insert after free rolls indicator const freeRollsIndicator = document.getElementById('free-rolls-indicator'); if (freeRollsIndicator) { freeRollsIndicator.parentNode.insertBefore(luckyRollsIndicator, freeRollsIndicator.nextSibling);10 行未改动 } } } }
// Update content luckyRollsIndicator.innerHTML = ` <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800"> <i class="fa fa-star mr-1" style="color: #f59e0b;"></i> <span>Lucky Rolls: <span id="lucky-rolls-count">${luckyRollsRemaining}</span> (1-2 won't count)</span> </span> `;
// Show indicator luckyRollsIndicator.classList.remove('hidden'); } else { // Remove indicator if exists2 行未改动 luckyRollsIndicator.classList.add('hidden'); } } }
// Show active item indicator function showActiveItemIndicator() { // Clear previous content activeItemIndicator.innerHTML = '';
// Check if any items are active if (activeItems.double === 0 && !activeItems.noPenalty) { activeItemIndicator.className = 'mt-3 text-center hidden'; return; }
// Create container for active items const itemsContainer = document.createElement('div'); itemsContainer.className = 'flex flex-wrap justify-center gap-2';
// Add double points cards indicator if (activeItems.double > 0) { const doublePointsIndicator = document.createElement('span'); doublePointsIndicator.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800';2 行未改动 <span>Double Points ×${activeItems.double}</span> `; itemsContainer.appendChild(doublePointsIndicator); }
// Add no penalty card indicator if (activeItems.noPenalty) { const noPenaltyIndicator = document.createElement('span'); noPenaltyIndicator.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800';2 行未改动 <span>No Penalty</span> `; itemsContainer.appendChild(noPenaltyIndicator); }
// Add indicators to container activeItemIndicator.appendChild(itemsContainer); activeItemIndicator.className = 'mt-3 text-center'; }
// Clear active items function clearActiveItems() { activeItems = { double: 0, noPenalty: false }; showActiveItemIndicator(); }
// End the game and display appropriate message function endGame(isWin) { console.log('=== endGame called ==='); console.log('Is win:', isWin, 'Current score:', currentScore);
// Disable all interactive elements rollButton.disabled = true; upgradeButton.disabled = true; rollButton.classList.add('opacity-70', 'cursor-not-allowed'); upgradeButton.classList.add('opacity-70', 'cursor-not-allowed');
// Disable all interactive elements colorOptions.forEach(option => { option.disabled = true; option.classList.add('opacity-50', 'cursor-not-allowed'); });
// Disable item buttons useDoublePointsButton.disabled = true; useNoPenaltyButton.disabled = true; useLuckyStreakButton.disabled = true;
// Hide active indicators activeItemIndicator.classList.add('hidden'); const luckyRollsIndicator = document.getElementById('lucky-rolls-indicator'); if (luckyRollsIndicator) { luckyRollsIndicator.classList.add('hidden'); }
// Create game over message element const gameOverMessage = document.createElement('div'); gameOverMessage.className = `mt-4 p-4 rounded-lg text-center font-bold ${isWin ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`;
// Format final score to 2 decimal places const formattedScore = currentScore.toFixed(2);
if (isWin) { gameOverMessage.innerHTML = ` <div class="text-2xl mb-2">Congratulations!</div> <p>You won the game!</p>24 行未改动 <i class="fa fa-refresh mr-1"></i> Play Again </button> `; }
// Add restart button event listener gameOverMessage.querySelector('#play-again').addEventListener('click', () => { window.location.reload(); });
// Replace game message display with game over message const gameMessageContainer = gameMessageDisplay.parentElement; gameMessageContainer.replaceChild(gameOverMessage, gameMessageDisplay); gameMessageDisplay = gameOverMessage;
// Add game end to history addToHistory(isWin ? 'GAME WIN' : 'GAME OVER', 0);
console.log('=== endGame completed ==='); }
// Show warning when score is low function showLowScoreWarning() { // Only show warning if not already showing if (gameMessageDisplay.classList.contains('hidden')) { showGameMessage('Warning: Low score! Risk of game over.', 'text-orange-500'); } }
// Update color selection UI to show the currently selected color function updateColorSelection(selectedIndex) { // Remove active state from all color options colorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary'));
// Add active state to the selected color option if (selectedIndex >= 0 && selectedIndex < colorOptions.length) { colorOptions[selectedIndex].classList.add('ring-2', 'ring-offset-2', 'ring-primary'); } }
// Add result to history function addToHistory(result, scoreChangeData, isFreeRoll = false, isLuckyRoll = false) { const now = new Date(); const timeString = now.toLocaleTimeString();
// Determine score change display and color let scoreChangeText = ''; let scoreChangeClass = ''; let actionText = '';
if (result === 'UPGRADE') { actionText = 'Upgraded dice'; scoreChangeText = `${scoreChangeData}`; scoreChangeClass = 'text-red-500';8 行未改动 } else { const scoreChange = scoreChangeData.finalChange; const baseChange = scoreChangeData.baseChange; const itemsUsed = scoreChangeData.itemsUsed;
actionText = `Rolled a <span class="font-bold text-primary">${result}</span>`;
// Add free roll indicator if applicable if (isFreeRoll) { actionText += ` <span class="text-yellow-500">(Free Roll)</span>`; }
// Add lucky roll indicator if applicable if (isLuckyRoll) { actionText += ` <span class="text-yellow-500">(Lucky Roll)</span>`; }
// Add item effect indicators if applicable const activeItemsText = []; if (itemsUsed && itemsUsed.double > 0) { activeItemsText.push(`<span class="text-green-500">(Double Points ×${itemsUsed.double})</span>`); } if (itemsUsed && itemsUsed.noPenalty) { activeItemsText.push(`<span class="text-blue-500">(No Penalty)</span>`); }
if (activeItemsText.length > 0) { actionText += ` ${activeItemsText.join(' ')}`; }
if (scoreChange > 0) { scoreChangeText = `+${scoreChange}`; scoreChangeClass = 'text-green-500'; } else if (scoreChange < 0) {2 行未改动 } else { scoreChangeText = '±0'; scoreChangeClass = 'text-gray-500'; }
// Show base change if different from final change (items were used) if ((itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) && baseChange !== scoreChange) { scoreChangeText += ` <span class="text-xs">(Base: ${baseChange > 0 ? '+' : ''}${baseChange})</span>`; } }
const listItem = document.createElement('li'); listItem.className = 'py-1 border-b border-gray-100 flex justify-between items-center'; listItem.innerHTML = ` <span><span class="text-gray-500">${timeString}</span>: ${actionText}</span> <span class="font-medium ${scoreChangeClass}">${scoreChangeText}</span> `;
historyList.prepend(listItem);
// Keep only last 5 history items if (historyList.children.length > 5) { historyList.removeChild(historyList.lastChild); } }
// Create confetti effect function createConfetti() { const confettiContainer = document.createElement('div'); confettiContainer.className = 'fixed inset-0 pointer-events-none overflow-hidden'; document.body.appendChild(confettiContainer);
// Create 50 confetti pieces for (let i = 0; i < 50; i++) { const confetti = document.createElement('div'); confetti.className = 'confetti';
// Random position const posX = Math.random() * 100; const delay = Math.random() * 3; const duration = 3 + Math.random() * 2;
// Random colors const colors = ['#3b82f6', '#f97316', '#10b981', '#ef4444', '#8b5cf6']; const color = colors[Math.floor(Math.random() * colors.length)];
confetti.style.left = `${posX}%`; confetti.style.backgroundColor = color; confetti.style.animationDelay = `${delay}s`; confetti.style.animationDuration = `${duration}s`;
confettiContainer.appendChild(confetti); }
// Remove confetti container after animation completes setTimeout(() => { document.body.removeChild(confettiContainer); }, 5000); }
// Create particle effect on lock function createLockParticles(lockElement) { // Get lock element position const rect = lockElement.getBoundingClientRect(); const centerX = rect.left + rect.width / 2; const centerY = rect.top + rect.height / 2;
// Create particle container const particleContainer = document.createElement('div'); particleContainer.className = 'absolute pointer-events-none'; particleContainer.style.left = `${centerX}px`; particleContainer.style.top = `${centerY}px`; particleContainer.style.transform = 'translate(-50%, -50%)'; document.body.appendChild(particleContainer);
// Create 15 particles for (let i = 0; i < 15; i++) { const particle = document.createElement('div'); particle.className = 'lock-particle';
// Random direction and distance const angle = Math.random() * Math.PI * 2; const distance = 10 + Math.random() * 20; const tx = Math.cos(angle) * distance; const ty = Math.sin(angle) * distance;
// Random color (use the color of the unlocked dice) const color = lockElement.style.backgroundColor;
// Random animation duration const duration = 0.5 + Math.random() * 0.5;
// Set particle styles particle.style.backgroundColor = color; particle.style.setProperty('--tx', `${tx}px`); particle.style.setProperty('--ty', `${ty}px`); particle.style.animation = `lock-particle ${duration}s ease-out forwards`;
particleContainer.appendChild(particle); }
// Remove particle container after animation completes setTimeout(() => { document.body.removeChild(particleContainer); }, 1000); }
// Function to darken a color by a certain percentage function darkenColor(color, percent) { const hex = color.replace('#', ''); let r = parseInt(hex.substr(0, 2), 16); let g = parseInt(hex.substr(2, 2), 16); let b = parseInt(hex.substr(4, 2), 16);
// Darken each channel by the percentage r = Math.max(0, Math.floor(r * (1 - percent / 100))); g = Math.max(0, Math.floor(g * (1 - percent / 100))); b = Math.max(0, Math.floor(b * (1 - percent / 100)));
// Convert back to hex const darkenedHex = '#' + r.toString(16).padStart(2, '0') + g.toString(16).padStart(2, '0') + const darkenedHex = '#' + r.toString(16).padStart(2, '0') + g.toString(16).padStart(2, '0') + b.toString(16).padStart(2, '0');
return darkenedHex; }
// Change dice color function function changeDiceColor(color) { console.log(`changeDiceColor called with color: ${color}`); const faces = document.querySelectorAll('.dice-face'); console.log(`Found ${faces.length} dice faces`); let dotColor, borderColor;
// Special cases for high contrast if (color.toUpperCase() === '#FFFFFF') { // White dice - use black dots and light gray borders dotColor = '#000000';6 行未改动 // Calculate darker color for dots and borders (40% darker for more contrast) dotColor = darkenColor(color, 40); borderColor = darkenColor(color, 30); // Slightly lighter border than dots }
faces.forEach(face => { // Set face background color face.style.backgroundColor = color;
// Set face border color face.style.border = `3px solid ${borderColor}`;
// Set dots color const dots = face.querySelectorAll('.dot'); dots.forEach(dot => { dot.style.backgroundColor = dotColor; // Add slight border to dots for better definition dot.style.border = color.toUpperCase() === '#FFFFFF' ? '1px solid rgba(0, 0, 0, 0.2)' : '1px solid rgba(0, 0, 0, 0.1)'; }); }); }
// Update tier multiplier display function updateTierMultiplierDisplay() { const display = document.getElementById('tier-multiplier-display'); if (display) { display.innerHTML = `Tier Multiplier: <span class="font-semibold text-purple-500">×${(1 + currentTier / 10).toFixed(1)}</span>`; } }
// Event listener for roll button rollButton.addEventListener('click', rollDice);
// Event listener for upgrade button upgradeButton.addEventListener('click', upgradeDice);
// Event listeners for item buttons useDoublePointsButton.addEventListener('click', useDoublePointsCard); useNoPenaltyButton.addEventListener('click', useNoPenaltyCard); useLuckyStreakButton.addEventListener('click', useLuckyStreakCard);
// Event listeners for color options colorOptions.forEach((option, index) => { // Disable all color options except the first one initially if (index !== 0) { option.disabled = true; option.classList.add('locked'); }
option.addEventListener('click', () => { // Check if game is over if (gameOver) { showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500'); return; }
// Check if color is unlocked if (option.disabled) { showGameMessage('You need to upgrade to unlock this dice color!', 'text-orange-500'); return; }
const color = option.getAttribute('data-color'); changeDiceColor(color);
// Add active state to selected color colorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary')); option.classList.add('ring-2', 'ring-offset-2', 'ring-primary');
// Update current tier to the selected color's tier currentTier = index; currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`; updateTierMultiplierDisplay(); }); });
// Initialize dice on page load window.addEventListener('DOMContentLoaded', () => { console.log('=== DOMContentLoaded event fired ===');
// Check if elements exist console.log('Checking if elements exist before initialization:'); console.log('best-record-display exists:', !!document.getElementById('best-record-display')); console.log('best-record-value exists:', !!document.getElementById('best-record-value'));
console.log('DOM fully loaded'); initializeDice();
// Set default color (first option) if (colorOptions.length > 0) { const defaultColor = colorOptions[0].getAttribute('data-color'); changeDiceColor(defaultColor); colorOptions[0].classList.add('ring-2', 'ring-offset-2', 'ring-primary'); }
// Initialize current tier display currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;
// Initialize tier multiplier display updateTierMultiplierDisplay();
// Initialize items display updateItemsDisplay();
// Initialize upgrade cost display updateUpgradeCostDisplay();
// Show welcome message setTimeout(() => { showGameMessage('Welcome! Roll the dice to earn points and upgrade your dice!', 'text-blue-500'); }, 1000); });
// Also try initializing on window load window.addEventListener('load', () => { console.log('Window loaded'); // If dice not already initialized, try again if (diceElement.children.length === 0) { console.log('Dice not initialized, trying again...'); initializeDice(); } });
// Game Rules Modal Functionality (function() { // Get elements const rulesButton = document.getElementById('game-rules-button'); const rulesModal = document.getElementById('game-rules-modal'); const closeButtons = rulesModal.querySelectorAll('.close-button'); const modalBackdrop = rulesModal.querySelector('.modal-backdrop'); const modalContent = rulesModal.querySelector('.modal-content');
// Function to prevent background scrolling function preventBackgroundScroll(event) { // Allow scrolling inside the modal content if (modalContent.contains(event.target)) { // Check if we're at the top or bottom of the modal content const isAtTop = modalContent.scrollTop === 0; const isAtBottom = modalContent.scrollTop + modalContent.clientHeight >= modalContent.scrollHeight;
// Prevent scrolling if at the top and scrolling up, or at the bottom and scrolling down if ((isAtTop && event.deltaY < 0) || (isAtBottom && event.deltaY > 0)) { event.preventDefault(); } } else { // Prevent scrolling outside the modal content event.preventDefault(); } }
// Function to open modal function openModal() { // Add event listeners to prevent background scrolling document.addEventListener('wheel', preventBackgroundScroll, { passive: false }); document.addEventListener('touchmove', preventBackgroundScroll, { passive: false });
// Add open class to trigger animations rulesModal.classList.add('modal-open');
// Show the modal rulesModal.style.visibility = 'visible'; }
// Function to close modal function closeModal() { // Remove open class to trigger animations rulesModal.classList.remove('modal-open');
// Remove event listeners that prevent background scrolling document.removeEventListener('wheel', preventBackgroundScroll); document.removeEventListener('touchmove', preventBackgroundScroll);
// Hide the modal after animation completes setTimeout(() => { rulesModal.style.visibility = 'hidden'; }, 300); }
// Add event listeners if (rulesButton) { rulesButton.addEventListener('click', openModal); }
// Close buttons closeButtons.forEach(button => { button.addEventListener('click', closeModal); });
// Close when clicking outside the modal content modalBackdrop.addEventListener('click', closeModal);
// Close when pressing Escape key document.addEventListener('keydown', (event) => { if (event.key === 'Escape' && rulesModal.classList.contains('modal-open')) { closeModal(); } });
// Add hover effect to rules button if (rulesButton) { rulesButton.addEventListener('mouseenter', () => { rulesButton.classList.add('scale-105'); });
rulesButton.addEventListener('mouseleave', () => { rulesButton.classList.remove('scale-105'); }); }
// Add click effect to close buttons closeButtons.forEach(button => { button.addEventListener('mousedown', () => { button.classList.add('scale-95'); });
button.addEventListener('mouseup', () => { button.classList.remove('scale-95'); });
button.addEventListener('mouseleave', () => { button.classList.remove('scale-95'); }); });15 行未改动 <!-- Tailwind CSS v3 --> <script src="https://cdn.tailwindcss.com"></script> <!-- Font Awesome --> <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script> tailwind.config = { theme: { extend: {20 行未改动 } } } </script>
<style type="text/tailwindcss"> @layer utilities { .preserve-3d { transform-style: preserve-3d;36 行未改动 .record-animation { animation: record-shine 2s ease-in-out; } }
@keyframes trophy-pulse { 0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(1); } }
@keyframes record-shine { 0% { box-shadow: 0 0 0 0 rgba(251, 191, 36, 0.7); } 70% { box-shadow: 0 0 0 15px rgba(251, 191, 36, 0); } 100% { box-shadow: 0 0 0 0 rgba(251, 191, 36, 0); } }
/* Custom styles for 3D dice */ .dice-scene { perspective: 1500px; width: 120px; height: 120px; display: flex; align-items: center; justify-content: center; }
.dice-container { position: relative; width: 100px; height: 100px; transform-style: preserve-3d; transition: transform 1s ease-out; transform: rotateX(20deg) rotateY(20deg); }
.dice-face { position: absolute; width: 100px; height: 100px;4 行未改动 align-items: center; justify-content: center; box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1); }
/* Dice face positions */ .face-1 { transform: translateZ(50px); } .face-2 { transform: rotateY(90deg) translateZ(50px); } .face-3 { transform: rotateY(180deg) translateZ(50px); } .face-4 { transform: rotateY(-90deg) translateZ(50px); } .face-5 { transform: rotateX(90deg) translateZ(50px); } .face-6 { transform: rotateX(-90deg) translateZ(50px); }
/* Dots on dice faces */ .dot { position: absolute; width: 20px; height: 20px; border-radius: 50%; background-color: black; }
/* Dot positions for each face */ .face-1 .dot { top: 40px; left: 40px; }
.face-2 .dot:nth-child(1) { top: 20px; left: 20px; } .face-2 .dot:nth-child(2) { top: 60px; left: 60px; }
.face-3 .dot:nth-child(1) { top: 20px; left: 20px; } .face-3 .dot:nth-child(2) { top: 40px; left: 40px; } .face-3 .dot:nth-child(3) { top: 60px; left: 60px; }
.face-4 .dot:nth-child(1) { top: 20px; left: 20px; } .face-4 .dot:nth-child(2) { top: 20px; left: 60px; } .face-4 .dot:nth-child(3) { top: 60px; left: 20px; } .face-4 .dot:nth-child(4) { top: 60px; left: 60px; }
.face-5 .dot:nth-child(1) { top: 20px; left: 20px; } .face-5 .dot:nth-child(2) { top: 20px; left: 60px; } .face-5 .dot:nth-child(3) { top: 40px; left: 40px; } .face-5 .dot:nth-child(4) { top: 60px; left: 20px; } .face-5 .dot:nth-child(5) { top: 60px; left: 60px; }
.face-6 .dot:nth-child(1) { top: 20px; left: 20px; } .face-6 .dot:nth-child(2) { top: 20px; left: 60px; } .face-6 .dot:nth-child(3) { top: 40px; left: 20px; } .face-6 .dot:nth-child(4) { top: 40px; left: 60px; } .face-6 .dot:nth-child(5) { top: 60px; left: 20px; } .face-6 .dot:nth-child(6) { top: 60px; left: 60px; }
.dice-result { transition: all 0.5s ease-out; }
/* Fixed height for result display to prevent page jumping */ #result-display { height: 40px; display: flex; align-items: center; justify-content: center; }
.result-shine { animation: shine 0.5s ease-out; }
.score-increase { color: #10b981; animation: scorePopup 1s ease-out; }
.score-decrease { color: #ef4444; animation: scorePopup 1s ease-out; }
.score-neutral { color: #6b7280; animation: scorePopup 1s ease-out; }
/* Locked color option styles */ .color-option.locked { position: relative; opacity: 0.5; cursor: not-allowed; }
.color-option.locked::after { content: '\f023'; /* Lock icon from Font Awesome */ font-family: 'FontAwesome'; position: absolute;2 行未改动 transform: translate(-50%, -50%); color: rgba(0, 0, 0, 0.5); font-size: 16px; }
@keyframes shine { 0% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4); }3 行未改动 100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); } }
@keyframes scorePopup { 0% { transform: translateY(0); opacity: 0;6 行未改动 transform: translateY(-20px); opacity: 0; } }
.confetti { position: absolute; width: 10px; height: 10px; background-color: #f97316; animation: confetti-fall 3s ease-in-out infinite; }
@keyframes confetti-fall { 0% { transform: translateY(-100vh) rotate(0deg); opacity: 1;2 行未改动 transform: translateY(100vh) rotate(720deg); opacity: 0; } }
@keyframes lock-particle { 0% { transform: translate(0, 0); opacity: 1;2 行未改动 transform: translate(var(--tx), var(--ty)); opacity: 0; } }
/* Game Rules Modal Styles */ .game-rules-modal { position: fixed; top: 0;7 行未改动 padding: 1rem; visibility: hidden; box-sizing: border-box; }
.game-rules-modal .modal-backdrop { position: absolute; top: 0; left: 0;2 行未改动 opacity: 0; visibility: hidden; transition: all 0.3s ease-out; }
.game-rules-modal .modal-content { position: relative; background-color: white; border-radius: 1rem;2 行未改动 width: 500px; overflow-y: auto; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); }
.game-rules-modal .modal-header { padding: 1.5rem; border-bottom: 1px solid #e5e7eb; display: flex; justify-content: space-between; align-items: center; }
.game-rules-modal .modal-title { font-size: 1.25rem; font-weight: 600; color: #1e293b; }
.game-rules-modal .close-button { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; transition: color 0.2s ease-in-out; }
.game-rules-modal .close-button:hover { color: #1e293b; }
.game-rules-modal .modal-body { padding: 1.5rem; line-height: 1.6; color: #374151; }
.game-rules-modal .modal-body h3 { font-size: 1.1rem; font-weight: 600; margin-top: 1.5rem; margin-bottom: 0.75rem; color: #1e293b; }
.game-rules-modal .modal-body p { margin-bottom: 1rem; }
.game-rules-modal .modal-body ul { margin-bottom: 1rem; padding-left: 1.5rem; list-style-type: disc; }
.game-rules-modal .modal-body li { margin-bottom: 0.5rem; }
.game-rules-modal .modal-body strong { font-weight: 600; color: #1e293b; }
.game-rules-modal .modal-footer { padding: 1rem 1.5rem; border-top: 1px solid #e5e7eb; display: flex; justify-content: flex-end; }
.game-rules-modal .modal-footer button { padding: 0.5rem 1rem; border-radius: 0.5rem; background-color: #3b82f6; color: white; font-size: 1.25rem; font-weight: 500; transition: background-color 0.2s ease-in-out; }
.game-rules-modal .modal-footer button:hover { background-color: #2563eb; }
/* Game Rules Button Styles */ .game-rules-button { position: fixed; top: 1rem;9 行未改动 gap: 0.5rem; transition: all 0.2s ease-in-out; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); }
.game-rules-button:hover { background-color: #2563eb; transform: translateY(-2px); }
.game-rules-button i { font-size: 1.1rem; } </style>3 行未改动 <button id="game-rules-button" class="game-rules-button"> <i class="fa fa-book"></i> <span>Game Rules</span> </button>
<!-- Game Rules Modal --> <div id="game-rules-modal" class="game-rules-modal"> <div class="modal-backdrop"></div> <div class="modal-content">2 行未改动 <button class="close-button">×</button> </div> <div class="modal-body"> <p>Welcome to the 3D Dice Game! This is an exciting game that combines luck, strategy, and upgrading mechanics. Below is the complete game rules explanation:</p>
<h3>Basic Gameplay</h3> <ul> <li>Click the "Roll Dice" button to roll the dice</li> <li>The dice will randomly show a number between 1-6</li> <li>Gain or lose points based on the number rolled</li> <li>The goal is to obtain the highest tier "Unique" dice</li> </ul>
<h3>Score System</h3> <ul> <li>Rolling 1 or 2: Lose 1 point (multiplier not applied)</li> <li>Rolling 3: No points gained or lost</li> <li>Rolling 4: Gain 1 point</li> <li>Rolling 5: Gain 2 points</li> <li>Rolling 6: Gain 3 points</li> </ul>
<h3>Dice Upgrade System</h3> <p>There are 10 different tiers of dice in the game, from common to rare:</p> <ul> <li><strong>Empty</strong> (Initial) - Score Multiplier ×1.0</li>7 行未改动 <li><strong>Super</strong> - Score Multiplier ×1.8</li> <li><strong>Unique</strong> - Score Multiplier ×1.9</li> </ul> <p>Each upgrade costs (5 + current tier) points. For example, upgrading from Empty (tier 0) costs 5 points, upgrading from Common (tier 1) costs 6 points, and so on. After upgrading, you can choose to use the new dice or continue using the old one.</p>
<h3>Item System</h3> <p>When upgrading, you have a chance to obtain item cards that can be used at critical moments:</p> <ul> <li><strong>Double Points Card</strong>: Doubles the points from one roll</li> <li><strong>No Penalty Card</strong>: Prevents point loss when rolling 1 or 2</li> <li><strong>Lucky Streak Card</strong>: Next 3 rolls of 1 or 2 won't count towards your total roll count</li> </ul> <p>Items can be stockpiled and each card can only be used once. Double Points Cards and No Penalty Cards can be used simultaneously. Lucky Streak Cards make your next 3 rolls of 1 or 2 not count towards your total roll count, giving you a chance to recover from bad luck.</p>
<h3>Game Rules</h3> <ul> <li>Initial score is 10 points</li> <li>Score multiplier changes based on the current dice tier being used</li> <li>Game over when score is less than 0</li> <li>Game victory when obtaining the Unique dice</li> <li>Unlocked dice colors can be switched at any time</li> </ul>
<h3>Operation Tips</h3> <ul> <li>Click on dice color options to switch the dice being used</li> <li>Click the "Upgrade Dice" button to upgrade your dice (requires 5 points)</li> <li>Click the "Use" button next to item cards to use them</li> <li>Press the ESC key to close the rules window</li> </ul>
<p>Good luck, and may you successfully obtain the highest tier Unique dice!</p> </div> <div class="modal-footer"> <button class="close-button">Got it</button> </div> </div> </div>
<div class="w-full max-w-md mx-auto glass-effect rounded-2xl p-6 dice-shadow relative z-10"> <h1 class="text-3xl font-bold text-center text-dark mb-8">3D Dice Roll</h1>
<div class="flex flex-col items-center justify-center mb-8"> <!-- Dice display area --> <div id="dice-display" class="w-48 h-48 flex items-center justify-center mb-4 bg-gray-100 rounded-lg"> <!-- Dice scene for 3D perspective -->2 行未改动 <!-- Dice faces will be inserted here by JavaScript --> </div> </div> </div>
<!-- Result display --> <div id="result-display" class="text-2xl font-bold text-center mb-4 hidden"> Result: <span id="result-value" class="text-primary">0</span> </div>
<!-- Score display --> <div id="score-display" class="text-xl font-bold text-center mb-2"> Score: <span id="score-value" class="text-secondary">10</span> <span id="score-change" class="ml-2 text-sm font-normal"></span> </div>
<!-- Roll count display --> <div id="roll-count-display" class="text-lg font-medium text-center mb-4"> Rolls: <span id="roll-count-value" class="text-gray-700">0</span> </div>
<!-- Roll button --> <button id="roll-button" class="bg-primary hover:bg-blue-600 text-white font-bold py-3 px-6 rounded-full transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-blue-300 focus:ring-opacity-50"> <i class="fa fa-random mr-2"></i> Roll Dice </button>
<!-- Upgrade button and current tier display --> <div class="flex flex-col items-center mt-4"> <div id="current-tier" class="text-sm text-gray-600 mb-2"> Current Dice: <span class="font-semibold text-primary">Empty</span>4 行未改动 <button id="upgrade-button" class="bg-secondary hover:bg-orange-600 text-white font-bold py-2 px-4 rounded-full transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-orange-300 focus:ring-opacity-50"> <i class="fa fa-arrow-up mr-1"></i> Upgrade Dice <span id="upgrade-cost">(Cost: 5)</span> </button> </div>
<!-- Game message display --> <div id="game-message" class="mt-4 text-center font-semibold hidden"></div>
<!-- Items display --> <div id="items-display" class="mt-6 grid grid-cols-2 gap-4"> <div class="bg-white rounded-lg p-3 dice-shadow"> <div class="flex items-center justify-between">9 行未改动 </div> </div> <p class="text-xs text-gray-500 mt-1">Doubles your score change for one roll</p> </div>
<div class="bg-white rounded-lg p-3 dice-shadow"> <div class="flex items-center justify-between"> <div class="flex items-center"> <i class="fa fa-shield text-blue-500 text-xl mr-2"></i>7 行未改动 </div> </div> <p class="text-xs text-gray-500 mt-1">Prevents score loss when rolling 1 or 2</p> </div>
<div class="bg-white rounded-lg p-3 dice-shadow"> <div class="flex items-center justify-between"> <div class="flex items-center"> <i class="fa fa-star text-yellow-500 text-xl mr-2"></i>8 行未改动 </div> <p class="text-xs text-gray-500 mt-1">Next 3 rolls of 1 or 2 won't count towards your total roll count</p> </div> </div>
<!-- Free rolls indicator --> <div id="free-rolls-indicator" class="mt-3 text-center hidden"> <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800"> <i class="fa fa-star mr-1" style="color: #f59e0b;"></i> <span>Free Rolls: <span id="free-rolls-count">0</span></span> </span> </div>
<!-- Active item indicator --> <div id="active-item-indicator" class="mt-3 text-center hidden"> <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"> <i id="active-item-icon" class="mr-1"></i> <span id="active-item-text">Active Item: None</span> </span> </div> </div>
<!-- Dice color selection --> <div class="mb-8"> <label class="block text-sm font-medium text-gray-700 mb-2">Dice Rarity</label> <div class="grid grid-cols-5 gap-4">48 行未改动 <span class="text-xs text-center text-gray-600">Unique</span> </div> </div> </div>
<!-- History log --> <div class="bg-white rounded-lg p-4"> <h2 class="text-lg font-semibold text-center mb-2">Roll History</h2> <div id="history-container" class="h-64 overflow-y-auto">7 行未改动 </ul> </div> </div> </div>
<footer class="mt-8 text-center text-gray-600 text-sm"> <p>Click the button to roll the dice and see the result!</p> </footer>
<script> // Set up global error handler window.addEventListener('error', function(event) { console.error('Global error caught:', event.error);
// Try to get roll button element const rollButton = document.getElementById('roll-button'); if (rollButton && rollButton.disabled) { console.warn('Error during dice roll, re-enabling button'); rollButton.disabled = false; rollButton.classList.remove('opacity-70', 'cursor-not-allowed');
// Try to show error message const gameMessage = document.getElementById('game-message'); if (gameMessage) { gameMessage.textContent = 'An error occurred. Please try again.'; gameMessage.className = 'mt-4 text-center font-semibold text-red-500'; gameMessage.classList.remove('hidden'); } } });
// DOM elements const diceElement = document.getElementById('dice'); const rollButton = document.getElementById('roll-button'); const resultDisplay = document.getElementById('result-display');8 行未改动 const gameMessageDisplay = document.getElementById('game-message'); const rollCountDisplay = document.getElementById('roll-count-display'); const rollCountValue = document.getElementById('roll-count-value'); const upgradeCost = document.getElementById('upgrade-cost');
// Item related DOM elements const doublePointsCount = document.getElementById('double-points-count'); const noPenaltyCount = document.getElementById('no-penalty-count'); const luckyStreakCount = document.getElementById('lucky-streak-count');2 行未改动 const useLuckyStreakButton = document.getElementById('use-lucky-streak'); const activeItemIndicator = document.getElementById('active-item-indicator'); const freeRollsIndicator = document.getElementById('free-rolls-indicator'); const freeRollsCountElement = document.getElementById('free-rolls-count');
// Game state let currentScore = 10; // Initial score let currentTier = 0; // Initial dice tier (0 = Empty) let gameOver = false; // Game over flag let rollCount = 0; // Number of dice rolls let luckyRollsRemaining = 0; // Number of lucky rolls remaining let isRolling = false; // Whether dice is currently rolling
// Item system let doublePointsCards = 0; // Number of double points cards let noPenaltyCards = 0; // Number of no penalty cards let luckyStreakCards = 0; // Number of lucky streak cards let freeRolls = 0; // Number of free rolls available let activeItems = { // Currently active items double: 0, // Number of active double points cards noPenalty: false // Whether no penalty card is active };
// Dice tiers configuration const diceTiers = [ { name: 'Empty', color: '#FFFFFF' }, { name: 'Common', color: '#7EEF6D' },5 行未改动 { name: 'Ultra', color: '#ff2b75' }, { name: 'Super', color: '#2bffa3' }, { name: 'Unique', color: '#555555' } ];
// Initialize 3D dice function initializeDice() { console.log('Initializing dice...'); // Create 6 faces for the dice const faces = [1, 2, 3, 4, 5, 6];
faces.forEach(faceNumber => { const face = document.createElement('div'); face.className = `dice-face face-${faceNumber}`;
// Add dots to the face based on the number for (let i = 0; i < faceNumber; i++) { const dot = document.createElement('div'); dot.className = 'dot'; face.appendChild(dot); }
diceElement.appendChild(face); console.log(`Added face ${faceNumber}`); });
console.log('Dice initialized with faces:', diceElement.children.length);
// Set initial position to show face 1 clearly diceElement.style.transform = 'rotateX(0deg) rotateY(0deg)'; }
// Get random rotation values for the dice function getRandomRotation() { // Determine which face we want to show const targetFace = Math.floor(Math.random() * 6) + 1;
// Get current rotation from dice element const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); const matrix = new DOMMatrix(currentTransform);
// Extract current rotation angles let currentX = 0, currentY = 0;
// If transform is not identity matrix, extract rotation if (currentTransform !== 'none') { // Calculate rotation from matrix currentX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI); currentY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI); }
// Set target rotation based on target face // These values are precisely calibrated to show the correct face let targetX = 0, targetY = 0; switch(targetFace) {21 行未改动 targetX = 90; targetY = 0; break; }
// Calculate the shortest path to the target rotation // This prevents large rotation values from accumulating let diffX = targetX - currentX; let diffY = targetY - currentY;
// Normalize the difference to the range [-180, 180] to find the shortest path diffX = ((diffX + 180) % 360) - 180; diffY = ((diffY + 180) % 360) - 180;
// Add multiple full rotations for spinning effect (2-4 full rotations) const fullRotations = 2 + Math.floor(Math.random() * 3);
// Calculate final rotation with full spins // We add full rotations in the direction of the shortest path const spinDirectionX = diffX >= 0 ? 1 : -1; const spinDirectionY = diffY >= 0 ? 1 : -1;
const finalX = currentX + diffX + spinDirectionX * fullRotations * 360; const finalY = currentY + diffY + spinDirectionY * fullRotations * 360;
// Add a tiny bit of randomness to make it look more natural // But not enough to change which face is visible const randomX = (Math.random() - 0.5) * 2; const randomY = (Math.random() - 0.5) * 2;
return { x: finalX + randomX, y: finalY + randomY, targetFace: targetFace // Return the target face so we don't have to recalculate it }; }
// Roll the dice function function rollDice() { // Check if game is over if (gameOver) { showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500'); return; }
// Check if there are free rolls available const isFreeRoll = freeRolls > 0;
// Check if in lucky streak mode const isLuckyRoll = luckyRollsRemaining > 0;
// Increment roll count only if not a free roll (lucky rolls will be handled based on result) if (!isFreeRoll) { rollCount++; console.log(`Roll count: ${rollCount}`);2 行未改动 freeRolls--; updateFreeRollsDisplay(); console.log(`Free roll used. Remaining free rolls: ${freeRolls}`); }
// Update roll count display if (rollCountValue) { rollCountValue.textContent = rollCount; }
console.log('Rolling dice...'); console.log('Button state before disable:', rollButton.disabled);
// Set rolling state and disable button during animation isRolling = true; rollButton.disabled = true; rollButton.classList.add('opacity-70', 'cursor-not-allowed');
// Disable other interactive elements during roll upgradeButton.disabled = true; upgradeButton.classList.add('opacity-70', 'cursor-not-allowed'); useDoublePointsButton.disabled = true; useNoPenaltyButton.disabled = true; useLuckyStreakButton.disabled = true;
// Disable color options during roll colorOptions.forEach(option => { option.disabled = true; });
console.log('Button state after disable:', rollButton.disabled);
// Hide result display resultDisplay.classList.add('hidden');
// Reset dice display height - use Tailwind class instead of inline style const diceDisplay = document.getElementById('dice-display'); if (diceDisplay) { // Ensure the height class is applied to prevent layout shifts during animation diceDisplay.classList.add('h-48'); }
try { // Set animation duration const duration = 2000; // Fixed duration for consistent experience
// Get random rotation values for the final position const rotationData = getRandomRotation(); console.log('Rotation data:', rotationData); console.log('Target face:', rotationData.targetFace);
// Animate the dice using JavaScript for more control animateDice(duration, rotationData, { isFreeRoll, isLuckyRoll });
// Set a safety timeout to ensure button is re-enabled even if something goes wrong setTimeout(() => { if (rollButton.disabled) { console.warn('Safety timeout: Re-enabling roll button');6 行未改动 enableRollButton(); showGameMessage('An error occurred during the dice roll. Please try again.', 'text-red-500'); } }
// Animate the dice with spin animation function animateDice(duration, rotationData, rollContext) { console.log('Animate dice called with rotationData:', rotationData); console.log('Roll context:', rollContext); const startTime = performance.now(); const finalRotation = rotationData;
// Get current rotation from dice element const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); const matrix = new DOMMatrix(currentTransform);
// Extract current rotation angles let startX = 0, startY = 0;
// If transform is not identity matrix, extract rotation if (currentTransform !== 'none') { // Calculate rotation from matrix startX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI); startY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI); }
// Function to handle each animation frame function animate(currentTime) { const elapsedTime = currentTime - startTime; const progress = Math.min(elapsedTime / duration, 1);
// Apply easing function for smooth, natural animation const easedProgress = easeOutCubic(progress);
// Calculate current rotation - smooth continuous rotation const currentX = startX + (finalRotation.x - startX) * easedProgress; const currentY = startY + (finalRotation.y - startY) * easedProgress;
// Spin animation: rotate in place diceElement.style.transform = `rotateX(${currentX}deg) rotateY(${currentY}deg)`;
// Continue animation if not complete if (progress < 1) { requestAnimationFrame(animate); } else { // Animation complete - ensure we're at the exact target rotation diceElement.style.transform = `rotateX(${finalRotation.x}deg) rotateY(${finalRotation.y}deg)`;
// Show result after a delay to ensure rotation is complete and CSS has applied console.log('Animation complete, waiting before finalizing...'); setTimeout(() => { // Double-check that the transform has been applied3 行未改动 finalizeAnimation(finalRotation, rollContext); }, 600); } }
// Start the animation requestAnimationFrame(animate); }
// Helper function to normalize angles to the range [-180, 180] function normalizeAngle(angle) { angle = angle % 360; if (angle > 180) angle -= 360; if (angle < -180) angle += 360; return angle; }
// Easing function for smooth, natural animation with gentle acceleration and deceleration // Uses a cubic easing function that starts slow, accelerates, then slows down at the end function easeOutCubic(t) { return 1 - Math.pow(1 - t, 3); }
// Calculate score change based on dice roll result function calculateScoreChange(result) { let baseChange = 0;
switch(result) { case 1: case 2: baseChange = -1;12 行未改动 break; default: baseChange = 0; }
// Apply current tier multiplier // If losing points (baseChange < 0), use multiplier of 1 instead of tier multiplier const tierMultiplier = 1 + currentTier / 10; let finalChange;
if (baseChange < 0) { // For point loss, use multiplier of 1 regardless of tier finalChange = baseChange * 1; } else { // For point gain or neutral, use tier multiplier finalChange = baseChange * tierMultiplier; }
// Apply active item effects const itemsUsed = { double: activeItems.double, noPenalty: activeItems.noPenalty };
// Apply no penalty card first if (activeItems.noPenalty && baseChange < 0) { finalChange = 0; }
// Apply double points cards if (activeItems.double > 0) { finalChange = finalChange * Math.pow(2, activeItems.double); }
// Round to 2 decimal places to avoid floating point precision issues finalChange = Math.round(finalChange * 100) / 100;
return { baseChange: baseChange, finalChange: finalChange, itemsUsed: itemsUsed, tierMultiplier: tierMultiplier }; }
// Enable roll button function enableRollButton() { console.log('Button state before enable:', rollButton.disabled);
// Directly enable the button rollButton.disabled = false; rollButton.classList.remove('opacity-70', 'cursor-not-allowed');
// Re-enable other interactive buttons based on their conditions updateUpgradeCostDisplay(); // This will enable/disable upgrade button based on score updateItemsDisplay(); // This will enable/disable item buttons based on availability
console.log('Button state after enable:', rollButton.disabled);
// Double-check and force enable if needed if (rollButton.disabled) { console.warn('Forcing button enable'); setTimeout(() => {2 行未改动 console.log('Button state after forced enable:', rollButton.disabled); }, 100); } }
// Finalize the animation and show result function finalizeAnimation(rotationData, rollContext) { console.log('=== Finalize animation called ==='); console.log('Current time:', new Date().toISOString().split('T')[1]); console.log('Rotation data:', rotationData); console.log('Roll context:', rollContext);
const finalRotation = rotationData; const isFreeRoll = rollContext && rollContext.isFreeRoll || false; const isLuckyRoll = rollContext && rollContext.isLuckyRoll || false;
// Use the target face directly instead of recalculating const result = finalRotation.targetFace; console.log(`Final result: ${result} (should show face ${result})`);
// Verify dice is in the correct position const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); console.log('Current dice transform:', currentTransform);
// Show result display console.log('Showing result display...'); resultValue.textContent = result; resultDisplay.classList.remove('hidden');
// Add shine effect to result resultDisplay.classList.add('result-shine'); setTimeout(() => { resultDisplay.classList.remove('result-shine'); }, 500);
// Calculate and update score console.log('Calculating score change...'); const scoreChangeData = calculateScoreChange(result); console.log('Score change data:', scoreChangeData);
currentScore += scoreChangeData.finalChange; console.log('Updated score:', currentScore);
// Update score display with animation console.log('Updating score display...'); updateScoreDisplay(scoreChangeData);
// Enable button console.log('Enabling roll button...'); enableRollButton();
// Add to history - include whether it was a free roll or lucky roll addToHistory(result, scoreChangeData, isFreeRoll, isLuckyRoll);
// Check if reached the Unique dice if (currentTier === diceTiers.length - 1) { showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500'); gameOver = true; createConfetti(); }
// Handle lucky roll logic if (luckyRollsRemaining > 0) { // Decrement remaining lucky rolls luckyRollsRemaining--;
// If rolled 1 or 2, decrement roll count if (result === 1 || result === 2) { rollCount--; console.log(`Lucky roll: Reverted roll count to ${rollCount}`);
// Update roll count display if (rollCountValue) { rollCountValue.textContent = rollCount; }
// Show message showGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500'); }
// Update lucky rolls display updateLuckyRollsDisplay();
// If no more lucky rolls, show message if (luckyRollsRemaining === 0) { setTimeout(() => { showGameMessage('Lucky Streak ended!', 'text-yellow-500'); }, 1000); } }
// Create confetti effect if result is 6 if (result === 6) { createConfetti(); }
// Debug: log final state console.log(`Final precise rotation: X=${finalRotation.x}°, Y=${finalRotation.y}°`); console.log(`Displayed result: ${result}`); console.log(`Score change: ${scoreChangeData.finalChange}, Current score: ${currentScore}`); console.log('=== finalizeAnimation completed ==='); }
// Update score display with animation function updateScoreDisplay(scoreChangeData) { console.log('=== updateScoreDisplay called ==='); console.log('Score change data:', scoreChangeData);
const change = scoreChangeData.finalChange; const baseChange = scoreChangeData.baseChange; const itemsUsed = scoreChangeData.itemsUsed; const tierMultiplier = scoreChangeData.tierMultiplier;
console.log('Change:', change, 'Base change:', baseChange, 'Items used:', itemsUsed);
// Update the score value - round to 2 decimal places currentScore = Math.round(currentScore * 100) / 100; scoreValue.textContent = currentScore; console.log('Score value updated to:', currentScore);
// Clear previous score change display scoreChange.textContent = ''; scoreChange.className = 'ml-2 text-sm font-normal'; console.log('Cleared previous score change display');
// Show score change with appropriate styling if (change > 0) { scoreChange.textContent = `+${change}`; scoreChange.classList.add('score-increase');6 行未改动 scoreChange.textContent = `±0`; scoreChange.classList.add('score-neutral'); console.log('Score neutral'); }
// Show item effect message if items were used if (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) { // Create container for item effects const itemEffectsContainer = document.createElement('div'); itemEffectsContainer.className = 'flex flex-wrap gap-2 mt-1';
// Add tier multiplier effect if applicable if (tierMultiplier !== 1) { const tierEffect = document.createElement('div'); tierEffect.className = 'text-xs text-purple-500'; tierEffect.textContent = `Tier Multiplier ×${tierMultiplier.toFixed(1)}!`; itemEffectsContainer.appendChild(tierEffect); }
// Add no penalty effect if (itemsUsed.noPenalty) { const noPenaltyEffect = document.createElement('div'); noPenaltyEffect.className = 'text-xs text-blue-500'; noPenaltyEffect.textContent = `No Penalty! (Score protected from ${baseChange < 0 ? baseChange : 0} loss)`; itemEffectsContainer.appendChild(noPenaltyEffect); }
// Add double points effect if (itemsUsed.double > 0) { const doublePointsEffect = document.createElement('div'); doublePointsEffect.className = 'text-xs text-green-500';
// Calculate multiplier const multiplier = Math.pow(2, itemsUsed.double); let calculationText = `${baseChange}`;
// Apply tier multiplier for display let displayChange = baseChange * tierMultiplier;
// Apply no penalty first for display if (itemsUsed.noPenalty && baseChange < 0) { displayChange = 0; calculationText = `(${baseChange} × ${tierMultiplier.toFixed(1)} → 0)`; } else if (tierMultiplier !== 1) { calculationText = `(${baseChange} × ${tierMultiplier.toFixed(1)} = ${displayChange.toFixed(2)})`; }
// Show multiplication steps if multiple double cards used if (itemsUsed.double > 1) { for (let i = 0; i < itemsUsed.double; i++) { calculationText += ` × 2`; } calculationText += ` = ${(displayChange * multiplier).toFixed(2)}`; } else { calculationText += ` × 2 = ${(displayChange * multiplier).toFixed(2)}`; }
doublePointsEffect.textContent = `Double Points ×${itemsUsed.double}! (${calculationText})`; itemEffectsContainer.appendChild(doublePointsEffect); }
// Add to score display scoreDisplay.appendChild(itemEffectsContainer);
// Remove after animation setTimeout(() => { scoreDisplay.removeChild(itemEffectsContainer); }, 1000); }
// Reset score change display after animation completes setTimeout(() => { scoreChange.textContent = ''; }, 1000);
// Clear active items after score update console.log('Checking if items need to be cleared...'); if (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) { console.log('Clearing active items...'); clearActiveItems(); console.log('Updating items display...'); updateItemsDisplay(); }
// Check game state after score update console.log('Checking game state...'); checkGameState();
// Update upgrade button state updateUpgradeCostDisplay();
console.log('=== updateScoreDisplay completed ==='); }
// Handle dice upgrade function upgradeDice() { // Check if game is already over if (gameOver) { showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500'); return; }
// Check if already at maximum tier if (currentTier >= diceTiers.length - 1) { // If not already game over, end the game with win condition if (!gameOver) {3 行未改动 showGameMessage('Congratulations! You already have the Unique dice!', 'text-green-500'); } return; }
// Calculate required score for upgrade (5 + currentTier) const requiredScore = 5 + currentTier;
// Check if enough score to upgrade if (currentScore < requiredScore) { showGameMessage(`Not enough score to upgrade! Need ${requiredScore} points.`, 'text-orange-500'); // Add shake animation to score display2 行未改动 scoreDisplay.classList.remove('animate-shake'); }, 500); return; }
// Deduct score for upgrade currentScore -= requiredScore; // Round to 2 decimal places currentScore = Math.round(currentScore * 100) / 100;
// Update score display scoreValue.textContent = currentScore; showScoreChange(-requiredScore);
// Increase tier currentTier++;
// Update current tier display currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;
// Update tier multiplier display updateTierMultiplierDisplay();
// Unlock the new dice color unlockDiceColor(currentTier);
// Update color selection UI updateColorSelection(currentTier);
// Update upgrade cost display updateUpgradeCostDisplay();
// Change to the new dice color console.log(`Changing dice color to ${diceTiers[currentTier].color} (${diceTiers[currentTier].name})`); changeDiceColor(diceTiers[currentTier].color);
// Check if this upgrade reached the maximum tier checkGameState();
// Randomly get an item const itemChance = Math.random(); if (itemChance < 0.30) { // 30% chance to get double points card doublePointsCards++;3 行未改动 luckyStreakCards++; } else { // 30% chance to get nothing // Do nothing }
// Update items display to show new counts updateItemsDisplay();
// Update items display updateItemsDisplay();
// Check if reached the Unique dice if (currentTier === diceTiers.length - 1) { showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500'); gameOver = true; createConfetti(); }
// Handle lucky roll logic if (luckyRollsRemaining > 0) { // Decrement remaining lucky rolls luckyRollsRemaining--;
// If rolled 1 or 2, decrement roll count if (result === 1 || result === 2) { rollCount--; console.log(`Lucky roll: Reverted roll count to ${rollCount}`);
// Update roll count display if (rollCountValue) { rollCountValue.textContent = rollCount; }
// Show message showGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500'); }
// Update lucky rolls display updateLuckyRollsDisplay();
// If no more lucky rolls, show message if (luckyRollsRemaining === 0) { setTimeout(() => { showGameMessage('Lucky Streak ended!', 'text-yellow-500'); }, 1000); } }
// Add to history addToHistory('UPGRADE', -5);
// Add item to history if obtained if (itemChance < 0.30) { addToHistory('ITEM', 'Double Points Card'); } else if (itemChance < 0.60) { addToHistory('ITEM', 'No Penalty Card'); } else if (itemChance < 0.70) { addToHistory('ITEM', 'Lucky Streak Card'); }
// Check game state after upgrade checkGameState(); }
// Show score change temporarily function showScoreChange(change) { scoreChange.textContent = change > 0 ? `+${change}` : change; scoreChange.className = `ml-2 text-sm font-normal ${change > 0 ? 'score-increase' : 'score-decrease'}`;
setTimeout(() => { scoreChange.textContent = ''; }, 1000); }
// Unlock a dice color option function unlockDiceColor(tierIndex) { if (tierIndex >= 0 && tierIndex < colorOptions.length) { const option = colorOptions[tierIndex];5 行未改动 option.classList.remove('locked'); }, 300); } }
// Show game message function showGameMessage(message, className) { gameMessageDisplay.textContent = message; gameMessageDisplay.className = `mt-4 text-center font-semibold ${className}`; gameMessageDisplay.classList.remove('hidden');
// Hide message after 3 seconds setTimeout(() => { if (!gameOver) { gameMessageDisplay.classList.add('hidden'); } }, 3000); }
// Check game state (win/lose conditions) function checkGameState() { console.log('=== checkGameState called ==='); console.log('Current score:', currentScore, 'Game over:', gameOver);
// Check if score is negative (lose condition) if (currentScore < 0 && !gameOver) { console.log('Score is negative, ending game...'); gameOver = true; endGame(false); }
// Check if reached Unique dice (win condition) if (currentTier === diceTiers.length - 1 && !gameOver) { console.log('Reached Unique dice, ending game...'); gameOver = true; endGame(true);
// Check if this is a new record setTimeout(() => { checkWinRecord(); }, 1000); }
// Check if score is low (warning) if (currentScore >= 0 && currentScore <= 5 && !gameOver) { showLowScoreWarning(); }
console.log('=== checkGameState completed ==='); }
// Update items display function updateItemsDisplay() { // Update counts doublePointsCount.textContent = doublePointsCards; noPenaltyCount.textContent = noPenaltyCards; luckyStreakCount.textContent = luckyStreakCards;
// Enable/disable buttons based on available items useDoublePointsButton.disabled = doublePointsCards <= 0 || gameOver; useNoPenaltyButton.disabled = noPenaltyCards <= 0 || activeItems.noPenalty || gameOver; useLuckyStreakButton.disabled = luckyStreakCards <= 0 || gameOver;
// Update free rolls display updateFreeRollsDisplay();
// Update lucky rolls display updateLuckyRollsDisplay(); }
// Update free rolls display function updateFreeRollsDisplay() { if (freeRolls > 0) { freeRollsCountElement.textContent = freeRolls; freeRollsIndicator.classList.remove('hidden'); } else { freeRollsIndicator.classList.add('hidden'); } }
// Update upgrade cost display and button state function updateUpgradeCostDisplay() { if (currentTier >= diceTiers.length - 1) { // Already at maximum tier2 行未改动 upgradeButton.classList.add('opacity-70', 'cursor-not-allowed'); } else { const requiredScore = 5 + currentTier; upgradeCost.textContent = `(Cost: ${requiredScore})`;
// Update button state based on available score if (currentScore >= requiredScore && !gameOver) { upgradeButton.disabled = false; upgradeButton.classList.remove('opacity-70', 'cursor-not-allowed');2 行未改动 upgradeButton.classList.add('opacity-70', 'cursor-not-allowed'); } } }
// Use double points card function useDoublePointsCard() { if (doublePointsCards > 0 && !gameOver) { activeItems.double++; doublePointsCards--;
// Update UI updateItemsDisplay(); showActiveItemIndicator();
// Show message showGameMessage('Double Points Card activated! Next roll will double your score change.', 'text-green-500'); } }
// Use no penalty card function useNoPenaltyCard() { if (noPenaltyCards > 0 && !activeItems.noPenalty && !gameOver) { activeItems.noPenalty = true; noPenaltyCards--;
// Update UI updateItemsDisplay(); showActiveItemIndicator();
// Show message showGameMessage('No Penalty Card activated! Next roll won\'t lose points.', 'text-blue-500'); } }
// Use lucky streak card function useLuckyStreakCard() { if (luckyStreakCards > 0 && !gameOver) { luckyRollsRemaining = 3; luckyStreakCards--;
// Update UI updateItemsDisplay(); updateLuckyRollsDisplay();
// Show message showGameMessage('Lucky Streak Card activated! Next 3 rolls of 1 or 2 won\'t count!', 'text-yellow-500');
// Add to history addToHistory('ITEM USE', 'Lucky Streak Card'); } }
// Update lucky rolls display function updateLuckyRollsDisplay() { if (luckyRollsRemaining > 0) { // Check if indicator exists, if not create it let luckyRollsIndicator = document.getElementById('lucky-rolls-indicator'); if (!luckyRollsIndicator) { luckyRollsIndicator = document.createElement('div'); luckyRollsIndicator.id = 'lucky-rolls-indicator'; luckyRollsIndicator.className = 'mt-3 text-center';
// Insert after free rolls indicator const freeRollsIndicator = document.getElementById('free-rolls-indicator'); if (freeRollsIndicator) { freeRollsIndicator.parentNode.insertBefore(luckyRollsIndicator, freeRollsIndicator.nextSibling);10 行未改动 } } } }
// Update content luckyRollsIndicator.innerHTML = ` <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800"> <i class="fa fa-star mr-1" style="color: #f59e0b;"></i> <span>Lucky Rolls: <span id="lucky-rolls-count">${luckyRollsRemaining}</span> (1-2 won't count)</span> </span> `;
// Show indicator luckyRollsIndicator.classList.remove('hidden'); } else { // Remove indicator if exists2 行未改动 luckyRollsIndicator.classList.add('hidden'); } } }
// Show active item indicator function showActiveItemIndicator() { // Clear previous content activeItemIndicator.innerHTML = '';
// Check if any items are active if (activeItems.double === 0 && !activeItems.noPenalty) { activeItemIndicator.className = 'mt-3 text-center hidden'; return; }
// Create container for active items const itemsContainer = document.createElement('div'); itemsContainer.className = 'flex flex-wrap justify-center gap-2';
// Add double points cards indicator if (activeItems.double > 0) { const doublePointsIndicator = document.createElement('span'); doublePointsIndicator.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800';2 行未改动 <span>Double Points ×${activeItems.double}</span> `; itemsContainer.appendChild(doublePointsIndicator); }
// Add no penalty card indicator if (activeItems.noPenalty) { const noPenaltyIndicator = document.createElement('span'); noPenaltyIndicator.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800';2 行未改动 <span>No Penalty</span> `; itemsContainer.appendChild(noPenaltyIndicator); }
// Add indicators to container activeItemIndicator.appendChild(itemsContainer); activeItemIndicator.className = 'mt-3 text-center'; }
// Clear active items function clearActiveItems() { activeItems = { double: 0, noPenalty: false }; showActiveItemIndicator(); }
// End the game and display appropriate message function endGame(isWin) { console.log('=== endGame called ==='); console.log('Is win:', isWin, 'Current score:', currentScore);
// Disable all interactive elements rollButton.disabled = true; upgradeButton.disabled = true; rollButton.classList.add('opacity-70', 'cursor-not-allowed'); upgradeButton.classList.add('opacity-70', 'cursor-not-allowed');
// Disable all interactive elements colorOptions.forEach(option => { option.disabled = true; option.classList.add('opacity-50', 'cursor-not-allowed'); });
// Disable item buttons useDoublePointsButton.disabled = true; useNoPenaltyButton.disabled = true; useLuckyStreakButton.disabled = true;
// Hide active indicators activeItemIndicator.classList.add('hidden'); const luckyRollsIndicator = document.getElementById('lucky-rolls-indicator'); if (luckyRollsIndicator) { luckyRollsIndicator.classList.add('hidden'); }
// Create game over message element const gameOverMessage = document.createElement('div'); gameOverMessage.className = `mt-4 p-4 rounded-lg text-center font-bold ${isWin ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`;
// Format final score to 2 decimal places const formattedScore = currentScore.toFixed(2);
if (isWin) { gameOverMessage.innerHTML = ` <div class="text-2xl mb-2">Congratulations!</div> <p>You won the game!</p>24 行未改动 <i class="fa fa-refresh mr-1"></i> Play Again </button> `; }
// Add restart button event listener gameOverMessage.querySelector('#play-again').addEventListener('click', () => { window.location.reload(); });
// Replace game message display with game over message const gameMessageContainer = gameMessageDisplay.parentElement; gameMessageContainer.replaceChild(gameOverMessage, gameMessageDisplay); gameMessageDisplay = gameOverMessage;
// Add game end to history addToHistory(isWin ? 'GAME WIN' : 'GAME OVER', 0);
console.log('=== endGame completed ==='); }
// Show warning when score is low function showLowScoreWarning() { // Only show warning if not already showing if (gameMessageDisplay.classList.contains('hidden')) { showGameMessage('Warning: Low score! Risk of game over.', 'text-orange-500'); } }
// Update color selection UI to show the currently selected color function updateColorSelection(selectedIndex) { // Remove active state from all color options colorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary'));
// Add active state to the selected color option if (selectedIndex >= 0 && selectedIndex < colorOptions.length) { colorOptions[selectedIndex].classList.add('ring-2', 'ring-offset-2', 'ring-primary'); } }
// Add result to history function addToHistory(result, scoreChangeData, isFreeRoll = false, isLuckyRoll = false) { const now = new Date(); const timeString = now.toLocaleTimeString();
// Determine score change display and color let scoreChangeText = ''; let scoreChangeClass = ''; let actionText = '';
if (result === 'UPGRADE') { actionText = 'Upgraded dice'; scoreChangeText = `${scoreChangeData}`; scoreChangeClass = 'text-red-500';8 行未改动 } else { const scoreChange = scoreChangeData.finalChange; const baseChange = scoreChangeData.baseChange; const itemsUsed = scoreChangeData.itemsUsed;
actionText = `Rolled a <span class="font-bold text-primary">${result}</span>`;
// Add free roll indicator if applicable if (isFreeRoll) { actionText += ` <span class="text-yellow-500">(Free Roll)</span>`; }
// Add lucky roll indicator if applicable if (isLuckyRoll) { actionText += ` <span class="text-yellow-500">(Lucky Roll)</span>`; }
// Add item effect indicators if applicable const activeItemsText = []; if (itemsUsed && itemsUsed.double > 0) { activeItemsText.push(`<span class="text-green-500">(Double Points ×${itemsUsed.double})</span>`); } if (itemsUsed && itemsUsed.noPenalty) { activeItemsText.push(`<span class="text-blue-500">(No Penalty)</span>`); }
if (activeItemsText.length > 0) { actionText += ` ${activeItemsText.join(' ')}`; }
if (scoreChange > 0) { scoreChangeText = `+${scoreChange}`; scoreChangeClass = 'text-green-500'; } else if (scoreChange < 0) {2 行未改动 } else { scoreChangeText = '±0'; scoreChangeClass = 'text-gray-500'; }
// Show base change if different from final change (items were used) if ((itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) && baseChange !== scoreChange) { scoreChangeText += ` <span class="text-xs">(Base: ${baseChange > 0 ? '+' : ''}${baseChange})</span>`; } }
const listItem = document.createElement('li'); listItem.className = 'py-1 border-b border-gray-100 grid grid-cols-3 gap-2 items-center'; listItem.innerHTML = ` <span class="col-span-1 text-gray-500">${timeString}</span> <span class="col-span-1">${actionText}</span> <span class="col-span-1 text-right font-medium ${scoreChangeClass}">${scoreChangeText}</span> `;
historyList.prepend(listItem);
// Keep only last 10 history items if (historyList.children.length > 10) { historyList.removeChild(historyList.lastChild); }
// Ensure scroll is at the bottom const historyContainer = document.getElementById('history-container'); if (historyContainer) { historyContainer.scrollTop = historyContainer.scrollHeight; } }
// Create confetti effect function createConfetti() { const confettiContainer = document.createElement('div'); confettiContainer.className = 'fixed inset-0 pointer-events-none overflow-hidden'; document.body.appendChild(confettiContainer);
// Create 50 confetti pieces for (let i = 0; i < 50; i++) { const confetti = document.createElement('div'); confetti.className = 'confetti';
// Random position const posX = Math.random() * 100; const delay = Math.random() * 3; const duration = 3 + Math.random() * 2;
// Random colors const colors = ['#3b82f6', '#f97316', '#10b981', '#ef4444', '#8b5cf6']; const color = colors[Math.floor(Math.random() * colors.length)];
confetti.style.left = `${posX}%`; confetti.style.backgroundColor = color; confetti.style.animationDelay = `${delay}s`; confetti.style.animationDuration = `${duration}s`;
confettiContainer.appendChild(confetti); }
// Remove confetti container after animation completes setTimeout(() => { document.body.removeChild(confettiContainer); }, 5000); }
// Create particle effect on lock function createLockParticles(lockElement) { // Get lock element position const rect = lockElement.getBoundingClientRect(); const centerX = rect.left + rect.width / 2; const centerY = rect.top + rect.height / 2;
// Create particle container const particleContainer = document.createElement('div'); particleContainer.className = 'absolute pointer-events-none'; particleContainer.style.left = `${centerX}px`; particleContainer.style.top = `${centerY}px`; particleContainer.style.transform = 'translate(-50%, -50%)'; document.body.appendChild(particleContainer);
// Create 15 particles for (let i = 0; i < 15; i++) { const particle = document.createElement('div'); particle.className = 'lock-particle';
// Random direction and distance const angle = Math.random() * Math.PI * 2; const distance = 10 + Math.random() * 20; const tx = Math.cos(angle) * distance; const ty = Math.sin(angle) * distance;
// Random color (use the color of the unlocked dice) const color = lockElement.style.backgroundColor;
// Random animation duration const duration = 0.5 + Math.random() * 0.5;
// Set particle styles particle.style.backgroundColor = color; particle.style.setProperty('--tx', `${tx}px`); particle.style.setProperty('--ty', `${ty}px`); particle.style.animation = `lock-particle ${duration}s ease-out forwards`;
particleContainer.appendChild(particle); }
// Remove particle container after animation completes setTimeout(() => { document.body.removeChild(particleContainer); }, 1000); }
// Function to darken a color by a certain percentage function darkenColor(color, percent) { const hex = color.replace('#', ''); let r = parseInt(hex.substr(0, 2), 16); let g = parseInt(hex.substr(2, 2), 16); let b = parseInt(hex.substr(4, 2), 16);
// Darken each channel by the percentage r = Math.max(0, Math.floor(r * (1 - percent / 100))); g = Math.max(0, Math.floor(g * (1 - percent / 100))); b = Math.max(0, Math.floor(b * (1 - percent / 100)));
// Convert back to hex const darkenedHex = '#' + r.toString(16).padStart(2, '0') + g.toString(16).padStart(2, '0') + const darkenedHex = '#' + r.toString(16).padStart(2, '0') + g.toString(16).padStart(2, '0') + b.toString(16).padStart(2, '0');
return darkenedHex; }
// Change dice color function function changeDiceColor(color) { console.log(`changeDiceColor called with color: ${color}`); const faces = document.querySelectorAll('.dice-face'); console.log(`Found ${faces.length} dice faces`); let dotColor, borderColor;
// Special cases for high contrast if (color.toUpperCase() === '#FFFFFF') { // White dice - use black dots and light gray borders dotColor = '#000000';6 行未改动 // Calculate darker color for dots and borders (40% darker for more contrast) dotColor = darkenColor(color, 40); borderColor = darkenColor(color, 30); // Slightly lighter border than dots }
faces.forEach(face => { // Set face background color face.style.backgroundColor = color;
// Set face border color face.style.border = `3px solid ${borderColor}`;
// Set dots color const dots = face.querySelectorAll('.dot'); dots.forEach(dot => { dot.style.backgroundColor = dotColor; // Add slight border to dots for better definition dot.style.border = color.toUpperCase() === '#FFFFFF' ? '1px solid rgba(0, 0, 0, 0.2)' : '1px solid rgba(0, 0, 0, 0.1)'; }); }); }
// Update tier multiplier display function updateTierMultiplierDisplay() { const display = document.getElementById('tier-multiplier-display'); if (display) { display.innerHTML = `Tier Multiplier: <span class="font-semibold text-purple-500">×${(1 + currentTier / 10).toFixed(1)}</span>`; } }
// Event listener for roll button rollButton.addEventListener('click', rollDice);
// Event listener for upgrade button upgradeButton.addEventListener('click', upgradeDice);
// Event listeners for item buttons useDoublePointsButton.addEventListener('click', useDoublePointsCard); useNoPenaltyButton.addEventListener('click', useNoPenaltyCard); useLuckyStreakButton.addEventListener('click', useLuckyStreakCard);
// Event listeners for color options colorOptions.forEach((option, index) => { // Disable all color options except the first one initially if (index !== 0) { option.disabled = true; option.classList.add('locked'); }
option.addEventListener('click', () => { // Check if game is over if (gameOver) { showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500'); return; }
// Check if color is unlocked if (option.disabled) { showGameMessage('You need to upgrade to unlock this dice color!', 'text-orange-500'); return; }
const color = option.getAttribute('data-color'); changeDiceColor(color);
// Add active state to selected color colorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary')); option.classList.add('ring-2', 'ring-offset-2', 'ring-primary');
// Update current tier to the selected color's tier currentTier = index; currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`; updateTierMultiplierDisplay(); }); });
// Initialize dice on page load window.addEventListener('DOMContentLoaded', () => { console.log('=== DOMContentLoaded event fired ===');
// Check if elements exist console.log('Checking if elements exist before initialization:'); console.log('best-record-display exists:', !!document.getElementById('best-record-display')); console.log('best-record-value exists:', !!document.getElementById('best-record-value'));
console.log('DOM fully loaded'); initializeDice();
// Set default color (first option) if (colorOptions.length > 0) { const defaultColor = colorOptions[0].getAttribute('data-color'); changeDiceColor(defaultColor); colorOptions[0].classList.add('ring-2', 'ring-offset-2', 'ring-primary'); }
// Initialize current tier display currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;
// Initialize tier multiplier display updateTierMultiplierDisplay();
// Initialize items display updateItemsDisplay();
// Initialize upgrade cost display updateUpgradeCostDisplay();
// Show welcome message setTimeout(() => { showGameMessage('Welcome! Roll the dice to earn points and upgrade your dice!', 'text-blue-500'); }, 1000); });
// Also try initializing on window load window.addEventListener('load', () => { console.log('Window loaded'); // If dice not already initialized, try again if (diceElement.children.length === 0) { console.log('Dice not initialized, trying again...'); initializeDice(); } });
// Game Rules Modal Functionality (function() { // Get elements const rulesButton = document.getElementById('game-rules-button'); const rulesModal = document.getElementById('game-rules-modal'); const closeButtons = rulesModal.querySelectorAll('.close-button'); const modalBackdrop = rulesModal.querySelector('.modal-backdrop'); const modalContent = rulesModal.querySelector('.modal-content');
// Function to prevent background scrolling function preventBackgroundScroll(event) { // Allow scrolling inside the modal content if (modalContent.contains(event.target)) { // Check if we're at the top or bottom of the modal content const isAtTop = modalContent.scrollTop === 0; const isAtBottom = modalContent.scrollTop + modalContent.clientHeight >= modalContent.scrollHeight;
// Prevent scrolling if at the top and scrolling up, or at the bottom and scrolling down if ((isAtTop && event.deltaY < 0) || (isAtBottom && event.deltaY > 0)) { event.preventDefault(); } } else { // Prevent scrolling outside the modal content event.preventDefault(); } }
// Function to open modal function openModal() { // Add event listeners to prevent background scrolling document.addEventListener('wheel', preventBackgroundScroll, { passive: false }); document.addEventListener('touchmove', preventBackgroundScroll, { passive: false });
// Add open class to trigger animations rulesModal.classList.add('modal-open');
// Show the modal rulesModal.style.visibility = 'visible'; }
// Function to close modal function closeModal() { // Remove open class to trigger animations rulesModal.classList.remove('modal-open');
// Remove event listeners that prevent background scrolling document.removeEventListener('wheel', preventBackgroundScroll); document.removeEventListener('touchmove', preventBackgroundScroll);
// Hide the modal after animation completes setTimeout(() => { rulesModal.style.visibility = 'hidden'; }, 300); }
// Add event listeners if (rulesButton) { rulesButton.addEventListener('click', openModal); }
// Close buttons closeButtons.forEach(button => { button.addEventListener('click', closeModal); });
// Close when clicking outside the modal content modalBackdrop.addEventListener('click', closeModal);
// Close when pressing Escape key document.addEventListener('keydown', (event) => { if (event.key === 'Escape' && rulesModal.classList.contains('modal-open')) { closeModal(); } });
// Add hover effect to rules button if (rulesButton) { rulesButton.addEventListener('mouseenter', () => { rulesButton.classList.add('scale-105'); });
rulesButton.addEventListener('mouseleave', () => { rulesButton.classList.remove('scale-105'); }); }
// Add click effect to close buttons closeButtons.forEach(button => { button.addEventListener('mousedown', () => { button.classList.add('scale-95'); });
button.addEventListener('mouseup', () => { button.classList.remove('scale-95'); });
button.addEventListener('mouseleave', () => { button.classList.remove('scale-95'); }); });16 行未改动 <!-- Tailwind CSS v3 --> <script src="https://cdn.tailwindcss.com"></script> <!-- Font Awesome --> <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script> tailwind.config = { theme: { extend: {20 行未改动 } } } </script>
<style type="text/tailwindcss"> @layer utilities { .preserve-3d { transform-style: preserve-3d;36 行未改动 .record-animation { animation: record-shine 2s ease-in-out; } }
@keyframes trophy-pulse { 0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(1); } }
@keyframes record-shine { 0% { box-shadow: 0 0 0 0 rgba(251, 191, 36, 0.7); } 70% { box-shadow: 0 0 0 15px rgba(251, 191, 36, 0); } 100% { box-shadow: 0 0 0 0 rgba(251, 191, 36, 0); } }
/* Custom styles for 3D dice */ .dice-scene { perspective: 1500px; width: 120px; height: 120px; display: flex; align-items: center; justify-content: center; }
.dice-container { position: relative; width: 100px; height: 100px; transform-style: preserve-3d; transition: transform 1s ease-out; transform: rotateX(20deg) rotateY(20deg); }
.dice-face { position: absolute; width: 100px; height: 100px;4 行未改动 align-items: center; justify-content: center; box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1); }
/* Dice face positions */ .face-1 { transform: translateZ(50px); } .face-2 { transform: rotateY(90deg) translateZ(50px); } .face-3 { transform: rotateY(180deg) translateZ(50px); } .face-4 { transform: rotateY(-90deg) translateZ(50px); } .face-5 { transform: rotateX(90deg) translateZ(50px); } .face-6 { transform: rotateX(-90deg) translateZ(50px); }
/* Dots on dice faces */ .dot { position: absolute; width: 20px; height: 20px; border-radius: 50%; background-color: black; }
/* Dot positions for each face */ .face-1 .dot { top: 40px; left: 40px; }
.face-2 .dot:nth-child(1) { top: 20px; left: 20px; } .face-2 .dot:nth-child(2) { top: 60px; left: 60px; }
.face-3 .dot:nth-child(1) { top: 20px; left: 20px; } .face-3 .dot:nth-child(2) { top: 40px; left: 40px; } .face-3 .dot:nth-child(3) { top: 60px; left: 60px; }
.face-4 .dot:nth-child(1) { top: 20px; left: 20px; } .face-4 .dot:nth-child(2) { top: 20px; left: 60px; } .face-4 .dot:nth-child(3) { top: 60px; left: 20px; } .face-4 .dot:nth-child(4) { top: 60px; left: 60px; }
.face-5 .dot:nth-child(1) { top: 20px; left: 20px; } .face-5 .dot:nth-child(2) { top: 20px; left: 60px; } .face-5 .dot:nth-child(3) { top: 40px; left: 40px; } .face-5 .dot:nth-child(4) { top: 60px; left: 20px; } .face-5 .dot:nth-child(5) { top: 60px; left: 60px; }
.face-6 .dot:nth-child(1) { top: 20px; left: 20px; } .face-6 .dot:nth-child(2) { top: 20px; left: 60px; } .face-6 .dot:nth-child(3) { top: 40px; left: 20px; } .face-6 .dot:nth-child(4) { top: 40px; left: 60px; } .face-6 .dot:nth-child(5) { top: 60px; left: 20px; } .face-6 .dot:nth-child(6) { top: 60px; left: 60px; }
.dice-result { transition: all 0.5s ease-out; }
/* Fixed height for result display to prevent page jumping */ #result-display { height: 40px; display: flex; align-items: center; justify-content: center; }
.result-shine { animation: shine 0.5s ease-out; }
.score-increase { color: #10b981; animation: scorePopup 1s ease-out; }
.score-decrease { color: #ef4444; animation: scorePopup 1s ease-out; }
.score-neutral { color: #6b7280; animation: scorePopup 1s ease-out; }
/* Locked color option styles */ .color-option.locked { position: relative; opacity: 0.5; cursor: not-allowed; }
.color-option.locked::after { content: '\f023'; /* Lock icon from Font Awesome */ font-family: 'FontAwesome'; position: absolute;2 行未改动 transform: translate(-50%, -50%); color: rgba(0, 0, 0, 0.5); font-size: 16px; }
@keyframes shine { 0% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4); }3 行未改动 100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); } }
@keyframes scorePopup { 0% { transform: translateY(0); opacity: 0;6 行未改动 transform: translateY(-20px); opacity: 0; } }
.confetti { position: absolute; width: 10px; height: 10px; background-color: #f97316; animation: confetti-fall 3s ease-in-out infinite; }
@keyframes confetti-fall { 0% { transform: translateY(-100vh) rotate(0deg); opacity: 1;2 行未改动 transform: translateY(100vh) rotate(720deg); opacity: 0; } }
@keyframes lock-particle { 0% { transform: translate(0, 0); opacity: 1;2 行未改动 transform: translate(var(--tx), var(--ty)); opacity: 0; } }
/* Game Rules Modal Styles */ .game-rules-modal { position: fixed; top: 0;7 行未改动 padding: 1rem; visibility: hidden; box-sizing: border-box; }
.game-rules-modal .modal-backdrop { position: absolute; top: 0; left: 0;2 行未改动 opacity: 0; visibility: hidden; transition: all 0.3s ease-out; }
.game-rules-modal .modal-content { position: relative; background-color: white; border-radius: 1rem;2 行未改动 width: 500px; overflow-y: auto; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); }
.game-rules-modal .modal-header { padding: 1.5rem; border-bottom: 1px solid #e5e7eb; display: flex; justify-content: space-between; align-items: center; }
.game-rules-modal .modal-title { font-size: 1.25rem; font-weight: 600; color: #1e293b; }
.game-rules-modal .close-button { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #6b7280; transition: color 0.2s ease-in-out; }
.game-rules-modal .close-button:hover { color: #1e293b; }
.game-rules-modal .modal-body { padding: 1.5rem; line-height: 1.6; color: #374151; }
.game-rules-modal .modal-body h3 { font-size: 1.1rem; font-weight: 600; margin-top: 1.5rem; margin-bottom: 0.75rem; color: #1e293b; }
.game-rules-modal .modal-body p { margin-bottom: 1rem; }
.game-rules-modal .modal-body ul { margin-bottom: 1rem; padding-left: 1.5rem; list-style-type: disc; }
.game-rules-modal .modal-body li { margin-bottom: 0.5rem; }
.game-rules-modal .modal-body strong { font-weight: 600; color: #1e293b; }
.game-rules-modal .modal-footer { padding: 1rem 1.5rem; border-top: 1px solid #e5e7eb; display: flex; justify-content: flex-end; }
.game-rules-modal .modal-footer button { padding: 0.5rem 1rem; border-radius: 0.5rem; background-color: #3b82f6; color: white; font-size: 1.25rem; font-weight: 500; transition: background-color 0.2s ease-in-out; }
.game-rules-modal .modal-footer button:hover { background-color: #2563eb; }
/* Game Rules Button Styles */ .game-rules-button { position: fixed; top: 1rem;9 行未改动 gap: 0.5rem; transition: all 0.2s ease-in-out; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); }
.game-rules-button:hover { background-color: #2563eb; transform: translateY(-2px); }
.game-rules-button i { font-size: 1.1rem; } </style>3 行未改动 <button id="game-rules-button" class="game-rules-button"> <i class="fa fa-book"></i> <span>Game Rules</span> </button>
<!-- Game Rules Modal --> <div id="game-rules-modal" class="game-rules-modal"> <div class="modal-backdrop"></div> <div class="modal-content">2 行未改动 <button class="close-button">×</button> </div> <div class="modal-body"> <p>Welcome to the 3D Dice Game! This is an exciting game that combines luck, strategy, and upgrading mechanics. Below is the complete game rules explanation:</p>
<h3>Basic Gameplay</h3> <ul> <li>Click the "Roll Dice" button to roll the dice</li> <li>The dice will randomly show a number between 1-6</li> <li>Gain or lose points based on the number rolled</li> <li>The goal is to obtain the highest tier "Unique" dice</li> </ul>
<h3>Score System</h3> <ul> <li>Rolling 1 or 2: Lose 1 point (multiplier not applied)</li> <li>Rolling 3: No points gained or lost</li> <li>Rolling 4: Gain 1 point</li> <li>Rolling 5: Gain 2 points</li> <li>Rolling 6: Gain 3 points</li> </ul>
<h3>Dice Upgrade System</h3> <p>There are 10 different tiers of dice in the game, from common to rare:</p> <ul> <li><strong>Empty</strong> (Initial) - Score Multiplier ×1.0</li>7 行未改动 <li><strong>Super</strong> - Score Multiplier ×1.8</li> <li><strong>Unique</strong> - Score Multiplier ×1.9</li> </ul> <p>Each upgrade costs (5 + current tier) points. For example, upgrading from Empty (tier 0) costs 5 points, upgrading from Common (tier 1) costs 6 points, and so on. After upgrading, you can choose to use the new dice or continue using the old one.</p>
<h3>Item System</h3> <p>When upgrading, you have a chance to obtain item cards that can be used at critical moments:</p> <ul> <li><strong>Double Points Card</strong>: Doubles the points from one roll</li> <li><strong>No Penalty Card</strong>: Prevents point loss when rolling 1 or 2</li> <li><strong>Lucky Streak Card</strong>: Next 3 rolls of 1 or 2 won't count towards your total roll count</li> </ul> <p>Items can be stockpiled and each card can only be used once. Double Points Cards and No Penalty Cards can be used simultaneously. Lucky Streak Cards make your next 3 rolls of 1 or 2 not count towards your total roll count, giving you a chance to recover from bad luck.</p>
<h3>Game Rules</h3> <ul> <li>Initial score is 10 points</li> <li>Score multiplier changes based on the current dice tier being used</li> <li>Game over when score is less than 0</li> <li>Game victory when obtaining the Unique dice</li> <li>Unlocked dice colors can be switched at any time</li> </ul>
<h3>Operation Tips</h3> <ul> <li>Click on dice color options to switch the dice being used</li> <li>Click the "Upgrade Dice" button to upgrade your dice (requires 5 points)</li> <li>Click the "Use" button next to item cards to use them</li> <li>Press the ESC key to close the rules window</li> </ul>
<p>Good luck, and may you successfully obtain the highest tier Unique dice!</p> </div> <div class="modal-footer"> <button class="close-button">Got it</button> </div> </div> </div>
<div class="w-full max-w-md mx-auto glass-effect rounded-2xl p-6 dice-shadow relative z-10"> <h1 class="text-3xl font-bold text-center text-dark mb-8">3D Dice Roll</h1>
<div class="flex flex-col items-center justify-center mb-8"> <!-- Dice display area --> <div id="dice-display" class="w-48 h-48 flex items-center justify-center mb-4 bg-gray-100 rounded-lg"> <!-- Dice scene for 3D perspective -->2 行未改动 <!-- Dice faces will be inserted here by JavaScript --> </div> </div> </div>
<!-- Result display --> <div id="result-display" class="text-2xl font-bold text-center mb-4 hidden"> Result: <span id="result-value" class="text-primary">0</span> </div>
<!-- Score display --> <div id="score-display" class="text-xl font-bold text-center mb-2"> Score: <span id="score-value" class="text-secondary">10</span> <span id="score-change" class="ml-2 text-sm font-normal"></span> </div>
<!-- Roll count display --> <div id="roll-count-display" class="text-lg font-medium text-center mb-4"> Rolls: <span id="roll-count-value" class="text-gray-700">0</span> </div>
<!-- Roll button --> <button id="roll-button" class="bg-primary hover:bg-blue-600 text-white font-bold py-3 px-6 rounded-full transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-blue-300 focus:ring-opacity-50"> <i class="fa fa-random mr-2"></i> Roll Dice </button>
<!-- Upgrade button and current tier display --> <div class="flex flex-col items-center mt-4"> <div id="current-tier" class="text-sm text-gray-600 mb-2"> Current Dice: <span class="font-semibold text-primary">Empty</span>4 行未改动 <button id="upgrade-button" class="bg-secondary hover:bg-orange-600 text-white font-bold py-2 px-4 rounded-full transition-all duration-300 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-orange-300 focus:ring-opacity-50"> <i class="fa fa-arrow-up mr-1"></i> Upgrade Dice <span id="upgrade-cost">(Cost: 5)</span> </button> </div>
<!-- Game message display --> <div id="game-message" class="mt-4 text-center font-semibold hidden"></div>
<!-- Items display --> <div id="items-display" class="mt-6 grid grid-cols-2 gap-4"> <div class="bg-white rounded-lg p-3 dice-shadow"> <div class="flex items-center justify-between">9 行未改动 </div> </div> <p class="text-xs text-gray-500 mt-1">Doubles your score change for one roll</p> </div>
<div class="bg-white rounded-lg p-3 dice-shadow"> <div class="flex items-center justify-between"> <div class="flex items-center"> <i class="fa fa-shield text-blue-500 text-xl mr-2"></i>7 行未改动 </div> </div> <p class="text-xs text-gray-500 mt-1">Prevents score loss when rolling 1 or 2</p> </div>
<div class="bg-white rounded-lg p-3 dice-shadow"> <div class="flex items-center justify-between"> <div class="flex items-center"> <i class="fa fa-star text-yellow-500 text-xl mr-2"></i>8 行未改动 </div> <p class="text-xs text-gray-500 mt-1">Next 3 rolls of 1 or 2 won't count towards your total roll count</p> </div> </div>
<!-- Free rolls indicator --> <div id="free-rolls-indicator" class="mt-3 text-center hidden"> <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800"> <i class="fa fa-star mr-1" style="color: #f59e0b;"></i> <span>Free Rolls: <span id="free-rolls-count">0</span></span> </span> </div>
<!-- Active item indicator --> <div id="active-item-indicator" class="mt-3 text-center hidden"> <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"> <i id="active-item-icon" class="mr-1"></i> <span id="active-item-text">Active Item: None</span> </span> </div> </div>
<!-- Dice color selection --> <div class="mb-8"> <label class="block text-sm font-medium text-gray-700 mb-2">Dice Rarity</label> <div class="grid grid-cols-5 gap-4">48 行未改动 <span class="text-xs text-center text-gray-600">Unique</span> </div> </div> </div>
<!-- History log --> <div class="bg-white rounded-lg p-4"> <h2 class="text-lg font-semibold text-center mb-2">Roll History</h2> <div id="history-container" class="h-64 overflow-y-auto">7 行未改动 </ul> </div> </div> </div>
<footer class="mt-8 text-center text-gray-600 text-sm"> <p>Click the button to roll the dice and see the result!</p> </footer>
<script> // Set up global error handler window.addEventListener('error', function(event) { console.error('Global error caught:', event.error);
// Try to get roll button element const rollButton = document.getElementById('roll-button'); if (rollButton && rollButton.disabled) { console.warn('Error during dice roll, re-enabling button'); rollButton.disabled = false; rollButton.classList.remove('opacity-70', 'cursor-not-allowed');
// Try to show error message const gameMessage = document.getElementById('game-message'); if (gameMessage) { gameMessage.textContent = 'An error occurred. Please try again.'; gameMessage.className = 'mt-4 text-center font-semibold text-red-500'; gameMessage.classList.remove('hidden'); } } });
// DOM elements const diceElement = document.getElementById('dice'); const rollButton = document.getElementById('roll-button'); const resultDisplay = document.getElementById('result-display');8 行未改动 const gameMessageDisplay = document.getElementById('game-message'); const rollCountDisplay = document.getElementById('roll-count-display'); const rollCountValue = document.getElementById('roll-count-value'); const upgradeCost = document.getElementById('upgrade-cost');
// Item related DOM elements const doublePointsCount = document.getElementById('double-points-count'); const noPenaltyCount = document.getElementById('no-penalty-count'); const luckyStreakCount = document.getElementById('lucky-streak-count');2 行未改动 const useLuckyStreakButton = document.getElementById('use-lucky-streak'); const activeItemIndicator = document.getElementById('active-item-indicator'); const freeRollsIndicator = document.getElementById('free-rolls-indicator'); const freeRollsCountElement = document.getElementById('free-rolls-count');
// Game state let currentScore = 10; // Initial score let currentTier = 0; // Initial dice tier (0 = Empty) let gameOver = false; // Game over flag let rollCount = 0; // Number of dice rolls let luckyRollsRemaining = 0; // Number of lucky rolls remaining let isRolling = false; // Whether dice is currently rolling
// Item system let doublePointsCards = 0; // Number of double points cards let noPenaltyCards = 0; // Number of no penalty cards let luckyStreakCards = 0; // Number of lucky streak cards let freeRolls = 0; // Number of free rolls available let activeItems = { // Currently active items double: 0, // Number of active double points cards noPenalty: false // Whether no penalty card is active };
// Dice tiers configuration const diceTiers = [ { name: 'Empty', color: '#FFFFFF' }, { name: 'Common', color: '#7EEF6D' },5 行未改动 { name: 'Ultra', color: '#ff2b75' }, { name: 'Super', color: '#2bffa3' }, { name: 'Unique', color: '#555555' } ];
// Initialize 3D dice function initializeDice() { console.log('Initializing dice...'); // Create 6 faces for the dice const faces = [1, 2, 3, 4, 5, 6];
faces.forEach(faceNumber => { const face = document.createElement('div'); face.className = `dice-face face-${faceNumber}`;
// Add dots to the face based on the number for (let i = 0; i < faceNumber; i++) { const dot = document.createElement('div'); dot.className = 'dot'; face.appendChild(dot); }
diceElement.appendChild(face); console.log(`Added face ${faceNumber}`); });
console.log('Dice initialized with faces:', diceElement.children.length);
// Set initial position to show face 1 clearly diceElement.style.transform = 'rotateX(0deg) rotateY(0deg)'; }
// Get random rotation values for the dice function getRandomRotation() { // Determine which face we want to show const targetFace = Math.floor(Math.random() * 6) + 1;
// Get current rotation from dice element const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); const matrix = new DOMMatrix(currentTransform);
// Extract current rotation angles let currentX = 0, currentY = 0;
// If transform is not identity matrix, extract rotation if (currentTransform !== 'none') { // Calculate rotation from matrix currentX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI); currentY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI); }
// Set target rotation based on target face // These values are precisely calibrated to show the correct face let targetX = 0, targetY = 0; switch(targetFace) {21 行未改动 targetX = 90; targetY = 0; break; }
// Calculate the shortest path to the target rotation // This prevents large rotation values from accumulating let diffX = targetX - currentX; let diffY = targetY - currentY;
// Normalize the difference to the range [-180, 180] to find the shortest path diffX = ((diffX + 180) % 360) - 180; diffY = ((diffY + 180) % 360) - 180;
// Add multiple full rotations for spinning effect (2-4 full rotations) const fullRotations = 2 + Math.floor(Math.random() * 3);
// Calculate final rotation with full spins // We add full rotations in the direction of the shortest path const spinDirectionX = diffX >= 0 ? 1 : -1; const spinDirectionY = diffY >= 0 ? 1 : -1;
const finalX = currentX + diffX + spinDirectionX * fullRotations * 360; const finalY = currentY + diffY + spinDirectionY * fullRotations * 360;
// Add a tiny bit of randomness to make it look more natural // But not enough to change which face is visible const randomX = (Math.random() - 0.5) * 2; const randomY = (Math.random() - 0.5) * 2;
return { x: finalX + randomX, y: finalY + randomY, targetFace: targetFace // Return the target face so we don't have to recalculate it }; }
// Roll the dice function function rollDice() { // Check if game is over if (gameOver) { showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500'); return; }
// Check if there are free rolls available const isFreeRoll = freeRolls > 0;
// Check if in lucky streak mode const isLuckyRoll = luckyRollsRemaining > 0;
// Increment roll count only if not a free roll (lucky rolls will be handled based on result) if (!isFreeRoll) { rollCount++; console.log(`Roll count: ${rollCount}`);2 行未改动 freeRolls--; updateFreeRollsDisplay(); console.log(`Free roll used. Remaining free rolls: ${freeRolls}`); }
// Update roll count display if (rollCountValue) { rollCountValue.textContent = rollCount; }
console.log('Rolling dice...'); console.log('Button state before disable:', rollButton.disabled);
// Set rolling state and disable button during animation isRolling = true; rollButton.disabled = true; rollButton.classList.add('opacity-70', 'cursor-not-allowed');
// Disable other interactive elements during roll upgradeButton.disabled = true; upgradeButton.classList.add('opacity-70', 'cursor-not-allowed'); useDoublePointsButton.disabled = true; useNoPenaltyButton.disabled = true; useLuckyStreakButton.disabled = true;
// Disable color options during roll colorOptions.forEach(option => { option.disabled = true; });
console.log('Button state after disable:', rollButton.disabled);
// Hide result display resultDisplay.classList.add('hidden');
// Reset dice display height - use Tailwind class instead of inline style const diceDisplay = document.getElementById('dice-display'); if (diceDisplay) { // Ensure the height class is applied to prevent layout shifts during animation diceDisplay.classList.add('h-48'); }
try { // Set animation duration const duration = 2000; // Fixed duration for consistent experience
// Get random rotation values for the final position const rotationData = getRandomRotation(); console.log('Rotation data:', rotationData); console.log('Target face:', rotationData.targetFace);
// Animate the dice using JavaScript for more control animateDice(duration, rotationData, { isFreeRoll, isLuckyRoll });
// Set a safety timeout to ensure button is re-enabled even if something goes wrong setTimeout(() => { if (rollButton.disabled) { console.warn('Safety timeout: Re-enabling roll button');6 行未改动 enableRollButton(); showGameMessage('An error occurred during the dice roll. Please try again.', 'text-red-500'); } }
// Animate the dice with spin animation function animateDice(duration, rotationData, rollContext) { console.log('Animate dice called with rotationData:', rotationData); console.log('Roll context:', rollContext); const startTime = performance.now(); const finalRotation = rotationData;
// Get current rotation from dice element const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); const matrix = new DOMMatrix(currentTransform);
// Extract current rotation angles let startX = 0, startY = 0;
// If transform is not identity matrix, extract rotation if (currentTransform !== 'none') { // Calculate rotation from matrix startX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI); startY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI); }
// Function to handle each animation frame function animate(currentTime) { const elapsedTime = currentTime - startTime; const progress = Math.min(elapsedTime / duration, 1);
// Apply easing function for smooth, natural animation const easedProgress = easeOutCubic(progress);
// Calculate current rotation - smooth continuous rotation const currentX = startX + (finalRotation.x - startX) * easedProgress; const currentY = startY + (finalRotation.y - startY) * easedProgress;
// Spin animation: rotate in place diceElement.style.transform = `rotateX(${currentX}deg) rotateY(${currentY}deg)`;
// Continue animation if not complete if (progress < 1) { requestAnimationFrame(animate); } else { // Animation complete - ensure we're at the exact target rotation diceElement.style.transform = `rotateX(${finalRotation.x}deg) rotateY(${finalRotation.y}deg)`;
// Show result after a delay to ensure rotation is complete and CSS has applied console.log('Animation complete, waiting before finalizing...'); setTimeout(() => { // Double-check that the transform has been applied3 行未改动 finalizeAnimation(finalRotation, rollContext); }, 600); } }
// Start the animation requestAnimationFrame(animate); }
// Helper function to normalize angles to the range [-180, 180] function normalizeAngle(angle) { angle = angle % 360; if (angle > 180) angle -= 360; if (angle < -180) angle += 360; return angle; }
// Easing function for smooth, natural animation with gentle acceleration and deceleration // Uses a cubic easing function that starts slow, accelerates, then slows down at the end function easeOutCubic(t) { return 1 - Math.pow(1 - t, 3); }
// Calculate score change based on dice roll result function calculateScoreChange(result) { let baseChange = 0;
switch(result) { case 1: case 2: baseChange = -1;12 行未改动 break; default: baseChange = 0; }
// Apply current tier multiplier // If losing points (baseChange < 0), use multiplier of 1 instead of tier multiplier const tierMultiplier = 1 + currentTier / 10; let finalChange;
if (baseChange < 0) { // For point loss, use multiplier of 1 regardless of tier finalChange = baseChange * 1; } else { // For point gain or neutral, use tier multiplier finalChange = baseChange * tierMultiplier; }
// Apply active item effects const itemsUsed = { double: activeItems.double, noPenalty: activeItems.noPenalty };
// Apply no penalty card first if (activeItems.noPenalty && baseChange < 0) { finalChange = 0; }
// Apply double points cards if (activeItems.double > 0) { finalChange = finalChange * Math.pow(2, activeItems.double); }
// Round to 2 decimal places to avoid floating point precision issues finalChange = Math.round(finalChange * 100) / 100;
return { baseChange: baseChange, finalChange: finalChange, itemsUsed: itemsUsed, tierMultiplier: tierMultiplier }; }
// Enable roll button function enableRollButton() { console.log('Button state before enable:', rollButton.disabled);
// Directly enable the button rollButton.disabled = false; rollButton.classList.remove('opacity-70', 'cursor-not-allowed');
// Re-enable other interactive buttons based on their conditions updateUpgradeCostDisplay(); // This will enable/disable upgrade button based on score updateItemsDisplay(); // This will enable/disable item buttons based on availability
console.log('Button state after enable:', rollButton.disabled);
// Double-check and force enable if needed if (rollButton.disabled) { console.warn('Forcing button enable'); setTimeout(() => {2 行未改动 console.log('Button state after forced enable:', rollButton.disabled); }, 100); } }
// Finalize the animation and show result function finalizeAnimation(rotationData, rollContext) { console.log('=== Finalize animation called ==='); console.log('Current time:', new Date().toISOString().split('T')[1]); console.log('Rotation data:', rotationData); console.log('Roll context:', rollContext);
const finalRotation = rotationData; const isFreeRoll = rollContext && rollContext.isFreeRoll || false; const isLuckyRoll = rollContext && rollContext.isLuckyRoll || false;
// Use the target face directly instead of recalculating const result = finalRotation.targetFace; console.log(`Final result: ${result} (should show face ${result})`);
// Verify dice is in the correct position const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); console.log('Current dice transform:', currentTransform);
// Show result display console.log('Showing result display...'); resultValue.textContent = result; resultDisplay.classList.remove('hidden');
// Add shine effect to result resultDisplay.classList.add('result-shine'); setTimeout(() => { resultDisplay.classList.remove('result-shine'); }, 500);
// Calculate and update score console.log('Calculating score change...'); const scoreChangeData = calculateScoreChange(result); console.log('Score change data:', scoreChangeData);
currentScore += scoreChangeData.finalChange; console.log('Updated score:', currentScore);
// Update score display with animation console.log('Updating score display...'); updateScoreDisplay(scoreChangeData);
// Enable button console.log('Enabling roll button...'); enableRollButton();
// Add to history - include whether it was a free roll or lucky roll addToHistory(result, scoreChangeData, isFreeRoll, isLuckyRoll);
// Check if reached the Unique dice if (currentTier === diceTiers.length - 1) { showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500'); gameOver = true; createConfetti(); }
// Handle lucky roll logic if (luckyRollsRemaining > 0) { // Decrement remaining lucky rolls luckyRollsRemaining--;
// If rolled 1 or 2, decrement roll count if (result === 1 || result === 2) { rollCount--; console.log(`Lucky roll: Reverted roll count to ${rollCount}`);
// Update roll count display if (rollCountValue) { rollCountValue.textContent = rollCount; }
// Show message showGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500'); }
// Update lucky rolls display updateLuckyRollsDisplay();
// If no more lucky rolls, show message if (luckyRollsRemaining === 0) { setTimeout(() => { showGameMessage('Lucky Streak ended!', 'text-yellow-500'); }, 1000); } }
// Create confetti effect if result is 6 if (result === 6) { createConfetti(); }
// Debug: log final state console.log(`Final precise rotation: X=${finalRotation.x}°, Y=${finalRotation.y}°`); console.log(`Displayed result: ${result}`); console.log(`Score change: ${scoreChangeData.finalChange}, Current score: ${currentScore}`); console.log('=== finalizeAnimation completed ==='); }
// Update score display with animation function updateScoreDisplay(scoreChangeData) { console.log('=== updateScoreDisplay called ==='); console.log('Score change data:', scoreChangeData);
const change = scoreChangeData.finalChange; const baseChange = scoreChangeData.baseChange; const itemsUsed = scoreChangeData.itemsUsed; const tierMultiplier = scoreChangeData.tierMultiplier;
console.log('Change:', change, 'Base change:', baseChange, 'Items used:', itemsUsed);
// Update the score value - round to 2 decimal places currentScore = Math.round(currentScore * 100) / 100; scoreValue.textContent = currentScore; console.log('Score value updated to:', currentScore);
// Clear previous score change display scoreChange.textContent = ''; scoreChange.className = 'ml-2 text-sm font-normal'; console.log('Cleared previous score change display');
// Show score change with appropriate styling if (change > 0) { scoreChange.textContent = `+${change}`; scoreChange.classList.add('score-increase');6 行未改动 scoreChange.textContent = `±0`; scoreChange.classList.add('score-neutral'); console.log('Score neutral'); }
// Show item effect message if items were used if (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) { // Create container for item effects const itemEffectsContainer = document.createElement('div'); itemEffectsContainer.className = 'flex flex-wrap gap-2 mt-1';
// Add tier multiplier effect if applicable if (tierMultiplier !== 1) { const tierEffect = document.createElement('div'); tierEffect.className = 'text-xs text-purple-500'; tierEffect.textContent = `Tier Multiplier ×${tierMultiplier.toFixed(1)}!`; itemEffectsContainer.appendChild(tierEffect); }
// Add no penalty effect if (itemsUsed.noPenalty) { const noPenaltyEffect = document.createElement('div'); noPenaltyEffect.className = 'text-xs text-blue-500'; noPenaltyEffect.textContent = `No Penalty! (Score protected from ${baseChange < 0 ? baseChange : 0} loss)`; itemEffectsContainer.appendChild(noPenaltyEffect); }
// Add double points effect if (itemsUsed.double > 0) { const doublePointsEffect = document.createElement('div'); doublePointsEffect.className = 'text-xs text-green-500';
// Calculate multiplier const multiplier = Math.pow(2, itemsUsed.double); let calculationText = `${baseChange}`;
// Apply tier multiplier for display let displayChange = baseChange * tierMultiplier;
// Apply no penalty first for display if (itemsUsed.noPenalty && baseChange < 0) { displayChange = 0; calculationText = `(${baseChange} × ${tierMultiplier.toFixed(1)} → 0)`; } else if (tierMultiplier !== 1) { calculationText = `(${baseChange} × ${tierMultiplier.toFixed(1)} = ${displayChange.toFixed(2)})`; }
// Show multiplication steps if multiple double cards used if (itemsUsed.double > 1) { for (let i = 0; i < itemsUsed.double; i++) { calculationText += ` × 2`; } calculationText += ` = ${(displayChange * multiplier).toFixed(2)}`; } else { calculationText += ` × 2 = ${(displayChange * multiplier).toFixed(2)}`; }
doublePointsEffect.textContent = `Double Points ×${itemsUsed.double}! (${calculationText})`; itemEffectsContainer.appendChild(doublePointsEffect); }
// Add to score display scoreDisplay.appendChild(itemEffectsContainer);
// Remove after animation setTimeout(() => { scoreDisplay.removeChild(itemEffectsContainer); }, 1000); }
// Reset score change display after animation completes setTimeout(() => { scoreChange.textContent = ''; }, 1000);
// Clear active items after score update console.log('Checking if items need to be cleared...'); if (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) { console.log('Clearing active items...'); clearActiveItems(); console.log('Updating items display...'); updateItemsDisplay(); }
// Check game state after score update console.log('Checking game state...'); checkGameState();
// Update upgrade button state updateUpgradeCostDisplay();
console.log('=== updateScoreDisplay completed ==='); }
// Handle dice upgrade function upgradeDice() { // Check if game is already over if (gameOver) { showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500'); return; }
// Check if already at maximum tier if (currentTier >= diceTiers.length - 1) { // If not already game over, end the game with win condition if (!gameOver) {3 行未改动 showGameMessage('Congratulations! You already have the Unique dice!', 'text-green-500'); } return; }
// Calculate required score for upgrade (5 + currentTier) const requiredScore = 5 + currentTier;
// Check if enough score to upgrade if (currentScore < requiredScore) { showGameMessage(`Not enough score to upgrade! Need ${requiredScore} points.`, 'text-orange-500'); // Add shake animation to score display2 行未改动 scoreDisplay.classList.remove('animate-shake'); }, 500); return; }
// Deduct score for upgrade currentScore -= requiredScore; // Round to 2 decimal places currentScore = Math.round(currentScore * 100) / 100;
// Update score display scoreValue.textContent = currentScore; showScoreChange(-requiredScore);
// Increase tier currentTier++;
// Update current tier display currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;
// Update tier multiplier display updateTierMultiplierDisplay();
// Unlock the new dice color unlockDiceColor(currentTier);
// Update color selection UI updateColorSelection(currentTier);
// Update upgrade cost display updateUpgradeCostDisplay();
// Change to the new dice color console.log(`Changing dice color to ${diceTiers[currentTier].color} (${diceTiers[currentTier].name})`); changeDiceColor(diceTiers[currentTier].color);
// Check if this upgrade reached the maximum tier checkGameState();
// Randomly get an item const itemChance = Math.random(); if (itemChance < 0.30) { // 30% chance to get double points card doublePointsCards++;3 行未改动 luckyStreakCards++; } else { // 30% chance to get nothing // Do nothing }
// Update items display to show new counts updateItemsDisplay();
// Update items display updateItemsDisplay();
// Check if reached the Unique dice if (currentTier === diceTiers.length - 1) { showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500'); gameOver = true; createConfetti(); }
// Handle lucky roll logic if (luckyRollsRemaining > 0) { // Decrement remaining lucky rolls luckyRollsRemaining--;
// If rolled 1 or 2, decrement roll count if (result === 1 || result === 2) { rollCount--; console.log(`Lucky roll: Reverted roll count to ${rollCount}`);
// Update roll count display if (rollCountValue) { rollCountValue.textContent = rollCount; }
// Show message showGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500'); }
// Update lucky rolls display updateLuckyRollsDisplay();
// If no more lucky rolls, show message if (luckyRollsRemaining === 0) { setTimeout(() => { showGameMessage('Lucky Streak ended!', 'text-yellow-500'); }, 1000); } }
// Add to history addToHistory('UPGRADE', -requiredScore);
// Add item to history if obtained if (itemChance < 0.30) { addToHistory('ITEM', 'Double Points Card'); } else if (itemChance < 0.60) { addToHistory('ITEM', 'No Penalty Card'); } else if (itemChance < 0.70) { addToHistory('ITEM', 'Lucky Streak Card'); }
// Check game state after upgrade checkGameState(); }
// Show score change temporarily function showScoreChange(change) { scoreChange.textContent = change > 0 ? `+${change}` : change; scoreChange.className = `ml-2 text-sm font-normal ${change > 0 ? 'score-increase' : 'score-decrease'}`;
setTimeout(() => { scoreChange.textContent = ''; }, 1000); }
// Unlock a dice color option function unlockDiceColor(tierIndex) { if (tierIndex >= 0 && tierIndex < colorOptions.length) { const option = colorOptions[tierIndex];5 行未改动 option.classList.remove('locked'); }, 300); } }
// Show game message function showGameMessage(message, className) { gameMessageDisplay.textContent = message; gameMessageDisplay.className = `mt-4 text-center font-semibold ${className}`; gameMessageDisplay.classList.remove('hidden');
// Hide message after 3 seconds setTimeout(() => { if (!gameOver) { gameMessageDisplay.classList.add('hidden'); } }, 3000); }
// Check game state (win/lose conditions) function checkGameState() { console.log('=== checkGameState called ==='); console.log('Current score:', currentScore, 'Game over:', gameOver);
// Check if score is negative (lose condition) if (currentScore < 0 && !gameOver) { console.log('Score is negative, ending game...'); gameOver = true; endGame(false); }
// Check if reached Unique dice (win condition) if (currentTier === diceTiers.length - 1 && !gameOver) { console.log('Reached Unique dice, ending game...'); gameOver = true; endGame(true);
// Check if this is a new record setTimeout(() => { checkWinRecord(); }, 1000); }
// Check if score is low (warning) if (currentScore >= 0 && currentScore <= 5 && !gameOver) { showLowScoreWarning(); }
console.log('=== checkGameState completed ==='); }
// Update items display function updateItemsDisplay() { // Update counts doublePointsCount.textContent = doublePointsCards; noPenaltyCount.textContent = noPenaltyCards; luckyStreakCount.textContent = luckyStreakCards;
// Enable/disable buttons based on available items useDoublePointsButton.disabled = doublePointsCards <= 0 || gameOver; useNoPenaltyButton.disabled = noPenaltyCards <= 0 || activeItems.noPenalty || gameOver; useLuckyStreakButton.disabled = luckyStreakCards <= 0 || gameOver;
// Update free rolls display updateFreeRollsDisplay();
// Update lucky rolls display updateLuckyRollsDisplay(); }
// Update free rolls display function updateFreeRollsDisplay() { if (freeRolls > 0) { freeRollsCountElement.textContent = freeRolls; freeRollsIndicator.classList.remove('hidden'); } else { freeRollsIndicator.classList.add('hidden'); } }
// Update upgrade cost display and button state function updateUpgradeCostDisplay() { if (currentTier >= diceTiers.length - 1) { // Already at maximum tier2 行未改动 upgradeButton.classList.add('opacity-70', 'cursor-not-allowed'); } else { const requiredScore = 5 + currentTier; upgradeCost.textContent = `(Cost: ${requiredScore})`;
// Update button state based on available score if (currentScore >= requiredScore && !gameOver) { upgradeButton.disabled = false; upgradeButton.classList.remove('opacity-70', 'cursor-not-allowed');2 行未改动 upgradeButton.classList.add('opacity-70', 'cursor-not-allowed'); } } }
// Use double points card function useDoublePointsCard() { if (doublePointsCards > 0 && !gameOver) { activeItems.double++; doublePointsCards--;
// Update UI updateItemsDisplay(); showActiveItemIndicator();
// Show message showGameMessage('Double Points Card activated! Next roll will double your score change.', 'text-green-500'); } }
// Use no penalty card function useNoPenaltyCard() { if (noPenaltyCards > 0 && !activeItems.noPenalty && !gameOver) { activeItems.noPenalty = true; noPenaltyCards--;
// Update UI updateItemsDisplay(); showActiveItemIndicator();
// Show message showGameMessage('No Penalty Card activated! Next roll won\'t lose points.', 'text-blue-500'); } }
// Use lucky streak card function useLuckyStreakCard() { if (luckyStreakCards > 0 && !gameOver) { luckyRollsRemaining = 3; luckyStreakCards--;
// Update UI updateItemsDisplay(); updateLuckyRollsDisplay();
// Show message showGameMessage('Lucky Streak Card activated! Next 3 rolls of 1 or 2 won\'t count!', 'text-yellow-500');
// Add to history addToHistory('ITEM USE', 'Lucky Streak Card'); } }
// Update lucky rolls display function updateLuckyRollsDisplay() { if (luckyRollsRemaining > 0) { // Check if indicator exists, if not create it let luckyRollsIndicator = document.getElementById('lucky-rolls-indicator'); if (!luckyRollsIndicator) { luckyRollsIndicator = document.createElement('div'); luckyRollsIndicator.id = 'lucky-rolls-indicator'; luckyRollsIndicator.className = 'mt-3 text-center';
// Insert after free rolls indicator const freeRollsIndicator = document.getElementById('free-rolls-indicator'); if (freeRollsIndicator) { freeRollsIndicator.parentNode.insertBefore(luckyRollsIndicator, freeRollsIndicator.nextSibling);10 行未改动 } } } }
// Update content luckyRollsIndicator.innerHTML = ` <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800"> <i class="fa fa-star mr-1" style="color: #f59e0b;"></i> <span>Lucky Rolls: <span id="lucky-rolls-count">${luckyRollsRemaining}</span> (1-2 won't count)</span> </span> `;
// Show indicator luckyRollsIndicator.classList.remove('hidden'); } else { // Remove indicator if exists2 行未改动 luckyRollsIndicator.classList.add('hidden'); } } }
// Show active item indicator function showActiveItemIndicator() { // Clear previous content activeItemIndicator.innerHTML = '';
// Check if any items are active if (activeItems.double === 0 && !activeItems.noPenalty) { activeItemIndicator.className = 'mt-3 text-center hidden'; return; }
// Create container for active items const itemsContainer = document.createElement('div'); itemsContainer.className = 'flex flex-wrap justify-center gap-2';
// Add double points cards indicator if (activeItems.double > 0) { const doublePointsIndicator = document.createElement('span'); doublePointsIndicator.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800';2 行未改动 <span>Double Points ×${activeItems.double}</span> `; itemsContainer.appendChild(doublePointsIndicator); }
// Add no penalty card indicator if (activeItems.noPenalty) { const noPenaltyIndicator = document.createElement('span'); noPenaltyIndicator.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800';2 行未改动 <span>No Penalty</span> `; itemsContainer.appendChild(noPenaltyIndicator); }
// Add indicators to container activeItemIndicator.appendChild(itemsContainer); activeItemIndicator.className = 'mt-3 text-center'; }
// Clear active items function clearActiveItems() { activeItems = { double: 0, noPenalty: false }; showActiveItemIndicator(); }
// End the game and display appropriate message function endGame(isWin) { console.log('=== endGame called ==='); console.log('Is win:', isWin, 'Current score:', currentScore);
// Disable all interactive elements rollButton.disabled = true; upgradeButton.disabled = true; rollButton.classList.add('opacity-70', 'cursor-not-allowed'); upgradeButton.classList.add('opacity-70', 'cursor-not-allowed');
// Disable all interactive elements colorOptions.forEach(option => { option.disabled = true; option.classList.add('opacity-50', 'cursor-not-allowed'); });
// Disable item buttons useDoublePointsButton.disabled = true; useNoPenaltyButton.disabled = true; useLuckyStreakButton.disabled = true;
// Hide active indicators activeItemIndicator.classList.add('hidden'); const luckyRollsIndicator = document.getElementById('lucky-rolls-indicator'); if (luckyRollsIndicator) { luckyRollsIndicator.classList.add('hidden'); }
// Create game over message element const gameOverMessage = document.createElement('div'); gameOverMessage.className = `mt-4 p-4 rounded-lg text-center font-bold ${isWin ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`;
// Format final score to 2 decimal places const formattedScore = currentScore.toFixed(2);
if (isWin) { gameOverMessage.innerHTML = ` <div class="text-2xl mb-2">Congratulations!</div> <p>You won the game!</p>24 行未改动 <i class="fa fa-refresh mr-1"></i> Play Again </button> `; }
// Add restart button event listener gameOverMessage.querySelector('#play-again').addEventListener('click', () => { window.location.reload(); });
// Replace game message display with game over message const gameMessageContainer = gameMessageDisplay.parentElement; gameMessageContainer.replaceChild(gameOverMessage, gameMessageDisplay); gameMessageDisplay = gameOverMessage;
// Add game end to history addToHistory(isWin ? 'GAME WIN' : 'GAME OVER', 0);
console.log('=== endGame completed ==='); }
// Show warning when score is low function showLowScoreWarning() { // Only show warning if not already showing if (gameMessageDisplay.classList.contains('hidden')) { showGameMessage('Warning: Low score! Risk of game over.', 'text-orange-500'); } }
// Update color selection UI to show the currently selected color function updateColorSelection(selectedIndex) { // Remove active state from all color options colorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary'));
// Add active state to the selected color option if (selectedIndex >= 0 && selectedIndex < colorOptions.length) { colorOptions[selectedIndex].classList.add('ring-2', 'ring-offset-2', 'ring-primary'); } }
// Add result to history function addToHistory(result, scoreChangeData, isFreeRoll = false, isLuckyRoll = false) { const now = new Date(); const timeString = now.toLocaleTimeString();
// Determine score change display and color let scoreChangeText = ''; let scoreChangeClass = ''; let actionText = '';
if (result === 'UPGRADE') { actionText = 'Upgraded dice'; scoreChangeText = `${scoreChangeData}`; scoreChangeClass = 'text-red-500';8 行未改动 } else { const scoreChange = scoreChangeData.finalChange; const baseChange = scoreChangeData.baseChange; const itemsUsed = scoreChangeData.itemsUsed;
actionText = `Rolled a <span class="font-bold text-primary">${result}</span>`;
// Add free roll indicator if applicable if (isFreeRoll) { actionText += ` <span class="text-yellow-500">(Free Roll)</span>`; }
// Add lucky roll indicator if applicable if (isLuckyRoll) { actionText += ` <span class="text-yellow-500">(Lucky Roll)</span>`; }
// Add item effect indicators if applicable const activeItemsText = []; if (itemsUsed && itemsUsed.double > 0) { activeItemsText.push(`<span class="text-green-500">(Double Points ×${itemsUsed.double})</span>`); } if (itemsUsed && itemsUsed.noPenalty) { activeItemsText.push(`<span class="text-blue-500">(No Penalty)</span>`); }
if (activeItemsText.length > 0) { actionText += ` ${activeItemsText.join(' ')}`; }
if (scoreChange > 0) { scoreChangeText = `+${scoreChange}`; scoreChangeClass = 'text-green-500'; } else if (scoreChange < 0) {2 行未改动 } else { scoreChangeText = '±0'; scoreChangeClass = 'text-gray-500'; }
// Show base change if different from final change (items were used) if ((itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) && baseChange !== scoreChange) { scoreChangeText += ` <span class="text-xs">(Base: ${baseChange > 0 ? '+' : ''}${baseChange})</span>`; } }
const listItem = document.createElement('li'); listItem.className = 'py-1 border-b border-gray-100 grid grid-cols-3 gap-2 items-center'; listItem.innerHTML = ` <span class="col-span-1 text-gray-500">${timeString}</span> <span class="col-span-1">${actionText}</span> <span class="col-span-1 text-right font-medium ${scoreChangeClass}">${scoreChangeText}</span> `;
historyList.prepend(listItem);
// Keep only last 10 history items if (historyList.children.length > 10) { historyList.removeChild(historyList.lastChild); }
// Ensure scroll is at the bottom const historyContainer = document.getElementById('history-container'); if (historyContainer) { historyContainer.scrollTop = historyContainer.scrollHeight; } }
// Create confetti effect function createConfetti() { const confettiContainer = document.createElement('div'); confettiContainer.className = 'fixed inset-0 pointer-events-none overflow-hidden'; document.body.appendChild(confettiContainer);
// Create 50 confetti pieces for (let i = 0; i < 50; i++) { const confetti = document.createElement('div'); confetti.className = 'confetti';
// Random position const posX = Math.random() * 100; const delay = Math.random() * 3; const duration = 3 + Math.random() * 2;
// Random colors const colors = ['#3b82f6', '#f97316', '#10b981', '#ef4444', '#8b5cf6']; const color = colors[Math.floor(Math.random() * colors.length)];
confetti.style.left = `${posX}%`; confetti.style.backgroundColor = color; confetti.style.animationDelay = `${delay}s`; confetti.style.animationDuration = `${duration}s`;
confettiContainer.appendChild(confetti); }
// Remove confetti container after animation completes setTimeout(() => { document.body.removeChild(confettiContainer); }, 5000); }
// Create particle effect on lock function createLockParticles(lockElement) { // Get lock element position const rect = lockElement.getBoundingClientRect(); const centerX = rect.left + rect.width / 2; const centerY = rect.top + rect.height / 2;
// Create particle container const particleContainer = document.createElement('div'); particleContainer.className = 'absolute pointer-events-none'; particleContainer.style.left = `${centerX}px`; particleContainer.style.top = `${centerY}px`; particleContainer.style.transform = 'translate(-50%, -50%)'; document.body.appendChild(particleContainer);
// Create 15 particles for (let i = 0; i < 15; i++) { const particle = document.createElement('div'); particle.className = 'lock-particle';
// Random direction and distance const angle = Math.random() * Math.PI * 2; const distance = 10 + Math.random() * 20; const tx = Math.cos(angle) * distance; const ty = Math.sin(angle) * distance;
// Random color (use the color of the unlocked dice) const color = lockElement.style.backgroundColor;
// Random animation duration const duration = 0.5 + Math.random() * 0.5;
// Set particle styles particle.style.backgroundColor = color; particle.style.setProperty('--tx', `${tx}px`); particle.style.setProperty('--ty', `${ty}px`); particle.style.animation = `lock-particle ${duration}s ease-out forwards`;
particleContainer.appendChild(particle); }
// Remove particle container after animation completes setTimeout(() => { document.body.removeChild(particleContainer); }, 1000); }
// Function to darken a color by a certain percentage function darkenColor(color, percent) { const hex = color.replace('#', ''); let r = parseInt(hex.substr(0, 2), 16); let g = parseInt(hex.substr(2, 2), 16); let b = parseInt(hex.substr(4, 2), 16);
// Darken each channel by the percentage r = Math.max(0, Math.floor(r * (1 - percent / 100))); g = Math.max(0, Math.floor(g * (1 - percent / 100))); b = Math.max(0, Math.floor(b * (1 - percent / 100)));
// Convert back to hex const darkenedHex = '#' + r.toString(16).padStart(2, '0') + g.toString(16).padStart(2, '0') + const darkenedHex = '#' + r.toString(16).padStart(2, '0') + g.toString(16).padStart(2, '0') + b.toString(16).padStart(2, '0');
return darkenedHex; }
// Change dice color function function changeDiceColor(color) { console.log(`changeDiceColor called with color: ${color}`); const faces = document.querySelectorAll('.dice-face'); console.log(`Found ${faces.length} dice faces`); let dotColor, borderColor;
// Special cases for high contrast if (color.toUpperCase() === '#FFFFFF') { // White dice - use black dots and light gray borders dotColor = '#000000';6 行未改动 // Calculate darker color for dots and borders (40% darker for more contrast) dotColor = darkenColor(color, 40); borderColor = darkenColor(color, 30); // Slightly lighter border than dots }
faces.forEach(face => { // Set face background color face.style.backgroundColor = color;
// Set face border color face.style.border = `3px solid ${borderColor}`;
// Set dots color const dots = face.querySelectorAll('.dot'); dots.forEach(dot => { dot.style.backgroundColor = dotColor; // Add slight border to dots for better definition dot.style.border = color.toUpperCase() === '#FFFFFF' ? '1px solid rgba(0, 0, 0, 0.2)' : '1px solid rgba(0, 0, 0, 0.1)'; }); }); }
// Update tier multiplier display function updateTierMultiplierDisplay() { const display = document.getElementById('tier-multiplier-display'); if (display) { display.innerHTML = `Tier Multiplier: <span class="font-semibold text-purple-500">×${(1 + currentTier / 10).toFixed(1)}</span>`; } }
// Event listener for roll button rollButton.addEventListener('click', rollDice);
// Event listener for upgrade button upgradeButton.addEventListener('click', upgradeDice);
// Event listeners for item buttons useDoublePointsButton.addEventListener('click', useDoublePointsCard); useNoPenaltyButton.addEventListener('click', useNoPenaltyCard); useLuckyStreakButton.addEventListener('click', useLuckyStreakCard);
// Event listeners for color options colorOptions.forEach((option, index) => { // Disable all color options except the first one initially if (index !== 0) { option.disabled = true; option.classList.add('locked'); }
option.addEventListener('click', () => { // Check if game is over if (gameOver) { showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500'); return; }
// Check if color is unlocked if (option.disabled) { showGameMessage('You need to upgrade to unlock this dice color!', 'text-orange-500'); return; }
const color = option.getAttribute('data-color'); changeDiceColor(color);
// Add active state to selected color colorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary')); option.classList.add('ring-2', 'ring-offset-2', 'ring-primary');
// Update current tier to the selected color's tier currentTier = index; currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`; updateTierMultiplierDisplay(); }); });
// Initialize dice on page load window.addEventListener('DOMContentLoaded', () => { console.log('=== DOMContentLoaded event fired ===');
// Check if elements exist console.log('Checking if elements exist before initialization:'); console.log('best-record-display exists:', !!document.getElementById('best-record-display')); console.log('best-record-value exists:', !!document.getElementById('best-record-value'));
console.log('DOM fully loaded'); initializeDice();
// Set default color (first option) if (colorOptions.length > 0) { const defaultColor = colorOptions[0].getAttribute('data-color'); changeDiceColor(defaultColor); colorOptions[0].classList.add('ring-2', 'ring-offset-2', 'ring-primary'); }
// Initialize current tier display currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;
// Initialize tier multiplier display updateTierMultiplierDisplay();
// Initialize items display updateItemsDisplay();
// Initialize upgrade cost display updateUpgradeCostDisplay();
// Show welcome message setTimeout(() => { showGameMessage('Welcome! Roll the dice to earn points and upgrade your dice!', 'text-blue-500'); }, 1000); });
// Also try initializing on window load window.addEventListener('load', () => { console.log('Window loaded'); // If dice not already initialized, try again if (diceElement.children.length === 0) { console.log('Dice not initialized, trying again...'); initializeDice(); } });
// Game Rules Modal Functionality (function() { // Get elements const rulesButton = document.getElementById('game-rules-button'); const rulesModal = document.getElementById('game-rules-modal'); const closeButtons = rulesModal.querySelectorAll('.close-button'); const modalBackdrop = rulesModal.querySelector('.modal-backdrop'); const modalContent = rulesModal.querySelector('.modal-content');
// Function to prevent background scrolling function preventBackgroundScroll(event) { // Allow scrolling inside the modal content if (modalContent.contains(event.target)) { // Check if we're at the top or bottom of the modal content const isAtTop = modalContent.scrollTop === 0; const isAtBottom = modalContent.scrollTop + modalContent.clientHeight >= modalContent.scrollHeight;
// Prevent scrolling if at the top and scrolling up, or at the bottom and scrolling down if ((isAtTop && event.deltaY < 0) || (isAtBottom && event.deltaY > 0)) { event.preventDefault(); } } else { // Prevent scrolling outside the modal content event.preventDefault(); } }
// Function to open modal function openModal() { // Add event listeners to prevent background scrolling document.addEventListener('wheel', preventBackgroundScroll, { passive: false }); document.addEventListener('touchmove', preventBackgroundScroll, { passive: false });
// Add open class to trigger animations rulesModal.classList.add('modal-open');
// Show the modal rulesModal.style.visibility = 'visible'; }
// Function to close modal function closeModal() { // Remove open class to trigger animations rulesModal.classList.remove('modal-open');
// Remove event listeners that prevent background scrolling document.removeEventListener('wheel', preventBackgroundScroll); document.removeEventListener('touchmove', preventBackgroundScroll);
// Hide the modal after animation completes setTimeout(() => { rulesModal.style.visibility = 'hidden'; }, 300); }
// Add event listeners if (rulesButton) { rulesButton.addEventListener('click', openModal); }
// Close buttons closeButtons.forEach(button => { button.addEventListener('click', closeModal); });
// Close when clicking outside the modal content modalBackdrop.addEventListener('click', closeModal);
// Close when pressing Escape key document.addEventListener('keydown', (event) => { if (event.key === 'Escape' && rulesModal.classList.contains('modal-open')) { closeModal(); } });
// Add hover effect to rules button if (rulesButton) { rulesButton.addEventListener('mouseenter', () => { rulesButton.classList.add('scale-105'); });
rulesButton.addEventListener('mouseleave', () => { rulesButton.classList.remove('scale-105'); }); }
// Add click effect to close buttons closeButtons.forEach(button => { button.addEventListener('mousedown', () => { button.classList.add('scale-95'); });
button.addEventListener('mouseup', () => { button.classList.remove('scale-95'); });
button.addEventListener('mouseleave', () => { button.classList.remove('scale-95'); }); });9 行未改动