简体   繁体   English

石头剪刀布JS游戏

[英]Rock Paper Scissors JS Game

I'm a complete beginner with JS and I'm struggling to understand the logic with this one. 我是JS的完全入门者,我正努力理解JS的逻辑。 Nothing is being logged in the console, although I am getting the alert inputs. 尽管我收到警报输入,但控制台中什么都没有记录。 Can anyone point out where I'm going wrong? 谁能指出我要去哪里了? Is it perhaps something to do with scope? 这可能与范围有关吗? I feel like this should be really simple but I can't get it working. 我觉得这应该很简单,但是我无法正常工作。

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())

Move your console log from where it is to inside the game() function like so: 将控制台日志从它所在的位置移到game()函数内部,如下所示:

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

You also don't need to call computerPlay() in the game function, as it is doing nothing. 您也不需要在游戏函数中调用computerPlay() ,因为它什么都不做。

Modify the game function this way. 以此方式修改游戏功能。

function game() {

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

}
game()

Then you call game(). 然后,您调用game()。 You will be able to see your console log and also you do not need to call the computerPlay function inside the game function. 您将能够看到您的控制台日志,也不需要在游戏功能内调用computerPlay功能。 It's functionality is already called in the playRound function. 在playRound函数中已经调用了它的功能。 Hope this helps cheers 希望这有助于加油

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM