石头剪刀布JS游戏

时间:2019-09-05 20:49:54

标签: javascript

我是JS的入门者,我一直在努力理解JS的逻辑。尽管我收到警报输入,但控制台中什么都没有记录。谁能指出我要去哪里了?这可能与范围有关吗?我觉得这应该很简单,但是我无法正常工作。

function computerPlay() {
    const options = ['rock', 'paper', 'scissors'];
    let result = options[Math.floor(Math.random() * options.length)];
    return result;
}

function playRound(playerSelection, computerSelection) {
    let selection = prompt('Please enter your selection');
    let playerScore = 0;
    let computerScore = 0;
    let result = "";

    computerSelection = computerPlay();

    playerSelection = selection.toLowerCase();
    if (playerSelection == 'rock') {
        if (computerSelection == 'rock') {
            return ["It's a draw!", playerScore + 1, computerScore + 1];
        } else if (computerSelection == 'paper') {
            return ["You lose!", computerScore + 1];
        } else {
            return ["You win!", computerScore + 1];
        }
    } else if (playerSelection == 'paper') {
        if (computerSelection == 'paper') {
            return "It's a draw!";
        } else if (computerSelection == 'scissors') {
            return "Computer wins!";
        } else {
            return "You win!";
        }
    } else if (playerSelection == 'scissors') {
        if (computerSelection == 'scissors') {
            return "It's a draw!"
        } else if (computerSelection == 'rock') {
            return "Computer wins!"
        } else {
            return "You win!"
        }
    }

    return result + "Player Score = " + playerScore + "Computer Score = " + computerScore;

}

function game() {

    for (let i = 0; i < 5; i++) {
        computerPlay();
        playRound();
    }

}

console.log(game())

2 个答案:

答案 0 :(得分:1)

将控制台日志从其位置移动到game()函数内部,如下所示:

for (let i = 0; i < 5; i++) {
    console.log(playRound());
}

您也不需要在游戏功能中调用computerPlay(),因为它什么也没做。

答案 1 :(得分:0)

以此方式修改游戏功能。

function game() {

  for (let i = 0; i < 5; i++) {
      const result = playRound();
      console.log(result)
  }

}
game()

然后调用game()。您将能够看到您的控制台日志,也不需要在游戏功能内调用computerPlay功能。在playRound函数中已经调用了它的功能。希望这可以帮助加油