The NandTier SeriesPart 11 of 12

Our First Game: Snake

A whole game in 320 lines of C: the field as tiles, the snake as a ring buffer, a frame loop, a game-over screen and a computer player for the demo.

11 min readGamesCGraphics
In this article
  1. What are we trying to do?
  2. The field
  3. Directions as tables
  4. One step
  5. Steering
  6. The frame loop
  7. The demo player
  8. Building it
  9. Conclusion

What are we trying to do?

Everything so far has been the machine. Now we use it. We will read Snake, the simplest of the eight games on the SD card, from top to bottom: how the field is drawn, how the snake moves and grows, how input arrives, and how the game goes from title screen to play to game over.

Snake is a good first game because almost nothing in it moves smoothly. The snake moves one cell at a time, so the whole game is drawn with tiles; it needs no sprites at all.

The field

The screen is 32 × 30 tiles. Snake uses rows 3 to 28 as its field, with a wall around it and two rows on top for the score:

fw/games/snake/snake.clines 14–18
14#define FX0     115#define FY0     316#define FW      3017#define FH      2618#define CELL(c, r)  ((r) * 32 + (c))

Every cell of the screen also has a meaning for the game: empty, snake, apple, gold apple or wall. One byte per cell keeps track:

fw/games/snake/snake.clines 20–21
20enum { EMPTY, SNAKE, APPLE, GOLD, WALL };21enum { M_TITLE, M_PLAY, M_DEAD, M_OVER };
fw/games/snake/snake.clines 23–24
23static uint8_t  occ[32 * 30];24static uint16_t body[1024];             // cells, a ring: body[head] is the head

occ (occupied) mirrors the screen: the game never reads the PPU (it cannot, video memory is write only); it keeps its own copy of what is where. body holds the snake's cells as a ring buffer: body[head] is the head, and the len entries before it, wrapping around at 1024, are the rest of the snake.

■■■■●head: body[head]tail: len − 1 behinda step: write the new head one to the right,and (unless growing) forget the tail; wraps at 1024
The snake lives in a ring buffer of cell numbers; moving is one write at the head.

Drawing the field fills the wall tiles and marks every cell:

fw/games/snake/snake.clines 60–73
60{61    ng_clear();62    ng_fill(0, 2, 32, 1, T_WALL, 0);63    ng_fill(0, 29, 32, 1, T_WALL, 0);64    ng_fill(0, 3, 1, FH, T_WALL, 0);65    ng_fill(31, 3, 1, FH, T_WALL, 0);66    for (int r = 0; r < 30; r++)67        for (int c = 0; c < 32; c++)68            occ[CELL(c, r)] = WALL;69    for (int r = FY0; r < FY0 + FH; r++)70        for (int c = FX0; c < FX0 + FW; c++)71            ground(c, r);72    draw_hud();73}

ng_fill is the tile rectangle from part 10. Every cell starts as wall, then the inside is cleared with ground(), which also scatters a few grass tufts for decoration.

Directions as tables

The four directions are numbered 0 to 3 (right, up, left, down), and two small tables say how each one moves:

fw/games/snake/snake.clines 31–32
31static const int8_t DX[4] = {1, 0, -1, 0};     // right, up, left, down32static const int8_t DY[4] = {0, -1, 0, 1};

That turns movement into arithmetic: the next cell is (col + DX[dir], row + DY[dir]), and the opposite direction is (dir + 2) & 3.

One step

Here is the heart of the game, one move of the snake. First, where the head goes and what is there:

fw/games/snake/snake.clines 220–223
220int hc = body[head] & 31, hr = body[head] >> 5;221int next = CELL(hc + DX[dir], hr + DY[dir]);222int tail = body[(head - len + 1) & 1023];223int t = occ[next];

tail is the last cell of the snake, len - 1 entries behind the head in the ring buffer.

fw/games/snake/snake.clines 225–228
225if (t == WALL || (t == SNAKE && (next != tail || grow))) {226    die();227    return;228}

Walls kill. So does the snake's own body, with one exception: moving into the cell the tail is just leaving is fine, unless the snake is growing this step (then the tail stays put).

fw/games/snake/snake.clines 229–239
229if (t == APPLE) {230    score += 10;231    grow += 3;232    if (++apples % 5 == 0)233        place(GOLD);234    place(APPLE);235} else if (t == GOLD) {236    score += 50;237    grow += 5;238    gold_timer = 0;239}

An apple is worth 10 points and three cells of growth; every fifth apple also brings a gold one, worth 50 and five cells, which disappears if you are too slow.

fw/games/snake/snake.clines 241–252
241if (grow) {242    grow--;243    len++;244} else {245    ground(tail & 31, tail >> 5);246}247ng_tile(hc, hr, T_BODY, 0);248head = (head + 1) & 1023;249body[head] = next;250occ[next] = SNAKE;251draw_head();252draw_hud();

Growing means "don't move the tail this step". Otherwise the tail cell goes back to ground. Then the old head becomes a body tile, the head moves forward in the ring buffer, and the new head is drawn. Notice how little is redrawn: three tiles per step, whatever the length of the snake.

Steering

Input comes from the UART as key presses (part 2), which ngame turns into button bits. A player can press two keys within one step, for example up then left to turn around a corner quickly, so the game queues up to two turns:

fw/games/snake/snake.clines 189–200
189static void steer(void)190{191    uint8_t p = ng_pressed();192    static const uint8_t btn[4] = {BTN_RIGHT, BTN_UP, BTN_LEFT, BTN_DOWN};193    for (int d = 0; d < 4; d++) {194        if (!(p & btn[d]) || n_queued == 2)195            continue;196        int last = n_queued ? queued[n_queued - 1] : dir;197        if (d != last && d != ((last + 2) & 3))198            queued[n_queued++] = d;199    }200}

A turn is ignored if it repeats the current direction or reverses into the snake's own neck.

The frame loop

The game is a state machine of four modes: title, play, dying, game over. Every frame the main loop does one tick of whichever mode it is in, then waits for the next frame:

frameframe nframe n+1n+2cpugame logicgame logiclogicng_frameone frame: 420,000 cyclesng_frame: waiting for the counter
Every frame: do the game's work, then wait in ng_frame() for the next one to begin.
fw/games/snake/snake.clines 255–262
255void game_main(void)256{257    ng_begin(art_chr, ART_TILES, art_palette);258    title();259 260    while (!ng_quit()) {261        uint8_t p = ng_pressed();262        timer++;

While playing, the snake does not move every frame; that would be 60 cells a second. It moves every few frames, and a little faster as it gets longer:

fw/games/snake/snake.clines 285–291
285{286    int delay = 7 - len / 12;287    if (++step_timer >= (delay < 3 ? 3 : delay)) {288        step_timer = 0;289        step();290    }291}

Seven frames per step at the start, down to three. That is the whole difficulty curve, in one line.

fw/games/snake/snake.clines 295–304
295snake_colours((timer >> 3) & 1);296if (timer == 60) {297    snake_colours(1);298    ng_fill(9, 13, 14, 5, 0, 0);299    ng_center(14, "GAME OVER", 2);300    ng_center(16, "PRESS START", 0);301    mode = M_OVER;302    timer = 0;303}304break;

Dying flashes the snake grey and green for a second by swapping two palette entries (no tiles change at all), then draws the game-over box.

The demo player

Leave the title screen alone for ten seconds and the computer plays. Its strategy is small but works well: of the directions that do not hit something, take the one that gets closest to the apple, but keep away from cells with no way out:

fw/games/snake/snake.clines 165–185
165for (int d = 0; d < 4; d++) {166    if (d == ((dir + 2) & 3))167        continue;168    int c = hc + DX[d], r = hr + DY[d];169    int t = occ[CELL(c, r)];170    if (t == WALL || t == SNAKE)171        continue;172    int cost = target < 0 ? 0 : (c > (target & 31) ? c - (target & 31) : (target & 31) - c) +173                                (r > (target >> 5) ? r - (target >> 5) : (target >> 5) - r);174    // keep away from dead ends: count free neighbours175    int free = 0;176    for (int k = 0; k < 4; k++) {177        int n = occ[CELL(c + DX[k], r + DY[k])];178        free += n != WALL && n != SNAKE;179    }180    cost = cost * 4 + (free == 0 ? 1000 : 4 - free) + (d != dir);181    if (cost < best_cost) {182        best_cost = cost;183        best_d = d;184    }185}

The cost is the distance to the apple times four, plus a penalty for each blocked neighbour of the new cell, and a huge one for a dead end. It is not perfect, and that is fine: a demo that sometimes loses looks more alive.

Building it

A game is a folder with a Makefile that includes the SDK's rules, and its art as a Python file that mkart.py turns into tile data:

Terminal
$ make -C fw/games/snake$ ls fw/games/snake/build/

The result is snake.bin, linked to run from the flash's cartridge slot at 0x0010_0000. make games builds all eight and packs them for the SD card; the next article shows how the launcher gets one from there into that slot.

Conclusion

Three hundred lines of C, two arrays and a ring buffer, and a frame loop that does a little work and then waits for the beam. Every game in the pack has this same shape; the others add sprites, scrolling and more rules, but nothing the PPU and ngame from part 10 don't already provide.

One question remains: the game is on the SD card, but the CPU runs code from the flash. In the last article we follow the launcher as it copies a game across and jumps into it.