Algo-Sim › Low-Level Design

Design Snake Game

Medium · Low-Level Design · step through it in Java, Python and C++ on your own input

A deque for the body and a set of occupied cells make every move O(1): move the head, drop the tail unless it ate, and check walls and self-bites.

Problem

Design the classic Snake game on a width × height board. The snake starts at the top-left cell with length 1. move(direction) moves it one cell; eating the next food item makes it longer and scores a point. Return the score after each move, or -1 once the snake hits a wall or its own body.

Constraints

Edge cases to test

Follow-up questions

Why remove the tail before checking the head?
The tail moves away in the same step, so the head may enter its old cell.
What is the cost per move?
O(1) with a deque and a hash set of body cells.

Solution

Java

class SnakeGame {
    private final int width, height;
    private final int[][] food;
    private int eaten = 0;
    private final Deque<Integer> body = new ArrayDeque<>();   // cells r * width + c, head first
    private final Set<Integer> occupied = new HashSet<>();

    public SnakeGame(int width, int height, int[][] food) {
        this.width = width;
        this.height = height;
        this.food = food;
        body.addFirst(0);
        occupied.add(0);
    }

    public int move(String direction) {
        int head = body.peekFirst(), r = head / width, c = head % width;
        switch (direction) {
            case "U": r--; break;
            case "D": r++; break;
            case "L": c--; break;
            default: c++;
        }
        if (r < 0 || r >= height || c < 0 || c >= width) return -1;
        int next = r * width + c;
        if (eaten < food.length && food[eaten][0] == r && food[eaten][1] == c) eaten++;
        else occupied.remove(body.pollLast());
        if (occupied.contains(next)) return -1;
        body.addFirst(next);
        occupied.add(next);
        return eaten;
    }
}

Python

from collections import deque


class SnakeGame:
    def __init__(self, width, height, food):
        self.width, self.height = width, height
        self.food = food
        self.eaten = 0
        self.body = deque([(0, 0)])     # head first
        self.occupied = {(0, 0)}

    def move(self, direction):
        r, c = self.body[0]
        dr, dc = {"U": (-1, 0), "D": (1, 0), "L": (0, -1), "R": (0, 1)}[direction]
        r, c = r + dr, c + dc
        if not (0 <= r < self.height and 0 <= c < self.width):
            return -1
        f = self.food
        if self.eaten < len(f) and f[self.eaten] == [r, c]:
            self.eaten += 1
        else:
            self.occupied.discard(self.body.pop())
        if (r, c) in self.occupied:
            return -1
        self.body.appendleft((r, c))
        self.occupied.add((r, c))
        return self.eaten

C++

#include <bits/stdc++.h>
using namespace std;

class SnakeGame {
  public:
    int width, height;
    vector<vector<int>> food;
    int eaten = 0;
    deque<int> body = {}; // cells r * width + c, head first
    unordered_set<int> occupied = {};

    SnakeGame(int width, int height, vector<vector<int>> &food) {
        this->width = width;
        this->height = height;
        this->food = food;
        body.push_front(0);
        occupied.insert(0);
    }

    int move(string &direction) {
        int head = body.front(), r = head / width, c = head % width;
        switch (direction[0]) {
        case 'U':
            r--;
            break;
        case 'D':
            r++;
            break;
        case 'L':
            c--;
            break;
        default:
            c++;
        }
        if (r < 0 || r >= height || c < 0 || c >= width)
            return -1;
        int next = r * width + c;
        if (eaten < int(food.size()) && food[eaten][0] == r && food[eaten][1] == c)
            eaten++;
        else {
            occupied.erase(body.back());
            body.pop_back();
        }
        if (occupied.count(next))
            return -1;
        body.push_front(next);
        occupied.insert(next);
        return eaten;
    }
};

More Low-Level Design problems