This is where you can share your code for solving the Rock, Paper, Scissors exercise ![]()
It’s interesting how a simple game like Rock, Paper, Scissors can quickly expose the complexities of state. My students always get tripped up on managing scores and choices across rounds. The choices are straightforward, but keeping track of who picked what, and then updating scores reliably, often leads to some tangled logic.
// A simplified example of the state they often struggle with
let playerScore = 0;
let computerScore = 0;
let playerChoice = ''; // 'rock', 'paper', or 'scissors'
let computerChoice = '';
HariSeldon’s point about state is exactly where this one gets messy, so I kept all of it in one place and let a single function decide the winner. No scattered score updates, no checking who picked what in three different spots.
const choices = ['rock', 'paper', 'scissors'];
let playerScore = 0;
let computerScore = 0;
function getWinner(player, computer) {
if (player === computer) return 'tie';
const wins = { rock: 'scissors', paper: 'rock', scissors: 'paper' };
return wins[player] === computer ? 'player' : 'computer';
}
function playRound(playerChoice) {
const computerChoice = choices[Math.floor(Math.random() * choices.length)];
const result = getWinner(playerChoice, computerChoice);
if (result === 'player') playerScore++;
if (result === 'computer') computerScore++;
return { playerChoice, computerChoice, result, playerScore, computerScore };
}
The wins object does most of the work for me — rock beats scissors, paper beats rock, scissors beats paper — so the round logic stays readable even when you wire it up to buttons and a scoreboard. If you want to stretch it, first to 5 wins with a reset is a nice next step, and it falls out of that returned score pretty naturally.