2 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
我看到您每次執(zhí)行 if/else 語(yǔ)句時(shí)都會(huì)調(diào)用 ComputerPlay() 函數(shù)。假設(shè)computerPlay() 隨機(jī)返回石頭、布或剪刀,這將返回不同的值。您可以做的一件簡(jiǎn)單的事情是將返回值存儲(chǔ)在像這樣的變量中
let computersHand = computerPlay();
然后在執(zhí)行 if/else 語(yǔ)句時(shí)使用此變量
if (computersHand === 'rock') {
? ? // ...
} else if (computersHand === 'paper') {
? ? // ...
} else {
? ? // ...
}
如果您出于某種原因不想將返回值存儲(chǔ)到變量中,可以使用 switch 語(yǔ)句
switch (computerPlay()) {
? ?case 'rock':
? ? ? ?// ...
? ? ? ?break;
? ?case 'paper':
? ? ? ?// ...
? ? ? ?break;
? ?case 'scissors':
? ? ? ?// ...
? ? ? ?break;
}

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超6個(gè)贊
您應(yīng)該調(diào)用該computerPlay函數(shù)一次
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像這樣調(diào)用函數(shù)
computerPlay();
if (computerPlay() === 'paper')
沒(méi)有意義,因?yàn)槟惴Q它為兩次(計(jì)算機(jī)一鍵播放兩次)
添加回答
舉報(bào)