HTML5 猜被杯子游戲源代碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>猜被杯子游戲</title> <style> /* 游戲面板樣式 */ #game-panel{ width: 400px; height: 450px; margin: 0 auto; background-color: #ccc; border-radius: 20px; text-align: center; position: relative; } /* 杯子樣式 */ .cup{ width: 120px; height: 120px; background-image: url(cup.png); background-size: contain; background-repeat: no-repeat; position: absolute; bottom: 0; left: 50%; margin-left: -60px; } /* 文字樣式 */ .words{ position: absolute; bottom: 130px; left: 50%; transform: translateX(-50%); color: #333; font-size: 28px; } </style> <script src="jquery.min.js"></script> <script> $(function(){ var currentIndex = 0;//當(dāng)前被杯子的下標(biāo) var isMoving = false;//是否正在進(jìn)行動(dòng)畫 var cupArr = $('div.cup');//被杯子的數(shù)組 var words = $('.words');//提示文字 //點(diǎn)擊開始游戲按鈕 $('#start-btn').click(function(){ currentIndex = Math.floor(Math.random()*3);//隨機(jī)排序 isMoving = true; words.text('杯子正在移動(dòng),請(qǐng)等待...'); //被杯子動(dòng)畫 cupArr.eq(currentIndex).animate({ bottom: '200px' }, 500, function(){ //動(dòng)畫完成后提示玩家 words.text('現(xiàn)在可以猜猜哪個(gè)杯子是被杯子啦!'); isMoving = false; }); }); //點(diǎn)擊猜測(cè)按鈕 $('#guess-btns button').click(function(){ if(isMoving){//還在動(dòng)畫中,不能猜測(cè) return false; } if($(this).data('id') == currentIndex){//猜測(cè)正確 words.text('恭喜你猜對(duì)啦!'); }else{//猜測(cè)錯(cuò)誤 words.text('很遺憾,猜錯(cuò)啦!正確答案是第'+(currentIndex+1)+'個(gè)杯子哦!'); } //重置游戲 setTimeout(function(){ cupArr.css('bottom','-120px'); currentIndex = 0; words.text('點(diǎn)擊“開始游戲”按鈕開始游戲!'); },2000); }); }); </script> </head> <body> <div id="game-panel"> <div class="cup" id="cup1"></div> <div class="cup" id="cup2"></div> <div class="cup" id="cup3"></div> <div class="words">點(diǎn)擊“開始游戲”按鈕開始游戲!</div> </div> <div id="guess-btns"> <button data-id="0">1</button> <button data-id="1">2</button> <button data-id="2">3</button> </div> <div id="start-panel"> <button id="start-btn">開始游戲</button> </div> </body> </html>