Skip to content
Tutorials Center
My learning

Topics

Lesson 125 of 132 ยท Projects

Project: 15 Puzzle and Flappy Bird

Build a sliding 15 puzzle with a solvable shuffle and animated tiles, then a Flappy Bird game driven by requestAnimationFrame and a pure step function in React.

Games are a stress test for your React habits. A turn-based game like the 15 puzzle shows how to model a grid as plain data and keep the rules in pure functions. A real-time game like Flappy Bird adds a new ingredient: time. Something has to update the screen sixty times a second, and React has to stay out of the way.

In this project you will build both. For the puzzle you will write a move function, a shuffle that can never produce an unsolvable board, and keyboard support with animated tiles. For Flappy Bird you will run a game loop with requestAnimationFrame inside an effect, and keep all the physics in one pure step function. Revisit useEffect, effect cleanup and reducers if needed. The earlier Tic-Tac-Toe project is also a good warm-up for grids.

Stage 1: the 15 puzzle as an array

A 4 by 4 board holds the numbers 1 to 15 and one blank. Store it as a flat array of 16 numbers, with 0 for the blank. The tile at index i is in row Math.floor(i / 4) and column i % 4. A tile can move only if it is directly next to the blank, so a move is "swap this tile with the blank".

Shuffling is a trap. If you just randomise the array, about half of all arrangements can never be solved. The safe way is to start from the solved board and make many random legal moves: every board reached that way can be undone, so it is solvable.

Notice what is derived: whether the puzzle is solved is a comparison with the solved board, so it is not stored. Only board and moves are state.

Stage 1: click to slide

moveTile returns the same array for an illegal move, so next !== board is a cheap way to ask "did anything happen?". The shuffle also avoids undoing its previous step immediately, which would waste moves.

Stage 2: animated tiles and arrow keys

Stage 1 re-orders buttons inside a grid, so the browser cannot animate a tile "sliding": it just appears in its new cell. The trick is to give every tile a stable key (its number) and position it with transform: translate(...) computed from its index. React keeps the same DOM element and only changes its style, so a CSS transition animates the slide for free. That is reconciliation working for you.

Keyboard play needs a keydown listener, which is a subscription to an outside system, so it lives in an effect with cleanup. Pressing an arrow moves the tile from the opposite side into the blank: Arrow Left moves the tile on the blank's right, because the tile slides left. The handler uses the functional setBoard form, so the effect has no dependencies.

Stage 2: transitions and keyboard

Tiles already in their final place turn green, which is another derived value (tile === index + 1). Without the key={tile}, React would reuse buttons by position, and the slide animation would disappear.

Stage 3: Flappy Bird and the game loop

A real-time game needs a loop: every frame, update the world, then draw it. The browser offers requestAnimationFrame (rAF), which calls your function just before each repaint and passes a timestamp. The loop is an effect: it starts when the game starts, and its cleanup calls cancelAnimationFrame when the game ends or the component unmounts, otherwise the loop would keep running on a dead component.

Two rules keep the game stable:

  • Use time, not frames. Movement is speed * dt, where dt is the seconds since the last frame, so the game runs at the same speed on a 60 Hz and a 144 Hz screen. Cap dt so a background tab does not cause a giant jump.
  • Keep physics in a pure function. step(game, dt, random) takes the old game and returns the new one. The random number for a new pipe's height is drawn by the loop and passed in, so step stays predictable and easy to test.

The game has three statuses: ready, playing and over. Space, Arrow Up, a click or a tap all call flap, which starts, flaps or restarts depending on the status.

Stage 3: Flappy Bird

Study the loop effect. Its dependency is playing, a boolean, not the whole game object, so the effect restarts only when play starts or stops and not 60 times a second. Inside, setGame((g) => ...) reads the latest state and the loop never needs a stale copy. The g.status === 'playing' guard makes a late frame harmless after the game ends.

Re-rendering a small SVG 60 times a second is fine. For games with thousands of objects you would keep the state in a useRef and draw to a <canvas>, and use React only for the menus around it.

Ideas to extend it

  • 15 puzzle: add a timer that starts on the first move and stops when solved, and a best-moves record kept in state.
  • Flappy Bird: increase SPEED slowly as the score rises, and keep a high score for the session.
  • Add a "pause" key that stops the loop by changing the status: the cleanup handles the rest.
  • Make the puzzle size selectable (3, 4 or 5) by turning SIZE into state and building the solved board from it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why shuffle the 15 puzzle by making random legal moves instead of randomising the array?

    Every arrangement reached by legal moves can be reversed back to solved. A uniformly random permutation is unsolvable half of the time.
  2. 2. Why is the tile's key its number rather than its index?

    With a stable key, React updates the style of the existing element (a new transform) instead of replacing it, so the browser can animate between the two positions.
  3. 3. What does the cleanup function of the game loop effect do?

    requestAnimationFrame keeps scheduling until you cancel it. The cleanup stops the pending frame so a stopped or unmounted game does not keep updating.
  4. 4. Why is movement computed as speed * dt instead of a fixed amount per frame?

    Frame rates vary. Scaling movement by elapsed time keeps the physics consistent whether the loop runs 30, 60 or 144 times per second.

Summary

  • Model a grid as a flat array and put the rules (neighbours, moves, solved check) in pure functions.
  • Shuffle by random legal moves so every puzzle is solvable; derive "won" instead of storing it.
  • Stable keys plus a position computed from the index let CSS transitions animate moves.
  • Run game loops in an effect: start requestAnimationFrame, and cancel it in the cleanup.
  • Scale movement by dt, keep the physics in a pure step function, and pass random numbers in.

Next: Project: Portfolio Site with Animations