You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现马里奥跳水管时分数仅+1?当前得分多次累加异常

解决马里奥跳过水管时分数多次累加的问题

问题原因

你的loop定时器每10毫秒执行一次,当管道完全移出窗口(pipePosition < 0)且马里奥处于有效跳跃高度时,管道移出窗口的整个时间段内,每一次循环都会触发scoreCount(),导致分数被连续累加多次,而不是只加1分。

解决方案:添加分数标记变量

通过一个布尔标记变量,确保每个管道仅在第一次满足加分条件时触发一次分数累加,管道重新进入屏幕时重置标记,等待下一次跳跃判定。

修改后的JavaScript代码如下:

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;
// 添加分数标记,初始为未加分状态
let scored = false;

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) {
    if (!scored) {
      scoreCount();
      scored = true;
    }
  } else if (pipePosition > 0) {
    // 管道重新进入屏幕,重置标记,允许下一次加分
    scored = false;
  }

  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);

逻辑说明

  • scored变量初始为false,表示当前管道尚未被加分
  • 当管道移出窗口且马里奥跳跃高度达标时,只有scored为false才会调用scoreCount(),并将scored设为true,避免重复加分
  • 当管道重新出现在屏幕右侧(pipePosition > 0)时,重置scored为false,确保下一次马里奥跳过该管道时能正常加分

内容的提问来源于stack exchange,提问作者Eduardo Varjão

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 02:12:21