溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JS如何實現(xiàn)點星星消除小游戲

發(fā)布時間:2021-04-19 09:42:55 來源:億速云 閱讀:202 作者:小新 欄目:web開發(fā)

這篇文章給大家分享的是有關JS如何實現(xiàn)點星星消除小游戲的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

具體內(nèi)容如下

步驟及游戲功能分析:

1.網(wǎng)頁上的隨機出現(xiàn)小星星;

2.點擊小星星,小星星消失;

    綁定一個onclick事件:
    對象.事件 = 事件處理函數(shù);
    注意:要想刪除某個節(jié)點,必須找到它的父節(jié)點
    注意:在綁定事件中this可以直接使用

3.添加功能開始游戲

4.添加功能暫停游戲

5.游戲進度條功能

<style type="text/css">
 #d2{
 width: 100px;
 height: 20px;
 border: 1px solid red;
 display: inline-block;
 }
 #d3{
 display: inline-block;
 background: yellow;
 height: 20px;
 }
</style>
<script type="text/javascript">
 //window.onload = init;
 
 var countstar = 0;//控制星星個數(shù)變量
 var timerStar;//生成星星定時器
 var timerGameTime
 var t = 0;//記錄時間變量
 //開始游戲的函數(shù)
 function startGame(){
 window.clearInterval(timerStar);
 window.clearInterval(timerGameTime);
 timerStar = window.setInterval("star()",500);
 timerGameTime = window.setInterval("time()",1000); //記錄游戲時間
 }
 
 //創(chuàng)建星星的函數(shù)
 function star(){
 var obj = document.createElement("img");
 obj.src = "images/star.png";
 obj.width = Math.floor(Math.random()*60+20);
 obj.style.position = "absolute";
 obj.style.left = Math.floor(Math.random()*1700+100)+"px";
 obj.style.top = Math.floor(Math.random()*500+30)+"px";
 document.body.appendChild(obj);
 countstar++;
 var sp = document.getElementById("d3");
 sp.style.width = countstar*10+"px";
 
 if (countstar > 10) {
  alert("游戲結束");
  window.clearInterval(timerStar);
  location.reload();
 }
 obj.onclick = removeStar;
 }
 
 //點擊刪除星星的函數(shù)
 function removeStar(){
 this.parentNode.removeChild(this);
 countstar --;
 var sp = document.getElementById("d3");
 sp.style.width = countstar*10+"px";
 }
 
 //點擊暫停游戲的函數(shù)
 function pauseGame(){
 alert("游戲已暫停,點擊確定繼續(xù)游戲。");
 }
 
 //記錄游戲時間的函數(shù)
 function time(){
 t++
 var obj = document.getElementById("d1");
 obj.innerHTML= "游戲進行了"+t+"秒";
 }
</script>
 
<body>
  <input type="button" value="開始游戲" οnclick="startGame()" name="">
  <input type="button" value="暫停游戲" οnclick="pauseGame()" name="">
  <span id="d1">游戲進行了0秒</span>
  <span id="d2"><span id="d3"></span></span>
</body>

游戲效果:

JS如何實現(xiàn)點星星消除小游戲

感謝各位的閱讀!關于“JS如何實現(xiàn)點星星消除小游戲”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

js
AI