Skip to content
Tutorials Center
My learning

Topics

Lesson 127 of 135 ยท Projects

Project: Console Snake Game

Build the classic Snake game in C: a grid, a snake stored as a queue of cells, walls, food, collision tests and growth, with a scripted run you can watch on the page.

Snake is the classic first game: a line of cells moves across a grid, eats food, grows, and dies if it hits a wall or itself. It is a good project because the whole game is a few rules acting on a small data structure. In this lesson you build the game logic so that it can be tested and replayed. Reading single key presses without waiting for Enter is not part of standard C, so the logic is kept separate from the input, and the program on this page is driven by a scripted list of moves instead of a keyboard.

Game loop

Every real-time game repeats the same four steps, called the game loop:

  1. Read input (a key press, or none).
  2. Update the state: move, eat, grow, check for death.
  3. Draw the new state.
  4. Wait a short time, so the game runs at a steady speed.

A turn-based game waits for input at step 1. A real-time game checks whether a key is available and carries on otherwise, which on Windows is _kbhit() from <conio.h> and on Linux and macOS means putting the terminal in raw, non-blocking mode with termios. Both are platform-specific, which is why this lesson puts steps 2 and 3 in functions that need no input library at all. Hooking up a keyboard then only means replacing the scripted moves.

The data

  • A grid of WIDTH by HEIGHT cells, surrounded by walls.
  • The snake as an array of positions, with the head at index 0. Moving is "insert a new head, remove the tail": you shift every body cell one place back and put the new head in front. When the snake eats, you skip removing the tail, and that is exactly what makes it grow. A queue in a circular buffer would avoid the shifting, but for a short snake the array is simpler.
  • A direction as dx, dy, where reversing straight into your own neck is ignored (a snake moving right cannot turn left).
  • Food at one cell, placed on a cell the snake does not occupy.

Collision rules

After computing the new head position, check before moving:

  1. Wall. If the head is outside the grid, the game is over.
  2. Self. If the head lands on a body cell, the game is over. The tail cell is a special case: it is about to move away, so entering it is legal when the snake is not growing.
  3. Food. If the head lands on the food, increase the score, grow and place new food.

Running it

To make the run reproducible, the program uses its own tiny pseudo-random generator (a linear congruential generator) with a fixed seed instead of rand(), so the food always appears in the same places. The random numbers lesson shows why a seeded generator repeats. The moves are a string: R, L, U and D.

C Snake: game logic with scripted moves

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 scanf or fgets), it gets the next line from this box.

The script steers the snake to the first piece of food, so you see the score rise and the snake grow, and then it runs into a wall, which gives the "game over" board. Change the move string to experiment: send it RRRRRRL and the reverse turn at the end is ignored, so it keeps moving right; send a longer, tighter loop to make it bite itself.

Collisions in detail

The subtle line is body_to_check = grows ? length : length - 1. Imagine a snake of four cells curled into a square so that its head is next to its own tail. If the head moves into the tail's cell and the snake is not growing, the tail moves away in the same tick, so the move is legal. If the snake is growing, the tail stays, and the same move is a collision. Many first versions of the game get this edge case wrong, in one direction or the other. Test it deliberately, which is easy because the moves are a string.

Making it playable

To turn the logic into a real-time game, replace the move string with live input and add a timer:

  • Windows: _kbhit() and _getch() from <conio.h>, plus Sleep(ms) from <windows.h>.
  • Linux and macOS: switch the terminal to raw mode with tcsetattr, read with read() after poll(), and wait with usleep or nanosleep (see signals and system calls).
  • Clearing the screen: print the ANSI sequence "\033[H\033[2J" before each frame, as in the 2048 project.
  • Speed: shorten the wait as the score rises.

Only the loop in main changes. step, draw and place_food stay as they are, which is the payoff of separating logic from input.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does the snake grow in this implementation?

    Normal movement drops the old tail; growing keeps it by increasing the length before shifting the body.
  2. 2. Why must the game loop contain a wait?

    A fixed delay per tick makes the speed a game rule instead of a result of CPU speed.
  3. 3. A snake of length 4 curled so the head touches its tail cell moves into the tail cell without eating. Is that a collision?

    The tail cell is vacated by the same move, so it is only a collision when the snake is growing.
  4. 4. Why ignore a turn straight back (right to left)?

    A reversal makes the head enter its own neck, so games treat it as no input.

Summary

  • A real-time game repeats read input, update, draw, wait.
  • Keep the game logic (state, step, collisions) independent from input and drawing, so it can be tested with scripted moves.
  • The snake is an array with the head first; moving drops the tail, growing keeps it.
  • Check walls first, then the body; the tail cell is free unless the snake grows.
  • Use a seeded generator for reproducible food positions, and place food only on empty cells.
  • Reading keys without Enter is platform-specific: _kbhit on Windows, termios on Unix.

Next: Practice and Review: the exercises