js實現(xiàn)小星星游戲
本文實例為大家分享了js實現(xiàn)小星星游戲的具體代碼,供大家參考,具體內(nèi)容如下
功能簡介
如圖:實現(xiàn)一個點擊游戲
準備
準備一個星星的圖片(這里我重命名為xxx.png)
開搞
新建一個html文件,并將其與準備好的圖片放在同一目錄下(東西多了不建議這樣搞,但這個就倆)
<!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()'>開始</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+'個小星星'); 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() { //通過父元素刪除子節(jié)點 this.parentNode.removeChild(this); var score= document.getElementById('score') if(meter.value!=100){ meter.value-=8; j-=8; c++; score.innerText='得分:'+c; } } function restart(){ //重新載入當前文檔 location.reload(); }</script></body></html>
結(jié)束
可以將css部分和js部分寫成單獨的文件,但是需要引入
<link href = 'http://m.4tl426be.cn/bcjs/css文件路徑' rel = 'stylesheet'><script src='http://m.4tl426be.cn/bcjs/js文件路徑' type='text/javascript'></script>
更多關(guān)于Js游戲的精彩文章,請查看專題: 《JavaScript經(jīng)典游戲 玩不停》
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python獲取抖音關(guān)注列表封號賬號的實現(xiàn)代碼2. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析3. php網(wǎng)絡安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究4. 解決Python 進程池Pool中一些坑5. php測試程序運行速度和頁面執(zhí)行速度的代碼6. Python如何讀寫CSV文件7. 三個不常見的 HTML5 實用新特性簡介8. ajax請求添加自定義header參數(shù)代碼9. python利用os模塊編寫文件復制功能——copy()函數(shù)用法10. 無線標記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁
