Могу также добавить мой ответ здесь.Я не использовал бы быстрый подход, но вместо этого кнопки.Сохраните результаты в объекте и используйте условное выражение, чтобы проверить, набрал ли кто-то пять очков после каждой игры:
const userScore = document.querySelector('.user .score')
const computerScore = document.querySelector('.computer .score')
const resultContainer = document.querySelector('.result')
const userThrowContainer = document.querySelector('.userThrow')
const opponentThrowContainer = document.querySelector('.opponentThrow')
const buttons = document.querySelectorAll('button')
const score = {
user: 0,
computer: 0
}
function rpsMatch(userThrow) {
// Define possible throws
const throwOptions = [
'rock',
'paper',
'scissors'
]
// Choose randomly from array of throws
let opponentThrow = throwOptions[Math.floor(Math.random() * throwOptions.length)]
// Print user and computer throws
userThrowContainer.innerText = `You threw ${userThrow}`
opponentThrowContainer.innerText = `Computer threw ${opponentThrow}`
function userWins() {
resultContainer.innerText = 'You win'
score.user++
updateScores()
}
function computerWins() {
resultContainer.innerText = 'You lose'
score.computer++
updateScores()
}
function updateScores() {
userScore.innerText = score.user
computerScore.innerText = score.computer
}
function resetScore() {
userScore.innerText = 0
computerScore.innerText = 0
score.user = 0
score.computer = 0
}
// RPS logic
if (userThrow == opponentThrow) {
resultContainer.innerText = 'You tied'
} else {
if (userThrow == 'rock') {
opponentThrow == 'scissors' ? userWins() : computerWins()
} else if (userThrow == 'paper') {
opponentThrow == 'rock' ? userWins() : computerWins()
} else {
opponentThrow == 'paper' ? userWins() : computerWins()
}
}
if (score.user === 5) {
alert('You won the first to 5!')
resetScore()
}
if (score.computer === 5) {
alert('You lost the first to 5!')
resetScore()
}
}
// Attach event handlers to each button
buttons.forEach(button => {
button.addEventListener('click', e => {
// Assign data attribute to variable
let userThrow = e.target.dataset.type
e.preventDefault()
// Pass user selection to rpsMatch
rpsMatch(userThrow)
})
})
<div class="user">User Score: <span class="score">0</span></div>
<div class="computer">Computer Score: <span class="score">0</span></div>
<button data-type="rock">Rock</button>
<button data-type="paper">Paper</button>
<button data-type="scissors">Scissors</button>
<div class="userThrow"></div>
<div class="opponentThrow"></div>
<div class="result"></div>