我正在通过The Odin Project学习JavaScript,目前仍坚持使用Rock-Paper-Scissors练习。下面的程序可以在一个回合中正常运行,但是当我在 game()函数中添加 for循环以调用 playRound()五次时并保持评分,就会为 for循环所在的行给出无限循环错误。
可以对程序进行不同的配置,但这是项目要求的。任何帮助表示赞赏。
//random choice generator
function computerPlay() {
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
let number = getRandomArbitrary(0, 3)
if (number == 0) {
return 'ROCK'
} else if (number == 1) {
return 'PAPER'
} else {
return 'SCISSORS'
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
// Single Round Main
function playRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toUpperCase()
if (computerSelection == playerSelection) {
console.log('DEUCE')
return 0
} else if ((playerSelection == 'ROCK' && computerSelection == 'SCISSORS') || (playerSelection == 'PAPER' &&
computerSelection == 'ROCK') || (playerSelection == 'SCISSORS' && computerSelection == 'PAPER')) {
console.log('You Win! ' + playerSelection + ' beats ' + computerSelection + '.')
return 1
} else if ((playerSelection == 'SCISSORS' && computerSelection == 'ROCK') || (playerSelection == 'ROCK' &&
computerSelection == 'PAPER') || (playerSelection == 'PAPER' && computerSelection == 'SCISSORS')) {
console.log('You Lose! ' + computerSelection + ' beats ' + playerSelection + '.')
return 0
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
function game() {
let score = 0
for (i = 0; i < 5; i++) {
let computerSelection = computerPlay()
let playerSelection = prompt('Choose one! Rock, Paper or Scissors.')
let result = playRound(playerSelection, computerSelection)
if (result == 1) {
score += 1
} else {
score += 0
}
}
console.log(score)
}
game()
答案 0 :(得分:0)
好吧,我刚刚尝试了此页面中的“运行代码段”功能,并且该功能正常运行,然后在“ repl.it”中进行了测试,并且在此位置也正常运行。我一直在使用“ playcode.io”来测试代码,但它给出了错误。也许“ playcode.io”出了问题。
所以,我认为它可行。