记分员不止步于赢取分数。

我一直在建立一个记分器作为一个有趣的项目,但当我试图让它停止在游戏的胜利分数,它不会停止。任何帮助将是感激的

var playerOne = document.querySelector("#p1")
var playerTwo = document.querySelector("#p2")
var playerOneScore = 0
var playerTwoScore = 0
var score1 = document.querySelector("#Score1")
var score2 = document.querySelector("#Score2")
var gameOver = false;
var winningScore = 5

playerOne.addEventListener("click", function(){
    if(!gameOver){
    playerOneScore++
    if(playerOneScore === winningScore){
        gameover = true;
    }
    score1.textContent = playerOneScore;
    }
});

playerTwo.addEventListener("click", function(){
    if(!gameOver){
    playerTwoScore++
    if(playerTwoScore === winningScore){
        gameover = true;
    }
    score2.textContent = playerTwoScore;
    }
});
    <h1><span id="Score1">0</span> to <span id="Score2">0</span></h1>

    <p>Playing to: 5</p>

    <input type="number" id="winningScore">
    <button id="p1">Player One</button>
    <button id="p2">Player Two</button>
    <button id="reset">Reset</button>
    <script src="index.js"></script>

解决方案:

看看你的gameover和gameOver变量……应该为

gameOver=true

 if (!gameOver) {
   playerOneScore++
   if (playerOneScore === winningScore) {
     gameOver = true;
   }
   score1.textContent = playerOneScore;
 }

另外,这看起来应该更好,更易读……考虑重构你的eventListener回调实现。同样适用于其他玩家。

playerOne.addEventListener("click", function() {
  if (gameOver) return;
  playerOneScore++

  gameOver = playerOneScore === winningScore;
  score1.textContent = playerOneScore;

});

本文来自投稿,不代表运维实战侠立场,如若转载,请注明出处:https://www.shizhanxia.com/799.html

(0)
上一篇 2022年6月29日 下午4:00
下一篇 2022年6月29日 下午4:00

相关推荐

发表评论

登录后才能评论