JS實現(xiàn)點星星消除小游戲
本文實例為大家分享了JS實現(xiàn)點星星消除游戲的具體代碼,供大家參考,具體內(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("游戲結(jié)束");
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>
游戲效果:

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
javascript 中設置window.location.href跳轉(zhuǎn)無效問題解決辦法
這篇文章主要介紹了javascript 中設置window.location.href跳轉(zhuǎn)無效問題解決辦法的相關(guān)資料,需要的朋友可以參考下2017-02-02
javascript實現(xiàn)簡單的省市區(qū)三級聯(lián)動
本文給大家反映的是javascript實現(xiàn)的簡單的省市區(qū)三級聯(lián)動特效,不需要訪問后臺服務器端,不使用Ajax,無刷新,純JS實現(xiàn)的省市區(qū)三級聯(lián)動。當省市區(qū)數(shù)據(jù)變動是只需調(diào)正js即可。2015-05-05
回車直接實現(xiàn)點擊某按鈕的效果即觸發(fā)單擊事件
這篇文章主要介紹了回車直接實現(xiàn)點擊某按鈕的效果即觸發(fā)單擊事件,需要的朋友可以參考下2014-02-02

