Skip to content

§ 5.6. Games

Five small games written in C run on the machines of this chapter: 2048, Sokoban, Snake, Pong and Tetris, plus Snake on the LED machine. They are ordinary RV32IM programs compiled with GCC: every pixel, every byte of console text and every reaction to a button is computed by the simulated core.

Each game comes in two versions, built from the same source:

Version Starts from Input Screen Where
Short A prepared board, one or two presses from the game's key event Presses queued at fixed cycles 32 × 24 A scenario in the simulator menu (Computer System / Games), run live with every wire's history
Long The game's normal start A computer player's whole session: one batch of button changes after each frame 64 × 48 A recording: the machine's state at every frame
One game program, two versions A short version starts from a prepared board, takes one or two button presses queued at fixed cycles, runs on a 32 by 24 screen and opens as a live scenario. A long version is a computer player's whole session: one batch of button changes after each frame, on the 64 by 48 screen, published as a recording with one checkpoint per frame. SHORT · SCENARIO Board prepared Presses 1–2, queued Machine 32 × 24 screen Scenario every wire LONG · RECORDING Player the C rules Batches one per frame Machine 64 × 48 screen Recording every frame Both: Compact parts on their proven delays, embedded timing, a 4.5 ns clock.
Same machine, same program source, two sizes of run. Both run on games-machine in Compact with embedded timing and a 4.5 ns clock, and both are checked instruction by instruction. The short version keeps every wire's history in the visualizer; the long version keeps the machine's state at each frame.

Both run on games-machine (games-machine-leds for the LED game; the long versions on its chapter-5 form, below), whose 256 KiB main memory is an on-chip SRAM answering one cycle after each request (§ 5.7), on the pipelined bus with the array multiplier (§ 5.5), with every part in its compact form on its proven delays, embedded timing and a 4.5 ns clock (222 MHz), for which the machine is certified (§ 5.7).

The software side

A guest is freestanding C: a start-up file sets the stack and clears the BSS region, main runs the game, EBREAK ends it. The platform library talks to the devices only through the generated header (§ 5.5):

#include "platform.h"      /* includes system.h: CONSOLE_TX, BUTTONS_COUNT, VIDEO_BASE, ... */

int main(void) {
    console_write("2048\n");
    geometry();                /* cell size from DISPLAY_WIDTH and DISPLAY_HEIGHT */
    prepare();                 /* game_init, then the short version's prepared board */
    clear_screen(0); render(); /* draw changed cells, then io_write(DISPLAY_PRESENT, 1) */
    while (actions < GAME_ACTIONS) {
        if (!io_read(BUTTONS_COUNT)) continue;  /* poll: no interrupts */
        uint32_t event = io_read(BUTTONS_HEAD);
        io_write(BUTTONS_POP, 1);
        if (!(event & BUTTONS_HEAD_DOWN)) continue;   /* releases are ignored */
        game_action(&game, event & BUTTONS_HEAD_BUTTON_MASK, io_read(BUTTONS_LEVELS));
        ++actions; render();
    }
    /* results at a fixed address for the checker; then "done" on the console */
}

The game rules (games.c) know nothing about the screen. render() asks for the whole board with game_board(), compares it with the colors it drew last time and redraws only the cells that changed. The cell size comes from the display's registers, so one program fits both screens:

Game Board (cells) Cell on 64 × 48 Cell on 32 × 24
2048 4 × 4 16 × 12, with the tile's value in 3 × 5 digits 8 × 6
Sokoban, Snake 8 × 8 6 × 6 3 × 3
Pong 32 × 16 2 × 3 1 × 1
Tetris 8 × 16 4 × 3 2 × 1

Drawing writes bytes to video memory (VIDEO_BASE + y × stride + x), whole words where a row allows; PRESENT marks a finished frame. Programs are built by tools/rv32im/build-guests.py with the pinned riscv-none-elf-gcc 12.4, -march=rv32im -mabi=ilp32 -Os; an audit of the disassembly rejects any instruction outside RV32IM.

Every instruction counts. The machine takes about four and a third cycles per instruction (fetches and data accesses share the bus and the SRAM, which answers one cycle after each request), and a short version must run live in a browser. Two changes to the library halved the short versions' work without changing a pixel: rect clips once and then loops with 32-bit offsets (it used to compare 64-bit values for every word it wrote), and the board is computed in one pass instead of one rule query per cell (the snake's body used to be scanned once per cell).

How a run is checked

Everything the machine does is checked against models that know nothing about its circuits:

Checked Against
Every retired instruction, register and the final state The independent RV32IM instruction model
Every load and store on the data port An independent RAM, video memory and device model
Every device read The value the device model gives at the same cycle
Every presented frame The pixels the program wrote, in order
Console bytes, button queue and levels at each frame The device model
LED pins at each frame (LED machine) LEDS and BLINK as written, and the cycle count
Every bus link (machines with check_ports) The port rules (§ 5.2)
Setup violations None allowed

A mismatch anywhere stops the run with an error; there is no partial success. Separately, the same C is compiled for the host with stand-in devices; its frames, console and report must equal the circuit's byte for byte (short versions), or the computer player's prediction (long versions).

Short versions

Each short version starts one or two presses away from the moment that makes the game what it is. Open one, press Play or jump between the checkpoints: reset released, press … (the presses enter the button queue right after reset; the program takes them after its first frame), console: …, frame 1, frame 2, …, halted. Select DISPLAY for the picture, BUTTONS for the queue, CONSOLE for the text and CORE for the instructions.

The short games: first and last frame For each short game, its first presented frame and its last, as the circuit drew them on the 32 by 24 screen: 2048 merges a row, Sokoban pushes a crate onto its goal, Snake eats, Pong bounces, Tetris clears a line, and the LED Snake runs into the wall. 2048 LEFT: four 2s merge into two 4s Sokoban RIGHT: the crate reaches its goal Snake two updates: the snake eats Pong two updates: a paddle bounce Tetris hard drop: the bottom line clears Snake with LEDs two updates: into the wall
First and last frame of each short version, pixel for pixel. Drawn from the host run of the same program, whose frames the circuit tests compare byte for byte.
Scenario Prepared board Presses Frames Cycles Instructions Simulated time Host time
game-2048 Four 2s in the top row LEFT 2 32,350 7,649 145.6 µs 60 s
game-sokoban Player, crate and goal in a row RIGHT 2 42,224 9,741 190.0 µs 89 s
game-snake Food two cells ahead UPDATE, UPDATE 3 29,357 6,679 132.1 µs 72 s
game-pong Ball one step from the right paddle UPDATE, UPDATE 3 13,453 3,189 60.5 µs 31 s
game-tetris Bottom row missing four cells, an I piece above ACTION (hard drop) 2 52,803 12,057 237.6 µs 128 s
game-snake-leds Head one cell from the wall UPDATE, UPDATE 3 27,185 6,184 122.3 µs 70 s

Simulated time is cycles × 4.5 ns. Host time is a native batch run on the development machine, without wire history; the scenario also keeps every wire's history and, in the browser, runs as WebAssembly, so it opens more slowly: Pong in under a minute, Tetris in about three on the development machine. The cycle counts are the same under the unit timing profile: realistic delays change when signals settle inside a cycle, not which cycle a result is ready in.

The short versions open only in Compact, where the core is one block whose registers and pipeline packets the inspector shows. With the core built from its stages (Logic, Visual) a game produces about 56 times more signal events per cycle, and the history of every wire outgrows a browser tab: Pong's short version passed 3 GB natively within 100 seconds. To watch the core's stages work on a real program, open the machine scenario (computer-system, the bring-up program, about 4,800 cycles) in Visual: it runs in under a minute natively and keeps about 400 MB.

2048: a merge

The top row holds four 2s. LEFT merges them pairwise into two 4s (score 8), and a new 2 appears in a free cell. Compare frame 1 and frame 2: three cells change, the digits are drawn pixel by pixel.

Open 2048

Sokoban: the winning push

Walls are red, the player magenta, the crate green and its goal blue. The player stands left of the crate, the crate left of the goal. RIGHT pushes the crate onto the goal, where it turns yellow; no crate is left off a goal, so the game is won (state 1, score 1).

Open Sokoban

Snake: a bite

The food lies two cells ahead of the head. The first UPDATE moves the snake one cell; the second moves its head onto the food: the snake grows to four cells and new food appears (score 1).

Open Snake

Pong: a bounce

The ball is one step from the right paddle and moving towards it. The first UPDATE bounces it off the paddle; the second carries it back to the left. Pong redraws only what moved (the ball and any paddle), so its frames are the cheapest.

Open Pong

Tetris: a line clear

The bottom row is missing four cells and an I piece hangs above the gap. ACTION drops it: the row is complete, it is removed, the rows above move down and a new piece appears at the top (score 100).

Open Tetris

Snake with LEDs: a crash

Snake compiled for the LED machine: one LED per segment, and all of them blink once the game is lost. The board is the left 24 × 24 pixels; its edge is the wall. The head (red) is one cell from the right edge; the first UPDATE moves it to the last column, the second runs into the wall and the snake stays where it was. Select LEDS: three lit LEDs in frames 1 and 2, then the blink (8 cycles on, 8 off) after the crash.

static void show_leds(void) {
    unsigned n = game.length > 16 ? 16 : game.length;
    io_write(LEDS_LEDS, n >= 16 ? 0xffffu : (1u << n) - 1u);
    io_write(LEDS_BLINK, game.status == GAME_LOST ? 3u : 0u);
}

Open Snake with LEDs

Long versions

A long version is a whole session played by a computer player (tools/rv32im/long_gameplay/plans.py). The long versions were recorded before the machines' bus and multiplier changed (2026-11-13) and are kept as recorded: they run on the chapter-5 machine (bus=single, multiplier=iterative), which their recordings name, and replay on it; the short versions run on the current machine. Each player chooses its moves by running the real C rules (games.c, loaded on the host) and stops at a goal; its moves become batches of button changes, delivered one batch after each presented frame, exactly as a person would press keys between frames.

Game Player Goal
2048 Looks two moves ahead, prefers empty cells, a smooth row and the biggest tile in a corner The first 128 tile
Sokoban Generates puzzles backwards from solved ones (so each is solvable), solves each by search Two puzzles, with a restart between them
Snake Follows a route through every cell, which can never trap it Length 10, then a turn into the wall
Pong Both paddles follow the ball; after a long rally one side lets it pass Two points
Tetris Tries every rotation and column, keeps the flattest stack with the fewest holes 20 pieces with at least 3 cleared lines
Snake with LEDs The Snake session on the LED machine LEDs count 3 → 10, then blink
Recording Updates Frames Result Cycles Instructions Simulated time Host time
sokoban-long 72 73 Both puzzles solved, 20 pushes 886,046 159,174 3.99 ms 26 min
snake-long 123 124 Length 10, then the wall 1,265,936 224,327 5.70 ms 37 min
snake-leds-long 123 124 Length 10, then the wall; LEDs blink 1,277,592 226,684 5.75 ms 42 min
2048-long 84 85 Tile 128, score 852 2,503,400 473,442 11.27 ms 74 min
tetris-long 144 145 20 pieces, 8 lines, score 800 2,837,961 502,831 12.77 ms 81 min
pong-long 369 370 Two points, 12 paddle bounces 2,788,844 511,921 12.55 ms 1 h 31 min

The recordings are made by tools/rv32im/run-long-gameplays.py, one game at a time in a memory-capped background job. A recording keeps the machine's state at every frame (not every wire change between frames), split into parts of 16 frames that the viewer loads as you move through the session. The files are stored gzip-compressed: the six recordings take 3.1 MB, and a machine save after every frame (about 37 KB each) another 35 MB. With the saves, a recording opens in the simulator itself: the frame bar jumps between frames, and the step button runs the program on from the shown frame event by event, following the recorded player's moves, with main memory and the devices inspectable (visualizer).

The same sessions in Visual

The six sessions are recorded a second time with the core built from its stages (the Visual preset): each frame then shows the fetch, decode, execute, memory and write-back stages, the pipeline registers, the forwarding and hazard units and the ALU's adders and shifters, with every one of their wires. Open a long game from the menu, then choose Visual in the Fidelity menu (switching keeps the frame), or use the links below. The memory, bus and devices are the same compact parts as in the Compact recordings, and every frame passed the same checks.

Recording Updates Frames Result Cycles Instructions Simulated time Host time
sokoban-long 72 73 Both puzzles solved, 20 pushes 886,046 159,174 3.99 ms 2 h 7 min
snake-long 123 124 Length 10, then the wall 1,265,936 224,327 5.70 ms 3 h 8 min
snake-leds-long 123 124 Length 10, then the wall; LEDs blink 1,277,592 226,684 5.75 ms 5 h 17 min
2048-long 84 85 Tile 128, score 852 2,503,400 473,442 11.27 ms 7 h 45 min
tetris-long 144 145 20 pieces, 8 lines, score 800 2,837,961 502,831 12.77 ms 5 h 42 min
pong-long 369 370 Two points, 12 paddle bounces 2,788,844 511,921 12.55 ms 6 h 8 min

The Visual recordings also keep a machine save after every frame, so they open in the simulator the same way, with the core's stages and the register file inspectable as well.

A Visual frame holds about 174,000 pin and wire values instead of about 1,900; compressed, the six Visual recordings take 34 MB, and the machine saves that let the page continue from any frame (one per frame, about 96 KB each) another 89 MB. Simulating the core from its stages is slower: about 110 cycles per second on the development machine against about 550 in Compact, so the six sessions took about 30 hours of simulation. Host times depend on what else the development machine was running: Snake with LEDs took 5 h 17 min beside other jobs, against 3 h 8 min for Snake.

Source and tests

Guest start-up, library and games, computer players, fixture binaries and inputs, checked native execution, the scenarios.

Test Coverage
Game2048ScenarioTest, GameSokobanScenarioTest, GameSnakeScenarioTest, GamePongScenarioTest, GameTetrisScenarioTest, GameSnakeLedsScenarioTest The short versions with every check above; their score, final state, console and frame count; LED pins per frame
RV32IMRecorded_<fixture>_Test A short fixture's circuit frames, console and report equal the host-compiled program's
RV32IMReference_<game>-long_Test A long fixture's host run reaches the computer player's predicted score, state and rule fingerprint
RV32IMGameRulesTest The rules on hand-made boards; game_board equals game_cell through hundreds of moves
GuestDisplayGeometryTest Drawing on odd strides and larger screens, clipping
GuestHeaderTest The headers the games are compiled with equal the ones generated from the descriptions