溫馨提示×

溫馨提示×

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

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

js實現(xiàn)小星星游戲

發(fā)布時間:2020-10-16 08:56:40 來源:腳本之家 閱讀:137 作者:0菜雞小白0 欄目:web開發(fā)

本文實例為大家分享了js實現(xiàn)小星星游戲的具體代碼,供大家參考,具體內(nèi)容如下

功能簡介

如圖:實現(xiàn)一個點擊游戲

js實現(xiàn)小星星游戲

準(zhǔn)備

準(zhǔn)備一個星星的圖片(這里我重命名為xxx.png)

開搞

新建一個html文件,并將其與準(zhǔn)備好的圖片放在同一目錄下(東西多了不建議這樣搞,但這個就倆)

<!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><h2 id="title">小星星游戲</h2></div>
<div><h2 id="score">得分:</h2></div>
<div id="jindu">
 <span>
 <meter id="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(){
 //重新載入當(dāng)前文檔
 location.reload();
 }

</script>
</body>
</html>

結(jié)束

可以將css部分和js部分寫成單獨的文件,但是需要引入

<link href = "css文件路徑" rel = "stylesheet">
<script src="js文件路徑" type="text/javascript"></script>

更多關(guān)于Js游戲的精彩文章,請查看專題: 《JavaScript經(jīng)典游戲 玩不?!?/p>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

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

AI