2 回答
TA贡献1804条经验 获得超2个赞
我看到您每次执行 if/else 语句时都会调用 ComputerPlay() 函数。假设computerPlay() 随机返回石头、布或剪刀,这将返回不同的值。您可以做的一件简单的事情是将返回值存储在像这样的变量中
let computersHand = computerPlay();
然后在执行 if/else 语句时使用此变量
if (computersHand === 'rock') {
// ...
} else if (computersHand === 'paper') {
// ...
} else {
// ...
}
如果您出于某种原因不想将返回值存储到变量中,可以使用 switch 语句
switch (computerPlay()) {
case 'rock':
// ...
break;
case 'paper':
// ...
break;
case 'scissors':
// ...
break;
}
TA贡献1802条经验 获得超6个赞
您应该调用该computerPlay函数一次
rock.addEventListener('click', function() {
const result = computerPlay();
if (result) {
itemRock.textContent = 'You have chosen rock and the computer has chosen paper.
' + 'You lose, paper beats rock! Try again';
computerScore += 1;
document.getElementById("computer-score").innerText = computerScore;
} else if(result) {
itemRock.textContent = 'You have chosen rock and the computer has chosen rock.
' + 'Its a draw, try again';
} else {
itemRock.textContent = 'You have chosen rock and the computer has chosen
scissors. ' + 'You win! Rock beats scissors.';
playerScore += 1;
document.getElementById("player-score").innerText = playerScore;
}
return 'rock';
})
computerPlay像这样调用函数
computerPlay();
if (computerPlay() === 'paper')
没有意义,因为你称它为两次(计算机一键播放两次)
添加回答
举报