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 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("調用");
//週期的調用函數,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 = "css文件路徑" rel = "stylesheet">
<script src="js文件路徑" type="text/javascript"></script>