版本比较
3D Dice Roll
正文
增加 5320 行删除 648 行
1123455678910111213141516171819201121222324252 行未改动2829303122323334353620 行未改动5758596051616263646530 行未改动96979899901001011021031041051061071081091001101111121131141151161171181091191201211221234 行未改动1281291301311221321331341351361371381391301401411421431441451461471481391491501511421521531541451551561571581491591601611621631541641651661671681691601701711721731741751761671771781791801711811821831841751851861871881891801901911921931941851951961971981991902002012022032042052061972072082092102112 行未改动2142152162172082182192202212223 行未改动2262272282292202302312322332346 行未改动2412422432442352452462472482492502512522432532542552562572 行未改动2602612622632542642652662672682 行未改动2712722732742652752762772782797 行未改动2872882892902812912922932942952 行未改动2982993003012923023033043053062 行未改动3093103113123033133143153163173183193203113213223233243253263173273283293303313323333343353263363373383393303403413423433443453363463473483493503513523533443543553563573483583593603613623633543643653663673583683693703713723633733743753763773783793703803813823833843853863873883793893903913923833933943953963979 行未改动4074084094104014114124134144154064164174184194203 行未改动4244254264274184284294304314322 行未改动4354364374384294394404414424434444454464374474484494504514524534544554464564574584594607 行未改动4684694704714624724734744754764774784794804714814824834844854864874884894804904914924934944954964974884984995005015025035045054965065075084995095105115125132 行未改动5165175185195105205215225235245155255265275285295305215315325335345355265365375385395405315415425435445454 行未改动5505515525535445545555565475575585595605619 行未改动5715725735745655755765775785797 行未改动5875885895905815915925935945958 行未改动60460560660759860860961061161261361461560661661761861962062162262362461562562662762862948 行未改动6786796806816726826836846856866876886896906816916926936946956966976986996907007017027037047057066977077087097107117127137147157167077177187197207218 行未改动7307317327337247347357367377382 行未改动7417427437447357457467477487497507417517527537547557567577587597607517617627637647655 行未改动77177277377476577577677777877978077178178278378477578578678778878979079178279279379479578679679778879879980080179280280380480580679780780880981080181181281380481481581681781881982081182182282382482521 行未改动8478488498508418518528538548558468568578588598508608618628538638648658668678588688698708618718728738748758668768778788798808818828738838848858868878888898908818918928938848948958968978982 行未改动9019029039048959059069079089099009109119129039139149159169079179189099199209219129229239249259169269279289299309219319329339249349359369379387 行未改动94694794894994095095195295395495594695695795895995096096196295396396496596696796896996097097197297397496597597697796897897998098197298298398497598598698798898999099198299299399499599699799899999010001001100210039941004100510061007100810091010101110021012101310141015101610171008101810191020102110121022102310241025102612 行未改动10391040104110421033104310441045104610471038104810491050105110521053105410551046105610571058105910601061105210621063106410651066105710671068106910701071106210721073107410651075107610771078107910801081108210731083108410851086107710871088108910901081109110921083109310941095109610972 行未改动110011011102110310941104110511061107110811091100111011111112111311041114111511161117110811181119112011211122112311141124112511261127112811191129113011311122113211331134113511261136113711381139113011401141114211331143114411451146114711481149114011501151115211531154114511551156115711581159116011611152116211631164116511661157116711681169117011711162117211731164117411751176117711781169117911801181118211831174118411851186118711886 行未改动11951196119711981189119912001201120212031204119512051206120712081209121012111212120312131214121512161217121812191220121112211222122312241225121612261227122812291220123012311232122312331234123512361237123812391240123112411242124312441245124612471248124912501241125112521253125412451255125612571248125812591260126112621263125412641265126612671268125912691270127112721273127412751276127712681278127912801281128212831274128412851286128712881289129012911282129212931294129512963 行未改动130013011302130312941304130513061297130713081309131013112 行未改动1314131513161317130813181319132013211322131313231324132513261317132713281329132013301331133213231333133413351326133613371338132913391340134113321342134313441335134513461347134813391349135013511342135213531354135513563 行未改动1360136113621363135413641365136613571367136813691360137013711372137313741375137613671377137813791370138013811382138313841385138613871388137913891390139113921383139313941395139613971388139813991400140114021393140314041405140614075 行未改动14131414141514161407141714181419142014211422141314231424142514261427142814291430142114311432143314341435142614361437143814391440144114421433144314441445144614471448144914401450145114521453145414451455145614571448145814591460146114621463146414551465146614671468146914601470147114721473146414741475147614771478147914801481148214831474148414851486148714882 行未改动14911492149314941485149514961497149814991500149115011502150315041495150515061507150815091500151015111512151315141515150615161517151815191510152015211522152315241515152515261527152815291530152115311532153315241534153515361527153715381539154015411532154215431544154515461537154715481549155015511552154315531554155515561547155715581559156015612 行未改动15641565156615671558156815691570157115722 行未改动157515761577157815691579158015811582158315741584158515861587158815891590159115921583159315941595159615971588159815991600160116021603159416041605160616071608160916001610161116121613160416141615161616071617161816191620161116211622162316141624162516261627162824 行未改动16531654165516561647165716581659166016611652166216631664166516661657166716681669166016701671167216631673167416751676167716781679168016711681168216831684168516761686168716881689169016911682169216931694169516961687169716981699170017011692170217031704170517068 行未改动17151716171717181709171917201711172117221723172417251716172617271728172917301731173217331734172517351736173717381729173917401741174217432 行未改动1746174717481749174017501751175217531754175517461756175717581759176017611762175317631764175517651766176717681769177017611771177217731774177517761767177717781779178017811772178217831784178517861777178717881789179017811791179217931794179517861796179717981789179918001801180218031804179518051806180718081809181018111802181218131814181518161817181818191810182018211822182318241815182518261827182818291830182118311832183318241834183518361827183718381839184018411842183318431844184518361846184718481849185018511842185218531854185518561857185818491859186018611862186318541864186518561857185818661867186818691860187018711872186318731874187518761877187818791870188018811882188318846 行未改动1891189218931894188518951896189718981889189919001901189219021903190419051906190719081909191019111902191219131914191519161917191819191910192019211922191319231924192519161926192719281929193019211931193219331934193519361937193819291939194019411942194319441945193619461947194819491950195119421952195319541945195519561957195819491959196019611962196319641965195619661967196819691970196119711972197319741975197619771968197819791980197119811982198319741984198519861977198719881989198019901991199219931994199519861996199719981999200020012002200320042005199620062007200820092010201120122013201420052015201620172018201920202021202220132023202420252026202720282029203020312032202320332034203520362037203820292039204020412032204220432044204520362046204720482049205020412051205220532054204520552056205720582059206020512061206220632064206520562066206720682069207020612071207220732064207420752076207720782079208020712081208220832084208520862077208720882089209020912082209220932094209520962097208820982099210021012092210221032104210521064 行未改动21112112211321142105211521162117211821193 行未改动212321242125212621172127212821292130213120 行未改动215221532154215521462156215721582159216036 行未改动2197219821992200219122012202220322042205220621972207220822092210221122122203221322142215221622172218221922202221222222132223222422252226222722282229223022312222223222332234223522364 行未改动2241224222432244223522452246224722482249225022512252224322532254225522562257225822592260226122522262226322642255226522662267225822682269227022712262227222732274227522762267227722782279228022812282227322832284228522862287228822892280229022912292229322842294229522962297228822982299230023012302229323032304230523062307229823082309231023112312230323132314231523162317231823192310232023212322232323242 行未改动23272328232923302321233123322333233423353 行未改动23392340234123422333234323442345234623476 行未改动23542355235623572348235823592360236123622363236423652356236623672368236923702 行未改动23732374237523762367237723782379238023812 行未改动23842385238623872378238823892390239123927 行未改动24002401240224032394240424052406240724082 行未改动24112412241324142405241524162417241824192 行未改动242224232424242524162426242724282429243024312432243324242434243524362437243824392430244024412442244324442445244624472448243924492450245124522443245324542455245624572458244924592460246124622463246424652466245724672468246924702461247124722473247424752476246724772478247924802471248124822483248424852476248624872488248924902491249224832493249424952496249724982499250025012502249325032504250525062497250725082509251025119 行未改动25212522252325242515252525262527252825292520253025312532253325343 行未改动25382539254025412532254225432544254525462 行未改动254925502551255225432553255425552556255725582559256025512561256225632564256525662567256825692560257025712572257325747 行未改动25822583258425852576258625872588258925902591259225932594258525952596259725982599260026012602260325942604260526062607260826092610261126022612261326142615261626172618261926102620262126222613262326242625262626272 行未改动263026312632263326242634263526362637263826292639264026412642264326442635264526462647264826492640265026512652265326542645265526562657265826594 行未改动266426652666266726582668266926702661267126722673267426759 行未改动26852686268726882679268926902691269226937 行未改动27012702270327042695270527062707270827098 行未改动2718271927202721271227222723272427252726272727282729272027302731273227332734273527362737273827292739274027412742274348 行未改动27922793279427952786279627972798279928002801280228032804279528052806280728082809281028112812281328042814281528162817281828192820281128212822282328242825282628272828282928302821283128322833283428358 行未改动28442845284628472838284828492850285128522 行未改动285528562857285828492859286028612862286328642865285628662867286828692870287128722873287428752866287628772878287928805 行未改动28862887288828892880289028912892289328942895288628962897289828992890290029012902290329042905290628972907290829092910290129112912290329132914291529162907291729182919292029212912292229232924292529162926292729282919292929302931293229332934293529262936293729382939294021 行未改动2962296329642965295629662967296829692970296129712972297329742965297529762977296829782979298029812982297329832984298529762986298729882989299029812991299229932994299529962997298829982999300030013002300330043005299630063007300829993009301030113002301230133014301530162 行未改动301930203021302230133023302430253026302730183028302930303021303130323033303430253035303630273037303830393030304030413042304330343044304530463047304830393049305030513042305230533054305530566 行未改动30633064306530663057306730683069307030713072306330733074307530763067307730783079307030803081308230833084308530863077308730883089309030913082309230933094308530953096309730983089309931003101309231023103310431053106310731083099310931103111311231133 行未改动31173118311931203111312131223123312431153125312631273128312931303131313231233133313431353136313731383129313931403141314231333143314431453146314712 行未改动31603161316231633154316431653166316731683159316931703171317231733174317531763167317731783179318031813182317331833184318531863187317831883189319031913192318331933194319531863196319731983199320032013202320331943204320532063207319832083209321032113202321232133204321432153216321732182 行未改动3221322232233224321532253226322732283229323032313222323232333234323532263236323732383239323032403241324232433244323532453246324732483249325032413251325232533254325532463256325732583249325932603261326232533263326432653266325732673268326932603270327132723273327432753276326732773278327932803281327232823283328432853286327732873288328932903291328232923293329432953286329632973298328932993300330133023303330433053306329733073308330933103311330233123313331433153316331733183309331933203321332233233314332433253326332733283319332933303321333133323333333433353326333633373338333933403331334133423343334433456 行未改动33523353335433553346335633573358335933603361335233623363336433653366336733683369336033703371337233733374337533763377336833783379338033813382337333833384338533863377338733883389338033903391339233933394339533963397338833983399340034013402340334043405340634073398340834093410341134023412341334143405341534163417341834193420341134213422342334243425341634263427342834293430343134323433343434253435343634373438342934393440344134323442344334443435344534463447344834493450345134523443345334543455345634573 行未改动346134623463346434553465346634673458346834693470347134722 行未改动3475347634773478346934793480348134823483347434843485348634873478348834893490348134913492349334843494349534963487349734983499349035003501350234933503350435053496350635073508350935003510351135123503351335143515351635173 行未改动3521352235233524351535253526352735183528352935303521353135323533353435353536353735283538353935403541354235333543354435453546354735383548354935503551355235433553355435553556354735573558355935503560356135623563356435653566356735583568356935703561357135723573357435753576357735783579357035803581358235833574358435853586358735883579358935903591359235933584359435953596359735985 行未改动360436053606360735983608360936103611361236133604361436153616361736183619362036213612362236233624362536263617362736283629363036313632363336243634363536363637363836393630364036413642364336443645363636463647364836493650364136513652365336443654365536563657365836593660365136613662366336643665365636663667366836593669367036713672366336733674367536763677367836793680368136823673368336843685368636872 行未改动36903691369236933684369436953696369736982 行未改动370137023703370436953705370637073708370937103701371137123713371437053715371637173718371937103720372137223723372437253716372637273728372937203730373137323733373437253735373637373738373937403731374137423743374437353745374637473738374837493750375137523743375337543755375637573758375937603761376237533763376437653766376710 行未改动37783779378037813772378237833784378537863787378837893780379037913792379337942 行未改动37973798379938003791380138023803380438053796380638073808380938103811380238123813381438153806381638173818381938202 行未改动38233824382538263817382738283829383038312 行未改动38343835383638373828383838393840384138423833384338443845384638473848384938503851384238523853385438553856384738573858385938603861386238533863386438653866386738683859386938703871387238733864387438753876387738783879388038713881388238833884387538853886388738783888388938903891389224 行未改动39173918391939203911392139223923392439253916392639273928392939303921393139323933392439343935393639273937393839393940394139423943394439353945394639473948394939403950395139523953395439553946395639573958395939603951396139623963396439653956396639673968396939708 行未改动39793980398139823973398339843975398539863987398839893980399039913992399339943985399539963997399839994000400140024003399440044005400640073998400840094010401140122 行未改动40154016401740184009401940204021402240234024401540254026402740284029403040314022403240334024403440354036403740384039403040404041404240434044404540364046404740484049405040414051405240534054405540464056405740584059405040604061406240634064405540654066406740584068406940704071407240734064406540664074407540764077407840794080408140824073408340844085408640874088408940904081409140924093409440954086409640974098409941004101409241024103410440954105410641074098410841094110411141124113410441144115411641074117411841194120412141224113412341244125412641274128412941204130413141324133413441254135413641274128412941374138413941404131414141424143413441444145414641474148414941504141415141524153415441556 行未改动4162416341644165415641664167416841694160417041714172416341734174417541764177417841794180418141824173418341844185418641874188418941904181419141924193418441944195419641874197419841994200420141924202420342044205420642074208420942004210421142124213421442154216420742174218421942204221422242134223422442254216422642274228422942204230423142324233423442354236422742374238423942404231424142424243424442454236424642474248423942494250425142524253425442554246425642574258424942594260426142524262426342644255426542664267425842684269427042714272427342644274427542764277427842794280428142824283427442844285428642874288428942904291429242834293429442954296429742984299430042914301430243034304430543064307430843094310430143114312431343144315431643074317431843194310432043214322432343144324432543264327432843194329433043314332432343334334433543364337433843294339434043414342434343344344434543464347434843394349435043514342435243534354435543564357435843494359436043614362436343644355436543664367436843694360437043714372437343744375436643764377437843794370438043814382438343842 行未改动4387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052访问次数 :访问次数 :。由于我极其可能会咕咕咕所以你们也可以直接把代码扔给 [AI](https://www.doubao.com/code/chat) 进行修改。
食用方法:建一个文本文档,后缀名 .html,用记事本编辑,把代码复制进去,双击运行。
更新日志:::::info[Update]{open}
- v.1.0:初版;- v.1.1:将 Lucky Streak Card 的效果改为了:接下来的 3 次投掷中,扔到 1,2 不会计入总共投掷次数。- v.1.2:修复 Lucky Streak Card 的 bug;通过修改投掷结果的出现方式,解决页面元素上下移动的问题;骰子被投掷时,原则上不能做别的动作(升级、使用技能卡);优化 Roll History,冻结表头,修改奇怪 bug。- v.1.2.1:修改了 Roll history 中升级后积分变化错误的问题。
::::
::::info[To do list]{open}- 增加一种新的技能卡。::::
:::::info[Code]{open}
::::info[v.1.0]```html```html line-numbers<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8">2 行未改动 <!-- 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'); }); });4 行未改动
```::::
::::success[v.1.1]::::info[v.1.1]```html line-numbers<!DOCTYPE html><html lang="en"><head>3 行未改动 <!-- 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'); }); });2 行未改动</body></html>```::::
::::info[v.1.2]```html line-numbers<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>3D Dice Roll Animation</title> <!-- 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: { colors: { primary: '#3b82f6', secondary: '#f97316', dark: '#1e293b', light: '#f8fafc' }, fontFamily: { sans: ['Inter', 'system-ui', 'sans-serif'], }, animation: { 'shake': 'shake 0.5s ease-in-out', }, keyframes: { shake: { '0%, 100%': { transform: 'translateX(0)' }, '25%': { transform: 'translateX(-5px)' }, '50%': { transform: 'translateX(5px)' }, '75%': { transform: 'translateX(-5px)' }, } } } } } </script>
<style type="text/tailwindcss"> @layer utilities { .preserve-3d { transform-style: preserve-3d; } .perspective { perspective: 1000px; } .backface-hidden { backface-visibility: hidden; } .dice-shadow { box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 6px -1px, rgba(0, 0, 0, 0.06) 0px 2px 4px -1px; } .glass-effect { background: rgba(255, 255, 255, 0.7); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); } .modal-backdrop { background-color: rgba(0, 0, 0, 0.5); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px); } .modal-content { transform: translateY(-20px); opacity: 0; transition: all 0.3s ease-out; } .modal-open .modal-content { transform: translateY(0); opacity: 1; } .modal-open .modal-backdrop { opacity: 1; visibility: visible; } .trophy-animation { animation: trophy-pulse 2s ease-in-out infinite; } .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; border-radius: 8px; background-color: white; border: 2px solid #f0f0f0; display: flex; 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; top: 50%; left: 50%; 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); } 70% { box-shadow: 0 0 0 10px rgba(59, 130, 246, 0); } 100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); } }
@keyframes scorePopup { 0% { transform: translateY(0); opacity: 0; } 50% { transform: translateY(-10px); opacity: 1; } 100% { 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; } 100% { transform: translateY(100vh) rotate(720deg); opacity: 0; } }
@keyframes lock-particle { 0% { transform: translate(0, 0); opacity: 1; } 100% { transform: translate(var(--tx), var(--ty)); opacity: 0; } }
/* Game Rules Modal Styles */ .game-rules-modal { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 50; display: flex; align-items: center; justify-content: center; padding: 1rem; visibility: hidden; box-sizing: border-box; }
.game-rules-modal .modal-backdrop { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; visibility: hidden; transition: all 0.3s ease-out; }
.game-rules-modal .modal-content { position: relative; background-color: white; border-radius: 1rem; max-width: 90%; max-height: 80vh; 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; right: 1rem; z-index: 40; padding: 0.5rem 1rem; border-radius: 0.5rem; background-color: #3b82f6; color: white; font-weight: 500; display: flex; align-items: center; 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></head><body class="bg-gradient-to-br from-light to-gray-200 min-h-screen flex flex-col items-center justify-center p-4 m-0"> <!-- Game Rules Button --> <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"> <div class="modal-header"> <h2 class="modal-title">3D Dice Game Rules</h2> <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> <li><strong>Common</strong> - Score Multiplier ×1.1</li> <li><strong>Unusual</strong> - Score Multiplier ×1.2</li> <li><strong>Rare</strong> - Score Multiplier ×1.3</li> <li><strong>Epic</strong> - Score Multiplier ×1.4</li> <li><strong>Legendary</strong> - Score Multiplier ×1.5</li> <li><strong>Mythic</strong> - Score Multiplier ×1.6</li> <li><strong>Ultra</strong> - Score Multiplier ×1.7</li> <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 --> <div class="dice-scene"> <div id="dice" class="dice-container"> <!-- 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> </div> <div id="tier-multiplier-display" class="text-sm text-gray-600 mb-2"> Tier Multiplier: <span class="font-semibold text-purple-500">×1.0</span> </div> <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"> <div class="flex items-center"> <i class="fa fa-plus-circle text-green-500 text-xl mr-2"></i> <span class="font-medium">Double Points Card</span> </div> <div class="flex items-center"> <span id="double-points-count" class="bg-green-100 text-green-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">0</span> <button id="use-double-points" class="bg-green-500 hover:bg-green-600 text-white text-xs py-1 px-2 rounded disabled:opacity-50 disabled:cursor-not-allowed" disabled> Use </button> </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> <span class="font-medium">No Penalty Card</span> </div> <div class="flex items-center"> <span id="no-penalty-count" class="bg-blue-100 text-blue-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">0</span> <button id="use-no-penalty" class="bg-blue-500 hover:bg-blue-600 text-white text-xs py-1 px-2 rounded disabled:opacity-50 disabled:cursor-not-allowed" disabled> Use </button> </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> <span class="font-medium">Lucky Streak Card</span> </div> <div class="flex items-center"> <span id="lucky-streak-count" class="bg-yellow-100 text-yellow-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">0</span> <button id="use-lucky-streak" class="bg-yellow-500 hover:bg-yellow-600 text-white text-xs py-1 px-2 rounded disabled:opacity-50 disabled:cursor-not-allowed" disabled> Use </button> </div> </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"> <!-- Empty --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #FFFFFF; border: 1px solid #dddddd;" data-color="#FFFFFF"></button> <span class="text-xs text-center text-gray-600">Empty</span> </div> <!-- Common --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #7EEF6D;" data-color="#7EEF6D"></button> <span class="text-xs text-center text-gray-600">Common</span> </div> <!-- Unusual --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #FFE65D;" data-color="#FFE65D"></button> <span class="text-xs text-center text-gray-600">Unusual</span> </div> <!-- Rare --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #4d52e3;" data-color="#4d52e3"></button> <span class="text-xs text-center text-gray-600">Rare</span> </div> <!-- Epic --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #861FDE;" data-color="#861FDE"></button> <span class="text-xs text-center text-gray-600">Epic</span> </div> <!-- Legendary --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #DE1F1F;" data-color="#DE1F1F"></button> <span class="text-xs text-center text-gray-600">Legendary</span> </div> <!-- Mythic --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #1fdbde;" data-color="#1fdbde"></button> <span class="text-xs text-center text-gray-600">Mythic</span> </div> <!-- Ultra --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #ff2b75;" data-color="#ff2b75"></button> <span class="text-xs text-center text-gray-600">Ultra</span> </div> <!-- Super --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #2bffa3;" data-color="#2bffa3"></button> <span class="text-xs text-center text-gray-600">Super</span> </div> <!-- Unique --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #555555;" data-color="#555555"></button> <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"> <div class="grid grid-cols-3 gap-2 text-xs font-medium text-gray-500 border-b border-gray-200 sticky top-0 bg-white z-10"> <div>Time</div> <div>Action</div> <div class="text-right">Score</div> </div> <ul id="history-list" class="text-sm"> <!-- History items will be inserted here by JavaScript --> </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'); const resultValue = document.getElementById('result-value'); const historyList = document.getElementById('history-list'); const colorOptions = document.querySelectorAll('.color-option'); const scoreDisplay = document.getElementById('score-display'); const scoreValue = document.getElementById('score-value'); const scoreChange = document.getElementById('score-change'); const upgradeButton = document.getElementById('upgrade-button'); const currentTierDisplay = document.getElementById('current-tier'); 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'); const useDoublePointsButton = document.getElementById('use-double-points'); const useNoPenaltyButton = document.getElementById('use-no-penalty'); 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' }, { name: 'Unusual', color: '#FFE65D' }, { name: 'Rare', color: '#4d52e3' }, { name: 'Epic', color: '#861FDE' }, { name: 'Legendary', color: '#DE1F1F' }, { name: 'Mythic', color: '#1fdbde' }, { 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) { case 1: // Front face (Z+) - visible when no rotation targetX = 0; targetY = 0; break; case 2: // Left face (X-) - visible when Y rotated 270 degrees targetX = 0; targetY = 270; break; case 3: // Back face (Z-) - visible when Y rotated 180 degrees targetX = 0; targetY = 180; break; case 4: // Right face (X+) - visible when Y rotated 90 degrees targetX = 0; targetY = 90; break; case 5: // Top face (Y-) - visible when X rotated -90 degrees targetX = -90; targetY = 0; break; case 6: // Bottom face (Y+) - visible when X rotated 90 degrees 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}`); } else { // Decrement free rolls count 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'); enableRollButton(); } }, duration + 1000); // Add 1 second buffer } catch (error) { console.error('Error during dice roll:', error); // Re-enable button if there's an error 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 applied const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); console.log('Current transform after animation:', currentTransform); console.log('Calling finalizeAnimation...'); 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; break; case 3: baseChange = 0; break; case 4: baseChange = 1; break; case 5: baseChange = 2; break; case 6: baseChange = 3; 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(() => { rollButton.disabled = false; rollButton.classList.remove('opacity-70', 'cursor-not-allowed'); 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'); console.log('Score increase:', change); } else if (change < 0) { scoreChange.textContent = `${change}`; scoreChange.classList.add('score-decrease'); console.log('Score decrease:', change); } else { 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) { gameOver = true; endGame(true); } else { 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 display scoreDisplay.classList.add('animate-shake'); setTimeout(() => { 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++; } else if (itemChance < 0.60) { // 30% chance to get no penalty card noPenaltyCards++; } else if (itemChance < 0.70) { // 10% chance to get lucky streak card 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]; // Show particle effect on the lock before unlocking createLockParticles(option); // Add a small delay to show the particles before unlocking setTimeout(() => { option.disabled = false; 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 tier upgradeCost.textContent = '(Max Tier)'; upgradeButton.disabled = true; 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'); } else { upgradeButton.disabled = true; 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); } else { // Fallback: insert after active item indicator const activeItemIndicator = document.getElementById('active-item-indicator'); if (activeItemIndicator) { activeItemIndicator.parentNode.insertBefore(luckyRollsIndicator, activeItemIndicator.nextSibling); } else { // Fallback: insert after items display const itemsDisplay = document.getElementById('items-display'); if (itemsDisplay) { itemsDisplay.parentNode.insertBefore(luckyRollsIndicator, itemsDisplay.nextSibling); } } } }
// 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 exists const luckyRollsIndicator = document.getElementById('lucky-rolls-indicator'); if (luckyRollsIndicator) { 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'; doublePointsIndicator.innerHTML = ` <i class="fa fa-plus-circle mr-1" style="color: #10b981;"></i> <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'; noPenaltyIndicator.innerHTML = ` <i class="fa fa-shield mr-1" style="color: #3b82f6;"></i> <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> <p>You obtained the Unique dice!</p> <p class="mt-2 text-sm">Final Score: ${formattedScore}</p> <p class="mt-1 text-sm">Total Rolls: ${rollCount}</p> <p class="mt-1 text-sm">Double Points Cards: ${doublePointsCards}</p> <p class="mt-1 text-sm">No Penalty Cards: ${noPenaltyCards}</p> <p class="mt-1 text-sm">Lucky Streak Cards: ${luckyStreakCards}</p> <p class="mt-1 text-sm">Final Tier Multiplier: ×${(1 + currentTier / 10).toFixed(1)}</p> <button id="play-again" class="mt-4 bg-primary hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-full transition-all duration-300 transform hover:scale-105"> <i class="fa fa-refresh mr-1"></i> Play Again </button> `; createConfetti(); } else { gameOverMessage.innerHTML = ` <div class="text-2xl mb-2">Game Over!</div> <p>Your score went negative.</p> <p>Better luck next time!</p> <p class="mt-2 text-sm">Final Score: ${formattedScore}</p> <p class="mt-1 text-sm">Total Rolls: ${rollCount}</p> <p class="mt-1 text-sm">Double Points Cards: ${doublePointsCards}</p> <p class="mt-1 text-sm">No Penalty Cards: ${noPenaltyCards}</p> <p class="mt-1 text-sm">Lucky Streak Cards: ${luckyStreakCards}</p> <p class="mt-1 text-sm">Final Tier Multiplier: ×${(1 + currentTier / 10).toFixed(1)}</p> <button id="play-again" class="mt-4 bg-primary hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-full transition-all duration-300 transform hover:scale-105"> <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'; } else if (result === 'ITEM') { actionText = `Received <span class="font-bold text-purple-500">${scoreChangeData}</span>`; scoreChangeText = '+1'; scoreChangeClass = 'text-purple-500'; } else if (result === 'GAME WIN' || result === 'GAME OVER') { actionText = result; scoreChangeText = ''; scoreChangeClass = ''; } 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) { scoreChangeText = `${scoreChange}`; scoreChangeClass = 'text-red-500'; } 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') + 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'; borderColor = '#CCCCCC'; } else if (color.toUpperCase() === '#555555') { // Dark gray dice - use white dots and slightly lighter gray borders dotColor = '#FFFFFF'; borderColor = '#777777'; } else { // 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'); }); }); })(); </script></body></html>
```::::
::::success[v.1.2.1]```html line-numbers<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>3D Dice Roll Animation</title> <!-- 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: { colors: { primary: '#3b82f6', secondary: '#f97316', dark: '#1e293b', light: '#f8fafc' }, fontFamily: { sans: ['Inter', 'system-ui', 'sans-serif'], }, animation: { 'shake': 'shake 0.5s ease-in-out', }, keyframes: { shake: { '0%, 100%': { transform: 'translateX(0)' }, '25%': { transform: 'translateX(-5px)' }, '50%': { transform: 'translateX(5px)' }, '75%': { transform: 'translateX(-5px)' }, } } } } } </script>
<style type="text/tailwindcss"> @layer utilities { .preserve-3d { transform-style: preserve-3d; } .perspective { perspective: 1000px; } .backface-hidden { backface-visibility: hidden; } .dice-shadow { box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 6px -1px, rgba(0, 0, 0, 0.06) 0px 2px 4px -1px; } .glass-effect { background: rgba(255, 255, 255, 0.7); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); } .modal-backdrop { background-color: rgba(0, 0, 0, 0.5); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px); } .modal-content { transform: translateY(-20px); opacity: 0; transition: all 0.3s ease-out; } .modal-open .modal-content { transform: translateY(0); opacity: 1; } .modal-open .modal-backdrop { opacity: 1; visibility: visible; } .trophy-animation { animation: trophy-pulse 2s ease-in-out infinite; } .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; border-radius: 8px; background-color: white; border: 2px solid #f0f0f0; display: flex; 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; top: 50%; left: 50%; 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); } 70% { box-shadow: 0 0 0 10px rgba(59, 130, 246, 0); } 100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0); } }
@keyframes scorePopup { 0% { transform: translateY(0); opacity: 0; } 50% { transform: translateY(-10px); opacity: 1; } 100% { 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; } 100% { transform: translateY(100vh) rotate(720deg); opacity: 0; } }
@keyframes lock-particle { 0% { transform: translate(0, 0); opacity: 1; } 100% { transform: translate(var(--tx), var(--ty)); opacity: 0; } }
/* Game Rules Modal Styles */ .game-rules-modal { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 50; display: flex; align-items: center; justify-content: center; padding: 1rem; visibility: hidden; box-sizing: border-box; }
.game-rules-modal .modal-backdrop { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; visibility: hidden; transition: all 0.3s ease-out; }
.game-rules-modal .modal-content { position: relative; background-color: white; border-radius: 1rem; max-width: 90%; max-height: 80vh; 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; right: 1rem; z-index: 40; padding: 0.5rem 1rem; border-radius: 0.5rem; background-color: #3b82f6; color: white; font-weight: 500; display: flex; align-items: center; 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></head><body class="bg-gradient-to-br from-light to-gray-200 min-h-screen flex flex-col items-center justify-center p-4 m-0"> <!-- Game Rules Button --> <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"> <div class="modal-header"> <h2 class="modal-title">3D Dice Game Rules</h2> <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> <li><strong>Common</strong> - Score Multiplier ×1.1</li> <li><strong>Unusual</strong> - Score Multiplier ×1.2</li> <li><strong>Rare</strong> - Score Multiplier ×1.3</li> <li><strong>Epic</strong> - Score Multiplier ×1.4</li> <li><strong>Legendary</strong> - Score Multiplier ×1.5</li> <li><strong>Mythic</strong> - Score Multiplier ×1.6</li> <li><strong>Ultra</strong> - Score Multiplier ×1.7</li> <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 --> <div class="dice-scene"> <div id="dice" class="dice-container"> <!-- 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> </div> <div id="tier-multiplier-display" class="text-sm text-gray-600 mb-2"> Tier Multiplier: <span class="font-semibold text-purple-500">×1.0</span> </div> <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"> <div class="flex items-center"> <i class="fa fa-plus-circle text-green-500 text-xl mr-2"></i> <span class="font-medium">Double Points Card</span> </div> <div class="flex items-center"> <span id="double-points-count" class="bg-green-100 text-green-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">0</span> <button id="use-double-points" class="bg-green-500 hover:bg-green-600 text-white text-xs py-1 px-2 rounded disabled:opacity-50 disabled:cursor-not-allowed" disabled> Use </button> </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> <span class="font-medium">No Penalty Card</span> </div> <div class="flex items-center"> <span id="no-penalty-count" class="bg-blue-100 text-blue-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">0</span> <button id="use-no-penalty" class="bg-blue-500 hover:bg-blue-600 text-white text-xs py-1 px-2 rounded disabled:opacity-50 disabled:cursor-not-allowed" disabled> Use </button> </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> <span class="font-medium">Lucky Streak Card</span> </div> <div class="flex items-center"> <span id="lucky-streak-count" class="bg-yellow-100 text-yellow-800 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded">0</span> <button id="use-lucky-streak" class="bg-yellow-500 hover:bg-yellow-600 text-white text-xs py-1 px-2 rounded disabled:opacity-50 disabled:cursor-not-allowed" disabled> Use </button> </div> </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"> <!-- Empty --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #FFFFFF; border: 1px solid #dddddd;" data-color="#FFFFFF"></button> <span class="text-xs text-center text-gray-600">Empty</span> </div> <!-- Common --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #7EEF6D;" data-color="#7EEF6D"></button> <span class="text-xs text-center text-gray-600">Common</span> </div> <!-- Unusual --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #FFE65D;" data-color="#FFE65D"></button> <span class="text-xs text-center text-gray-600">Unusual</span> </div> <!-- Rare --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #4d52e3;" data-color="#4d52e3"></button> <span class="text-xs text-center text-gray-600">Rare</span> </div> <!-- Epic --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #861FDE;" data-color="#861FDE"></button> <span class="text-xs text-center text-gray-600">Epic</span> </div> <!-- Legendary --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #DE1F1F;" data-color="#DE1F1F"></button> <span class="text-xs text-center text-gray-600">Legendary</span> </div> <!-- Mythic --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #1fdbde;" data-color="#1fdbde"></button> <span class="text-xs text-center text-gray-600">Mythic</span> </div> <!-- Ultra --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #ff2b75;" data-color="#ff2b75"></button> <span class="text-xs text-center text-gray-600">Ultra</span> </div> <!-- Super --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #2bffa3;" data-color="#2bffa3"></button> <span class="text-xs text-center text-gray-600">Super</span> </div> <!-- Unique --> <div class="flex flex-col items-center"> <button class="color-option w-full h-8 rounded-md mb-1" style="background-color: #555555;" data-color="#555555"></button> <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"> <div class="grid grid-cols-3 gap-2 text-xs font-medium text-gray-500 border-b border-gray-200 sticky top-0 bg-white z-10"> <div>Time</div> <div>Action</div> <div class="text-right">Score</div> </div> <ul id="history-list" class="text-sm"> <!-- History items will be inserted here by JavaScript --> </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'); const resultValue = document.getElementById('result-value'); const historyList = document.getElementById('history-list'); const colorOptions = document.querySelectorAll('.color-option'); const scoreDisplay = document.getElementById('score-display'); const scoreValue = document.getElementById('score-value'); const scoreChange = document.getElementById('score-change'); const upgradeButton = document.getElementById('upgrade-button'); const currentTierDisplay = document.getElementById('current-tier'); 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'); const useDoublePointsButton = document.getElementById('use-double-points'); const useNoPenaltyButton = document.getElementById('use-no-penalty'); 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' }, { name: 'Unusual', color: '#FFE65D' }, { name: 'Rare', color: '#4d52e3' }, { name: 'Epic', color: '#861FDE' }, { name: 'Legendary', color: '#DE1F1F' }, { name: 'Mythic', color: '#1fdbde' }, { 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) { case 1: // Front face (Z+) - visible when no rotation targetX = 0; targetY = 0; break; case 2: // Left face (X-) - visible when Y rotated 270 degrees targetX = 0; targetY = 270; break; case 3: // Back face (Z-) - visible when Y rotated 180 degrees targetX = 0; targetY = 180; break; case 4: // Right face (X+) - visible when Y rotated 90 degrees targetX = 0; targetY = 90; break; case 5: // Top face (Y-) - visible when X rotated -90 degrees targetX = -90; targetY = 0; break; case 6: // Bottom face (Y+) - visible when X rotated 90 degrees 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}`); } else { // Decrement free rolls count 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'); enableRollButton(); } }, duration + 1000); // Add 1 second buffer } catch (error) { console.error('Error during dice roll:', error); // Re-enable button if there's an error 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 applied const currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform'); console.log('Current transform after animation:', currentTransform); console.log('Calling finalizeAnimation...'); 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; break; case 3: baseChange = 0; break; case 4: baseChange = 1; break; case 5: baseChange = 2; break; case 6: baseChange = 3; 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(() => { rollButton.disabled = false; rollButton.classList.remove('opacity-70', 'cursor-not-allowed'); 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'); console.log('Score increase:', change); } else if (change < 0) { scoreChange.textContent = `${change}`; scoreChange.classList.add('score-decrease'); console.log('Score decrease:', change); } else { 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) { gameOver = true; endGame(true); } else { 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 display scoreDisplay.classList.add('animate-shake'); setTimeout(() => { 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++; } else if (itemChance < 0.60) { // 30% chance to get no penalty card noPenaltyCards++; } else if (itemChance < 0.70) { // 10% chance to get lucky streak card 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]; // Show particle effect on the lock before unlocking createLockParticles(option); // Add a small delay to show the particles before unlocking setTimeout(() => { option.disabled = false; 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 tier upgradeCost.textContent = '(Max Tier)'; upgradeButton.disabled = true; 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'); } else { upgradeButton.disabled = true; 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); } else { // Fallback: insert after active item indicator const activeItemIndicator = document.getElementById('active-item-indicator'); if (activeItemIndicator) { activeItemIndicator.parentNode.insertBefore(luckyRollsIndicator, activeItemIndicator.nextSibling); } else { // Fallback: insert after items display const itemsDisplay = document.getElementById('items-display'); if (itemsDisplay) { itemsDisplay.parentNode.insertBefore(luckyRollsIndicator, itemsDisplay.nextSibling); } } } }
// 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 exists const luckyRollsIndicator = document.getElementById('lucky-rolls-indicator'); if (luckyRollsIndicator) { 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'; doublePointsIndicator.innerHTML = ` <i class="fa fa-plus-circle mr-1" style="color: #10b981;"></i> <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'; noPenaltyIndicator.innerHTML = ` <i class="fa fa-shield mr-1" style="color: #3b82f6;"></i> <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> <p>You obtained the Unique dice!</p> <p class="mt-2 text-sm">Final Score: ${formattedScore}</p> <p class="mt-1 text-sm">Total Rolls: ${rollCount}</p> <p class="mt-1 text-sm">Double Points Cards: ${doublePointsCards}</p> <p class="mt-1 text-sm">No Penalty Cards: ${noPenaltyCards}</p> <p class="mt-1 text-sm">Lucky Streak Cards: ${luckyStreakCards}</p> <p class="mt-1 text-sm">Final Tier Multiplier: ×${(1 + currentTier / 10).toFixed(1)}</p> <button id="play-again" class="mt-4 bg-primary hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-full transition-all duration-300 transform hover:scale-105"> <i class="fa fa-refresh mr-1"></i> Play Again </button> `; createConfetti(); } else { gameOverMessage.innerHTML = ` <div class="text-2xl mb-2">Game Over!</div> <p>Your score went negative.</p> <p>Better luck next time!</p> <p class="mt-2 text-sm">Final Score: ${formattedScore}</p> <p class="mt-1 text-sm">Total Rolls: ${rollCount}</p> <p class="mt-1 text-sm">Double Points Cards: ${doublePointsCards}</p> <p class="mt-1 text-sm">No Penalty Cards: ${noPenaltyCards}</p> <p class="mt-1 text-sm">Lucky Streak Cards: ${luckyStreakCards}</p> <p class="mt-1 text-sm">Final Tier Multiplier: ×${(1 + currentTier / 10).toFixed(1)}</p> <button id="play-again" class="mt-4 bg-primary hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-full transition-all duration-300 transform hover:scale-105"> <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'; } else if (result === 'ITEM') { actionText = `Received <span class="font-bold text-purple-500">${scoreChangeData}</span>`; scoreChangeText = '+1'; scoreChangeClass = 'text-purple-500'; } else if (result === 'GAME WIN' || result === 'GAME OVER') { actionText = result; scoreChangeText = ''; scoreChangeClass = ''; } 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) { scoreChangeText = `${scoreChange}`; scoreChangeClass = 'text-red-500'; } 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') + 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'; borderColor = '#CCCCCC'; } else if (color.toUpperCase() === '#555555') { // Dark gray dice - use white dots and slightly lighter gray borders dotColor = '#FFFFFF'; borderColor = '#777777'; } else { // 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'); }); }); })(); </script></body></html>
```::::
:::::