js實(shí)現(xiàn)小星星游戲
本文實(shí)例為大家分享了js實(shí)現(xiàn)小星星游戲的具體代碼,供大家參考,具體內(nèi)容如下
功能簡(jiǎn)介
如圖:實(shí)現(xiàn)一個(gè)點(diǎn)擊游戲

準(zhǔn)備
準(zhǔn)備一個(gè)星星的圖片(這里我重命名為xxx.png)
開(kāi)搞
新建一個(gè)html文件,并將其與準(zhǔn)備好的圖片放在同一目錄下(東西多了不建議這樣搞,但這個(gè)就倆)
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>小星星游戲</title></head><style> body{ background-color: black; } meter{ width:100%; } #title{ width:100%; position: relative; text-align: center; color: #ffffff; } #score{ position: absolute; top:0; left:90%; width:10%; color: #ffffff; } #jindu{ padding:0 33%; } span{ display: block; text-align: center; } span > button{ width:20%; }</style><body><div><h1 id='title'>小星星游戲</h1></div><div><h1 id='score'>得分:</h1></div><div id='jindu'> <span> <meter min='0' max='100'></meter> </span> <span> <button onclick='start()'>開(kāi)始</button> <button onclick='restart()'>重玩</button> </span></div><script> var c = 0; function start(){ //console.log('調(diào)用'); //周期的調(diào)用函數(shù),0.2s t1 = window.setInterval(show,200) } var meter = document.getElementById('meter'); meter.value=0; var j =0; function show(){ meter.value+=5; // console.log(meter.value) if(j<=meter.value){ j=meter.value; }else{ window.clearInterval(t1) } if(j==100){ j=101; alert('游戲結(jié)束,共消除了'+c+'個(gè)小星星'); window.clearInterval(t1) } var img = document.createElement(’img’); img.src=’xxx.png’; img.style.position='absolute'; //math.floor向下取整 var w = Math.floor(Math.random()*(100-20+1)+20); var l = Math.floor(Math.random()*(1500-20+1)+20); var t = Math.floor(Math.random()*(600-150+1)+150); img.width = w; img.style.top = t+'px'; img.style.left = l+'px'; document.body.appendChild(img); img.onclick =rem; } function rem() { //通過(guò)父元素刪除子節(jié)點(diǎn) this.parentNode.removeChild(this); var score= document.getElementById('score') if(meter.value!=100){ meter.value-=8; j-=8; c++; score.innerText='得分:'+c; } } function restart(){ //重新載入當(dāng)前文檔 location.reload(); }</script></body></html>
結(jié)束
可以將css部分和js部分寫(xiě)成單獨(dú)的文件,但是需要引入
<link href = 'http://m.b3g6.com/bcjs/css文件路徑' rel = 'stylesheet'><script src='http://m.b3g6.com/bcjs/js文件路徑' type='text/javascript'></script>
更多關(guān)于Js游戲的精彩文章,請(qǐng)查看專(zhuān)題: 《JavaScript經(jīng)典游戲 玩不停》
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JavaScript實(shí)現(xiàn)簡(jiǎn)單的彈窗效果2. Java commons-httpclient如果實(shí)現(xiàn)get及post請(qǐng)求3. javascript實(shí)現(xiàn)貪吃蛇小練習(xí)4. 我所理解的JavaScript中的this指向5. Vue 實(shí)現(xiàn)對(duì)quill-editor組件中的工具欄添加title6. PHP驗(yàn)證碼工具-Securimage7. PHP單件模式和命令鏈模式的基礎(chǔ)知識(shí)8. 一文帶你徹底理解Java序列化和反序列化9. PHP利用curl發(fā)送HTTP請(qǐng)求的實(shí)例代碼10. js實(shí)現(xiàn)碰撞檢測(cè)

網(wǎng)公網(wǎng)安備