Skip to content
Tutorials Center
My learning

Topics

Lesson 120 of 132 ยท Projects

Project: Rock Paper Scissors and Dice/Coin Games

Build rock paper scissors, a dice roller and a coin flipper in React. Practise randomness, score state, reducers and testable game rules with live editors.

Small games are a gentle way to practise the part of React that matters most: deciding what is state and what is just a calculation. A game of rock paper scissors has a score, a history and a result for every round, and only some of those need to be stored.

In this project you will build three tiny games. First comes rock paper scissors against the computer. Then you will move its rules into a pure function and a reducer so they can be tested without clicking anything. Finally you will build a dice roller and a coin flipper and look at what random numbers really do. If you need a refresher, read useState and state updates first.

Stage 1: one round with useState

The rules are small: rock beats scissors, scissors beats paper, paper beats rock, and equal choices are a draw. A neat way to write that is a table that says what each choice beats. Then the result of a round is a calculation, not state.

Stage 1: play one round

Notice what is not in state: the message. It is computed from round during rendering, so it can never disagree with the choices. We also pick the computer's choice inside the event handler, not during render, because Math.random() makes a function impure and render must stay pure (pure components).

Stage 2: score and history with a reducer

A score needs three counters, and every round changes more than one thing: a counter, the history and the last round. That is a good fit for useReducer. We will also separate the rules into a pure function, decide(player, computer), which returns 'win', 'lose' or 'draw'.

The reducer takes the computer's choice in the action instead of generating it. That keeps the reducer pure: given the same state and action it always returns the same result, which is what makes it easy to test.

Stage 2: a reducer with score and history

The win rate is again derived: played and the percentage are calculated from the three counters. Storing them would create the risk of numbers that drift apart. The console above shows the rules working on their own, which is the payoff of the pure function.

Because the random choice travels inside the action, you can write a test that dispatches { type: 'played', player: 'rock', computer: 'scissors' } and expects win to be 1. No mocking of Math.random is needed. See testing hooks and logic.

Stage 3: dice and coin flips

Randomness belongs in event handlers (or effects), never in render. Both games below follow that rule. The dice roller keeps an array of values in state, one per die, so changing the number of dice just changes the array length. The coin flipper keeps counters and can flip a thousand times at once, so you can see that random does not mean "alternating".

Stage 3: dice roller and coin flipper

Two details are worth noticing. First, Array.from({ length: n }, rollDie) builds a fresh array each time, so React sees a new reference. Second, the coin updates counters with the functional form setCounts((c) => ...), which always starts from the latest value (state updates). Press "Flip 1000 times" a few times: the share of heads hovers near 50% but is almost never exactly 50%.

Math.random() is fine for games but not for secrets such as passwords or tokens. The next project uses crypto.getRandomValues for that.

Ideas to extend it

  • Add "best of 5" mode: stop accepting clicks when someone reaches three wins (derived from the counters).
  • Make the computer less random: it can favour whatever beats your last move. Keep the strategy in a pure function so you can test it.
  • Animate the dice with a short interval that shows random faces before the final one, and clean the interval up in an effect (effect cleanup).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the 'You win!' message not stored in state?

    Anything computable from existing state or props should be derived while rendering. Storing it would add a second source of truth that could get out of sync.
  2. 2. Why does the reducer receive the computer's choice in the action?

    A reducer that called Math.random() would be impure and hard to test, and React may call reducers twice in development to catch exactly that.
  3. 3. Where should random numbers be generated in a React component?

    Render must be pure. Handlers and effects run in response to events or after rendering, so randomness there does not change what a given render produces.
  4. 4. Which Math.random() use is wrong for a password generator?

    Math.random() is predictable and not designed for security. Secrets should come from crypto.getRandomValues.

Summary

  • Keep the minimum in state (choices, counters) and derive results, totals and percentages while rendering.
  • Put game rules in pure functions such as decide; a reducer built on them is easy to test.
  • Pass random values into reducers via actions, and generate them in event handlers or effects.
  • Use functional updates (setCounts(c => ...)) when the new value depends on the old one.
  • Math.random() suits games, not secrets.

Next: Project: Small Utility Apps (BMI, Word Counter, Card Validator)