当马里奥跳过管道时,我试图让分数增加+1个单位,但当这种情况发生时,分数增加了超过1个单位.我怎么能这样做呢?
const mario = document.querySelector('.mario');
const pipe = document.querySelector('.pipe');
const jump = () => {
mario.classList.add('jump');
setTimeout(() => {
mario.classList.remove('jump');
}, 500);
}
let score = 0;
function scoreCount() {
score++;
document.querySelector('#score').innerHTML = `SCORE: ${score}`;
}
const loop = setInterval(() => {
const pipePosition = pipe.offsetLeft;
const marioPosition = +window.getComputedStyle(mario).bottom.replace('px', '');
if (pipePosition < 0 && marioPosition >= 80) {
scoreCount();
}
if (pipePosition <= 120 && pipePosition > 0 && marioPosition < 80) {
pipe.style.animation = 'none';
pipe.style.left = `${pipePosition}px`;
mario.style.animation = 'none';
mario.style.bottom = `${marioPosition}px`;
mario.src = './marioImages/game-over.png';
mario.style.width = '75px';
mario.style.margin = '50px';
clearInterval(loop);
}
}, 10)
document.addEventListener('keydown', jump);
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#score {
font-family: 'Super Mario 256';
margin: 10px;
z-index: 3;
}
.game-board {
width: 100%;
height: 500px;
border-bottom: 15px solid rgb(35, 160, 35);
margin: 0 auto;
position: relative;
overflow: hidden;
background: linear-gradient(#87CEEB, #E0F6FF);
}
.pipe {
position: absolute;
bottom: 0;
width: 80px;
animation: pipe-animation 1.5s infinite linear;
}
.mario {
position: absolute;
width: 150px;
bottom: 0;
z-index: 2;
}
.jump {
animation: jump 500ms ease-out;
}
.clouds {
position: absolute;
width: 500px;
animation: clouds-animation 4s infinite linear;
z-index: 1;
}
@keyframes pipe-animation {
from {
right: -80px;
}
to {
right: 100%;
}
}
@keyframes jump {
0% {
bottom: 0;
}
40% {
bottom: 180px;
}
50% {
bottom: 180px;
}
60% {
bottom: 180px;
}
100% {
bottom: 0;
}
}
@keyframes clouds-animation {
from {
right: -500px;
}
to {
right: 100%;
}
}
@font-face {
font-family: 'Super Mario 256';
src: url(/marioFont/SuperMario256.ttf);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="marioCSS/mario.css">
<script src="marioJS/mario.js" defer></script>
<title>Mario Jump</title>
</head>
<body>
<div class="game-board">
<h2 id="score">SCORE: 0</h2>
<img src="marioImages/clouds.png" class="clouds">
<img src="marioImages/mario.gif" class="mario">
<img src="marioImages/pipe.png" class="pipe">
</div>
</body>
</html>
我试图创建一个函数scoreCount
来增加分数.
然后,我将scoreCount
函数调用到"循环"中,当"pipePosition"移出窗口时,将分数加+1.
但它的增量远远超过1.