<!DOCTYPE html>
<html>
<head>
<title>Rock Paper Scissors</title>
</head>
<body>
<p>Rock Paper Scissors</p>
<button onclick="
playGame('rock');
">Rock</button>
<button onclick="
playGame('paper');
">Paper</button>
<button onclick="
playGame('scissors');
">Scissors</button>
<p class="js-result"></p>
<p class="js-moves"></p>
<p class="js-score"></p>
<button onclick="
score.wins = 0;
score.losses = 0;
score.ties = 0;
localStorage.removeItem('score');
updateScoreElement();
">Reset Score</button>
<script>
let score = JSON.parse(localStorage.getItem('score')) || {
wins: 0,
losses: 0,
ties: 0
};
updateScoreElement();
/*
if (!score) {
score = {
wins: 0,
losses: 0,
ties: 0
};
}
*/
function playGame(playerMove) {
const computerMove = pickComputerMove();
let result = '';
if (playerMove === 'scissors') {
if (computerMove === 'rock') {
result = 'You lose.';
} else if (computerMove === 'paper') {
result = 'You win.';
} else if (computerMove === 'scissors') {
result = 'Tie.';
}
} else if (playerMove === 'paper') {
if (computerMove === 'rock') {
result = 'You win.';
} else if (computerMove === 'paper') {
result = 'Tie.';
} else if (computerMove === 'scissors') {
result = 'You lose.';
}
} else if (playerMove === 'rock') {
if (computerMove === 'rock') {
result = 'Tie.';
} else if (computerMove === 'paper') {
result = 'You lose.';
} else if (computerMove === 'scissors') {
result = 'You win.';
}
}
if (result === 'You win.') {
score.wins += 1;
} else if (result === 'You lose.') {
score.losses += 1;
} else if (result === 'Tie.') {
score.ties += 1;
}
localStorage.setItem('score', JSON.stringify(score));
updateScoreElement();
document.querySelector('.js-result').innerHTML = result;
document.querySelector('.js-moves').innerHTML = `You ${playerMove} - ${computerMove} Computer`;
}
function updateScoreElement() {
document.querySelector('.js-score')
.innerHTML = `Wins: ${score.wins}, Losses: ${score.losses}, Ties: ${score.ties}`;
}
function pickComputerMove() {
const randomNumber = Math.random();
let computerMove = '';
if (randomNumber >= 0 && randomNumber < 1 / 3) {
computerMove = 'rock';
} else if (randomNumber >= 1 / 3 && randomNumber < 2 / 3) {
computerMove = 'paper';
} else if (randomNumber >= 2 / 3 && randomNumber < 1) {
computerMove = 'scissors';
}
return computerMove;
}
</script>
</body>
</html>
This is the code my YouTube teacher used to create rock paper scissors game. My problem is, score shows undefined. It worked just fine before LocalStorage lessonsā¦I asked ChatGPT and Bard for help too and the YouTube channel is remains unresponsive.
Can someone help me? Iām 100% sure itās some dumbass error Iām missing.