这是我第一次在这里提问。所以,我的主要问题是,当我玩石头、剪子、布的游戏时,我只会打平或输掉一局——我从来没有赢过。我已经在多个浏览器和codependency上进行了测试,结果是相似的。我完全不知道我的代码出了什么问题。有人可以指出我在正确的方向或指出任何明显的错误在我的js代码?谢谢你!
// declares that default score of both players is set to zero at begining of each game
let playerScore = 0
let computerScore = 0
const buttons = document.querySelectorAll('input')
// this function randomly returns either rock, paper, or scissors
function computerPlay() {
let choices = ['Rock', 'Paper', 'Scissors']
return choices[Math.floor(Math.random() * choices.length)]
}
// disables multiple buttons when one is clicked
function disableButtons() {
buttons.forEach(elem => {
elem.disabled = true
})
}
// main function for game
function playRound(playerSelection) {
let computerSelection = computerPlay()
let result = ""
if ((playerSelection == 'rock' && computerSelection == 'scissors') ||
(playerSelection == 'scissors' && computerSelection == 'paper') ||
(playerSelection == 'paper' && computerSelection == 'rock')) {
playerScore += 1
result = ('You win! ' + playerSelection + ' beats ' + computerSelection
+ '<br><br>Player score: ' + playerScore + '<br>Computer score: ' + computerScore)
if (playerScore == 5) {
result += '<br><br>You won the game! Reload the page to play again.'
disableButtons()
}
}
else if (playerSelection == computerSelection) {
result = ('It's a tie... You both chose ' + playerSelection
+ '<br><br>Player score: ' + playerScore + '<br>Computer score: ' + computerScore)
}
else {
computerScore += 1
result = ('You lose. ' + computerSelection + ' beats ' + playerSelection + '.'
+ '<br><br>Player score: ' + playerScore + '<br>Computer score: ' + computerScore)
if (computerScore == 5) {
result += '<br><br>Computer won the game! Reload the page to play again.'
disableButtons()
}
}
// prints result to html file
document.getElementById('result').innerHTML = result
return
}
// adds the functionality to initiate a round of the game when a button is clicked
buttons.forEach(button =>{
button.addEventListener('click', function(){
playRound(button.value)
})
})
计算机的选择是(computerSelection
):
let choices = ['Rock', 'Paper', 'Scissors']
但是在你的比较条件下:
if ((playerSelection == 'rock' && computerSelection == 'scissors') ||
(playerSelection == 'scissors' && computerSelection == 'paper') ||
(playerSelection == 'paper' && computerSelection == 'rock')) {
比较总是返回false,
摇滚
剪刀!=剪刀
Paper != Paper
如上所述,它还取决于您从按钮(即playerSelection
)获得的值。保持选择的小写/大写一致,我认为它应该工作。