我正在制作一个游戏,玩家必须输入数字来猜测一个国家的人口,但我在计算他们的分数时遇到了问题。我有这个 if 语句:
if (player1 === "" || player2 === "") {
resultSpan.innerHTML = "One or two empty values";
} else {
resultSpan.innerHTML = `The correct number is ${population.toLocaleString()}`;
let playerWin = document.querySelector(".results-player-win");
if (
Math.abs(parseInt(population) - playerOneTotal) <
Math.abs(parseInt(population) - playerTwoTotal)
) {
playerWin.innerText = "Player 1 wins!";
playerOneScore++;
}
if (
Math.abs(parseInt(population) - playerOneTotal) >
Math.abs(parseInt(population) - playerTwoTotal)
) {
playerWin.innerText = "Player 2 wins!";
playerTwoScore++;
}
document.getElementById(
"current-score"
).innerHTML = `P1: ${playerOneScore} --- P2: ${playerTwoScore}`;
}
但是,有时分数不是加 1,而是 2 或 3。我猜这是因为预先调用了另一个 eventListener
。但是,我找不到将它们完全分开的方法,因为它们都需要使用相同的总体变量才能正确计算分数。
我尝试在 IF 语句中添加 this.remove()
,但它删除了按钮。我也尝试过 e.stopImmediatePropagation();
并创建一个变量 isFirst
,然后设置为 true 然后 false,但它们在第二次执行时完全阻止了代码。
为了更清楚,我还发布了一个 JSFiddle。
答案 0 :(得分:0)
我通过初始化变量设法解决了这个问题
playerOneScore = 0;
playerTwoScore = 0
; (跟踪分数的那些)在全球环境中。我还向跟踪用户输入/分数的监听器添加了 { once: true }
,因为多次点击按钮会导致不良行为。