为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

凤凰求蛊 2023-04-27 16:40:59
我按照教程制作了剪刀石头布游戏,现在我想更进一步,在玩家或计算机得分达到 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...
查看完整描述

1 回答

?
噜噜哒

TA贡献1784条经验 获得超7个赞

每次分数变化时,您都需要检查条件。为此,将您的 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();

 


查看完整回答
反对 回复 2023-04-27
  • 1 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信