<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>重新开始</title>
<style>
*{
margin: 0;
padding: 0;
}
html, body{
width: 100%;
height: 100%;
}
body{
background: url("images/bg.jpg") no-repeat center center;
background-size: cover;
overflow: hidden;
}
img{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.specter{
width: 300px;
height: 300px;
background: url("images/yy.png") no-repeat;
position: absolute;
}
.specter span{
position: absolute;
top: 200px;
left: 70px;
font-size: 60px;
font-weight: bold;
text-shadow: 5px 5px 5px #3e427a;
}
</style>
</head>
<body>
<img src="images/play.png" alt="">
<audio src="media/bg.ogg" loop autoplay></audio>
<!--<div class="specter">-->
<!-- <span>m</span>-->
<!--</div>-->
</body>
<script>
let oImg = document.querySelector("img");
let oAudio =document.querySelector("audio")
let list = []
let id = null;
oImg.onclick = function (){
oImg.parentElement.removeChild(oImg);
oAudio.play();
id = window.setInterval(function (){
let s = new Specter();
s.fly();
list.push(s);
}, 1000);
}
class Specter {
constructor (){
let oDiv = document.createElement("div");
// oDiv.className = "specter";
oDiv.style.top = "1000px";
oDiv.style.left = Math.random() * 1500 + "px";
let oSpan = document.createElement("span");
// oSpan.innerText = "m";
let key = this.generateKey();
oSpan.innerText = key;
oDiv.className = "specter " + key;
document.body.appendChild(oDiv);
oDiv.appendChild(oSpan);
this.oDiv = oDiv
}
bomb(){
document.body.removeChild(this.oDiv);
clearInterval(this.timer);
}
fly(){
let offset = parseInt(this.oDiv.style.top);
this.timer = window.setInterval( () =>{
offset -= 20;
if (offset <= -300){
this.bomb();
}
if (this.oDiv.style.top < -500 + "px"){
alert("Game Over");
clearInterval(id);
return false;
}
this.oDiv.style.top = offset + "px";
}, 200)
}
generateKey(){
let num = Math.floor(Math.random() * (90 - 65 + 1) + 65);
return String.fromCharCode(num)
}
}
document.body.onkeydown = function (event){
let key = event.key.toUpperCase();
let oDiv = document.querySelector("." + key);
let currentIndex = list.findIndex(function (currentValue){
return currentValue.oDiv === oDiv;
});if(currentIndex === -1)return;
let currentSpecter = list[currentIndex];
currentSpecter.bomb();
list.splice(currentIndex, 1);
}
/*
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min); //The maximum is inclusive and the minimum is inclusive
}
*/
</script>
</html>
这个是完整代码
if (this.oDiv.style.top < -500 + "px"){
alert("Game Over");
clearInterval(id);
return false;
}
这里我也写了clearInterval(id);来关闭定时器 但是还是没有结束游戏
你应该clear的是this.timer,你这个代码是this.timer控制的你动画的行驶轨迹