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')
沒有意義,因為你稱它為兩次(計算機一鍵播放兩次)
添加回答
舉報