正文
增加 5320 行删除 648 行
1234567891011121314152 行未改动18192021222324252620 行未改动47484950515253545530 行未改动86878889909192939495969798991001011021031041051061071081091101111121134 行未改动1181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012 行未改动2042052062072082092102112123 行未改动2162172182192202212222232246 行未改动2312322332342352362372382392402412422432442452462472 行未改动2502512522532542552562572582 行未改动2612622632642652662672682697 行未改动2772782792802812822832842852 行未改动2882892902912922932942952962 行未改动2993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863879 行未改动3973983994004014024034044054064074084094103 行未改动4144154164174184194204214222 行未改动4254264274284294304314324334344354364374384394404414424434444454464474484494507 行未改动4584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025032 行未改动5065075085095105115125135145155165175185195205215225235245255265275285295305315325335345354 行未改动5405415425435445455465475485495505519 行未改动5615625635645655665675685697 行未改动5775785795805815825835845858 行未改动59459559659759859960060160260360460560660760860961061161261361461561661761861948 行未改动6686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107118 行未改动7207217227237247257267277282 行未改动7317327337347357367377387397407417427437447457467477487497507517527537547555 行未改动76176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481521 行未改动8378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878882 行未改动8918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279287 行未改动9369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101612 行未改动102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610872 行未改动109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711786 行未改动1185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512863 行未改动1290129112921293129412951296129712981299130013012 行未改动13041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513463 行未改动1350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613975 行未改动14031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714782 行未改动148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015512 行未改动1554155515561557155815591560156115622 行未改动15651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161824 行未改动1643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516968 行未改动170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217332 行未改动17361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318746 行未改动1881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520964 行未改动2101210221032104210521062107210821093 行未改动21132114211521162117211821192120212120 行未改动21422143214421452146214721482149215036 行未改动21872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522264 行未改动2231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142 行未改动2317231823192320232123222323232423253 行未改动2329233023312332233323342335233623376 行未改动234423452346234723482349235023512352235323542355235623572358235923602 行未改动2363236423652366236723682369237023712 行未改动2374237523762377237823792380238123827 行未改动2390239123922393239423952396239723982 行未改动2401240224032404240524062407240824092 行未改动2412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025019 行未改动251125122513251425152516251725182519252025212522252325243 行未改动2528252925302531253225332534253525362 行未改动253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325647 行未改动25722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172 行未改动2620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826494 行未改动2654265526562657265826592660266126622663266426659 行未改动2675267626772678267926802681268226837 行未改动2691269226932694269526962697269826998 行未改动2708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273348 行未改动278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428258 行未改动2834283528362837283828392840284128422 行未改动284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928705 行未改动287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293021 行未改动29522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530062 行未改动300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530466 行未改动3053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033 行未改动310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313712 行未改动315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732082 行未改动321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433356 行未改动33423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473 行未改动3451345234533454345534563457345834593460346134622 行未改动34653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073 行未改动3511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735885 行未改动3594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636772 行未改动3680368136823683368436853686368736882 行未改动369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375710 行未改动376837693770377137723773377437753776377737783779378037813782378337842 行未改动3787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938102 行未改动3813381438153816381738183819382038212 行未改动3824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388224 行未改动3907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939608 行未改动39693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140022 行未改动4005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441456 行未改动41524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343742 行未改动4377437843794380访问次数 :食用方法:建一个文本文档,后缀名 .html,用记事本编辑,把代码复制进去,双击运行。更新日志:- v.1.0:初版;- v.1.1:将 Lucky Streak Card 的效果改为了:接下来的 3 次投掷中,扔到 1,2 不会计入总共投掷次数。::::info[v.1.0]```html<!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 handlerwindow.addEventListener('error', function(event) {console.error('Global error caught:', event.error);// Try to get roll button elementconst 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 messageconst 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 elementsconst 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 elementsconst 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 statelet currentScore = 10; // Initial scorelet currentTier = 0; // Initial dice tier (0 = Empty)let gameOver = false; // Game over flaglet rollCount = 0; // Number of dice rolls// Item systemlet doublePointsCards = 0; // Number of double points cardslet noPenaltyCards = 0; // Number of no penalty cardslet luckyStreakCards = 0; // Number of lucky streak cardslet freeRolls = 0; // Number of free rolls availablelet activeItems = { // Currently active itemsdouble: 0, // Number of active double points cardsnoPenalty: false // Whether no penalty card is active};// Dice tiers configurationconst diceTiers = [{ name: 'Empty', color: '#FFFFFF' },{ name: 'Common', color: '#7EEF6D' },5 行未改动{ name: 'Ultra', color: '#ff2b75' },{ name: 'Super', color: '#2bffa3' },{ name: 'Unique', color: '#555555' }];// Initialize 3D dicefunction initializeDice() {console.log('Initializing dice...');// Create 6 faces for the diceconst 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 numberfor (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 clearlydiceElement.style.transform = 'rotateX(0deg) rotateY(0deg)';}// Get random rotation values for the dicefunction getRandomRotation() {// Determine which face we want to showconst targetFace = Math.floor(Math.random() * 6) + 1;// Get current rotation from dice elementconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');const matrix = new DOMMatrix(currentTransform);// Extract current rotation angleslet currentX = 0, currentY = 0;// If transform is not identity matrix, extract rotationif (currentTransform !== 'none') {// Calculate rotation from matrixcurrentX = 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 facelet 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 accumulatinglet diffX = targetX - currentX;let diffY = targetY - currentY;// Normalize the difference to the range [-180, 180] to find the shortest pathdiffX = ((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 pathconst 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 visibleconst 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 functionfunction rollDice() {// Check if game is overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if there are free rolls availableconst isFreeRoll = freeRolls > 0;// Increment roll count only if not a free rollif (!isFreeRoll) {rollCount++;console.log(`Roll count: ${rollCount}`);2 行未改动freeRolls--;updateFreeRollsDisplay();console.log(`Free roll used. Remaining free rolls: ${freeRolls}`);}// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}console.log('Rolling dice...');console.log('Button state before disable:', rollButton.disabled);// Disable button during animationrollButton.disabled = true;rollButton.classList.add('opacity-70', 'cursor-not-allowed');console.log('Button state after disable:', rollButton.disabled);// Hide result displayresultDisplay.classList.add('hidden');try {// Set animation durationconst duration = 2000; // Fixed duration for consistent experience// Get random rotation values for the final positionconst rotationData = getRandomRotation();console.log('Rotation data:', rotationData);console.log('Target face:', rotationData.targetFace);// Animate the dice using JavaScript for more controlanimateDice(duration, rotationData);// Set a safety timeout to ensure button is re-enabled even if something goes wrongsetTimeout(() => {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 animationfunction animateDice(duration, rotationData) {console.log('Animate dice called with rotationData:', rotationData);const startTime = performance.now();const finalRotation = rotationData;// Get current rotation from dice elementconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');const matrix = new DOMMatrix(currentTransform);// Extract current rotation angleslet startX = 0, startY = 0;// If transform is not identity matrix, extract rotationif (currentTransform !== 'none') {// Calculate rotation from matrixstartX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI);startY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI);}// Function to handle each animation framefunction animate(currentTime) {const elapsedTime = currentTime - startTime;const progress = Math.min(elapsedTime / duration, 1);// Apply easing function for smooth, natural animationconst easedProgress = easeOutCubic(progress);// Calculate current rotation - smooth continuous rotationconst currentX = startX + (finalRotation.x - startX) * easedProgress;const currentY = startY + (finalRotation.y - startY) * easedProgress;// Spin animation: rotate in placediceElement.style.transform = `rotateX(${currentX}deg) rotateY(${currentY}deg)`;// Continue animation if not completeif (progress < 1) {requestAnimationFrame(animate);} else {// Animation complete - ensure we're at the exact target rotationdiceElement.style.transform = `rotateX(${finalRotation.x}deg) rotateY(${finalRotation.y}deg)`;// Show result after a short delay to ensure rotation is completeconsole.log('Animation complete, calling finalizeAnimation...');setTimeout(() => {finalizeAnimation(finalRotation);}, 50);}}// Start the animationrequestAnimationFrame(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 endfunction easeOutCubic(t) {return 1 - Math.pow(1 - t, 3);}// Calculate score change based on dice roll resultfunction 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 multiplierconst tierMultiplier = 1 + currentTier / 10;let finalChange;if (baseChange < 0) {// For point loss, use multiplier of 1 regardless of tierfinalChange = baseChange * 1;} else {// For point gain or neutral, use tier multiplierfinalChange = baseChange * tierMultiplier;}// Apply active item effectsconst itemsUsed = {double: activeItems.double,noPenalty: activeItems.noPenalty};// Apply no penalty card firstif (activeItems.noPenalty && baseChange < 0) {finalChange = 0;}// Apply double points cardsif (activeItems.double > 0) {finalChange = finalChange * Math.pow(2, activeItems.double);}// Round to 2 decimal places to avoid floating point precision issuesfinalChange = Math.round(finalChange * 100) / 100;return {baseChange: baseChange,finalChange: finalChange,itemsUsed: itemsUsed,tierMultiplier: tierMultiplier};}// Enable roll buttonfunction enableRollButton() {console.log('Button state before enable:', rollButton.disabled);// Directly enable the buttonrollButton.disabled = false;rollButton.classList.remove('opacity-70', 'cursor-not-allowed');console.log('Button state after enable:', rollButton.disabled);// Double-check and force enable if neededif (rollButton.disabled) {console.warn('Forcing button enable');setTimeout(() => {2 行未改动console.log('Button state after forced enable:', rollButton.disabled);}, 100);}}// Finalize the animation and show resultfunction finalizeAnimation(rotationData) {console.log('=== Finalize animation called ===');console.log('Rotation data:', rotationData);const finalRotation = rotationData;// Use the target face directly instead of recalculatingconst result = finalRotation.targetFace;console.log(`Final result: ${result} (should show face ${result})`);// Show result displayresultValue.textContent = result;resultDisplay.classList.remove('hidden');// Add shine effect to resultresultDisplay.classList.add('result-shine');setTimeout(() => {resultDisplay.classList.remove('result-shine');}, 500);// Calculate and update scoreconsole.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 animationconsole.log('Updating score display...');updateScoreDisplay(scoreChangeData);// Enable buttonconsole.log('Enabling roll button...');enableRollButton();// Add to history - include whether it was a free rolladdToHistory(result, scoreChangeData, isFreeRoll);// Check if reached the Unique diceif (currentTier === diceTiers.length - 1) {showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500');gameOver = true;createConfetti();}// Create confetti effect if result is 6if (result === 6) {createConfetti();}// Debug: log final stateconsole.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 animationfunction 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 placescurrentScore = Math.round(currentScore * 100) / 100;scoreValue.textContent = currentScore;console.log('Score value updated to:', currentScore);// Clear previous score change displayscoreChange.textContent = '';scoreChange.className = 'ml-2 text-sm font-normal';console.log('Cleared previous score change display');// Show score change with appropriate stylingif (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 usedif (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) {// Create container for item effectsconst itemEffectsContainer = document.createElement('div');itemEffectsContainer.className = 'flex flex-wrap gap-2 mt-1';// Add tier multiplier effect if applicableif (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 effectif (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 effectif (itemsUsed.double > 0) {const doublePointsEffect = document.createElement('div');doublePointsEffect.className = 'text-xs text-green-500';// Calculate multiplierconst multiplier = Math.pow(2, itemsUsed.double);let calculationText = `${baseChange}`;// Apply tier multiplier for displaylet displayChange = baseChange * tierMultiplier;// Apply no penalty first for displayif (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 usedif (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 displayscoreDisplay.appendChild(itemEffectsContainer);// Remove after animationsetTimeout(() => {scoreDisplay.removeChild(itemEffectsContainer);}, 1000);}// Reset score change display after animation completessetTimeout(() => {scoreChange.textContent = '';}, 1000);// Clear active items after score updateconsole.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 updateconsole.log('Checking game state...');checkGameState();console.log('=== updateScoreDisplay completed ===');}// Handle dice upgradefunction upgradeDice() {// Check if game is already overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if already at maximum tierif (currentTier >= diceTiers.length - 1) {// If not already game over, end the game with win conditionif (!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 upgradeif (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 upgradecurrentScore -= requiredScore;// Round to 2 decimal placescurrentScore = Math.round(currentScore * 100) / 100;// Update score displayscoreValue.textContent = currentScore;showScoreChange(-5);// Increase tiercurrentTier++;// Update current tier displaycurrentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;// Update tier multiplier displayupdateTierMultiplierDisplay();// Unlock the new dice colorunlockDiceColor(currentTier);// Update color selection UIupdateColorSelection(currentTier);// Update upgrade cost displayupdateUpgradeCostDisplay();// Change to the new dice colorconsole.log(`Changing dice color to ${diceTiers[currentTier].color} (${diceTiers[currentTier].name})`);changeDiceColor(diceTiers[currentTier].color);// Check if this upgrade reached the maximum tiercheckGameState();// Randomly get an itemconst itemChance = Math.random();if (itemChance < 0.32) { // 32% chance to get double points carddoublePointsCards++;3 行未改动// Do nothing} else { // 2% chance to get lucky streak cardluckyStreakCards++;}// Update items display to show new countsupdateItemsDisplay();// Update items displayupdateItemsDisplay();// Check if reached the Unique diceif (currentTier === diceTiers.length - 1) {showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500');gameOver = true;createConfetti();}// Add to historyaddToHistory('UPGRADE', -5);// Add item to history if obtainedif (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 upgradecheckGameState();}// Show score change temporarilyfunction 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 optionfunction unlockDiceColor(tierIndex) {if (tierIndex >= 0 && tierIndex < colorOptions.length) {const option = colorOptions[tierIndex];5 行未改动option.classList.remove('locked');}, 300);}}// Show game messagefunction showGameMessage(message, className) {gameMessageDisplay.textContent = message;gameMessageDisplay.className = `mt-4 text-center font-semibold ${className}`;gameMessageDisplay.classList.remove('hidden');// Hide message after 3 secondssetTimeout(() => {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 displayfunction updateItemsDisplay() {// Update countsdoublePointsCount.textContent = doublePointsCards;noPenaltyCount.textContent = noPenaltyCards;luckyStreakCount.textContent = luckyStreakCards;// Enable/disable buttons based on available itemsuseDoublePointsButton.disabled = doublePointsCards <= 0 || gameOver;useNoPenaltyButton.disabled = noPenaltyCards <= 0 || activeItems.noPenalty || gameOver;useLuckyStreakButton.disabled = luckyStreakCards <= 0 || gameOver;// Update free rolls displayupdateFreeRollsDisplay();}// Update free rolls displayfunction updateFreeRollsDisplay() {if (freeRolls > 0) {freeRollsCountElement.textContent = freeRolls;freeRollsIndicator.classList.remove('hidden');} else {freeRollsIndicator.classList.add('hidden');}}// Update upgrade cost displayfunction updateUpgradeCostDisplay() {if (currentTier >= diceTiers.length - 1) {// Already at maximum tier2 行未改动const requiredScore = 5 + currentTier;upgradeCost.textContent = `(Cost: ${requiredScore})`;}}// Use double points cardfunction useDoublePointsCard() {if (doublePointsCards > 0 && !gameOver) {activeItems.double++;doublePointsCards--;// Update UIupdateItemsDisplay();showActiveItemIndicator();// Show messageshowGameMessage('Double Points Card activated! Next roll will double your score change.', 'text-green-500');}}// Use no penalty cardfunction useNoPenaltyCard() {if (noPenaltyCards > 0 && !activeItems.noPenalty && !gameOver) {activeItems.noPenalty = true;noPenaltyCards--;// Update UIupdateItemsDisplay();showActiveItemIndicator();// Show messageshowGameMessage('No Penalty Card activated! Next roll won\'t lose points.', 'text-blue-500');}}// Use lucky streak cardfunction useLuckyStreakCard() {if (luckyStreakCards > 0 && !gameOver) {freeRolls += 3;luckyStreakCards--;// Update UIupdateItemsDisplay();// Show messageshowGameMessage('Lucky Streak Card activated! You have 3 free rolls!', 'text-yellow-500');// Add to historyaddToHistory('ITEM USE', 'Lucky Streak Card');}}// Show active item indicatorfunction showActiveItemIndicator() {// Clear previous contentactiveItemIndicator.innerHTML = '';// Check if any items are activeif (activeItems.double === 0 && !activeItems.noPenalty) {activeItemIndicator.className = 'mt-3 text-center hidden';return;}// Create container for active itemsconst itemsContainer = document.createElement('div');itemsContainer.className = 'flex flex-wrap justify-center gap-2';// Add double points cards indicatorif (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 indicatorif (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 containeractiveItemIndicator.appendChild(itemsContainer);activeItemIndicator.className = 'mt-3 text-center';}// Clear active itemsfunction clearActiveItems() {activeItems = {double: 0,noPenalty: false};showActiveItemIndicator();}// End the game and display appropriate messagefunction endGame(isWin) {console.log('=== endGame called ===');console.log('Is win:', isWin, 'Current score:', currentScore);// Disable all interactive elementsrollButton.disabled = true;upgradeButton.disabled = true;rollButton.classList.add('opacity-70', 'cursor-not-allowed');upgradeButton.classList.add('opacity-70', 'cursor-not-allowed');// Disable all interactive elementscolorOptions.forEach(option => {option.disabled = true;option.classList.add('opacity-50', 'cursor-not-allowed');});// Disable item buttonsuseDoublePointsButton.disabled = true;useNoPenaltyButton.disabled = true;// Hide active item indicatoractiveItemIndicator.classList.add('hidden');// Create game over message elementconst 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 placesconst 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 listenergameOverMessage.querySelector('#play-again').addEventListener('click', () => {window.location.reload();});// Replace game message display with game over messageconst gameMessageContainer = gameMessageDisplay.parentElement;gameMessageContainer.replaceChild(gameOverMessage, gameMessageDisplay);gameMessageDisplay = gameOverMessage;// Add game end to historyaddToHistory(isWin ? 'GAME WIN' : 'GAME OVER', 0);console.log('=== endGame completed ===');}// Show warning when score is lowfunction showLowScoreWarning() {// Only show warning if not already showingif (gameMessageDisplay.classList.contains('hidden')) {showGameMessage('Warning: Low score! Risk of game over.', 'text-orange-500');}}// Update color selection UI to show the currently selected colorfunction updateColorSelection(selectedIndex) {// Remove active state from all color optionscolorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary'));// Add active state to the selected color optionif (selectedIndex >= 0 && selectedIndex < colorOptions.length) {colorOptions[selectedIndex].classList.add('ring-2', 'ring-offset-2', 'ring-primary');}}// Add result to historyfunction addToHistory(result, scoreChangeData, isFreeRoll = false) {const now = new Date();const timeString = now.toLocaleTimeString();// Determine score change display and colorlet 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 applicableif (isFreeRoll) {actionText += ` <span class="text-yellow-500">(Free Roll)</span>`;}// Add item effect indicators if applicableconst 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 itemsif (historyList.children.length > 5) {historyList.removeChild(historyList.lastChild);}}// Create confetti effectfunction createConfetti() {const confettiContainer = document.createElement('div');confettiContainer.className = 'fixed inset-0 pointer-events-none overflow-hidden';document.body.appendChild(confettiContainer);// Create 50 confetti piecesfor (let i = 0; i < 50; i++) {const confetti = document.createElement('div');confetti.className = 'confetti';// Random positionconst posX = Math.random() * 100;const delay = Math.random() * 3;const duration = 3 + Math.random() * 2;// Random colorsconst 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 completessetTimeout(() => {document.body.removeChild(confettiContainer);}, 5000);}// Create particle effect on lockfunction createLockParticles(lockElement) {// Get lock element positionconst rect = lockElement.getBoundingClientRect();const centerX = rect.left + rect.width / 2;const centerY = rect.top + rect.height / 2;// Create particle containerconst 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 particlesfor (let i = 0; i < 15; i++) {const particle = document.createElement('div');particle.className = 'lock-particle';// Random direction and distanceconst 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 durationconst duration = 0.5 + Math.random() * 0.5;// Set particle stylesparticle.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 completessetTimeout(() => {document.body.removeChild(particleContainer);}, 1000);}// Function to darken a color by a certain percentagefunction 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 percentager = 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 hexconst darkenedHex = '#' +r.toString(16).padStart(2, '0') +g.toString(16).padStart(2, '0') +b.toString(16).padStart(2, '0');return darkenedHex;}// Change dice color functionfunction 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 contrastif (color.toUpperCase() === '#FFFFFF') {// White dice - use black dots and light gray bordersdotColor = '#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 colorface.style.backgroundColor = color;// Set face border colorface.style.border = `3px solid ${borderColor}`;// Set dots colorconst dots = face.querySelectorAll('.dot');dots.forEach(dot => {dot.style.backgroundColor = dotColor;// Add slight border to dots for better definitiondot.style.border = color.toUpperCase() === '#FFFFFF' ? '1px solid rgba(0, 0, 0, 0.2)' : '1px solid rgba(0, 0, 0, 0.1)';});});}// Update tier multiplier displayfunction 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 buttonrollButton.addEventListener('click', rollDice);// Event listener for upgrade buttonupgradeButton.addEventListener('click', upgradeDice);// Event listeners for item buttonsuseDoublePointsButton.addEventListener('click', useDoublePointsCard);useNoPenaltyButton.addEventListener('click', useNoPenaltyCard);useLuckyStreakButton.addEventListener('click', useLuckyStreakCard);// Event listeners for color optionscolorOptions.forEach((option, index) => {// Disable all color options except the first one initiallyif (index !== 0) {option.disabled = true;option.classList.add('locked');}option.addEventListener('click', () => {// Check if game is overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if color is unlockedif (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 colorcolorOptions.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 tiercurrentTier = index;currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;updateTierMultiplierDisplay();});});// Initialize dice on page loadwindow.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 displaycurrentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;// Initialize tier multiplier displayupdateTierMultiplierDisplay();// Initialize items displayupdateItemsDisplay();// Initialize upgrade cost displayupdateUpgradeCostDisplay();// Show welcome messagesetTimeout(() => {showGameMessage('Welcome! Roll the dice to earn points and upgrade your dice!', 'text-blue-500');}, 1000);});// Also try initializing on window loadwindow.addEventListener('load', () => {console.log('Window loaded');// If dice not already initialized, try againif (diceElement.children.length === 0) {console.log('Dice not initialized, trying again...');initializeDice();}});// Game Rules Modal Functionality(function() {// Get elementsconst 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 scrollingfunction preventBackgroundScroll(event) {// Allow scrolling inside the modal contentif (modalContent.contains(event.target)) {// Check if we're at the top or bottom of the modal contentconst 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 downif ((isAtTop && event.deltaY < 0) || (isAtBottom && event.deltaY > 0)) {event.preventDefault();}} else {// Prevent scrolling outside the modal contentevent.preventDefault();}}// Function to open modalfunction openModal() {// Add event listeners to prevent background scrollingdocument.addEventListener('wheel', preventBackgroundScroll, { passive: false });document.addEventListener('touchmove', preventBackgroundScroll, { passive: false });// Add open class to trigger animationsrulesModal.classList.add('modal-open');// Show the modalrulesModal.style.visibility = 'visible';}// Function to close modalfunction closeModal() {// Remove open class to trigger animationsrulesModal.classList.remove('modal-open');// Remove event listeners that prevent background scrollingdocument.removeEventListener('wheel', preventBackgroundScroll);document.removeEventListener('touchmove', preventBackgroundScroll);// Hide the modal after animation completessetTimeout(() => {rulesModal.style.visibility = 'hidden';}, 300);}// Add event listenersif (rulesButton) {rulesButton.addEventListener('click', openModal);}// Close buttonscloseButtons.forEach(button => {button.addEventListener('click', closeModal);});// Close when clicking outside the modal contentmodalBackdrop.addEventListener('click', closeModal);// Close when pressing Escape keydocument.addEventListener('keydown', (event) => {if (event.key === 'Escape' && rulesModal.classList.contains('modal-open')) {closeModal();}});// Add hover effect to rules buttonif (rulesButton) {rulesButton.addEventListener('mouseenter', () => {rulesButton.classList.add('scale-105');});rulesButton.addEventListener('mouseleave', () => {rulesButton.classList.remove('scale-105');});}// Add click effect to close buttonscloseButtons.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]```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 handlerwindow.addEventListener('error', function(event) {console.error('Global error caught:', event.error);// Try to get roll button elementconst 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 messageconst 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 elementsconst 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 elementsconst 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 statelet currentScore = 10; // Initial scorelet currentTier = 0; // Initial dice tier (0 = Empty)let gameOver = false; // Game over flaglet rollCount = 0; // Number of dice rollslet luckyRollsRemaining = 0; // Number of lucky rolls remaining// Item systemlet doublePointsCards = 0; // Number of double points cardslet noPenaltyCards = 0; // Number of no penalty cardslet luckyStreakCards = 0; // Number of lucky streak cardslet freeRolls = 0; // Number of free rolls availablelet activeItems = { // Currently active itemsdouble: 0, // Number of active double points cardsnoPenalty: false // Whether no penalty card is active};// Dice tiers configurationconst diceTiers = [{ name: 'Empty', color: '#FFFFFF' },{ name: 'Common', color: '#7EEF6D' },5 行未改动{ name: 'Ultra', color: '#ff2b75' },{ name: 'Super', color: '#2bffa3' },{ name: 'Unique', color: '#555555' }];// Initialize 3D dicefunction initializeDice() {console.log('Initializing dice...');// Create 6 faces for the diceconst 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 numberfor (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 clearlydiceElement.style.transform = 'rotateX(0deg) rotateY(0deg)';}// Get random rotation values for the dicefunction getRandomRotation() {// Determine which face we want to showconst targetFace = Math.floor(Math.random() * 6) + 1;// Get current rotation from dice elementconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');const matrix = new DOMMatrix(currentTransform);// Extract current rotation angleslet currentX = 0, currentY = 0;// If transform is not identity matrix, extract rotationif (currentTransform !== 'none') {// Calculate rotation from matrixcurrentX = 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 facelet 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 accumulatinglet diffX = targetX - currentX;let diffY = targetY - currentY;// Normalize the difference to the range [-180, 180] to find the shortest pathdiffX = ((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 pathconst 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 visibleconst 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 functionfunction rollDice() {// Check if game is overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if there are free rolls availableconst isFreeRoll = freeRolls > 0;// Check if in lucky streak modeconst isLuckyRoll = luckyRollsRemaining > 0;// Increment roll count only if not a free roll and not a lucky roll that will be revertedif (!isFreeRoll && !isLuckyRoll) {rollCount++;console.log(`Roll count: ${rollCount}`);2 行未改动freeRolls--;updateFreeRollsDisplay();console.log(`Free roll used. Remaining free rolls: ${freeRolls}`);}// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}console.log('Rolling dice...');console.log('Button state before disable:', rollButton.disabled);// Disable button during animationrollButton.disabled = true;rollButton.classList.add('opacity-70', 'cursor-not-allowed');console.log('Button state after disable:', rollButton.disabled);// Hide result displayresultDisplay.classList.add('hidden');try {// Set animation durationconst duration = 2000; // Fixed duration for consistent experience// Get random rotation values for the final positionconst rotationData = getRandomRotation();console.log('Rotation data:', rotationData);console.log('Target face:', rotationData.targetFace);// Animate the dice using JavaScript for more controlanimateDice(duration, rotationData);// Set a safety timeout to ensure button is re-enabled even if something goes wrongsetTimeout(() => {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 animationfunction animateDice(duration, rotationData) {console.log('Animate dice called with rotationData:', rotationData);const startTime = performance.now();const finalRotation = rotationData;// Get current rotation from dice elementconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');const matrix = new DOMMatrix(currentTransform);// Extract current rotation angleslet startX = 0, startY = 0;// If transform is not identity matrix, extract rotationif (currentTransform !== 'none') {// Calculate rotation from matrixstartX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI);startY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI);}// Function to handle each animation framefunction animate(currentTime) {const elapsedTime = currentTime - startTime;const progress = Math.min(elapsedTime / duration, 1);// Apply easing function for smooth, natural animationconst easedProgress = easeOutCubic(progress);// Calculate current rotation - smooth continuous rotationconst currentX = startX + (finalRotation.x - startX) * easedProgress;const currentY = startY + (finalRotation.y - startY) * easedProgress;// Spin animation: rotate in placediceElement.style.transform = `rotateX(${currentX}deg) rotateY(${currentY}deg)`;// Continue animation if not completeif (progress < 1) {requestAnimationFrame(animate);} else {// Animation complete - ensure we're at the exact target rotationdiceElement.style.transform = `rotateX(${finalRotation.x}deg) rotateY(${finalRotation.y}deg)`;// Show result after a delay to ensure rotation is complete and CSS has appliedconsole.log('Animation complete, waiting before finalizing...');setTimeout(() => {// Double-check that the transform has been applied3 行未改动finalizeAnimation(finalRotation);}, 600);}}// Start the animationrequestAnimationFrame(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 endfunction easeOutCubic(t) {return 1 - Math.pow(1 - t, 3);}// Calculate score change based on dice roll resultfunction 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 multiplierconst tierMultiplier = 1 + currentTier / 10;let finalChange;if (baseChange < 0) {// For point loss, use multiplier of 1 regardless of tierfinalChange = baseChange * 1;} else {// For point gain or neutral, use tier multiplierfinalChange = baseChange * tierMultiplier;}// Apply active item effectsconst itemsUsed = {double: activeItems.double,noPenalty: activeItems.noPenalty};// Apply no penalty card firstif (activeItems.noPenalty && baseChange < 0) {finalChange = 0;}// Apply double points cardsif (activeItems.double > 0) {finalChange = finalChange * Math.pow(2, activeItems.double);}// Round to 2 decimal places to avoid floating point precision issuesfinalChange = Math.round(finalChange * 100) / 100;return {baseChange: baseChange,finalChange: finalChange,itemsUsed: itemsUsed,tierMultiplier: tierMultiplier};}// Enable roll buttonfunction enableRollButton() {console.log('Button state before enable:', rollButton.disabled);// Directly enable the buttonrollButton.disabled = false;rollButton.classList.remove('opacity-70', 'cursor-not-allowed');console.log('Button state after enable:', rollButton.disabled);// Double-check and force enable if neededif (rollButton.disabled) {console.warn('Forcing button enable');setTimeout(() => {2 行未改动console.log('Button state after forced enable:', rollButton.disabled);}, 100);}}// Finalize the animation and show resultfunction 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 recalculatingconst result = finalRotation.targetFace;console.log(`Final result: ${result} (should show face ${result})`);// Verify dice is in the correct positionconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');console.log('Current dice transform:', currentTransform);// Show result displayconsole.log('Showing result display...');resultValue.textContent = result;resultDisplay.classList.remove('hidden');// Add shine effect to resultresultDisplay.classList.add('result-shine');setTimeout(() => {resultDisplay.classList.remove('result-shine');}, 500);// Calculate and update scoreconsole.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 animationconsole.log('Updating score display...');updateScoreDisplay(scoreChangeData);// Enable buttonconsole.log('Enabling roll button...');enableRollButton();// Add to history - include whether it was a free roll or lucky rolladdToHistory(result, scoreChangeData, isFreeRoll, isLuckyRoll);// Check if reached the Unique diceif (currentTier === diceTiers.length - 1) {showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500');gameOver = true;createConfetti();}// Handle lucky roll logicif (luckyRollsRemaining > 0) {// Decrement remaining lucky rollsluckyRollsRemaining--;// If rolled 1 or 2, decrement roll countif (result === 1 || result === 2) {rollCount--;console.log(`Lucky roll: Reverted roll count to ${rollCount}`);// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}// Show messageshowGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500');}// Update lucky rolls displayupdateLuckyRollsDisplay();// If no more lucky rolls, show messageif (luckyRollsRemaining === 0) {setTimeout(() => {showGameMessage('Lucky Streak ended!', 'text-yellow-500');}, 1000);}}// Create confetti effect if result is 6if (result === 6) {createConfetti();}// Debug: log final stateconsole.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 animationfunction 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 placescurrentScore = Math.round(currentScore * 100) / 100;scoreValue.textContent = currentScore;console.log('Score value updated to:', currentScore);// Clear previous score change displayscoreChange.textContent = '';scoreChange.className = 'ml-2 text-sm font-normal';console.log('Cleared previous score change display');// Show score change with appropriate stylingif (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 usedif (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) {// Create container for item effectsconst itemEffectsContainer = document.createElement('div');itemEffectsContainer.className = 'flex flex-wrap gap-2 mt-1';// Add tier multiplier effect if applicableif (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 effectif (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 effectif (itemsUsed.double > 0) {const doublePointsEffect = document.createElement('div');doublePointsEffect.className = 'text-xs text-green-500';// Calculate multiplierconst multiplier = Math.pow(2, itemsUsed.double);let calculationText = `${baseChange}`;// Apply tier multiplier for displaylet displayChange = baseChange * tierMultiplier;// Apply no penalty first for displayif (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 usedif (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 displayscoreDisplay.appendChild(itemEffectsContainer);// Remove after animationsetTimeout(() => {scoreDisplay.removeChild(itemEffectsContainer);}, 1000);}// Reset score change display after animation completessetTimeout(() => {scoreChange.textContent = '';}, 1000);// Clear active items after score updateconsole.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 updateconsole.log('Checking game state...');checkGameState();// Update upgrade button stateupdateUpgradeCostDisplay();console.log('=== updateScoreDisplay completed ===');}// Handle dice upgradefunction upgradeDice() {// Check if game is already overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if already at maximum tierif (currentTier >= diceTiers.length - 1) {// If not already game over, end the game with win conditionif (!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 upgradeif (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 upgradecurrentScore -= requiredScore;// Round to 2 decimal placescurrentScore = Math.round(currentScore * 100) / 100;// Update score displayscoreValue.textContent = currentScore;showScoreChange(-requiredScore);// Increase tiercurrentTier++;// Update current tier displaycurrentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;// Update tier multiplier displayupdateTierMultiplierDisplay();// Unlock the new dice colorunlockDiceColor(currentTier);// Update color selection UIupdateColorSelection(currentTier);// Update upgrade cost displayupdateUpgradeCostDisplay();// Change to the new dice colorconsole.log(`Changing dice color to ${diceTiers[currentTier].color} (${diceTiers[currentTier].name})`);changeDiceColor(diceTiers[currentTier].color);// Check if this upgrade reached the maximum tiercheckGameState();// Randomly get an itemconst itemChance = Math.random();if (itemChance < 0.30) { // 30% chance to get double points carddoublePointsCards++;3 行未改动luckyStreakCards++;} else { // 30% chance to get nothing// Do nothing}// Update items display to show new countsupdateItemsDisplay();// Update items displayupdateItemsDisplay();// Check if reached the Unique diceif (currentTier === diceTiers.length - 1) {showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500');gameOver = true;createConfetti();}// Handle lucky roll logicif (luckyRollsRemaining > 0) {// Decrement remaining lucky rollsluckyRollsRemaining--;// If rolled 1 or 2, decrement roll countif (result === 1 || result === 2) {rollCount--;console.log(`Lucky roll: Reverted roll count to ${rollCount}`);// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}// Show messageshowGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500');}// Update lucky rolls displayupdateLuckyRollsDisplay();// If no more lucky rolls, show messageif (luckyRollsRemaining === 0) {setTimeout(() => {showGameMessage('Lucky Streak ended!', 'text-yellow-500');}, 1000);}}// Add to historyaddToHistory('UPGRADE', -5);// Add item to history if obtainedif (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 upgradecheckGameState();}// Show score change temporarilyfunction 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 optionfunction unlockDiceColor(tierIndex) {if (tierIndex >= 0 && tierIndex < colorOptions.length) {const option = colorOptions[tierIndex];5 行未改动option.classList.remove('locked');}, 300);}}// Show game messagefunction showGameMessage(message, className) {gameMessageDisplay.textContent = message;gameMessageDisplay.className = `mt-4 text-center font-semibold ${className}`;gameMessageDisplay.classList.remove('hidden');// Hide message after 3 secondssetTimeout(() => {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 recordsetTimeout(() => {checkWinRecord();}, 1000);}// Check if score is low (warning)if (currentScore >= 0 && currentScore <= 5 && !gameOver) {showLowScoreWarning();}console.log('=== checkGameState completed ===');}// Update items displayfunction updateItemsDisplay() {// Update countsdoublePointsCount.textContent = doublePointsCards;noPenaltyCount.textContent = noPenaltyCards;luckyStreakCount.textContent = luckyStreakCards;// Enable/disable buttons based on available itemsuseDoublePointsButton.disabled = doublePointsCards <= 0 || gameOver;useNoPenaltyButton.disabled = noPenaltyCards <= 0 || activeItems.noPenalty || gameOver;useLuckyStreakButton.disabled = luckyStreakCards <= 0 || gameOver;// Update free rolls displayupdateFreeRollsDisplay();// Update lucky rolls displayupdateLuckyRollsDisplay();}// Update free rolls displayfunction updateFreeRollsDisplay() {if (freeRolls > 0) {freeRollsCountElement.textContent = freeRolls;freeRollsIndicator.classList.remove('hidden');} else {freeRollsIndicator.classList.add('hidden');}}// Update upgrade cost display and button statefunction 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 scoreif (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 cardfunction useDoublePointsCard() {if (doublePointsCards > 0 && !gameOver) {activeItems.double++;doublePointsCards--;// Update UIupdateItemsDisplay();showActiveItemIndicator();// Show messageshowGameMessage('Double Points Card activated! Next roll will double your score change.', 'text-green-500');}}// Use no penalty cardfunction useNoPenaltyCard() {if (noPenaltyCards > 0 && !activeItems.noPenalty && !gameOver) {activeItems.noPenalty = true;noPenaltyCards--;// Update UIupdateItemsDisplay();showActiveItemIndicator();// Show messageshowGameMessage('No Penalty Card activated! Next roll won\'t lose points.', 'text-blue-500');}}// Use lucky streak cardfunction useLuckyStreakCard() {if (luckyStreakCards > 0 && !gameOver) {luckyRollsRemaining = 3;luckyStreakCards--;// Update UIupdateItemsDisplay();updateLuckyRollsDisplay();// Show messageshowGameMessage('Lucky Streak Card activated! Next 3 rolls of 1 or 2 won\'t count!', 'text-yellow-500');// Add to historyaddToHistory('ITEM USE', 'Lucky Streak Card');}}// Update lucky rolls displayfunction updateLuckyRollsDisplay() {if (luckyRollsRemaining > 0) {// Check if indicator exists, if not create itlet 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 indicatorconst freeRollsIndicator = document.getElementById('free-rolls-indicator');if (freeRollsIndicator) {freeRollsIndicator.parentNode.insertBefore(luckyRollsIndicator, freeRollsIndicator.nextSibling);10 行未改动}}}}// Update contentluckyRollsIndicator.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 indicatorluckyRollsIndicator.classList.remove('hidden');} else {// Remove indicator if exists2 行未改动luckyRollsIndicator.classList.add('hidden');}}}// Show active item indicatorfunction showActiveItemIndicator() {// Clear previous contentactiveItemIndicator.innerHTML = '';// Check if any items are activeif (activeItems.double === 0 && !activeItems.noPenalty) {activeItemIndicator.className = 'mt-3 text-center hidden';return;}// Create container for active itemsconst itemsContainer = document.createElement('div');itemsContainer.className = 'flex flex-wrap justify-center gap-2';// Add double points cards indicatorif (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 indicatorif (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 containeractiveItemIndicator.appendChild(itemsContainer);activeItemIndicator.className = 'mt-3 text-center';}// Clear active itemsfunction clearActiveItems() {activeItems = {double: 0,noPenalty: false};showActiveItemIndicator();}// End the game and display appropriate messagefunction endGame(isWin) {console.log('=== endGame called ===');console.log('Is win:', isWin, 'Current score:', currentScore);// Disable all interactive elementsrollButton.disabled = true;upgradeButton.disabled = true;rollButton.classList.add('opacity-70', 'cursor-not-allowed');upgradeButton.classList.add('opacity-70', 'cursor-not-allowed');// Disable all interactive elementscolorOptions.forEach(option => {option.disabled = true;option.classList.add('opacity-50', 'cursor-not-allowed');});// Disable item buttonsuseDoublePointsButton.disabled = true;useNoPenaltyButton.disabled = true;useLuckyStreakButton.disabled = true;// Hide active indicatorsactiveItemIndicator.classList.add('hidden');const luckyRollsIndicator = document.getElementById('lucky-rolls-indicator');if (luckyRollsIndicator) {luckyRollsIndicator.classList.add('hidden');}// Create game over message elementconst 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 placesconst 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 listenergameOverMessage.querySelector('#play-again').addEventListener('click', () => {window.location.reload();});// Replace game message display with game over messageconst gameMessageContainer = gameMessageDisplay.parentElement;gameMessageContainer.replaceChild(gameOverMessage, gameMessageDisplay);gameMessageDisplay = gameOverMessage;// Add game end to historyaddToHistory(isWin ? 'GAME WIN' : 'GAME OVER', 0);console.log('=== endGame completed ===');}// Show warning when score is lowfunction showLowScoreWarning() {// Only show warning if not already showingif (gameMessageDisplay.classList.contains('hidden')) {showGameMessage('Warning: Low score! Risk of game over.', 'text-orange-500');}}// Update color selection UI to show the currently selected colorfunction updateColorSelection(selectedIndex) {// Remove active state from all color optionscolorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary'));// Add active state to the selected color optionif (selectedIndex >= 0 && selectedIndex < colorOptions.length) {colorOptions[selectedIndex].classList.add('ring-2', 'ring-offset-2', 'ring-primary');}}// Add result to historyfunction addToHistory(result, scoreChangeData, isFreeRoll = false, isLuckyRoll = false) {const now = new Date();const timeString = now.toLocaleTimeString();// Determine score change display and colorlet 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 applicableif (isFreeRoll) {actionText += ` <span class="text-yellow-500">(Free Roll)</span>`;}// Add lucky roll indicator if applicableif (isLuckyRoll) {actionText += ` <span class="text-yellow-500">(Lucky Roll)</span>`;}// Add item effect indicators if applicableconst 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 itemsif (historyList.children.length > 5) {historyList.removeChild(historyList.lastChild);}}// Create confetti effectfunction createConfetti() {const confettiContainer = document.createElement('div');confettiContainer.className = 'fixed inset-0 pointer-events-none overflow-hidden';document.body.appendChild(confettiContainer);// Create 50 confetti piecesfor (let i = 0; i < 50; i++) {const confetti = document.createElement('div');confetti.className = 'confetti';// Random positionconst posX = Math.random() * 100;const delay = Math.random() * 3;const duration = 3 + Math.random() * 2;// Random colorsconst 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 completessetTimeout(() => {document.body.removeChild(confettiContainer);}, 5000);}// Create particle effect on lockfunction createLockParticles(lockElement) {// Get lock element positionconst rect = lockElement.getBoundingClientRect();const centerX = rect.left + rect.width / 2;const centerY = rect.top + rect.height / 2;// Create particle containerconst 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 particlesfor (let i = 0; i < 15; i++) {const particle = document.createElement('div');particle.className = 'lock-particle';// Random direction and distanceconst 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 durationconst duration = 0.5 + Math.random() * 0.5;// Set particle stylesparticle.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 completessetTimeout(() => {document.body.removeChild(particleContainer);}, 1000);}// Function to darken a color by a certain percentagefunction 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 percentager = 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 hexconst darkenedHex = '#' +r.toString(16).padStart(2, '0') +g.toString(16).padStart(2, '0') +b.toString(16).padStart(2, '0');return darkenedHex;}// Change dice color functionfunction 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 contrastif (color.toUpperCase() === '#FFFFFF') {// White dice - use black dots and light gray bordersdotColor = '#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 colorface.style.backgroundColor = color;// Set face border colorface.style.border = `3px solid ${borderColor}`;// Set dots colorconst dots = face.querySelectorAll('.dot');dots.forEach(dot => {dot.style.backgroundColor = dotColor;// Add slight border to dots for better definitiondot.style.border = color.toUpperCase() === '#FFFFFF' ? '1px solid rgba(0, 0, 0, 0.2)' : '1px solid rgba(0, 0, 0, 0.1)';});});}// Update tier multiplier displayfunction 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 buttonrollButton.addEventListener('click', rollDice);// Event listener for upgrade buttonupgradeButton.addEventListener('click', upgradeDice);// Event listeners for item buttonsuseDoublePointsButton.addEventListener('click', useDoublePointsCard);useNoPenaltyButton.addEventListener('click', useNoPenaltyCard);useLuckyStreakButton.addEventListener('click', useLuckyStreakCard);// Event listeners for color optionscolorOptions.forEach((option, index) => {// Disable all color options except the first one initiallyif (index !== 0) {option.disabled = true;option.classList.add('locked');}option.addEventListener('click', () => {// Check if game is overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if color is unlockedif (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 colorcolorOptions.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 tiercurrentTier = index;currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;updateTierMultiplierDisplay();});});// Initialize dice on page loadwindow.addEventListener('DOMContentLoaded', () => {console.log('=== DOMContentLoaded event fired ===');// Check if elements existconsole.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 displaycurrentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;// Initialize tier multiplier displayupdateTierMultiplierDisplay();// Initialize items displayupdateItemsDisplay();// Initialize upgrade cost displayupdateUpgradeCostDisplay();// Show welcome messagesetTimeout(() => {showGameMessage('Welcome! Roll the dice to earn points and upgrade your dice!', 'text-blue-500');}, 1000);});// Also try initializing on window loadwindow.addEventListener('load', () => {console.log('Window loaded');// If dice not already initialized, try againif (diceElement.children.length === 0) {console.log('Dice not initialized, trying again...');initializeDice();}});// Game Rules Modal Functionality(function() {// Get elementsconst 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 scrollingfunction preventBackgroundScroll(event) {// Allow scrolling inside the modal contentif (modalContent.contains(event.target)) {// Check if we're at the top or bottom of the modal contentconst 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 downif ((isAtTop && event.deltaY < 0) || (isAtBottom && event.deltaY > 0)) {event.preventDefault();}} else {// Prevent scrolling outside the modal contentevent.preventDefault();}}// Function to open modalfunction openModal() {// Add event listeners to prevent background scrollingdocument.addEventListener('wheel', preventBackgroundScroll, { passive: false });document.addEventListener('touchmove', preventBackgroundScroll, { passive: false });// Add open class to trigger animationsrulesModal.classList.add('modal-open');// Show the modalrulesModal.style.visibility = 'visible';}// Function to close modalfunction closeModal() {// Remove open class to trigger animationsrulesModal.classList.remove('modal-open');// Remove event listeners that prevent background scrollingdocument.removeEventListener('wheel', preventBackgroundScroll);document.removeEventListener('touchmove', preventBackgroundScroll);// Hide the modal after animation completessetTimeout(() => {rulesModal.style.visibility = 'hidden';}, 300);}// Add event listenersif (rulesButton) {rulesButton.addEventListener('click', openModal);}// Close buttonscloseButtons.forEach(button => {button.addEventListener('click', closeModal);});// Close when clicking outside the modal contentmodalBackdrop.addEventListener('click', closeModal);// Close when pressing Escape keydocument.addEventListener('keydown', (event) => {if (event.key === 'Escape' && rulesModal.classList.contains('modal-open')) {closeModal();}});// Add hover effect to rules buttonif (rulesButton) {rulesButton.addEventListener('mouseenter', () => {rulesButton.classList.add('scale-105');});rulesButton.addEventListener('mouseleave', () => {rulesButton.classList.remove('scale-105');});}// Add click effect to close buttonscloseButtons.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>```::::123456789101112131415161718192021222324252 行未改动28293031323334353620 行未改动57585960616263646530 行未改动969798991001011021031041051061071081091101111121131141151161171181191201211221234 行未改动1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112 行未改动2142152162172182192202212223 行未改动2262272282292302312322332346 行未改动2412422432442452462472482492502512522532542552562572 行未改动2602612622632642652662672682 行未改动2712722732742752762772782797 行未改动2872882892902912922932942952 行未改动2982993003013023033043053062 行未改动3093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963979 行未改动4074084094104114124134144154164174184194203 行未改动4244254264274284294304314322 行未改动4354364374384394404414424434444454464474484494504514524534544554564574584594607 行未改动4684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125132 行未改动5165175185195205215225235245255265275285295305315325335345355365375385395405415425435445454 行未改动5505515525535545555565575585595605619 行未改动5715725735745755765775785797 行未改动5875885895905915925935945958 行未改动60460560660760860961061161261361461561661761861962062162262362462562662762862948 行未改动6786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207218 行未改动7307317327337347357367377382 行未改动7417427437447457467477487497507517527537547557567577587597607617627637647655 行未改动77177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482521 行未改动8478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978982 行未改动9019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379387 行未改动94694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102612 行未改动103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610972 行未改动110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711886 行未改动1195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512963 行未改动1300130113021303130413051306130713081309131013112 行未改动13141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513563 行未改动1360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614075 行未改动14131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714882 行未改动149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015612 行未改动1564156515661567156815691570157115722 行未改动15751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162824 行未改动1653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517068 行未改动171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217432 行未改动17461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318846 行未改动1891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521064 行未改动2111211221132114211521162117211821193 行未改动21232124212521262127212821292130213120 行未改动21522153215421552156215721582159216036 行未改动21972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522364 行未改动2241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242 行未改动2327232823292330233123322333233423353 行未改动2339234023412342234323442345234623476 行未改动235423552356235723582359236023612362236323642365236623672368236923702 行未改动2373237423752376237723782379238023812 行未改动2384238523862387238823892390239123927 行未改动2400240124022403240424052406240724082 行未改动2411241224132414241524162417241824192 行未改动2422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025119 行未改动252125222523252425252526252725282529253025312532253325343 行未改动2538253925402541254225432544254525462 行未改动254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325747 行未改动25822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272 行未改动2630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826594 行未改动2664266526662667266826692670267126722673267426759 行未改动2685268626872688268926902691269226937 行未改动2701270227032704270527062707270827098 行未改动2718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274348 行未改动279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428358 行未改动2844284528462847284828492850285128522 行未改动285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928805 行未改动288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294021 行未改动29622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530162 行未改动301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530566 行未改动3063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133 行未改动311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314712 行未改动316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732182 行未改动322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433456 行未改动33523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573 行未改动3461346234633464346534663467346834693470347134722 行未改动34753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173 行未改动3521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735985 行未改动3604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636872 行未改动3690369136923693369436953696369736982 行未改动370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376710 行未改动377837793780378137823783378437853786378737883789379037913792379337942 行未改动3797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938202 行未改动3823382438253826382738283829383038312 行未改动3834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389224 行未改动3917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939708 行未改动39793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140122 行未改动4015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441556 行未改动41624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343842 行未改动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 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 handlerwindow.addEventListener('error', function(event) {console.error('Global error caught:', event.error);// Try to get roll button elementconst 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 messageconst 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 elementsconst 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 elementsconst 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 statelet currentScore = 10; // Initial scorelet currentTier = 0; // Initial dice tier (0 = Empty)let gameOver = false; // Game over flaglet rollCount = 0; // Number of dice rolls// Item systemlet doublePointsCards = 0; // Number of double points cardslet noPenaltyCards = 0; // Number of no penalty cardslet luckyStreakCards = 0; // Number of lucky streak cardslet freeRolls = 0; // Number of free rolls availablelet activeItems = { // Currently active itemsdouble: 0, // Number of active double points cardsnoPenalty: false // Whether no penalty card is active};// Dice tiers configurationconst diceTiers = [{ name: 'Empty', color: '#FFFFFF' },{ name: 'Common', color: '#7EEF6D' },5 行未改动{ name: 'Ultra', color: '#ff2b75' },{ name: 'Super', color: '#2bffa3' },{ name: 'Unique', color: '#555555' }];// Initialize 3D dicefunction initializeDice() {console.log('Initializing dice...');// Create 6 faces for the diceconst 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 numberfor (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 clearlydiceElement.style.transform = 'rotateX(0deg) rotateY(0deg)';}// Get random rotation values for the dicefunction getRandomRotation() {// Determine which face we want to showconst targetFace = Math.floor(Math.random() * 6) + 1;// Get current rotation from dice elementconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');const matrix = new DOMMatrix(currentTransform);// Extract current rotation angleslet currentX = 0, currentY = 0;// If transform is not identity matrix, extract rotationif (currentTransform !== 'none') {// Calculate rotation from matrixcurrentX = 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 facelet 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 accumulatinglet diffX = targetX - currentX;let diffY = targetY - currentY;// Normalize the difference to the range [-180, 180] to find the shortest pathdiffX = ((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 pathconst 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 visibleconst 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 functionfunction rollDice() {// Check if game is overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if there are free rolls availableconst isFreeRoll = freeRolls > 0;// Increment roll count only if not a free rollif (!isFreeRoll) {rollCount++;console.log(`Roll count: ${rollCount}`);2 行未改动freeRolls--;updateFreeRollsDisplay();console.log(`Free roll used. Remaining free rolls: ${freeRolls}`);}// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}console.log('Rolling dice...');console.log('Button state before disable:', rollButton.disabled);// Disable button during animationrollButton.disabled = true;rollButton.classList.add('opacity-70', 'cursor-not-allowed');console.log('Button state after disable:', rollButton.disabled);// Hide result displayresultDisplay.classList.add('hidden');try {// Set animation durationconst duration = 2000; // Fixed duration for consistent experience// Get random rotation values for the final positionconst rotationData = getRandomRotation();console.log('Rotation data:', rotationData);console.log('Target face:', rotationData.targetFace);// Animate the dice using JavaScript for more controlanimateDice(duration, rotationData);// Set a safety timeout to ensure button is re-enabled even if something goes wrongsetTimeout(() => {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 animationfunction animateDice(duration, rotationData) {console.log('Animate dice called with rotationData:', rotationData);const startTime = performance.now();const finalRotation = rotationData;// Get current rotation from dice elementconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');const matrix = new DOMMatrix(currentTransform);// Extract current rotation angleslet startX = 0, startY = 0;// If transform is not identity matrix, extract rotationif (currentTransform !== 'none') {// Calculate rotation from matrixstartX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI);startY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI);}// Function to handle each animation framefunction animate(currentTime) {const elapsedTime = currentTime - startTime;const progress = Math.min(elapsedTime / duration, 1);// Apply easing function for smooth, natural animationconst easedProgress = easeOutCubic(progress);// Calculate current rotation - smooth continuous rotationconst currentX = startX + (finalRotation.x - startX) * easedProgress;const currentY = startY + (finalRotation.y - startY) * easedProgress;// Spin animation: rotate in placediceElement.style.transform = `rotateX(${currentX}deg) rotateY(${currentY}deg)`;// Continue animation if not completeif (progress < 1) {requestAnimationFrame(animate);} else {// Animation complete - ensure we're at the exact target rotationdiceElement.style.transform = `rotateX(${finalRotation.x}deg) rotateY(${finalRotation.y}deg)`;// Show result after a short delay to ensure rotation is completeconsole.log('Animation complete, calling finalizeAnimation...');setTimeout(() => {finalizeAnimation(finalRotation);}, 50);}}// Start the animationrequestAnimationFrame(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 endfunction easeOutCubic(t) {return 1 - Math.pow(1 - t, 3);}// Calculate score change based on dice roll resultfunction 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 multiplierconst tierMultiplier = 1 + currentTier / 10;let finalChange;if (baseChange < 0) {// For point loss, use multiplier of 1 regardless of tierfinalChange = baseChange * 1;} else {// For point gain or neutral, use tier multiplierfinalChange = baseChange * tierMultiplier;}// Apply active item effectsconst itemsUsed = {double: activeItems.double,noPenalty: activeItems.noPenalty};// Apply no penalty card firstif (activeItems.noPenalty && baseChange < 0) {finalChange = 0;}// Apply double points cardsif (activeItems.double > 0) {finalChange = finalChange * Math.pow(2, activeItems.double);}// Round to 2 decimal places to avoid floating point precision issuesfinalChange = Math.round(finalChange * 100) / 100;return {baseChange: baseChange,finalChange: finalChange,itemsUsed: itemsUsed,tierMultiplier: tierMultiplier};}// Enable roll buttonfunction enableRollButton() {console.log('Button state before enable:', rollButton.disabled);// Directly enable the buttonrollButton.disabled = false;rollButton.classList.remove('opacity-70', 'cursor-not-allowed');console.log('Button state after enable:', rollButton.disabled);// Double-check and force enable if neededif (rollButton.disabled) {console.warn('Forcing button enable');setTimeout(() => {2 行未改动console.log('Button state after forced enable:', rollButton.disabled);}, 100);}}// Finalize the animation and show resultfunction finalizeAnimation(rotationData) {console.log('=== Finalize animation called ===');console.log('Rotation data:', rotationData);const finalRotation = rotationData;// Use the target face directly instead of recalculatingconst result = finalRotation.targetFace;console.log(`Final result: ${result} (should show face ${result})`);// Show result displayresultValue.textContent = result;resultDisplay.classList.remove('hidden');// Add shine effect to resultresultDisplay.classList.add('result-shine');setTimeout(() => {resultDisplay.classList.remove('result-shine');}, 500);// Calculate and update scoreconsole.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 animationconsole.log('Updating score display...');updateScoreDisplay(scoreChangeData);// Enable buttonconsole.log('Enabling roll button...');enableRollButton();// Add to history - include whether it was a free rolladdToHistory(result, scoreChangeData, isFreeRoll);// Check if reached the Unique diceif (currentTier === diceTiers.length - 1) {showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500');gameOver = true;createConfetti();}// Create confetti effect if result is 6if (result === 6) {createConfetti();}// Debug: log final stateconsole.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 animationfunction 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 placescurrentScore = Math.round(currentScore * 100) / 100;scoreValue.textContent = currentScore;console.log('Score value updated to:', currentScore);// Clear previous score change displayscoreChange.textContent = '';scoreChange.className = 'ml-2 text-sm font-normal';console.log('Cleared previous score change display');// Show score change with appropriate stylingif (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 usedif (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) {// Create container for item effectsconst itemEffectsContainer = document.createElement('div');itemEffectsContainer.className = 'flex flex-wrap gap-2 mt-1';// Add tier multiplier effect if applicableif (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 effectif (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 effectif (itemsUsed.double > 0) {const doublePointsEffect = document.createElement('div');doublePointsEffect.className = 'text-xs text-green-500';// Calculate multiplierconst multiplier = Math.pow(2, itemsUsed.double);let calculationText = `${baseChange}`;// Apply tier multiplier for displaylet displayChange = baseChange * tierMultiplier;// Apply no penalty first for displayif (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 usedif (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 displayscoreDisplay.appendChild(itemEffectsContainer);// Remove after animationsetTimeout(() => {scoreDisplay.removeChild(itemEffectsContainer);}, 1000);}// Reset score change display after animation completessetTimeout(() => {scoreChange.textContent = '';}, 1000);// Clear active items after score updateconsole.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 updateconsole.log('Checking game state...');checkGameState();console.log('=== updateScoreDisplay completed ===');}// Handle dice upgradefunction upgradeDice() {// Check if game is already overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if already at maximum tierif (currentTier >= diceTiers.length - 1) {// If not already game over, end the game with win conditionif (!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 upgradeif (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 upgradecurrentScore -= requiredScore;// Round to 2 decimal placescurrentScore = Math.round(currentScore * 100) / 100;// Update score displayscoreValue.textContent = currentScore;showScoreChange(-5);// Increase tiercurrentTier++;// Update current tier displaycurrentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;// Update tier multiplier displayupdateTierMultiplierDisplay();// Unlock the new dice colorunlockDiceColor(currentTier);// Update color selection UIupdateColorSelection(currentTier);// Update upgrade cost displayupdateUpgradeCostDisplay();// Change to the new dice colorconsole.log(`Changing dice color to ${diceTiers[currentTier].color} (${diceTiers[currentTier].name})`);changeDiceColor(diceTiers[currentTier].color);// Check if this upgrade reached the maximum tiercheckGameState();// Randomly get an itemconst itemChance = Math.random();if (itemChance < 0.32) { // 32% chance to get double points carddoublePointsCards++;3 行未改动// Do nothing} else { // 2% chance to get lucky streak cardluckyStreakCards++;}// Update items display to show new countsupdateItemsDisplay();// Update items displayupdateItemsDisplay();// Check if reached the Unique diceif (currentTier === diceTiers.length - 1) {showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500');gameOver = true;createConfetti();}// Add to historyaddToHistory('UPGRADE', -5);// Add item to history if obtainedif (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 upgradecheckGameState();}// Show score change temporarilyfunction 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 optionfunction unlockDiceColor(tierIndex) {if (tierIndex >= 0 && tierIndex < colorOptions.length) {const option = colorOptions[tierIndex];5 行未改动option.classList.remove('locked');}, 300);}}// Show game messagefunction showGameMessage(message, className) {gameMessageDisplay.textContent = message;gameMessageDisplay.className = `mt-4 text-center font-semibold ${className}`;gameMessageDisplay.classList.remove('hidden');// Hide message after 3 secondssetTimeout(() => {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 displayfunction updateItemsDisplay() {// Update countsdoublePointsCount.textContent = doublePointsCards;noPenaltyCount.textContent = noPenaltyCards;luckyStreakCount.textContent = luckyStreakCards;// Enable/disable buttons based on available itemsuseDoublePointsButton.disabled = doublePointsCards <= 0 || gameOver;useNoPenaltyButton.disabled = noPenaltyCards <= 0 || activeItems.noPenalty || gameOver;useLuckyStreakButton.disabled = luckyStreakCards <= 0 || gameOver;// Update free rolls displayupdateFreeRollsDisplay();}// Update free rolls displayfunction updateFreeRollsDisplay() {if (freeRolls > 0) {freeRollsCountElement.textContent = freeRolls;freeRollsIndicator.classList.remove('hidden');} else {freeRollsIndicator.classList.add('hidden');}}// Update upgrade cost displayfunction updateUpgradeCostDisplay() {if (currentTier >= diceTiers.length - 1) {// Already at maximum tier2 行未改动const requiredScore = 5 + currentTier;upgradeCost.textContent = `(Cost: ${requiredScore})`;}}// Use double points cardfunction useDoublePointsCard() {if (doublePointsCards > 0 && !gameOver) {activeItems.double++;doublePointsCards--;// Update UIupdateItemsDisplay();showActiveItemIndicator();// Show messageshowGameMessage('Double Points Card activated! Next roll will double your score change.', 'text-green-500');}}// Use no penalty cardfunction useNoPenaltyCard() {if (noPenaltyCards > 0 && !activeItems.noPenalty && !gameOver) {activeItems.noPenalty = true;noPenaltyCards--;// Update UIupdateItemsDisplay();showActiveItemIndicator();// Show messageshowGameMessage('No Penalty Card activated! Next roll won\'t lose points.', 'text-blue-500');}}// Use lucky streak cardfunction useLuckyStreakCard() {if (luckyStreakCards > 0 && !gameOver) {freeRolls += 3;luckyStreakCards--;// Update UIupdateItemsDisplay();// Show messageshowGameMessage('Lucky Streak Card activated! You have 3 free rolls!', 'text-yellow-500');// Add to historyaddToHistory('ITEM USE', 'Lucky Streak Card');}}// Show active item indicatorfunction showActiveItemIndicator() {// Clear previous contentactiveItemIndicator.innerHTML = '';// Check if any items are activeif (activeItems.double === 0 && !activeItems.noPenalty) {activeItemIndicator.className = 'mt-3 text-center hidden';return;}// Create container for active itemsconst itemsContainer = document.createElement('div');itemsContainer.className = 'flex flex-wrap justify-center gap-2';// Add double points cards indicatorif (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 indicatorif (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 containeractiveItemIndicator.appendChild(itemsContainer);activeItemIndicator.className = 'mt-3 text-center';}// Clear active itemsfunction clearActiveItems() {activeItems = {double: 0,noPenalty: false};showActiveItemIndicator();}// End the game and display appropriate messagefunction endGame(isWin) {console.log('=== endGame called ===');console.log('Is win:', isWin, 'Current score:', currentScore);// Disable all interactive elementsrollButton.disabled = true;upgradeButton.disabled = true;rollButton.classList.add('opacity-70', 'cursor-not-allowed');upgradeButton.classList.add('opacity-70', 'cursor-not-allowed');// Disable all interactive elementscolorOptions.forEach(option => {option.disabled = true;option.classList.add('opacity-50', 'cursor-not-allowed');});// Disable item buttonsuseDoublePointsButton.disabled = true;useNoPenaltyButton.disabled = true;// Hide active item indicatoractiveItemIndicator.classList.add('hidden');// Create game over message elementconst 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 placesconst 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 listenergameOverMessage.querySelector('#play-again').addEventListener('click', () => {window.location.reload();});// Replace game message display with game over messageconst gameMessageContainer = gameMessageDisplay.parentElement;gameMessageContainer.replaceChild(gameOverMessage, gameMessageDisplay);gameMessageDisplay = gameOverMessage;// Add game end to historyaddToHistory(isWin ? 'GAME WIN' : 'GAME OVER', 0);console.log('=== endGame completed ===');}// Show warning when score is lowfunction showLowScoreWarning() {// Only show warning if not already showingif (gameMessageDisplay.classList.contains('hidden')) {showGameMessage('Warning: Low score! Risk of game over.', 'text-orange-500');}}// Update color selection UI to show the currently selected colorfunction updateColorSelection(selectedIndex) {// Remove active state from all color optionscolorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary'));// Add active state to the selected color optionif (selectedIndex >= 0 && selectedIndex < colorOptions.length) {colorOptions[selectedIndex].classList.add('ring-2', 'ring-offset-2', 'ring-primary');}}// Add result to historyfunction addToHistory(result, scoreChangeData, isFreeRoll = false) {const now = new Date();const timeString = now.toLocaleTimeString();// Determine score change display and colorlet 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 applicableif (isFreeRoll) {actionText += ` <span class="text-yellow-500">(Free Roll)</span>`;}// Add item effect indicators if applicableconst 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 itemsif (historyList.children.length > 5) {historyList.removeChild(historyList.lastChild);}}// Create confetti effectfunction createConfetti() {const confettiContainer = document.createElement('div');confettiContainer.className = 'fixed inset-0 pointer-events-none overflow-hidden';document.body.appendChild(confettiContainer);// Create 50 confetti piecesfor (let i = 0; i < 50; i++) {const confetti = document.createElement('div');confetti.className = 'confetti';// Random positionconst posX = Math.random() * 100;const delay = Math.random() * 3;const duration = 3 + Math.random() * 2;// Random colorsconst 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 completessetTimeout(() => {document.body.removeChild(confettiContainer);}, 5000);}// Create particle effect on lockfunction createLockParticles(lockElement) {// Get lock element positionconst rect = lockElement.getBoundingClientRect();const centerX = rect.left + rect.width / 2;const centerY = rect.top + rect.height / 2;// Create particle containerconst 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 particlesfor (let i = 0; i < 15; i++) {const particle = document.createElement('div');particle.className = 'lock-particle';// Random direction and distanceconst 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 durationconst duration = 0.5 + Math.random() * 0.5;// Set particle stylesparticle.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 completessetTimeout(() => {document.body.removeChild(particleContainer);}, 1000);}// Function to darken a color by a certain percentagefunction 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 percentager = 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 hexconst darkenedHex = '#' +r.toString(16).padStart(2, '0') +g.toString(16).padStart(2, '0') +b.toString(16).padStart(2, '0');return darkenedHex;}// Change dice color functionfunction 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 contrastif (color.toUpperCase() === '#FFFFFF') {// White dice - use black dots and light gray bordersdotColor = '#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 colorface.style.backgroundColor = color;// Set face border colorface.style.border = `3px solid ${borderColor}`;// Set dots colorconst dots = face.querySelectorAll('.dot');dots.forEach(dot => {dot.style.backgroundColor = dotColor;// Add slight border to dots for better definitiondot.style.border = color.toUpperCase() === '#FFFFFF' ? '1px solid rgba(0, 0, 0, 0.2)' : '1px solid rgba(0, 0, 0, 0.1)';});});}// Update tier multiplier displayfunction 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 buttonrollButton.addEventListener('click', rollDice);// Event listener for upgrade buttonupgradeButton.addEventListener('click', upgradeDice);// Event listeners for item buttonsuseDoublePointsButton.addEventListener('click', useDoublePointsCard);useNoPenaltyButton.addEventListener('click', useNoPenaltyCard);useLuckyStreakButton.addEventListener('click', useLuckyStreakCard);// Event listeners for color optionscolorOptions.forEach((option, index) => {// Disable all color options except the first one initiallyif (index !== 0) {option.disabled = true;option.classList.add('locked');}option.addEventListener('click', () => {// Check if game is overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if color is unlockedif (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 colorcolorOptions.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 tiercurrentTier = index;currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;updateTierMultiplierDisplay();});});// Initialize dice on page loadwindow.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 displaycurrentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;// Initialize tier multiplier displayupdateTierMultiplierDisplay();// Initialize items displayupdateItemsDisplay();// Initialize upgrade cost displayupdateUpgradeCostDisplay();// Show welcome messagesetTimeout(() => {showGameMessage('Welcome! Roll the dice to earn points and upgrade your dice!', 'text-blue-500');}, 1000);});// Also try initializing on window loadwindow.addEventListener('load', () => {console.log('Window loaded');// If dice not already initialized, try againif (diceElement.children.length === 0) {console.log('Dice not initialized, trying again...');initializeDice();}});// Game Rules Modal Functionality(function() {// Get elementsconst 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 scrollingfunction preventBackgroundScroll(event) {// Allow scrolling inside the modal contentif (modalContent.contains(event.target)) {// Check if we're at the top or bottom of the modal contentconst 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 downif ((isAtTop && event.deltaY < 0) || (isAtBottom && event.deltaY > 0)) {event.preventDefault();}} else {// Prevent scrolling outside the modal contentevent.preventDefault();}}// Function to open modalfunction openModal() {// Add event listeners to prevent background scrollingdocument.addEventListener('wheel', preventBackgroundScroll, { passive: false });document.addEventListener('touchmove', preventBackgroundScroll, { passive: false });// Add open class to trigger animationsrulesModal.classList.add('modal-open');// Show the modalrulesModal.style.visibility = 'visible';}// Function to close modalfunction closeModal() {// Remove open class to trigger animationsrulesModal.classList.remove('modal-open');// Remove event listeners that prevent background scrollingdocument.removeEventListener('wheel', preventBackgroundScroll);document.removeEventListener('touchmove', preventBackgroundScroll);// Hide the modal after animation completessetTimeout(() => {rulesModal.style.visibility = 'hidden';}, 300);}// Add event listenersif (rulesButton) {rulesButton.addEventListener('click', openModal);}// Close buttonscloseButtons.forEach(button => {button.addEventListener('click', closeModal);});// Close when clicking outside the modal contentmodalBackdrop.addEventListener('click', closeModal);// Close when pressing Escape keydocument.addEventListener('keydown', (event) => {if (event.key === 'Escape' && rulesModal.classList.contains('modal-open')) {closeModal();}});// Add hover effect to rules buttonif (rulesButton) {rulesButton.addEventListener('mouseenter', () => {rulesButton.classList.add('scale-105');});rulesButton.addEventListener('mouseleave', () => {rulesButton.classList.remove('scale-105');});}// Add click effect to close buttonscloseButtons.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 行未改动```::::::::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 handlerwindow.addEventListener('error', function(event) {console.error('Global error caught:', event.error);// Try to get roll button elementconst 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 messageconst 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 elementsconst 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 elementsconst 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 statelet currentScore = 10; // Initial scorelet currentTier = 0; // Initial dice tier (0 = Empty)let gameOver = false; // Game over flaglet rollCount = 0; // Number of dice rollslet luckyRollsRemaining = 0; // Number of lucky rolls remaining// Item systemlet doublePointsCards = 0; // Number of double points cardslet noPenaltyCards = 0; // Number of no penalty cardslet luckyStreakCards = 0; // Number of lucky streak cardslet freeRolls = 0; // Number of free rolls availablelet activeItems = { // Currently active itemsdouble: 0, // Number of active double points cardsnoPenalty: false // Whether no penalty card is active};// Dice tiers configurationconst diceTiers = [{ name: 'Empty', color: '#FFFFFF' },{ name: 'Common', color: '#7EEF6D' },5 行未改动{ name: 'Ultra', color: '#ff2b75' },{ name: 'Super', color: '#2bffa3' },{ name: 'Unique', color: '#555555' }];// Initialize 3D dicefunction initializeDice() {console.log('Initializing dice...');// Create 6 faces for the diceconst 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 numberfor (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 clearlydiceElement.style.transform = 'rotateX(0deg) rotateY(0deg)';}// Get random rotation values for the dicefunction getRandomRotation() {// Determine which face we want to showconst targetFace = Math.floor(Math.random() * 6) + 1;// Get current rotation from dice elementconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');const matrix = new DOMMatrix(currentTransform);// Extract current rotation angleslet currentX = 0, currentY = 0;// If transform is not identity matrix, extract rotationif (currentTransform !== 'none') {// Calculate rotation from matrixcurrentX = 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 facelet 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 accumulatinglet diffX = targetX - currentX;let diffY = targetY - currentY;// Normalize the difference to the range [-180, 180] to find the shortest pathdiffX = ((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 pathconst 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 visibleconst 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 functionfunction rollDice() {// Check if game is overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if there are free rolls availableconst isFreeRoll = freeRolls > 0;// Check if in lucky streak modeconst isLuckyRoll = luckyRollsRemaining > 0;// Increment roll count only if not a free roll and not a lucky roll that will be revertedif (!isFreeRoll && !isLuckyRoll) {rollCount++;console.log(`Roll count: ${rollCount}`);2 行未改动freeRolls--;updateFreeRollsDisplay();console.log(`Free roll used. Remaining free rolls: ${freeRolls}`);}// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}console.log('Rolling dice...');console.log('Button state before disable:', rollButton.disabled);// Disable button during animationrollButton.disabled = true;rollButton.classList.add('opacity-70', 'cursor-not-allowed');console.log('Button state after disable:', rollButton.disabled);// Hide result displayresultDisplay.classList.add('hidden');try {// Set animation durationconst duration = 2000; // Fixed duration for consistent experience// Get random rotation values for the final positionconst rotationData = getRandomRotation();console.log('Rotation data:', rotationData);console.log('Target face:', rotationData.targetFace);// Animate the dice using JavaScript for more controlanimateDice(duration, rotationData);// Set a safety timeout to ensure button is re-enabled even if something goes wrongsetTimeout(() => {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 animationfunction animateDice(duration, rotationData) {console.log('Animate dice called with rotationData:', rotationData);const startTime = performance.now();const finalRotation = rotationData;// Get current rotation from dice elementconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');const matrix = new DOMMatrix(currentTransform);// Extract current rotation angleslet startX = 0, startY = 0;// If transform is not identity matrix, extract rotationif (currentTransform !== 'none') {// Calculate rotation from matrixstartX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI);startY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI);}// Function to handle each animation framefunction animate(currentTime) {const elapsedTime = currentTime - startTime;const progress = Math.min(elapsedTime / duration, 1);// Apply easing function for smooth, natural animationconst easedProgress = easeOutCubic(progress);// Calculate current rotation - smooth continuous rotationconst currentX = startX + (finalRotation.x - startX) * easedProgress;const currentY = startY + (finalRotation.y - startY) * easedProgress;// Spin animation: rotate in placediceElement.style.transform = `rotateX(${currentX}deg) rotateY(${currentY}deg)`;// Continue animation if not completeif (progress < 1) {requestAnimationFrame(animate);} else {// Animation complete - ensure we're at the exact target rotationdiceElement.style.transform = `rotateX(${finalRotation.x}deg) rotateY(${finalRotation.y}deg)`;// Show result after a delay to ensure rotation is complete and CSS has appliedconsole.log('Animation complete, waiting before finalizing...');setTimeout(() => {// Double-check that the transform has been applied3 行未改动finalizeAnimation(finalRotation);}, 600);}}// Start the animationrequestAnimationFrame(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 endfunction easeOutCubic(t) {return 1 - Math.pow(1 - t, 3);}// Calculate score change based on dice roll resultfunction 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 multiplierconst tierMultiplier = 1 + currentTier / 10;let finalChange;if (baseChange < 0) {// For point loss, use multiplier of 1 regardless of tierfinalChange = baseChange * 1;} else {// For point gain or neutral, use tier multiplierfinalChange = baseChange * tierMultiplier;}// Apply active item effectsconst itemsUsed = {double: activeItems.double,noPenalty: activeItems.noPenalty};// Apply no penalty card firstif (activeItems.noPenalty && baseChange < 0) {finalChange = 0;}// Apply double points cardsif (activeItems.double > 0) {finalChange = finalChange * Math.pow(2, activeItems.double);}// Round to 2 decimal places to avoid floating point precision issuesfinalChange = Math.round(finalChange * 100) / 100;return {baseChange: baseChange,finalChange: finalChange,itemsUsed: itemsUsed,tierMultiplier: tierMultiplier};}// Enable roll buttonfunction enableRollButton() {console.log('Button state before enable:', rollButton.disabled);// Directly enable the buttonrollButton.disabled = false;rollButton.classList.remove('opacity-70', 'cursor-not-allowed');console.log('Button state after enable:', rollButton.disabled);// Double-check and force enable if neededif (rollButton.disabled) {console.warn('Forcing button enable');setTimeout(() => {2 行未改动console.log('Button state after forced enable:', rollButton.disabled);}, 100);}}// Finalize the animation and show resultfunction 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 recalculatingconst result = finalRotation.targetFace;console.log(`Final result: ${result} (should show face ${result})`);// Verify dice is in the correct positionconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');console.log('Current dice transform:', currentTransform);// Show result displayconsole.log('Showing result display...');resultValue.textContent = result;resultDisplay.classList.remove('hidden');// Add shine effect to resultresultDisplay.classList.add('result-shine');setTimeout(() => {resultDisplay.classList.remove('result-shine');}, 500);// Calculate and update scoreconsole.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 animationconsole.log('Updating score display...');updateScoreDisplay(scoreChangeData);// Enable buttonconsole.log('Enabling roll button...');enableRollButton();// Add to history - include whether it was a free roll or lucky rolladdToHistory(result, scoreChangeData, isFreeRoll, isLuckyRoll);// Check if reached the Unique diceif (currentTier === diceTiers.length - 1) {showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500');gameOver = true;createConfetti();}// Handle lucky roll logicif (luckyRollsRemaining > 0) {// Decrement remaining lucky rollsluckyRollsRemaining--;// If rolled 1 or 2, decrement roll countif (result === 1 || result === 2) {rollCount--;console.log(`Lucky roll: Reverted roll count to ${rollCount}`);// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}// Show messageshowGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500');}// Update lucky rolls displayupdateLuckyRollsDisplay();// If no more lucky rolls, show messageif (luckyRollsRemaining === 0) {setTimeout(() => {showGameMessage('Lucky Streak ended!', 'text-yellow-500');}, 1000);}}// Create confetti effect if result is 6if (result === 6) {createConfetti();}// Debug: log final stateconsole.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 animationfunction 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 placescurrentScore = Math.round(currentScore * 100) / 100;scoreValue.textContent = currentScore;console.log('Score value updated to:', currentScore);// Clear previous score change displayscoreChange.textContent = '';scoreChange.className = 'ml-2 text-sm font-normal';console.log('Cleared previous score change display');// Show score change with appropriate stylingif (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 usedif (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) {// Create container for item effectsconst itemEffectsContainer = document.createElement('div');itemEffectsContainer.className = 'flex flex-wrap gap-2 mt-1';// Add tier multiplier effect if applicableif (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 effectif (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 effectif (itemsUsed.double > 0) {const doublePointsEffect = document.createElement('div');doublePointsEffect.className = 'text-xs text-green-500';// Calculate multiplierconst multiplier = Math.pow(2, itemsUsed.double);let calculationText = `${baseChange}`;// Apply tier multiplier for displaylet displayChange = baseChange * tierMultiplier;// Apply no penalty first for displayif (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 usedif (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 displayscoreDisplay.appendChild(itemEffectsContainer);// Remove after animationsetTimeout(() => {scoreDisplay.removeChild(itemEffectsContainer);}, 1000);}// Reset score change display after animation completessetTimeout(() => {scoreChange.textContent = '';}, 1000);// Clear active items after score updateconsole.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 updateconsole.log('Checking game state...');checkGameState();// Update upgrade button stateupdateUpgradeCostDisplay();console.log('=== updateScoreDisplay completed ===');}// Handle dice upgradefunction upgradeDice() {// Check if game is already overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if already at maximum tierif (currentTier >= diceTiers.length - 1) {// If not already game over, end the game with win conditionif (!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 upgradeif (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 upgradecurrentScore -= requiredScore;// Round to 2 decimal placescurrentScore = Math.round(currentScore * 100) / 100;// Update score displayscoreValue.textContent = currentScore;showScoreChange(-requiredScore);// Increase tiercurrentTier++;// Update current tier displaycurrentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;// Update tier multiplier displayupdateTierMultiplierDisplay();// Unlock the new dice colorunlockDiceColor(currentTier);// Update color selection UIupdateColorSelection(currentTier);// Update upgrade cost displayupdateUpgradeCostDisplay();// Change to the new dice colorconsole.log(`Changing dice color to ${diceTiers[currentTier].color} (${diceTiers[currentTier].name})`);changeDiceColor(diceTiers[currentTier].color);// Check if this upgrade reached the maximum tiercheckGameState();// Randomly get an itemconst itemChance = Math.random();if (itemChance < 0.30) { // 30% chance to get double points carddoublePointsCards++;3 行未改动luckyStreakCards++;} else { // 30% chance to get nothing// Do nothing}// Update items display to show new countsupdateItemsDisplay();// Update items displayupdateItemsDisplay();// Check if reached the Unique diceif (currentTier === diceTiers.length - 1) {showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500');gameOver = true;createConfetti();}// Handle lucky roll logicif (luckyRollsRemaining > 0) {// Decrement remaining lucky rollsluckyRollsRemaining--;// If rolled 1 or 2, decrement roll countif (result === 1 || result === 2) {rollCount--;console.log(`Lucky roll: Reverted roll count to ${rollCount}`);// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}// Show messageshowGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500');}// Update lucky rolls displayupdateLuckyRollsDisplay();// If no more lucky rolls, show messageif (luckyRollsRemaining === 0) {setTimeout(() => {showGameMessage('Lucky Streak ended!', 'text-yellow-500');}, 1000);}}// Add to historyaddToHistory('UPGRADE', -5);// Add item to history if obtainedif (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 upgradecheckGameState();}// Show score change temporarilyfunction 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 optionfunction unlockDiceColor(tierIndex) {if (tierIndex >= 0 && tierIndex < colorOptions.length) {const option = colorOptions[tierIndex];5 行未改动option.classList.remove('locked');}, 300);}}// Show game messagefunction showGameMessage(message, className) {gameMessageDisplay.textContent = message;gameMessageDisplay.className = `mt-4 text-center font-semibold ${className}`;gameMessageDisplay.classList.remove('hidden');// Hide message after 3 secondssetTimeout(() => {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 recordsetTimeout(() => {checkWinRecord();}, 1000);}// Check if score is low (warning)if (currentScore >= 0 && currentScore <= 5 && !gameOver) {showLowScoreWarning();}console.log('=== checkGameState completed ===');}// Update items displayfunction updateItemsDisplay() {// Update countsdoublePointsCount.textContent = doublePointsCards;noPenaltyCount.textContent = noPenaltyCards;luckyStreakCount.textContent = luckyStreakCards;// Enable/disable buttons based on available itemsuseDoublePointsButton.disabled = doublePointsCards <= 0 || gameOver;useNoPenaltyButton.disabled = noPenaltyCards <= 0 || activeItems.noPenalty || gameOver;useLuckyStreakButton.disabled = luckyStreakCards <= 0 || gameOver;// Update free rolls displayupdateFreeRollsDisplay();// Update lucky rolls displayupdateLuckyRollsDisplay();}// Update free rolls displayfunction updateFreeRollsDisplay() {if (freeRolls > 0) {freeRollsCountElement.textContent = freeRolls;freeRollsIndicator.classList.remove('hidden');} else {freeRollsIndicator.classList.add('hidden');}}// Update upgrade cost display and button statefunction 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 scoreif (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 cardfunction useDoublePointsCard() {if (doublePointsCards > 0 && !gameOver) {activeItems.double++;doublePointsCards--;// Update UIupdateItemsDisplay();showActiveItemIndicator();// Show messageshowGameMessage('Double Points Card activated! Next roll will double your score change.', 'text-green-500');}}// Use no penalty cardfunction useNoPenaltyCard() {if (noPenaltyCards > 0 && !activeItems.noPenalty && !gameOver) {activeItems.noPenalty = true;noPenaltyCards--;// Update UIupdateItemsDisplay();showActiveItemIndicator();// Show messageshowGameMessage('No Penalty Card activated! Next roll won\'t lose points.', 'text-blue-500');}}// Use lucky streak cardfunction useLuckyStreakCard() {if (luckyStreakCards > 0 && !gameOver) {luckyRollsRemaining = 3;luckyStreakCards--;// Update UIupdateItemsDisplay();updateLuckyRollsDisplay();// Show messageshowGameMessage('Lucky Streak Card activated! Next 3 rolls of 1 or 2 won\'t count!', 'text-yellow-500');// Add to historyaddToHistory('ITEM USE', 'Lucky Streak Card');}}// Update lucky rolls displayfunction updateLuckyRollsDisplay() {if (luckyRollsRemaining > 0) {// Check if indicator exists, if not create itlet 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 indicatorconst freeRollsIndicator = document.getElementById('free-rolls-indicator');if (freeRollsIndicator) {freeRollsIndicator.parentNode.insertBefore(luckyRollsIndicator, freeRollsIndicator.nextSibling);10 行未改动}}}}// Update contentluckyRollsIndicator.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 indicatorluckyRollsIndicator.classList.remove('hidden');} else {// Remove indicator if exists2 行未改动luckyRollsIndicator.classList.add('hidden');}}}// Show active item indicatorfunction showActiveItemIndicator() {// Clear previous contentactiveItemIndicator.innerHTML = '';// Check if any items are activeif (activeItems.double === 0 && !activeItems.noPenalty) {activeItemIndicator.className = 'mt-3 text-center hidden';return;}// Create container for active itemsconst itemsContainer = document.createElement('div');itemsContainer.className = 'flex flex-wrap justify-center gap-2';// Add double points cards indicatorif (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 indicatorif (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 containeractiveItemIndicator.appendChild(itemsContainer);activeItemIndicator.className = 'mt-3 text-center';}// Clear active itemsfunction clearActiveItems() {activeItems = {double: 0,noPenalty: false};showActiveItemIndicator();}// End the game and display appropriate messagefunction endGame(isWin) {console.log('=== endGame called ===');console.log('Is win:', isWin, 'Current score:', currentScore);// Disable all interactive elementsrollButton.disabled = true;upgradeButton.disabled = true;rollButton.classList.add('opacity-70', 'cursor-not-allowed');upgradeButton.classList.add('opacity-70', 'cursor-not-allowed');// Disable all interactive elementscolorOptions.forEach(option => {option.disabled = true;option.classList.add('opacity-50', 'cursor-not-allowed');});// Disable item buttonsuseDoublePointsButton.disabled = true;useNoPenaltyButton.disabled = true;useLuckyStreakButton.disabled = true;// Hide active indicatorsactiveItemIndicator.classList.add('hidden');const luckyRollsIndicator = document.getElementById('lucky-rolls-indicator');if (luckyRollsIndicator) {luckyRollsIndicator.classList.add('hidden');}// Create game over message elementconst 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 placesconst 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 listenergameOverMessage.querySelector('#play-again').addEventListener('click', () => {window.location.reload();});// Replace game message display with game over messageconst gameMessageContainer = gameMessageDisplay.parentElement;gameMessageContainer.replaceChild(gameOverMessage, gameMessageDisplay);gameMessageDisplay = gameOverMessage;// Add game end to historyaddToHistory(isWin ? 'GAME WIN' : 'GAME OVER', 0);console.log('=== endGame completed ===');}// Show warning when score is lowfunction showLowScoreWarning() {// Only show warning if not already showingif (gameMessageDisplay.classList.contains('hidden')) {showGameMessage('Warning: Low score! Risk of game over.', 'text-orange-500');}}// Update color selection UI to show the currently selected colorfunction updateColorSelection(selectedIndex) {// Remove active state from all color optionscolorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary'));// Add active state to the selected color optionif (selectedIndex >= 0 && selectedIndex < colorOptions.length) {colorOptions[selectedIndex].classList.add('ring-2', 'ring-offset-2', 'ring-primary');}}// Add result to historyfunction addToHistory(result, scoreChangeData, isFreeRoll = false, isLuckyRoll = false) {const now = new Date();const timeString = now.toLocaleTimeString();// Determine score change display and colorlet 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 applicableif (isFreeRoll) {actionText += ` <span class="text-yellow-500">(Free Roll)</span>`;}// Add lucky roll indicator if applicableif (isLuckyRoll) {actionText += ` <span class="text-yellow-500">(Lucky Roll)</span>`;}// Add item effect indicators if applicableconst 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 itemsif (historyList.children.length > 5) {historyList.removeChild(historyList.lastChild);}}// Create confetti effectfunction createConfetti() {const confettiContainer = document.createElement('div');confettiContainer.className = 'fixed inset-0 pointer-events-none overflow-hidden';document.body.appendChild(confettiContainer);// Create 50 confetti piecesfor (let i = 0; i < 50; i++) {const confetti = document.createElement('div');confetti.className = 'confetti';// Random positionconst posX = Math.random() * 100;const delay = Math.random() * 3;const duration = 3 + Math.random() * 2;// Random colorsconst 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 completessetTimeout(() => {document.body.removeChild(confettiContainer);}, 5000);}// Create particle effect on lockfunction createLockParticles(lockElement) {// Get lock element positionconst rect = lockElement.getBoundingClientRect();const centerX = rect.left + rect.width / 2;const centerY = rect.top + rect.height / 2;// Create particle containerconst 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 particlesfor (let i = 0; i < 15; i++) {const particle = document.createElement('div');particle.className = 'lock-particle';// Random direction and distanceconst 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 durationconst duration = 0.5 + Math.random() * 0.5;// Set particle stylesparticle.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 completessetTimeout(() => {document.body.removeChild(particleContainer);}, 1000);}// Function to darken a color by a certain percentagefunction 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 percentager = 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 hexconst darkenedHex = '#' +r.toString(16).padStart(2, '0') +g.toString(16).padStart(2, '0') +b.toString(16).padStart(2, '0');return darkenedHex;}// Change dice color functionfunction 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 contrastif (color.toUpperCase() === '#FFFFFF') {// White dice - use black dots and light gray bordersdotColor = '#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 colorface.style.backgroundColor = color;// Set face border colorface.style.border = `3px solid ${borderColor}`;// Set dots colorconst dots = face.querySelectorAll('.dot');dots.forEach(dot => {dot.style.backgroundColor = dotColor;// Add slight border to dots for better definitiondot.style.border = color.toUpperCase() === '#FFFFFF' ? '1px solid rgba(0, 0, 0, 0.2)' : '1px solid rgba(0, 0, 0, 0.1)';});});}// Update tier multiplier displayfunction 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 buttonrollButton.addEventListener('click', rollDice);// Event listener for upgrade buttonupgradeButton.addEventListener('click', upgradeDice);// Event listeners for item buttonsuseDoublePointsButton.addEventListener('click', useDoublePointsCard);useNoPenaltyButton.addEventListener('click', useNoPenaltyCard);useLuckyStreakButton.addEventListener('click', useLuckyStreakCard);// Event listeners for color optionscolorOptions.forEach((option, index) => {// Disable all color options except the first one initiallyif (index !== 0) {option.disabled = true;option.classList.add('locked');}option.addEventListener('click', () => {// Check if game is overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if color is unlockedif (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 colorcolorOptions.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 tiercurrentTier = index;currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;updateTierMultiplierDisplay();});});// Initialize dice on page loadwindow.addEventListener('DOMContentLoaded', () => {console.log('=== DOMContentLoaded event fired ===');// Check if elements existconsole.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 displaycurrentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;// Initialize tier multiplier displayupdateTierMultiplierDisplay();// Initialize items displayupdateItemsDisplay();// Initialize upgrade cost displayupdateUpgradeCostDisplay();// Show welcome messagesetTimeout(() => {showGameMessage('Welcome! Roll the dice to earn points and upgrade your dice!', 'text-blue-500');}, 1000);});// Also try initializing on window loadwindow.addEventListener('load', () => {console.log('Window loaded');// If dice not already initialized, try againif (diceElement.children.length === 0) {console.log('Dice not initialized, trying again...');initializeDice();}});// Game Rules Modal Functionality(function() {// Get elementsconst 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 scrollingfunction preventBackgroundScroll(event) {// Allow scrolling inside the modal contentif (modalContent.contains(event.target)) {// Check if we're at the top or bottom of the modal contentconst 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 downif ((isAtTop && event.deltaY < 0) || (isAtBottom && event.deltaY > 0)) {event.preventDefault();}} else {// Prevent scrolling outside the modal contentevent.preventDefault();}}// Function to open modalfunction openModal() {// Add event listeners to prevent background scrollingdocument.addEventListener('wheel', preventBackgroundScroll, { passive: false });document.addEventListener('touchmove', preventBackgroundScroll, { passive: false });// Add open class to trigger animationsrulesModal.classList.add('modal-open');// Show the modalrulesModal.style.visibility = 'visible';}// Function to close modalfunction closeModal() {// Remove open class to trigger animationsrulesModal.classList.remove('modal-open');// Remove event listeners that prevent background scrollingdocument.removeEventListener('wheel', preventBackgroundScroll);document.removeEventListener('touchmove', preventBackgroundScroll);// Hide the modal after animation completessetTimeout(() => {rulesModal.style.visibility = 'hidden';}, 300);}// Add event listenersif (rulesButton) {rulesButton.addEventListener('click', openModal);}// Close buttonscloseButtons.forEach(button => {button.addEventListener('click', closeModal);});// Close when clicking outside the modal contentmodalBackdrop.addEventListener('click', closeModal);// Close when pressing Escape keydocument.addEventListener('keydown', (event) => {if (event.key === 'Escape' && rulesModal.classList.contains('modal-open')) {closeModal();}});// Add hover effect to rules buttonif (rulesButton) {rulesButton.addEventListener('mouseenter', () => {rulesButton.classList.add('scale-105');});rulesButton.addEventListener('mouseleave', () => {rulesButton.classList.remove('scale-105');});}// Add click effect to close buttonscloseButtons.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 handlerwindow.addEventListener('error', function(event) {console.error('Global error caught:', event.error);// Try to get roll button elementconst 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 messageconst 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 elementsconst 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 elementsconst 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 statelet currentScore = 10; // Initial scorelet currentTier = 0; // Initial dice tier (0 = Empty)let gameOver = false; // Game over flaglet rollCount = 0; // Number of dice rollslet luckyRollsRemaining = 0; // Number of lucky rolls remaininglet isRolling = false; // Whether dice is currently rolling// Item systemlet doublePointsCards = 0; // Number of double points cardslet noPenaltyCards = 0; // Number of no penalty cardslet luckyStreakCards = 0; // Number of lucky streak cardslet freeRolls = 0; // Number of free rolls availablelet activeItems = { // Currently active itemsdouble: 0, // Number of active double points cardsnoPenalty: false // Whether no penalty card is active};// Dice tiers configurationconst 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 dicefunction initializeDice() {console.log('Initializing dice...');// Create 6 faces for the diceconst 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 numberfor (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 clearlydiceElement.style.transform = 'rotateX(0deg) rotateY(0deg)';}// Get random rotation values for the dicefunction getRandomRotation() {// Determine which face we want to showconst targetFace = Math.floor(Math.random() * 6) + 1;// Get current rotation from dice elementconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');const matrix = new DOMMatrix(currentTransform);// Extract current rotation angleslet currentX = 0, currentY = 0;// If transform is not identity matrix, extract rotationif (currentTransform !== 'none') {// Calculate rotation from matrixcurrentX = 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 facelet targetX = 0, targetY = 0;switch(targetFace) {case 1: // Front face (Z+) - visible when no rotationtargetX = 0;targetY = 0;break;case 2: // Left face (X-) - visible when Y rotated 270 degreestargetX = 0;targetY = 270;break;case 3: // Back face (Z-) - visible when Y rotated 180 degreestargetX = 0;targetY = 180;break;case 4: // Right face (X+) - visible when Y rotated 90 degreestargetX = 0;targetY = 90;break;case 5: // Top face (Y-) - visible when X rotated -90 degreestargetX = -90;targetY = 0;break;case 6: // Bottom face (Y+) - visible when X rotated 90 degreestargetX = 90;targetY = 0;break;}// Calculate the shortest path to the target rotation// This prevents large rotation values from accumulatinglet diffX = targetX - currentX;let diffY = targetY - currentY;// Normalize the difference to the range [-180, 180] to find the shortest pathdiffX = ((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 pathconst 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 visibleconst 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 functionfunction rollDice() {// Check if game is overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if there are free rolls availableconst isFreeRoll = freeRolls > 0;// Check if in lucky streak modeconst 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 countfreeRolls--;updateFreeRollsDisplay();console.log(`Free roll used. Remaining free rolls: ${freeRolls}`);}// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}console.log('Rolling dice...');console.log('Button state before disable:', rollButton.disabled);// Set rolling state and disable button during animationisRolling = true;rollButton.disabled = true;rollButton.classList.add('opacity-70', 'cursor-not-allowed');// Disable other interactive elements during rollupgradeButton.disabled = true;upgradeButton.classList.add('opacity-70', 'cursor-not-allowed');useDoublePointsButton.disabled = true;useNoPenaltyButton.disabled = true;useLuckyStreakButton.disabled = true;// Disable color options during rollcolorOptions.forEach(option => {option.disabled = true;});console.log('Button state after disable:', rollButton.disabled);// Hide result displayresultDisplay.classList.add('hidden');// Reset dice display height - use Tailwind class instead of inline styleconst diceDisplay = document.getElementById('dice-display');if (diceDisplay) {// Ensure the height class is applied to prevent layout shifts during animationdiceDisplay.classList.add('h-48');}try {// Set animation durationconst duration = 2000; // Fixed duration for consistent experience// Get random rotation values for the final positionconst rotationData = getRandomRotation();console.log('Rotation data:', rotationData);console.log('Target face:', rotationData.targetFace);// Animate the dice using JavaScript for more controlanimateDice(duration, rotationData, { isFreeRoll, isLuckyRoll });// Set a safety timeout to ensure button is re-enabled even if something goes wrongsetTimeout(() => {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 errorenableRollButton();showGameMessage('An error occurred during the dice roll. Please try again.', 'text-red-500');}}// Animate the dice with spin animationfunction 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 elementconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');const matrix = new DOMMatrix(currentTransform);// Extract current rotation angleslet startX = 0, startY = 0;// If transform is not identity matrix, extract rotationif (currentTransform !== 'none') {// Calculate rotation from matrixstartX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI);startY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI);}// Function to handle each animation framefunction animate(currentTime) {const elapsedTime = currentTime - startTime;const progress = Math.min(elapsedTime / duration, 1);// Apply easing function for smooth, natural animationconst easedProgress = easeOutCubic(progress);// Calculate current rotation - smooth continuous rotationconst currentX = startX + (finalRotation.x - startX) * easedProgress;const currentY = startY + (finalRotation.y - startY) * easedProgress;// Spin animation: rotate in placediceElement.style.transform = `rotateX(${currentX}deg) rotateY(${currentY}deg)`;// Continue animation if not completeif (progress < 1) {requestAnimationFrame(animate);} else {// Animation complete - ensure we're at the exact target rotationdiceElement.style.transform = `rotateX(${finalRotation.x}deg) rotateY(${finalRotation.y}deg)`;// Show result after a delay to ensure rotation is complete and CSS has appliedconsole.log('Animation complete, waiting before finalizing...');setTimeout(() => {// Double-check that the transform has been appliedconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');console.log('Current transform after animation:', currentTransform);console.log('Calling finalizeAnimation...');finalizeAnimation(finalRotation, rollContext);}, 600);}}// Start the animationrequestAnimationFrame(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 endfunction easeOutCubic(t) {return 1 - Math.pow(1 - t, 3);}// Calculate score change based on dice roll resultfunction 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 multiplierconst tierMultiplier = 1 + currentTier / 10;let finalChange;if (baseChange < 0) {// For point loss, use multiplier of 1 regardless of tierfinalChange = baseChange * 1;} else {// For point gain or neutral, use tier multiplierfinalChange = baseChange * tierMultiplier;}// Apply active item effectsconst itemsUsed = {double: activeItems.double,noPenalty: activeItems.noPenalty};// Apply no penalty card firstif (activeItems.noPenalty && baseChange < 0) {finalChange = 0;}// Apply double points cardsif (activeItems.double > 0) {finalChange = finalChange * Math.pow(2, activeItems.double);}// Round to 2 decimal places to avoid floating point precision issuesfinalChange = Math.round(finalChange * 100) / 100;return {baseChange: baseChange,finalChange: finalChange,itemsUsed: itemsUsed,tierMultiplier: tierMultiplier};}// Enable roll buttonfunction enableRollButton() {console.log('Button state before enable:', rollButton.disabled);// Directly enable the buttonrollButton.disabled = false;rollButton.classList.remove('opacity-70', 'cursor-not-allowed');// Re-enable other interactive buttons based on their conditionsupdateUpgradeCostDisplay(); // This will enable/disable upgrade button based on scoreupdateItemsDisplay(); // This will enable/disable item buttons based on availabilityconsole.log('Button state after enable:', rollButton.disabled);// Double-check and force enable if neededif (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 resultfunction 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 recalculatingconst result = finalRotation.targetFace;console.log(`Final result: ${result} (should show face ${result})`);// Verify dice is in the correct positionconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');console.log('Current dice transform:', currentTransform);// Show result displayconsole.log('Showing result display...');resultValue.textContent = result;resultDisplay.classList.remove('hidden');// Add shine effect to resultresultDisplay.classList.add('result-shine');setTimeout(() => {resultDisplay.classList.remove('result-shine');}, 500);// Calculate and update scoreconsole.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 animationconsole.log('Updating score display...');updateScoreDisplay(scoreChangeData);// Enable buttonconsole.log('Enabling roll button...');enableRollButton();// Add to history - include whether it was a free roll or lucky rolladdToHistory(result, scoreChangeData, isFreeRoll, isLuckyRoll);// Check if reached the Unique diceif (currentTier === diceTiers.length - 1) {showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500');gameOver = true;createConfetti();}// Handle lucky roll logicif (luckyRollsRemaining > 0) {// Decrement remaining lucky rollsluckyRollsRemaining--;// If rolled 1 or 2, decrement roll countif (result === 1 || result === 2) {rollCount--;console.log(`Lucky roll: Reverted roll count to ${rollCount}`);// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}// Show messageshowGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500');}// Update lucky rolls displayupdateLuckyRollsDisplay();// If no more lucky rolls, show messageif (luckyRollsRemaining === 0) {setTimeout(() => {showGameMessage('Lucky Streak ended!', 'text-yellow-500');}, 1000);}}// Create confetti effect if result is 6if (result === 6) {createConfetti();}// Debug: log final stateconsole.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 animationfunction 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 placescurrentScore = Math.round(currentScore * 100) / 100;scoreValue.textContent = currentScore;console.log('Score value updated to:', currentScore);// Clear previous score change displayscoreChange.textContent = '';scoreChange.className = 'ml-2 text-sm font-normal';console.log('Cleared previous score change display');// Show score change with appropriate stylingif (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 usedif (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) {// Create container for item effectsconst itemEffectsContainer = document.createElement('div');itemEffectsContainer.className = 'flex flex-wrap gap-2 mt-1';// Add tier multiplier effect if applicableif (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 effectif (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 effectif (itemsUsed.double > 0) {const doublePointsEffect = document.createElement('div');doublePointsEffect.className = 'text-xs text-green-500';// Calculate multiplierconst multiplier = Math.pow(2, itemsUsed.double);let calculationText = `${baseChange}`;// Apply tier multiplier for displaylet displayChange = baseChange * tierMultiplier;// Apply no penalty first for displayif (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 usedif (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 displayscoreDisplay.appendChild(itemEffectsContainer);// Remove after animationsetTimeout(() => {scoreDisplay.removeChild(itemEffectsContainer);}, 1000);}// Reset score change display after animation completessetTimeout(() => {scoreChange.textContent = '';}, 1000);// Clear active items after score updateconsole.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 updateconsole.log('Checking game state...');checkGameState();// Update upgrade button stateupdateUpgradeCostDisplay();console.log('=== updateScoreDisplay completed ===');}// Handle dice upgradefunction upgradeDice() {// Check if game is already overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if already at maximum tierif (currentTier >= diceTiers.length - 1) {// If not already game over, end the game with win conditionif (!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 upgradeif (currentScore < requiredScore) {showGameMessage(`Not enough score to upgrade! Need ${requiredScore} points.`, 'text-orange-500');// Add shake animation to score displayscoreDisplay.classList.add('animate-shake');setTimeout(() => {scoreDisplay.classList.remove('animate-shake');}, 500);return;}// Deduct score for upgradecurrentScore -= requiredScore;// Round to 2 decimal placescurrentScore = Math.round(currentScore * 100) / 100;// Update score displayscoreValue.textContent = currentScore;showScoreChange(-requiredScore);// Increase tiercurrentTier++;// Update current tier displaycurrentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;// Update tier multiplier displayupdateTierMultiplierDisplay();// Unlock the new dice colorunlockDiceColor(currentTier);// Update color selection UIupdateColorSelection(currentTier);// Update upgrade cost displayupdateUpgradeCostDisplay();// Change to the new dice colorconsole.log(`Changing dice color to ${diceTiers[currentTier].color} (${diceTiers[currentTier].name})`);changeDiceColor(diceTiers[currentTier].color);// Check if this upgrade reached the maximum tiercheckGameState();// Randomly get an itemconst itemChance = Math.random();if (itemChance < 0.30) { // 30% chance to get double points carddoublePointsCards++;} else if (itemChance < 0.60) { // 30% chance to get no penalty cardnoPenaltyCards++;} else if (itemChance < 0.70) { // 10% chance to get lucky streak cardluckyStreakCards++;} else { // 30% chance to get nothing// Do nothing}// Update items display to show new countsupdateItemsDisplay();// Update items displayupdateItemsDisplay();// Check if reached the Unique diceif (currentTier === diceTiers.length - 1) {showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500');gameOver = true;createConfetti();}// Handle lucky roll logicif (luckyRollsRemaining > 0) {// Decrement remaining lucky rollsluckyRollsRemaining--;// If rolled 1 or 2, decrement roll countif (result === 1 || result === 2) {rollCount--;console.log(`Lucky roll: Reverted roll count to ${rollCount}`);// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}// Show messageshowGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500');}// Update lucky rolls displayupdateLuckyRollsDisplay();// If no more lucky rolls, show messageif (luckyRollsRemaining === 0) {setTimeout(() => {showGameMessage('Lucky Streak ended!', 'text-yellow-500');}, 1000);}}// Add to historyaddToHistory('UPGRADE', -5);// Add item to history if obtainedif (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 upgradecheckGameState();}// Show score change temporarilyfunction 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 optionfunction unlockDiceColor(tierIndex) {if (tierIndex >= 0 && tierIndex < colorOptions.length) {const option = colorOptions[tierIndex];// Show particle effect on the lock before unlockingcreateLockParticles(option);// Add a small delay to show the particles before unlockingsetTimeout(() => {option.disabled = false;option.classList.remove('locked');}, 300);}}// Show game messagefunction showGameMessage(message, className) {gameMessageDisplay.textContent = message;gameMessageDisplay.className = `mt-4 text-center font-semibold ${className}`;gameMessageDisplay.classList.remove('hidden');// Hide message after 3 secondssetTimeout(() => {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 recordsetTimeout(() => {checkWinRecord();}, 1000);}// Check if score is low (warning)if (currentScore >= 0 && currentScore <= 5 && !gameOver) {showLowScoreWarning();}console.log('=== checkGameState completed ===');}// Update items displayfunction updateItemsDisplay() {// Update countsdoublePointsCount.textContent = doublePointsCards;noPenaltyCount.textContent = noPenaltyCards;luckyStreakCount.textContent = luckyStreakCards;// Enable/disable buttons based on available itemsuseDoublePointsButton.disabled = doublePointsCards <= 0 || gameOver;useNoPenaltyButton.disabled = noPenaltyCards <= 0 || activeItems.noPenalty || gameOver;useLuckyStreakButton.disabled = luckyStreakCards <= 0 || gameOver;// Update free rolls displayupdateFreeRollsDisplay();// Update lucky rolls displayupdateLuckyRollsDisplay();}// Update free rolls displayfunction updateFreeRollsDisplay() {if (freeRolls > 0) {freeRollsCountElement.textContent = freeRolls;freeRollsIndicator.classList.remove('hidden');} else {freeRollsIndicator.classList.add('hidden');}}// Update upgrade cost display and button statefunction updateUpgradeCostDisplay() {if (currentTier >= diceTiers.length - 1) {// Already at maximum tierupgradeCost.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 scoreif (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 cardfunction useDoublePointsCard() {if (doublePointsCards > 0 && !gameOver) {activeItems.double++;doublePointsCards--;// Update UIupdateItemsDisplay();showActiveItemIndicator();// Show messageshowGameMessage('Double Points Card activated! Next roll will double your score change.', 'text-green-500');}}// Use no penalty cardfunction useNoPenaltyCard() {if (noPenaltyCards > 0 && !activeItems.noPenalty && !gameOver) {activeItems.noPenalty = true;noPenaltyCards--;// Update UIupdateItemsDisplay();showActiveItemIndicator();// Show messageshowGameMessage('No Penalty Card activated! Next roll won\'t lose points.', 'text-blue-500');}}// Use lucky streak cardfunction useLuckyStreakCard() {if (luckyStreakCards > 0 && !gameOver) {luckyRollsRemaining = 3;luckyStreakCards--;// Update UIupdateItemsDisplay();updateLuckyRollsDisplay();// Show messageshowGameMessage('Lucky Streak Card activated! Next 3 rolls of 1 or 2 won\'t count!', 'text-yellow-500');// Add to historyaddToHistory('ITEM USE', 'Lucky Streak Card');}}// Update lucky rolls displayfunction updateLuckyRollsDisplay() {if (luckyRollsRemaining > 0) {// Check if indicator exists, if not create itlet 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 indicatorconst freeRollsIndicator = document.getElementById('free-rolls-indicator');if (freeRollsIndicator) {freeRollsIndicator.parentNode.insertBefore(luckyRollsIndicator, freeRollsIndicator.nextSibling);} else {// Fallback: insert after active item indicatorconst activeItemIndicator = document.getElementById('active-item-indicator');if (activeItemIndicator) {activeItemIndicator.parentNode.insertBefore(luckyRollsIndicator, activeItemIndicator.nextSibling);} else {// Fallback: insert after items displayconst itemsDisplay = document.getElementById('items-display');if (itemsDisplay) {itemsDisplay.parentNode.insertBefore(luckyRollsIndicator, itemsDisplay.nextSibling);}}}}// Update contentluckyRollsIndicator.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 indicatorluckyRollsIndicator.classList.remove('hidden');} else {// Remove indicator if existsconst luckyRollsIndicator = document.getElementById('lucky-rolls-indicator');if (luckyRollsIndicator) {luckyRollsIndicator.classList.add('hidden');}}}// Show active item indicatorfunction showActiveItemIndicator() {// Clear previous contentactiveItemIndicator.innerHTML = '';// Check if any items are activeif (activeItems.double === 0 && !activeItems.noPenalty) {activeItemIndicator.className = 'mt-3 text-center hidden';return;}// Create container for active itemsconst itemsContainer = document.createElement('div');itemsContainer.className = 'flex flex-wrap justify-center gap-2';// Add double points cards indicatorif (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 indicatorif (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 containeractiveItemIndicator.appendChild(itemsContainer);activeItemIndicator.className = 'mt-3 text-center';}// Clear active itemsfunction clearActiveItems() {activeItems = {double: 0,noPenalty: false};showActiveItemIndicator();}// End the game and display appropriate messagefunction endGame(isWin) {console.log('=== endGame called ===');console.log('Is win:', isWin, 'Current score:', currentScore);// Disable all interactive elementsrollButton.disabled = true;upgradeButton.disabled = true;rollButton.classList.add('opacity-70', 'cursor-not-allowed');upgradeButton.classList.add('opacity-70', 'cursor-not-allowed');// Disable all interactive elementscolorOptions.forEach(option => {option.disabled = true;option.classList.add('opacity-50', 'cursor-not-allowed');});// Disable item buttonsuseDoublePointsButton.disabled = true;useNoPenaltyButton.disabled = true;useLuckyStreakButton.disabled = true;// Hide active indicatorsactiveItemIndicator.classList.add('hidden');const luckyRollsIndicator = document.getElementById('lucky-rolls-indicator');if (luckyRollsIndicator) {luckyRollsIndicator.classList.add('hidden');}// Create game over message elementconst 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 placesconst 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 listenergameOverMessage.querySelector('#play-again').addEventListener('click', () => {window.location.reload();});// Replace game message display with game over messageconst gameMessageContainer = gameMessageDisplay.parentElement;gameMessageContainer.replaceChild(gameOverMessage, gameMessageDisplay);gameMessageDisplay = gameOverMessage;// Add game end to historyaddToHistory(isWin ? 'GAME WIN' : 'GAME OVER', 0);console.log('=== endGame completed ===');}// Show warning when score is lowfunction showLowScoreWarning() {// Only show warning if not already showingif (gameMessageDisplay.classList.contains('hidden')) {showGameMessage('Warning: Low score! Risk of game over.', 'text-orange-500');}}// Update color selection UI to show the currently selected colorfunction updateColorSelection(selectedIndex) {// Remove active state from all color optionscolorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary'));// Add active state to the selected color optionif (selectedIndex >= 0 && selectedIndex < colorOptions.length) {colorOptions[selectedIndex].classList.add('ring-2', 'ring-offset-2', 'ring-primary');}}// Add result to historyfunction addToHistory(result, scoreChangeData, isFreeRoll = false, isLuckyRoll = false) {const now = new Date();const timeString = now.toLocaleTimeString();// Determine score change display and colorlet 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 applicableif (isFreeRoll) {actionText += ` <span class="text-yellow-500">(Free Roll)</span>`;}// Add lucky roll indicator if applicableif (isLuckyRoll) {actionText += ` <span class="text-yellow-500">(Lucky Roll)</span>`;}// Add item effect indicators if applicableconst 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 itemsif (historyList.children.length > 10) {historyList.removeChild(historyList.lastChild);}// Ensure scroll is at the bottomconst historyContainer = document.getElementById('history-container');if (historyContainer) {historyContainer.scrollTop = historyContainer.scrollHeight;}}// Create confetti effectfunction createConfetti() {const confettiContainer = document.createElement('div');confettiContainer.className = 'fixed inset-0 pointer-events-none overflow-hidden';document.body.appendChild(confettiContainer);// Create 50 confetti piecesfor (let i = 0; i < 50; i++) {const confetti = document.createElement('div');confetti.className = 'confetti';// Random positionconst posX = Math.random() * 100;const delay = Math.random() * 3;const duration = 3 + Math.random() * 2;// Random colorsconst 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 completessetTimeout(() => {document.body.removeChild(confettiContainer);}, 5000);}// Create particle effect on lockfunction createLockParticles(lockElement) {// Get lock element positionconst rect = lockElement.getBoundingClientRect();const centerX = rect.left + rect.width / 2;const centerY = rect.top + rect.height / 2;// Create particle containerconst 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 particlesfor (let i = 0; i < 15; i++) {const particle = document.createElement('div');particle.className = 'lock-particle';// Random direction and distanceconst 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 durationconst duration = 0.5 + Math.random() * 0.5;// Set particle stylesparticle.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 completessetTimeout(() => {document.body.removeChild(particleContainer);}, 1000);}// Function to darken a color by a certain percentagefunction 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 percentager = 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 hexconst darkenedHex = '#' +r.toString(16).padStart(2, '0') +g.toString(16).padStart(2, '0') +b.toString(16).padStart(2, '0');return darkenedHex;}// Change dice color functionfunction 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 contrastif (color.toUpperCase() === '#FFFFFF') {// White dice - use black dots and light gray bordersdotColor = '#000000';borderColor = '#CCCCCC';} else if (color.toUpperCase() === '#555555') {// Dark gray dice - use white dots and slightly lighter gray bordersdotColor = '#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 colorface.style.backgroundColor = color;// Set face border colorface.style.border = `3px solid ${borderColor}`;// Set dots colorconst dots = face.querySelectorAll('.dot');dots.forEach(dot => {dot.style.backgroundColor = dotColor;// Add slight border to dots for better definitiondot.style.border = color.toUpperCase() === '#FFFFFF' ? '1px solid rgba(0, 0, 0, 0.2)' : '1px solid rgba(0, 0, 0, 0.1)';});});}// Update tier multiplier displayfunction 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 buttonrollButton.addEventListener('click', rollDice);// Event listener for upgrade buttonupgradeButton.addEventListener('click', upgradeDice);// Event listeners for item buttonsuseDoublePointsButton.addEventListener('click', useDoublePointsCard);useNoPenaltyButton.addEventListener('click', useNoPenaltyCard);useLuckyStreakButton.addEventListener('click', useLuckyStreakCard);// Event listeners for color optionscolorOptions.forEach((option, index) => {// Disable all color options except the first one initiallyif (index !== 0) {option.disabled = true;option.classList.add('locked');}option.addEventListener('click', () => {// Check if game is overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if color is unlockedif (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 colorcolorOptions.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 tiercurrentTier = index;currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;updateTierMultiplierDisplay();});});// Initialize dice on page loadwindow.addEventListener('DOMContentLoaded', () => {console.log('=== DOMContentLoaded event fired ===');// Check if elements existconsole.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 displaycurrentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;// Initialize tier multiplier displayupdateTierMultiplierDisplay();// Initialize items displayupdateItemsDisplay();// Initialize upgrade cost displayupdateUpgradeCostDisplay();// Show welcome messagesetTimeout(() => {showGameMessage('Welcome! Roll the dice to earn points and upgrade your dice!', 'text-blue-500');}, 1000);});// Also try initializing on window loadwindow.addEventListener('load', () => {console.log('Window loaded');// If dice not already initialized, try againif (diceElement.children.length === 0) {console.log('Dice not initialized, trying again...');initializeDice();}});// Game Rules Modal Functionality(function() {// Get elementsconst 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 scrollingfunction preventBackgroundScroll(event) {// Allow scrolling inside the modal contentif (modalContent.contains(event.target)) {// Check if we're at the top or bottom of the modal contentconst 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 downif ((isAtTop && event.deltaY < 0) || (isAtBottom && event.deltaY > 0)) {event.preventDefault();}} else {// Prevent scrolling outside the modal contentevent.preventDefault();}}// Function to open modalfunction openModal() {// Add event listeners to prevent background scrollingdocument.addEventListener('wheel', preventBackgroundScroll, { passive: false });document.addEventListener('touchmove', preventBackgroundScroll, { passive: false });// Add open class to trigger animationsrulesModal.classList.add('modal-open');// Show the modalrulesModal.style.visibility = 'visible';}// Function to close modalfunction closeModal() {// Remove open class to trigger animationsrulesModal.classList.remove('modal-open');// Remove event listeners that prevent background scrollingdocument.removeEventListener('wheel', preventBackgroundScroll);document.removeEventListener('touchmove', preventBackgroundScroll);// Hide the modal after animation completessetTimeout(() => {rulesModal.style.visibility = 'hidden';}, 300);}// Add event listenersif (rulesButton) {rulesButton.addEventListener('click', openModal);}// Close buttonscloseButtons.forEach(button => {button.addEventListener('click', closeModal);});// Close when clicking outside the modal contentmodalBackdrop.addEventListener('click', closeModal);// Close when pressing Escape keydocument.addEventListener('keydown', (event) => {if (event.key === 'Escape' && rulesModal.classList.contains('modal-open')) {closeModal();}});// Add hover effect to rules buttonif (rulesButton) {rulesButton.addEventListener('mouseenter', () => {rulesButton.classList.add('scale-105');});rulesButton.addEventListener('mouseleave', () => {rulesButton.classList.remove('scale-105');});}// Add click effect to close buttonscloseButtons.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 handlerwindow.addEventListener('error', function(event) {console.error('Global error caught:', event.error);// Try to get roll button elementconst 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 messageconst 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 elementsconst 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 elementsconst 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 statelet currentScore = 10; // Initial scorelet currentTier = 0; // Initial dice tier (0 = Empty)let gameOver = false; // Game over flaglet rollCount = 0; // Number of dice rollslet luckyRollsRemaining = 0; // Number of lucky rolls remaininglet isRolling = false; // Whether dice is currently rolling// Item systemlet doublePointsCards = 0; // Number of double points cardslet noPenaltyCards = 0; // Number of no penalty cardslet luckyStreakCards = 0; // Number of lucky streak cardslet freeRolls = 0; // Number of free rolls availablelet activeItems = { // Currently active itemsdouble: 0, // Number of active double points cardsnoPenalty: false // Whether no penalty card is active};// Dice tiers configurationconst 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 dicefunction initializeDice() {console.log('Initializing dice...');// Create 6 faces for the diceconst 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 numberfor (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 clearlydiceElement.style.transform = 'rotateX(0deg) rotateY(0deg)';}// Get random rotation values for the dicefunction getRandomRotation() {// Determine which face we want to showconst targetFace = Math.floor(Math.random() * 6) + 1;// Get current rotation from dice elementconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');const matrix = new DOMMatrix(currentTransform);// Extract current rotation angleslet currentX = 0, currentY = 0;// If transform is not identity matrix, extract rotationif (currentTransform !== 'none') {// Calculate rotation from matrixcurrentX = 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 facelet targetX = 0, targetY = 0;switch(targetFace) {case 1: // Front face (Z+) - visible when no rotationtargetX = 0;targetY = 0;break;case 2: // Left face (X-) - visible when Y rotated 270 degreestargetX = 0;targetY = 270;break;case 3: // Back face (Z-) - visible when Y rotated 180 degreestargetX = 0;targetY = 180;break;case 4: // Right face (X+) - visible when Y rotated 90 degreestargetX = 0;targetY = 90;break;case 5: // Top face (Y-) - visible when X rotated -90 degreestargetX = -90;targetY = 0;break;case 6: // Bottom face (Y+) - visible when X rotated 90 degreestargetX = 90;targetY = 0;break;}// Calculate the shortest path to the target rotation// This prevents large rotation values from accumulatinglet diffX = targetX - currentX;let diffY = targetY - currentY;// Normalize the difference to the range [-180, 180] to find the shortest pathdiffX = ((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 pathconst 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 visibleconst 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 functionfunction rollDice() {// Check if game is overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if there are free rolls availableconst isFreeRoll = freeRolls > 0;// Check if in lucky streak modeconst 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 countfreeRolls--;updateFreeRollsDisplay();console.log(`Free roll used. Remaining free rolls: ${freeRolls}`);}// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}console.log('Rolling dice...');console.log('Button state before disable:', rollButton.disabled);// Set rolling state and disable button during animationisRolling = true;rollButton.disabled = true;rollButton.classList.add('opacity-70', 'cursor-not-allowed');// Disable other interactive elements during rollupgradeButton.disabled = true;upgradeButton.classList.add('opacity-70', 'cursor-not-allowed');useDoublePointsButton.disabled = true;useNoPenaltyButton.disabled = true;useLuckyStreakButton.disabled = true;// Disable color options during rollcolorOptions.forEach(option => {option.disabled = true;});console.log('Button state after disable:', rollButton.disabled);// Hide result displayresultDisplay.classList.add('hidden');// Reset dice display height - use Tailwind class instead of inline styleconst diceDisplay = document.getElementById('dice-display');if (diceDisplay) {// Ensure the height class is applied to prevent layout shifts during animationdiceDisplay.classList.add('h-48');}try {// Set animation durationconst duration = 2000; // Fixed duration for consistent experience// Get random rotation values for the final positionconst rotationData = getRandomRotation();console.log('Rotation data:', rotationData);console.log('Target face:', rotationData.targetFace);// Animate the dice using JavaScript for more controlanimateDice(duration, rotationData, { isFreeRoll, isLuckyRoll });// Set a safety timeout to ensure button is re-enabled even if something goes wrongsetTimeout(() => {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 errorenableRollButton();showGameMessage('An error occurred during the dice roll. Please try again.', 'text-red-500');}}// Animate the dice with spin animationfunction 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 elementconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');const matrix = new DOMMatrix(currentTransform);// Extract current rotation angleslet startX = 0, startY = 0;// If transform is not identity matrix, extract rotationif (currentTransform !== 'none') {// Calculate rotation from matrixstartX = Math.atan2(matrix.b, matrix.a) * (180 / Math.PI);startY = Math.atan2(-matrix.c, matrix.f) * (180 / Math.PI);}// Function to handle each animation framefunction animate(currentTime) {const elapsedTime = currentTime - startTime;const progress = Math.min(elapsedTime / duration, 1);// Apply easing function for smooth, natural animationconst easedProgress = easeOutCubic(progress);// Calculate current rotation - smooth continuous rotationconst currentX = startX + (finalRotation.x - startX) * easedProgress;const currentY = startY + (finalRotation.y - startY) * easedProgress;// Spin animation: rotate in placediceElement.style.transform = `rotateX(${currentX}deg) rotateY(${currentY}deg)`;// Continue animation if not completeif (progress < 1) {requestAnimationFrame(animate);} else {// Animation complete - ensure we're at the exact target rotationdiceElement.style.transform = `rotateX(${finalRotation.x}deg) rotateY(${finalRotation.y}deg)`;// Show result after a delay to ensure rotation is complete and CSS has appliedconsole.log('Animation complete, waiting before finalizing...');setTimeout(() => {// Double-check that the transform has been appliedconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');console.log('Current transform after animation:', currentTransform);console.log('Calling finalizeAnimation...');finalizeAnimation(finalRotation, rollContext);}, 600);}}// Start the animationrequestAnimationFrame(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 endfunction easeOutCubic(t) {return 1 - Math.pow(1 - t, 3);}// Calculate score change based on dice roll resultfunction 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 multiplierconst tierMultiplier = 1 + currentTier / 10;let finalChange;if (baseChange < 0) {// For point loss, use multiplier of 1 regardless of tierfinalChange = baseChange * 1;} else {// For point gain or neutral, use tier multiplierfinalChange = baseChange * tierMultiplier;}// Apply active item effectsconst itemsUsed = {double: activeItems.double,noPenalty: activeItems.noPenalty};// Apply no penalty card firstif (activeItems.noPenalty && baseChange < 0) {finalChange = 0;}// Apply double points cardsif (activeItems.double > 0) {finalChange = finalChange * Math.pow(2, activeItems.double);}// Round to 2 decimal places to avoid floating point precision issuesfinalChange = Math.round(finalChange * 100) / 100;return {baseChange: baseChange,finalChange: finalChange,itemsUsed: itemsUsed,tierMultiplier: tierMultiplier};}// Enable roll buttonfunction enableRollButton() {console.log('Button state before enable:', rollButton.disabled);// Directly enable the buttonrollButton.disabled = false;rollButton.classList.remove('opacity-70', 'cursor-not-allowed');// Re-enable other interactive buttons based on their conditionsupdateUpgradeCostDisplay(); // This will enable/disable upgrade button based on scoreupdateItemsDisplay(); // This will enable/disable item buttons based on availabilityconsole.log('Button state after enable:', rollButton.disabled);// Double-check and force enable if neededif (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 resultfunction 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 recalculatingconst result = finalRotation.targetFace;console.log(`Final result: ${result} (should show face ${result})`);// Verify dice is in the correct positionconst currentTransform = window.getComputedStyle(diceElement).getPropertyValue('transform');console.log('Current dice transform:', currentTransform);// Show result displayconsole.log('Showing result display...');resultValue.textContent = result;resultDisplay.classList.remove('hidden');// Add shine effect to resultresultDisplay.classList.add('result-shine');setTimeout(() => {resultDisplay.classList.remove('result-shine');}, 500);// Calculate and update scoreconsole.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 animationconsole.log('Updating score display...');updateScoreDisplay(scoreChangeData);// Enable buttonconsole.log('Enabling roll button...');enableRollButton();// Add to history - include whether it was a free roll or lucky rolladdToHistory(result, scoreChangeData, isFreeRoll, isLuckyRoll);// Check if reached the Unique diceif (currentTier === diceTiers.length - 1) {showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500');gameOver = true;createConfetti();}// Handle lucky roll logicif (luckyRollsRemaining > 0) {// Decrement remaining lucky rollsluckyRollsRemaining--;// If rolled 1 or 2, decrement roll countif (result === 1 || result === 2) {rollCount--;console.log(`Lucky roll: Reverted roll count to ${rollCount}`);// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}// Show messageshowGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500');}// Update lucky rolls displayupdateLuckyRollsDisplay();// If no more lucky rolls, show messageif (luckyRollsRemaining === 0) {setTimeout(() => {showGameMessage('Lucky Streak ended!', 'text-yellow-500');}, 1000);}}// Create confetti effect if result is 6if (result === 6) {createConfetti();}// Debug: log final stateconsole.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 animationfunction 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 placescurrentScore = Math.round(currentScore * 100) / 100;scoreValue.textContent = currentScore;console.log('Score value updated to:', currentScore);// Clear previous score change displayscoreChange.textContent = '';scoreChange.className = 'ml-2 text-sm font-normal';console.log('Cleared previous score change display');// Show score change with appropriate stylingif (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 usedif (itemsUsed && (itemsUsed.double > 0 || itemsUsed.noPenalty)) {// Create container for item effectsconst itemEffectsContainer = document.createElement('div');itemEffectsContainer.className = 'flex flex-wrap gap-2 mt-1';// Add tier multiplier effect if applicableif (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 effectif (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 effectif (itemsUsed.double > 0) {const doublePointsEffect = document.createElement('div');doublePointsEffect.className = 'text-xs text-green-500';// Calculate multiplierconst multiplier = Math.pow(2, itemsUsed.double);let calculationText = `${baseChange}`;// Apply tier multiplier for displaylet displayChange = baseChange * tierMultiplier;// Apply no penalty first for displayif (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 usedif (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 displayscoreDisplay.appendChild(itemEffectsContainer);// Remove after animationsetTimeout(() => {scoreDisplay.removeChild(itemEffectsContainer);}, 1000);}// Reset score change display after animation completessetTimeout(() => {scoreChange.textContent = '';}, 1000);// Clear active items after score updateconsole.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 updateconsole.log('Checking game state...');checkGameState();// Update upgrade button stateupdateUpgradeCostDisplay();console.log('=== updateScoreDisplay completed ===');}// Handle dice upgradefunction upgradeDice() {// Check if game is already overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if already at maximum tierif (currentTier >= diceTiers.length - 1) {// If not already game over, end the game with win conditionif (!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 upgradeif (currentScore < requiredScore) {showGameMessage(`Not enough score to upgrade! Need ${requiredScore} points.`, 'text-orange-500');// Add shake animation to score displayscoreDisplay.classList.add('animate-shake');setTimeout(() => {scoreDisplay.classList.remove('animate-shake');}, 500);return;}// Deduct score for upgradecurrentScore -= requiredScore;// Round to 2 decimal placescurrentScore = Math.round(currentScore * 100) / 100;// Update score displayscoreValue.textContent = currentScore;showScoreChange(-requiredScore);// Increase tiercurrentTier++;// Update current tier displaycurrentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;// Update tier multiplier displayupdateTierMultiplierDisplay();// Unlock the new dice colorunlockDiceColor(currentTier);// Update color selection UIupdateColorSelection(currentTier);// Update upgrade cost displayupdateUpgradeCostDisplay();// Change to the new dice colorconsole.log(`Changing dice color to ${diceTiers[currentTier].color} (${diceTiers[currentTier].name})`);changeDiceColor(diceTiers[currentTier].color);// Check if this upgrade reached the maximum tiercheckGameState();// Randomly get an itemconst itemChance = Math.random();if (itemChance < 0.30) { // 30% chance to get double points carddoublePointsCards++;} else if (itemChance < 0.60) { // 30% chance to get no penalty cardnoPenaltyCards++;} else if (itemChance < 0.70) { // 10% chance to get lucky streak cardluckyStreakCards++;} else { // 30% chance to get nothing// Do nothing}// Update items display to show new countsupdateItemsDisplay();// Update items displayupdateItemsDisplay();// Check if reached the Unique diceif (currentTier === diceTiers.length - 1) {showGameMessage('Congratulations! You obtained the Unique dice!', 'text-green-500');gameOver = true;createConfetti();}// Handle lucky roll logicif (luckyRollsRemaining > 0) {// Decrement remaining lucky rollsluckyRollsRemaining--;// If rolled 1 or 2, decrement roll countif (result === 1 || result === 2) {rollCount--;console.log(`Lucky roll: Reverted roll count to ${rollCount}`);// Update roll count displayif (rollCountValue) {rollCountValue.textContent = rollCount;}// Show messageshowGameMessage('Lucky! This 1/2 roll doesn\'t count!', 'text-yellow-500');}// Update lucky rolls displayupdateLuckyRollsDisplay();// If no more lucky rolls, show messageif (luckyRollsRemaining === 0) {setTimeout(() => {showGameMessage('Lucky Streak ended!', 'text-yellow-500');}, 1000);}}// Add to historyaddToHistory('UPGRADE', -requiredScore);// Add item to history if obtainedif (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 upgradecheckGameState();}// Show score change temporarilyfunction 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 optionfunction unlockDiceColor(tierIndex) {if (tierIndex >= 0 && tierIndex < colorOptions.length) {const option = colorOptions[tierIndex];// Show particle effect on the lock before unlockingcreateLockParticles(option);// Add a small delay to show the particles before unlockingsetTimeout(() => {option.disabled = false;option.classList.remove('locked');}, 300);}}// Show game messagefunction showGameMessage(message, className) {gameMessageDisplay.textContent = message;gameMessageDisplay.className = `mt-4 text-center font-semibold ${className}`;gameMessageDisplay.classList.remove('hidden');// Hide message after 3 secondssetTimeout(() => {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 recordsetTimeout(() => {checkWinRecord();}, 1000);}// Check if score is low (warning)if (currentScore >= 0 && currentScore <= 5 && !gameOver) {showLowScoreWarning();}console.log('=== checkGameState completed ===');}// Update items displayfunction updateItemsDisplay() {// Update countsdoublePointsCount.textContent = doublePointsCards;noPenaltyCount.textContent = noPenaltyCards;luckyStreakCount.textContent = luckyStreakCards;// Enable/disable buttons based on available itemsuseDoublePointsButton.disabled = doublePointsCards <= 0 || gameOver;useNoPenaltyButton.disabled = noPenaltyCards <= 0 || activeItems.noPenalty || gameOver;useLuckyStreakButton.disabled = luckyStreakCards <= 0 || gameOver;// Update free rolls displayupdateFreeRollsDisplay();// Update lucky rolls displayupdateLuckyRollsDisplay();}// Update free rolls displayfunction updateFreeRollsDisplay() {if (freeRolls > 0) {freeRollsCountElement.textContent = freeRolls;freeRollsIndicator.classList.remove('hidden');} else {freeRollsIndicator.classList.add('hidden');}}// Update upgrade cost display and button statefunction updateUpgradeCostDisplay() {if (currentTier >= diceTiers.length - 1) {// Already at maximum tierupgradeCost.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 scoreif (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 cardfunction useDoublePointsCard() {if (doublePointsCards > 0 && !gameOver) {activeItems.double++;doublePointsCards--;// Update UIupdateItemsDisplay();showActiveItemIndicator();// Show messageshowGameMessage('Double Points Card activated! Next roll will double your score change.', 'text-green-500');}}// Use no penalty cardfunction useNoPenaltyCard() {if (noPenaltyCards > 0 && !activeItems.noPenalty && !gameOver) {activeItems.noPenalty = true;noPenaltyCards--;// Update UIupdateItemsDisplay();showActiveItemIndicator();// Show messageshowGameMessage('No Penalty Card activated! Next roll won\'t lose points.', 'text-blue-500');}}// Use lucky streak cardfunction useLuckyStreakCard() {if (luckyStreakCards > 0 && !gameOver) {luckyRollsRemaining = 3;luckyStreakCards--;// Update UIupdateItemsDisplay();updateLuckyRollsDisplay();// Show messageshowGameMessage('Lucky Streak Card activated! Next 3 rolls of 1 or 2 won\'t count!', 'text-yellow-500');// Add to historyaddToHistory('ITEM USE', 'Lucky Streak Card');}}// Update lucky rolls displayfunction updateLuckyRollsDisplay() {if (luckyRollsRemaining > 0) {// Check if indicator exists, if not create itlet 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 indicatorconst freeRollsIndicator = document.getElementById('free-rolls-indicator');if (freeRollsIndicator) {freeRollsIndicator.parentNode.insertBefore(luckyRollsIndicator, freeRollsIndicator.nextSibling);} else {// Fallback: insert after active item indicatorconst activeItemIndicator = document.getElementById('active-item-indicator');if (activeItemIndicator) {activeItemIndicator.parentNode.insertBefore(luckyRollsIndicator, activeItemIndicator.nextSibling);} else {// Fallback: insert after items displayconst itemsDisplay = document.getElementById('items-display');if (itemsDisplay) {itemsDisplay.parentNode.insertBefore(luckyRollsIndicator, itemsDisplay.nextSibling);}}}}// Update contentluckyRollsIndicator.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 indicatorluckyRollsIndicator.classList.remove('hidden');} else {// Remove indicator if existsconst luckyRollsIndicator = document.getElementById('lucky-rolls-indicator');if (luckyRollsIndicator) {luckyRollsIndicator.classList.add('hidden');}}}// Show active item indicatorfunction showActiveItemIndicator() {// Clear previous contentactiveItemIndicator.innerHTML = '';// Check if any items are activeif (activeItems.double === 0 && !activeItems.noPenalty) {activeItemIndicator.className = 'mt-3 text-center hidden';return;}// Create container for active itemsconst itemsContainer = document.createElement('div');itemsContainer.className = 'flex flex-wrap justify-center gap-2';// Add double points cards indicatorif (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 indicatorif (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 containeractiveItemIndicator.appendChild(itemsContainer);activeItemIndicator.className = 'mt-3 text-center';}// Clear active itemsfunction clearActiveItems() {activeItems = {double: 0,noPenalty: false};showActiveItemIndicator();}// End the game and display appropriate messagefunction endGame(isWin) {console.log('=== endGame called ===');console.log('Is win:', isWin, 'Current score:', currentScore);// Disable all interactive elementsrollButton.disabled = true;upgradeButton.disabled = true;rollButton.classList.add('opacity-70', 'cursor-not-allowed');upgradeButton.classList.add('opacity-70', 'cursor-not-allowed');// Disable all interactive elementscolorOptions.forEach(option => {option.disabled = true;option.classList.add('opacity-50', 'cursor-not-allowed');});// Disable item buttonsuseDoublePointsButton.disabled = true;useNoPenaltyButton.disabled = true;useLuckyStreakButton.disabled = true;// Hide active indicatorsactiveItemIndicator.classList.add('hidden');const luckyRollsIndicator = document.getElementById('lucky-rolls-indicator');if (luckyRollsIndicator) {luckyRollsIndicator.classList.add('hidden');}// Create game over message elementconst 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 placesconst 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 listenergameOverMessage.querySelector('#play-again').addEventListener('click', () => {window.location.reload();});// Replace game message display with game over messageconst gameMessageContainer = gameMessageDisplay.parentElement;gameMessageContainer.replaceChild(gameOverMessage, gameMessageDisplay);gameMessageDisplay = gameOverMessage;// Add game end to historyaddToHistory(isWin ? 'GAME WIN' : 'GAME OVER', 0);console.log('=== endGame completed ===');}// Show warning when score is lowfunction showLowScoreWarning() {// Only show warning if not already showingif (gameMessageDisplay.classList.contains('hidden')) {showGameMessage('Warning: Low score! Risk of game over.', 'text-orange-500');}}// Update color selection UI to show the currently selected colorfunction updateColorSelection(selectedIndex) {// Remove active state from all color optionscolorOptions.forEach(opt => opt.classList.remove('ring-2', 'ring-offset-2', 'ring-primary'));// Add active state to the selected color optionif (selectedIndex >= 0 && selectedIndex < colorOptions.length) {colorOptions[selectedIndex].classList.add('ring-2', 'ring-offset-2', 'ring-primary');}}// Add result to historyfunction addToHistory(result, scoreChangeData, isFreeRoll = false, isLuckyRoll = false) {const now = new Date();const timeString = now.toLocaleTimeString();// Determine score change display and colorlet 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 applicableif (isFreeRoll) {actionText += ` <span class="text-yellow-500">(Free Roll)</span>`;}// Add lucky roll indicator if applicableif (isLuckyRoll) {actionText += ` <span class="text-yellow-500">(Lucky Roll)</span>`;}// Add item effect indicators if applicableconst 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 itemsif (historyList.children.length > 10) {historyList.removeChild(historyList.lastChild);}// Ensure scroll is at the bottomconst historyContainer = document.getElementById('history-container');if (historyContainer) {historyContainer.scrollTop = historyContainer.scrollHeight;}}// Create confetti effectfunction createConfetti() {const confettiContainer = document.createElement('div');confettiContainer.className = 'fixed inset-0 pointer-events-none overflow-hidden';document.body.appendChild(confettiContainer);// Create 50 confetti piecesfor (let i = 0; i < 50; i++) {const confetti = document.createElement('div');confetti.className = 'confetti';// Random positionconst posX = Math.random() * 100;const delay = Math.random() * 3;const duration = 3 + Math.random() * 2;// Random colorsconst 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 completessetTimeout(() => {document.body.removeChild(confettiContainer);}, 5000);}// Create particle effect on lockfunction createLockParticles(lockElement) {// Get lock element positionconst rect = lockElement.getBoundingClientRect();const centerX = rect.left + rect.width / 2;const centerY = rect.top + rect.height / 2;// Create particle containerconst 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 particlesfor (let i = 0; i < 15; i++) {const particle = document.createElement('div');particle.className = 'lock-particle';// Random direction and distanceconst 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 durationconst duration = 0.5 + Math.random() * 0.5;// Set particle stylesparticle.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 completessetTimeout(() => {document.body.removeChild(particleContainer);}, 1000);}// Function to darken a color by a certain percentagefunction 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 percentager = 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 hexconst darkenedHex = '#' +r.toString(16).padStart(2, '0') +g.toString(16).padStart(2, '0') +b.toString(16).padStart(2, '0');return darkenedHex;}// Change dice color functionfunction 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 contrastif (color.toUpperCase() === '#FFFFFF') {// White dice - use black dots and light gray bordersdotColor = '#000000';borderColor = '#CCCCCC';} else if (color.toUpperCase() === '#555555') {// Dark gray dice - use white dots and slightly lighter gray bordersdotColor = '#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 colorface.style.backgroundColor = color;// Set face border colorface.style.border = `3px solid ${borderColor}`;// Set dots colorconst dots = face.querySelectorAll('.dot');dots.forEach(dot => {dot.style.backgroundColor = dotColor;// Add slight border to dots for better definitiondot.style.border = color.toUpperCase() === '#FFFFFF' ? '1px solid rgba(0, 0, 0, 0.2)' : '1px solid rgba(0, 0, 0, 0.1)';});});}// Update tier multiplier displayfunction 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 buttonrollButton.addEventListener('click', rollDice);// Event listener for upgrade buttonupgradeButton.addEventListener('click', upgradeDice);// Event listeners for item buttonsuseDoublePointsButton.addEventListener('click', useDoublePointsCard);useNoPenaltyButton.addEventListener('click', useNoPenaltyCard);useLuckyStreakButton.addEventListener('click', useLuckyStreakCard);// Event listeners for color optionscolorOptions.forEach((option, index) => {// Disable all color options except the first one initiallyif (index !== 0) {option.disabled = true;option.classList.add('locked');}option.addEventListener('click', () => {// Check if game is overif (gameOver) {showGameMessage('Game over! Click "Play Again" to restart.', 'text-red-500');return;}// Check if color is unlockedif (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 colorcolorOptions.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 tiercurrentTier = index;currentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;updateTierMultiplierDisplay();});});// Initialize dice on page loadwindow.addEventListener('DOMContentLoaded', () => {console.log('=== DOMContentLoaded event fired ===');// Check if elements existconsole.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 displaycurrentTierDisplay.innerHTML = `Current Dice: <span class="font-semibold text-primary">${diceTiers[currentTier].name}</span>`;// Initialize tier multiplier displayupdateTierMultiplierDisplay();// Initialize items displayupdateItemsDisplay();// Initialize upgrade cost displayupdateUpgradeCostDisplay();// Show welcome messagesetTimeout(() => {showGameMessage('Welcome! Roll the dice to earn points and upgrade your dice!', 'text-blue-500');}, 1000);});// Also try initializing on window loadwindow.addEventListener('load', () => {console.log('Window loaded');// If dice not already initialized, try againif (diceElement.children.length === 0) {console.log('Dice not initialized, trying again...');initializeDice();}});// Game Rules Modal Functionality(function() {// Get elementsconst 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 scrollingfunction preventBackgroundScroll(event) {// Allow scrolling inside the modal contentif (modalContent.contains(event.target)) {// Check if we're at the top or bottom of the modal contentconst 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 downif ((isAtTop && event.deltaY < 0) || (isAtBottom && event.deltaY > 0)) {event.preventDefault();}} else {// Prevent scrolling outside the modal contentevent.preventDefault();}}// Function to open modalfunction openModal() {// Add event listeners to prevent background scrollingdocument.addEventListener('wheel', preventBackgroundScroll, { passive: false });document.addEventListener('touchmove', preventBackgroundScroll, { passive: false });// Add open class to trigger animationsrulesModal.classList.add('modal-open');// Show the modalrulesModal.style.visibility = 'visible';}// Function to close modalfunction closeModal() {// Remove open class to trigger animationsrulesModal.classList.remove('modal-open');// Remove event listeners that prevent background scrollingdocument.removeEventListener('wheel', preventBackgroundScroll);document.removeEventListener('touchmove', preventBackgroundScroll);// Hide the modal after animation completessetTimeout(() => {rulesModal.style.visibility = 'hidden';}, 300);}// Add event listenersif (rulesButton) {rulesButton.addEventListener('click', openModal);}// Close buttonscloseButtons.forEach(button => {button.addEventListener('click', closeModal);});// Close when clicking outside the modal contentmodalBackdrop.addEventListener('click', closeModal);// Close when pressing Escape keydocument.addEventListener('keydown', (event) => {if (event.key === 'Escape' && rulesModal.classList.contains('modal-open')) {closeModal();}});// Add hover effect to rules buttonif (rulesButton) {rulesButton.addEventListener('mouseenter', () => {rulesButton.classList.add('scale-105');});rulesButton.addEventListener('mouseleave', () => {rulesButton.classList.remove('scale-105');});}// Add click effect to close buttonscloseButtons.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>```:::::::::