js實現小星星游戲
本文實例為大家分享了js實現小星星游戲的具體代碼,供大家參考,具體內容如下
功能簡介
如圖:實現一個點擊游戲
準備
準備一個星星的圖片(這里我重命名為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('調用'); //周期的調用函數,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('游戲結束,共消除了'+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() { //通過父元素刪除子節點 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>
結束
可以將css部分和js部分寫成單獨的文件,但是需要引入
<link href = 'http://m.lshqa.cn/bcjs/css文件路徑' rel = 'stylesheet'><script src='http://m.lshqa.cn/bcjs/js文件路徑' type='text/javascript'></script>
更多關于Js游戲的精彩文章,請查看專題: 《JavaScript經典游戲 玩不停》
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: