Vanilla Javascript - 当玩家达到一定分数时结束游戏

我按照教程制作了剪刀石头布游戏,现在我想更进一步,在玩家或计算机得分达到 10 分时添加消息/结束游戏。我无法确定出我需要做的事情。


  let user = ["Player", "Computer"];

  let pScore = 0;

  let cScore = 0;

  let gameIsOver = false;

  

  // Some other functions in here...


  // End Game

  if (pScore === 10) {

    isGameOver = true;

    winner.textContent = `${user[0]} Wins the Game!`;

    return;

  } else if (cScore === 10) {

    isGameOver = true;

    winner.textContent = `${user[1]} Wins the Game!`;

    return;

  } else {

    isGameOver = false;

  }


  // Some other functions here...


凤凰求蛊
浏览 65回答 1
1回答

噜噜哒

每次分数变化时,您都需要检查条件。为此,将您的 if 语句放在一个单独的函数中,并从有人得分时触发的函数中调用它。我创建小函数是因为,在我看来,这是最佳实践,但对于这么小的操作来说并不是必需的。let pScore = 0;let cScore = 0;let user = ["Player", "Computer"];let isGameOver = (score) => {  if (pScore === 10 || cScore === 10) {    return true;  }  return false;}function gameOver() {  let winner = pScore === 10 ? user[0] : user[1];  console.log(winner);}function theFunctionThatChangesTheScores() {  // after the code that changes the score  if ( isGameOver() ) {    // you can code in this block, but ideally.    // create another function and call it:    return gameOver();  }  return console.log("game is still on");}theFunctionThatChangesTheScores(); 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript