如何修复计分板:实现每次仅增加1分而非10分
问题:如何让计分板每次增加1分,而不是10分?
问题原因
你的loopGame定时器每10毫秒执行一次,当管道移动到pipePosition <= 0的区域时,在管道彻底离开屏幕的这段时间里,定时器会反复触发updated()函数,每次触发都让pontuacao加1,所以看起来分数一下子跳了10分左右。
另外,你代码里的placar定时器完全是多余的——setInterval(updated)没有设置间隔时间,而且updated()里第一时间就清除了它,直接调用updated()函数就行。
修复方案
添加一个标记变量,用来记录当前管道是否已经被计分,避免重复触发加分逻辑:
修改后的完整JavaScript代码:
let pontuacao = 0; // 新增标记:记录当前管道是否已计分 let hasScored = false; function updated() { const pontos = document.getElementById('score'); pontos.innerHTML = "score: " + pontuacao++; } const loopGame = setInterval(() => { const pipePosition = pipe.offsetLeft; const marioPosition = +window .getComputedStyle(mario) .bottom.replace("px", ""); 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 = "./images/mario-game-over.png"; mario.style.width = "75px"; mario.style.marginLeft = "45px"; clearInterval(loopGame); } // 仅当管道移出屏幕、马里奥存活且未计过分时,才执行加分 else if (pipePosition <= 0 && marioPosition >= 0 && !hasScored) { updated(); // 标记为已计分,防止同一管道重复加分 hasScored = true; } // 如果是多管道循环场景,管道完全移出屏幕后重置标记,给下一个管道计分 else if (pipePosition < -100) { hasScored = false; } }, 10);
关键说明
hasScored变量用来控制同一管道只触发一次加分:当管道进入计分区域时,只有在!hasScored为真的情况下才执行updated(),加分后立刻将hasScored设为true。- 如果你的游戏是多管道循环生成的,当管道完全移出屏幕左侧(比如
pipePosition < -100,数值可以根据你的管道实际宽度调整),把hasScored重置为false,这样下一个管道过来时能正常触发计分。
内容的提问来源于stack exchange,提问作者Ana Sampaio
相关产品推荐
相关产品推荐

