Project: a snake game with SFML

A complete game built from the course's pieces — a state stack of unique_ptrs, virtual functions, a fixed-timestep loop and a snake that recycles its tail. Playable below.

What you'll learn
  • {"Read a small game's architecture"=>"the game loop, states and the state manager"}
  • Follow how the snake moves and grows using std::list iterators
  • Spot an input-handling bug and fix it

The repository’s snake game uses SFML for the window, textures and keyboard. Below is a port of its game logic to the browser, using the game’s own 16×16 textures and its rules: a 640×352 field walled in on all sides, a step every 0.1 s, +10 points per food, and game over on hitting a wall or yourself.

Arrow keys (click the field first), the buttons, or swipe to steer; Space pauses. The readout shows the same pixel coordinates the C++ version uses.

The game loop

Game::Run advances the game in fixed steps, whatever the frame rate:

timeSinceLastFrame += clock.restart();
while (timeSinceLastFrame > TIME_PER_FRAME) {          // 1/60 s
    timeSinceLastFrame -= TIME_PER_FRAME;
    m_context->m_states->ProcessStateChange();
    m_context->m_states->GetCurrent()->ProcessInput();
    m_context->m_states->GetCurrent()->Update(TIME_PER_FRAME);
    m_context->m_states->GetCurrent()->Draw();
}

Because each update receives the same deltaTime, the snake moves at the same speed on a fast machine and a slow one. GamePlay::Update then adds up those slices and moves the snake once m_elapsedTime passes 0.1 s.

States on a stack

Menus, gameplay, pause and game-over screens are separate classes deriving from an abstract Engine::State with pure virtual Init, ProcessInput, Update and Draw (lesson 9). StateMan keeps them in a std::stack<std::unique_ptr<State>> (lesson 6):

State diagram of the snake game. MainMenu goes to GamePlay on Enter, replacing it. GamePlay pushes PauseGame on Escape, and PauseGame pops itself on Escape to return. GamePlay is replaced by GameOver on a wall or self collision, and GameOver is replaced by a new GamePlay on Retry. State diagram of the snake game. MainMenu goes to GamePlay on Enter, replacing it. GamePlay pushes PauseGame on Escape, and PauseGame pops itself on Escape to return. GamePlay is replaced by GameOver on a wall or self collision, and GameOver is replaced by a new GamePlay on Retry.
Pausing pushes a state on top, so the game underneath survives; every other transition replaces the top of the stack.

A state never modifies the stack while it is running. Add only stores the new state in m_newState (with std::move, since it is a unique_ptr) and sets a flag; ProcessStateChange applies it at the start of the next frame. Popping the current state from inside its own Update would destroy the object whose member function is still executing.

A snake that recycles its tail

The snake is a std::list<sf::Sprite> with two iterators, m_head and m_tail. Moving does not shift every piece; it picks up the tail and puts it in front of the head:

void Snake::Move(const sf::Vector2f& direction) {
    m_tail->setPosition(m_head->getPosition() + direction);
    m_head = m_tail;
    ++m_tail;
    if (m_tail == m_body.end()) m_tail = m_body.begin();
}

Moving a snake of any length costs one setPosition and two iterator updates. The list is used as a ring: the iterators wrap around instead of the nodes moving. Grow inserts a new sprite after the head, and Snake.hpp explains the choice of container: unlike a std::vector, a list never relocates its nodes, so m_head and m_tail stay valid as the snake grows (lesson 4).

Collisions are bounding-box tests: IsOn asks whether the head’s rectangle intersects another sprite’s. SFML’s intersects requires a positive overlap, so pieces that merely touch edge to edge — every pair of neighbours in the body — do not count.

An input bug worth fixing

ProcessInput blocks reversing into yourself by refusing a direction on the same axis as the current one:

if (std::abs(m_snakeDirection.x) != std::abs(newDirection.x) ||
    std::abs(m_snakeDirection.y) != std::abs(newDirection.y))
    m_snakeDirection = newDirection;

But it checks against the latest requested direction, not the direction the snake last moved in, and input is processed every 1/60 s while the snake moves only every 0.1 s. Moving right, a quick Up then Left — both inside one 0.1 s step — passes both checks, and on the next step the snake turns straight back into its own neck. The browser version above applies at most one turn per step, which is the usual fix: store the requested turn, and validate it against the direction of the last actual move.

Two smaller notes: the food is placed at random pixel positions, so it is often not aligned with the 16-pixel grid the snake moves on (eating still works because any overlap counts), and it can appear on top of the snake.

Try it yourself. Build the game with make and reproduce the reversal: while moving right, press Up and Left in quick succession. Then fix it in GamePlay.cpp by keeping a m_lastMoveDirection updated in Update and validating new input against it. Finally, snap the food to the grid with x -= x % 16.

View source on GitHub →