Skip to content
Tutorials Center
My learning

Topics

Lesson 180 of 201 ยท Projects

Project: Snake Game

Build the Snake game in Java - a testable game model with a deque, tick logic and collisions, buffered key presses, a BFS autopilot and a Swing window.

Snake is the perfect first real-time game. A line of segments crawls across a grid, you steer it with the arrow keys, it grows every time it eats, and the game ends when it hits a wall or its own body. The rules fit in one sentence, yet building it well teaches the central idea of every game: separate the model (what the game state is and how it changes) from the view (how it's drawn) and the controller (how keys and time drive it).

You'll build the model first and run it in the browser as text frames, because the model doesn't care whether it's drawn with characters or pixels. Then you'll fix a famous input bug, let a breadth-first search play the game by itself, and finally put the very same model into a Swing window with a timer and key bindings. Our server has no screen, so the window itself is read-only code you run on your own computer; but you'll still run its drawing code here, painting into an image in memory and checking the pixels.

The project uses records, enums, ArrayDeque, HashSet, Random, a graph search, and Swing with events.

Designing the model

A Snake board is a grid of cells, addressed by x (column, growing to the right) and y (row, growing downward, as on screens). The game state is:

  • The snake's body, an ordered list of cells from head to tail.
  • The direction it's moving in.
  • The food, one cell somewhere free on the board.
  • The score, and whether (and why) the game is over.

The game moves in ticks. On every tick, the head advances one cell in the current direction. If the new cell has food, the snake grows: the tail stays where it is. Otherwise the tail moves up by one cell too, so the length doesn't change. The game ends when the head leaves the board or lands on the body.

The key observation for the data structure: on each tick you add a cell at the front and remove one at the back. That's exactly what a deque (double-ended queue) does in constant time. An ArrayDeque is the right choice; an ArrayList would have to shift every element to insert at the front.

Stage 1: points, directions and a moving deque

Two small types carry the geometry. Point is a record, so two points with the same coordinates are equal and have the same hashCode, which lets them work as keys in sets and maps. Direction is an enum whose constants carry their step, dx and dy, so moving is just addition, with no switch anywhere.

Java Stage 1: moving and growing a snake in a deque

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows the body after each step, head first. Moving right adds (4,2) at the front and drops (1,2) from the back. Growing keeps the tail, so the length becomes 4.

Note how "opposite" is defined: two directions are opposite when their steps cancel out. That's one line instead of four case labels, and it can't get out of sync if you add diagonal directions later.

Stage 2: the Game class

Now the full model. The Game class owns the body (a deque), a HashSet of the same cells for fast "is this cell taken?" checks, the direction, the food and the score. Its public surface is tiny: turn(direction) records what the player wants, tick() advances time, and a few getters plus render() let others look at the state.

Food goes on a random free cell. The model gets its RandomGenerator from outside, so a fixed seed gives the same food positions every run, which makes the game testable and the output below predictable. In this stage, the run is scripted: a Map says which key is pressed before which tick.

Java Stage 2: the game model, tick by tick

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The snake eats on tick 7, turns down along the right wall and leaves the board on tick 11. The final frame shows the board just before the fatal move.

The important details in tick():

  • The tail moves before the collision check. If the head moves into the cell the tail is just leaving, that's legal: the tail is gone by the time the head arrives. Checking the collision first would kill a snake for chasing its own tail, a bug many first versions have. When the snake eats, the tail doesn't move, so that cell stays blocked.
  • occupied mirrors body. ArrayDeque.contains walks the whole deque, so checking every tick would be slow for a long snake. A HashSet answers in constant time. The cost is keeping two collections in sync, which is why every change goes through tick() and the fields are private.
  • Food picks from a list of free cells. The tempting alternative, "pick random cells until one is free", gets slower and slower as the snake fills the board and never ends when the board is full. Building the list costs a scan of the board, which is tiny here. When the list is empty, the player has filled the board and won.
  • direction and nextDirection are separate. A turn changes only nextDirection; tick() applies it. The reversal check compares against direction, the way the snake actually moved last, not the last key pressed.

That last point exists to stop a classic bug. If turn checked against the last key instead, pressing up and then left quickly while moving right would be accepted (up isn't opposite right, and left isn't opposite up), and on the next tick the snake would turn straight back into its own neck. Our check prevents that, but the last line of the output shows its own problem: the player pressed up and left, and only up happened. The left key was simply lost. Stage 3 fixes that.

Stage 3: buffered turns and keys from the Input box

Fast players often press two keys between two ticks, for example up and then left to make a tight U-turn. The fix is a small queue of turns: each key press is appended, and each tick consumes one. Every queued turn is checked against the turn queued before it (or the current direction if the queue is empty), so a reversal is still impossible. The queue holds at most two turns, so mashing keys can't build up a long backlog of moves that play out seconds later.

The keys now come from the Input box. The first line is the random seed. After that, every whitespace-separated token is one tick: . means no key, and w, a, s, d mean up, left, down and right. A token with several letters, like wa, means several keys were pressed during the same tick. The program prints a frame each time the snake eats, and the final frame.

Java Stage 3: buffered turns, controlled from the Input box

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Follow the input:

  • The a in the first line is ignored: the snake moves right, and left would be a reversal. It still counts as a tick.
  • After eight ticks right, s turns down, and two more ticks reach the food in the corner.
  • The second line drives left along the bottom, then wa presses up and left within one tick. The snake goes up on that tick and left on the next, because the left turn waited in the queue. With the Stage 2 model, the left key would have been lost. Then w and three more ticks climb the left edge to the second piece of food.
  • The third line runs the snake into the top wall. The final frame is the board just before the crash.

in.next() reads whitespace-separated tokens, so line breaks in the Input box don't matter; they only make the input easier to read. Change the seed to get different food positions, or add an unknown key such as x to see the program ignore it.

Because the model knows nothing about keyboards, a program can play it just as well as a person. This stage adds an autopilot that, before every tick, searches for the shortest path from the head to the food and steers along it.

The board is a graph: every free cell is a node, connected to its four neighbors. Breadth-first search (BFS) explores it in rings of increasing distance from the head, so the first time it reaches the food, it has found a shortest path. The search remembers, for every cell it reaches, which first step from the head led there. When it reaches the food, that first step is the move to make. If the food can't be reached at all, the autopilot takes any move that doesn't crash immediately. Graphs and Recursion covers BFS in general.

Java Stage 4: a breadth-first search autopilot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The autopilot eats quickly at first: 5 pieces of food by tick 39, 20 by tick 135. Then the board fills up, the snake's own body walls off the path, and with a score of 32 it finally boxes itself into the top-left corner and crashes.

That ending is the interesting part. A greedy shortest path is a fine strategy while the snake is short, but it never considers whether the snake can get out again after eating. Strong Snake programs add a safety check: before following the path, simulate it and make sure the head can still reach the tail afterwards (the tail is the one cell guaranteed to keep moving away). That's a good extension once you're comfortable with BFS.

Two implementation details:

  • ArrayDeque is the BFS queue too: addLast to enqueue, removeFirst to dequeue. The same class serves as the snake's body and the search frontier.
  • The model needed no changes to be driven by code. The autopilot uses only head(), food(), isFree() and turn(), the same methods a keyboard handler would use. Good model design pays off in tests, bots and replays.

Stage 5: the Swing window

Finally, the graphics. A Swing game needs three pieces, and each maps onto what you already have:

  • A view: a JPanel subclass whose paintComponent draws the current state.
  • A clock: a javax.swing.Timer that calls game.tick() and then repaint() every 120 milliseconds.
  • A controller: key bindings that call game.turn(...).

Here is the complete window. It's read-only because our server has no display: save it as Main.java, paste the Point, Direction and Game classes from Stage 3 at the bottom, and run java Main.java. Arrow keys or WASD steer, P pauses and Space starts a new game.

Java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.random.RandomGenerator;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Snake");
            SnakePanel panel = new SnakePanel(20, 15);
            frame.add(panel);
            frame.pack();                               // size the window to the panel
            frame.setResizable(false);
            frame.setLocationRelativeTo(null);          // center on screen
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            panel.start();
        });
    }
}

class SnakePanel extends JPanel {
    static final int CELL = 24;
    static final int TICK_MILLIS = 120;

    private final int columns;
    private final int rows;
    private final Timer timer;
    private Game game;

    SnakePanel(int columns, int rows) {
        this.columns = columns;
        this.rows = rows;
        this.game = new Game(columns, rows, new Random());
        setPreferredSize(new Dimension(columns * CELL, rows * CELL));
        timer = new Timer(TICK_MILLIS, e -> step());    // fires on the event dispatch thread

        bind("UP", Direction.UP);
        bind("DOWN", Direction.DOWN);
        bind("LEFT", Direction.LEFT);
        bind("RIGHT", Direction.RIGHT);
        bind("W", Direction.UP);
        bind("S", Direction.DOWN);
        bind("A", Direction.LEFT);
        bind("D", Direction.RIGHT);
        onKey("SPACE", "restart", this::restart);
        onKey("P", "pause", this::togglePause);
    }

    void start() {
        timer.start();
    }

    private void bind(String key, Direction direction) {
        onKey(key, "turn-" + key, () -> game.turn(direction));
    }

    private void onKey(String key, String name, Runnable action) {
        getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(key), name);
        getActionMap().put(name, new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                action.run();
            }
        });
    }

    private void step() {
        game.tick();
        if (game.isOver()) {
            timer.stop();
        }
        repaint();                                      // asks Swing to call paintComponent soon
    }

    private void restart() {
        game = new Game(columns, rows, new Random());
        timer.restart();
        repaint();
    }

    private void togglePause() {
        if (game.isOver()) {
            return;
        }
        if (timer.isRunning()) {
            timer.stop();
        } else {
            timer.start();
        }
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g.create();
        try {
            SnakeRenderer.draw(g2, game, CELL);
            g2.setColor(Color.WHITE);
            g2.setFont(getFont().deriveFont(Font.BOLD, 14f));
            g2.drawString("Score " + game.score(), 8, 18);
            if (game.isOver()) {
                banner(g2, "The snake " + game.endReason() + ". Space = new game");
            } else if (!timer.isRunning()) {
                banner(g2, "Paused. P = continue");
            }
        } finally {
            g2.dispose();
        }
    }

    private void banner(Graphics2D g, String text) {
        g.setColor(new Color(0, 0, 0, 170));
        g.fillRect(0, getHeight() / 2 - 22, getWidth(), 44);
        g.setColor(Color.WHITE);
        FontMetrics metrics = g.getFontMetrics();
        int x = (getWidth() - metrics.stringWidth(text)) / 2;
        int y = getHeight() / 2 + (metrics.getAscent() - metrics.getDescent()) / 2;
        g.drawString(text, x, y);
    }
}

/** All drawing in one place: used by the window and by the test above. */
class SnakeRenderer {
    static final Color BACKGROUND = new Color(0x1E2229);
    static final Color BODY = new Color(0x3FA34D);
    static final Color HEAD = new Color(0x8FE388);
    static final Color FOOD = new Color(0xE5484D);

    static void draw(Graphics2D g, Game game, int cell) {
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(BACKGROUND);
        g.fillRect(0, 0, game.width() * cell, game.height() * cell);

        Point food = game.food();
        if (food != null) {
            g.setColor(FOOD);
            g.fillOval(food.x() * cell + 2, food.y() * cell + 2, cell - 4, cell - 4);
        }
        g.setColor(BODY);
        for (Point p : game.body()) {
            g.fillRoundRect(p.x() * cell + 1, p.y() * cell + 1, cell - 2, cell - 2, cell / 3, cell / 3);
        }
        Point head = game.head();
        g.setColor(HEAD);
        g.fillRoundRect(head.x() * cell + 1, head.y() * cell + 1, cell - 2, cell - 2, cell / 3, cell / 3);
    }
}

// Paste record Point, enum Direction and class Game from Stage 3 here.

How it fits together, and why it's written this way:

  • Everything happens on the event dispatch thread. SwingUtilities.invokeLater builds the window on the EDT, javax.swing.Timer fires its action on the EDT, and key bindings run there too. So game is only ever touched by one thread, and the model needs no locks. A java.util.Timer or a Thread.sleep loop would call tick() from another thread while paintComponent reads the same deque, which is a data race (see Swing Basics on the EDT rule).
  • repaint() doesn't paint. It asks Swing to call paintComponent soon, and several requests are merged into one. Never call paintComponent yourself.
  • Key bindings, not KeyListener. A KeyListener only receives keys when its component has keyboard focus, which breaks as soon as anything else in the window takes focus. WHEN_IN_FOCUSED_WINDOW bindings work whenever the window is active. The onKey helper wraps a Runnable in an AbstractAction so each binding is one line.
  • g.create() and dispose(). Painting on a copy of the Graphics object means font and color changes can't leak into Swing's own painting of borders or child components.
  • The speed is a constant. 120 ms per tick is about 8 moves per second. A common extension is to shorten the delay as the score rises with timer.setDelay(...).

The drawing itself lives in a separate SnakeRenderer class that only needs a Graphics2D and a Game. That separation makes it possible to run the drawing code without a screen: Java can paint into a BufferedImage in memory (this is how servers generate charts and thumbnails). The program below draws a game into an image, reads one pixel from the middle of every cell, turns the colors back into characters, and compares the result with the text frame from render():

Java Stage 5: running the Swing drawing code without a screen

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

It prints Pixels match the text frame: true: the pixel picture and the text frame agree cell by cell. This is a real technique for testing graphics code. You can't easily assert on what a window looks like, but you can render into an image and check the pixels (or compare it with a saved reference image).

The renderer uses rounded rectangles for the body and an oval for the food, all with antialiasing. The sample point is the center of each cell, where every shape is fully opaque, so the colors match exactly; near the rounded edges, antialiasing blends colors, which is why the test doesn't sample there.

Ideas to extend it

  • Wrap-around walls. Instead of dying at the edge, come out on the other side: Math.floorMod(x, width) handles negative coordinates correctly, unlike %.
  • Speed levels. Lower the timer delay every 5 points, and show the level next to the score.
  • High scores. Save the best score with Files.writeString in the user's home directory and show it in the banner (see Files).
  • A safer autopilot. Before following a path to the food, simulate eating and check with a second BFS that the head can still reach the tail. If not, follow the tail instead.
  • Obstacles and levels. Load walls from a text file where # marks a blocked cell; isFree and food placement just need to know about them.
  • Unit tests. With a seeded generator, write JUnit tests such as "moving into the vacating tail cell is allowed" and "a reversal is ignored" (see Unit Testing).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is an ArrayDeque a better fit for the snake's body than an ArrayList?

    Inserting at index 0 of an ArrayList shifts every element. ArrayDeque adds and removes at both ends in constant time. (It doesn't allow null, by the way.)
  2. 2. The snake moves right and its head is next to its own tail, which is directly to the right. It doesn't eat on this tick. What happens?

    tick() removes the tail before checking for collisions when the snake isn't eating, so the head may move into the cell the tail is vacating.
  3. 3. With the Stage 2 model, the snake moves right and the player presses up and then left before the next tick. What happens over the next two ticks?

    Up is accepted. Left is checked against the direction the snake actually moved (right), so it's rejected as a reversal. Stage 3's turn queue keeps both keys.
  4. 4. Why does the Swing version use javax.swing.Timer instead of a thread with Thread.sleep in a loop?

    With everything on the EDT, the model is used by only one thread and needs no synchronization. A separate thread calling tick() would race with paintComponent.
  5. 5. Why does breadth-first search find a shortest path to the food?

    BFS uses a FIFO queue, so all cells at distance 1 are explored before distance 2, and so on. The first arrival at any cell uses the fewest steps.

Summary

  • Split the game into a model (Game), a view (text render() or SnakeRenderer) and a controller (input tokens, key bindings or an autopilot); the model never reads keys or draws.
  • Point is a record (value equality for sets and maps) and Direction an enum carrying dx/dy; opposites are directions whose steps cancel out.
  • The body is an ArrayDeque (add head, remove tail) mirrored by a HashSet for constant-time collision checks; the tail moves before the collision check.
  • Food is chosen from the list of free cells with an injected, seedable RandomGenerator.
  • A queue of at most two turns, each checked against the previous one, keeps fast key presses without allowing reversals.
  • BFS over free cells finds the shortest path to the food; greedy paths eventually trap a long snake.
  • In Swing, a javax.swing.Timer drives tick() and repaint() on the EDT, key bindings call turn(), and the drawing code can be tested by painting into a BufferedImage.

Next: Project: A Swing Text Editor, where you'll build a document model with find and replace, open and save files with NIO, and wrap it in a Swing window.