A terminal game in Jennifer

Jennifer

A small snake game, one idea at a time: keys, frames, a loop, a ring buffer and a high score file you can trust.

November 2026, by @mplx.
Based on Jennifer 0.27.0

Powered by Jennifer's Cantrip - Markdown into slide decks, https://github.com/jennifer-language/cantrip
1 / 20

What we build

----------------------------
|                  oo@     |
|                  o       |
|                          |
|              *           |
|                          |
----------------------------
 score 1   best 0   q quits

Arrow keys or w a s d steer, q quits: jennifer run snake.j

2 / 20

A game is a loop

StepWhat happensJennifer
waitlet a little time passtime.sleep
inputwas a key pressed? never wait for onescreen.pollKey
updatemove the snake, check for crashesour step
drawbuild the next frame, send the changesscreen.diff

Every 150 ms, round and round, until the game is over.

3 / 20

Raw keys with the term library

def state as term.State init term.makeRaw("stdin");
defer term.restore($state);
io.printf("press any key when you see GO!\r\n");
# wait 1 to 3 seconds; a key pressed before GO! is a false start
def early as int init term.readByteTimeout(math.randInt(1000, 3000));
if ($early != -2) {
    io.printf("too early!\r\n");

From reaction.j, a reaction timer in 29 lines.

4 / 20

readByteTimeout: three kinds of answer

ResultMeaning
0 to 255a byte: the key that was pressed
-1end of input: nothing more will come
-2the time ran out, no key
press any key when you see GO!          press any key when you see GO!
too early!                              GO!
                                        264 ms
5 / 20

The screen module does the rest

if (os.isTerminal("stdin")) {
    def state as term.State init screen.begin();
    defer screen.end($state);
    $score = play($best, true);
} else {
    $score = play($best, false); # moves from a pipe or a file
    io.printf("%s", screen.moveTo(0, H + 3));
}

begin: raw mode, alternate screen, cursor hidden. end undoes it all.

6 / 20

Keys without waiting

def input as screen.Input init screen.startInput();
...
def key as screen.Key init screen.pollKey($input);
key.namewhen
"char"a printable key, the letter is in key.char
"up" "down" "left" "right"arrow keys
"escape" "ctrl-c" "enter" ...the other named keys
"none"no key is waiting right now
"eof"input has ended
7 / 20

One key per tick, no U-turns

func turn(g as Game, key as screen.Key) {
    def d as list of int init direction($key);
    def isTurn as bool init $d[0] != 0 or $d[1] != 0;
    def isReverse as bool init $d[0] == -$g.dx and $d[1] == -$g.dy;
    if ($isTurn and not $isReverse) {
        $g.dx = $d[0];
        $g.dy = $d[1];
    }
    return $g;
}
8 / 20

The field is a buffer of cells

func draw(g as Game, best as int) {
    def buf as screen.Buffer init screen.newScreen(H + 3, W + 2);
    $buf = screen.hline($buf, 0, 0, W + 2, "-");
    $buf = screen.vline($buf, 0, 1, H, "|");
    ...
    $buf = plot($buf, $g.food, "*");
    for (def c in ringbuffer.toList($g.body)) {
        $buf = plot($buf, $c, "o");
    }
    $buf = plot($buf, ringbuffer.last($g.body), "@");
9 / 20

Draw everything, send only the changes

def frame as screen.Buffer init draw($g, $best);
io.printf("%s", screen.diff($shown, $frame));
$shown = $frame;
OutputBytes
first frame, screen.render376
one tick, screen.diff15
ESC[5;4H ESC[5;6Ho@
10 / 20

The snake is a ring buffer

def body as ringbuffer.RingBuffer init ringbuffer.new(3);
for (def x in 2..5) {
    $body = ringbuffer.push($body, cell($x, 3));
}
Cells, oldest first
"2,3" "3,3" "4,3"tail ... head, the ring is full
"3,3" "4,3" "5,3"after push("5,3"): the tail fell off
11 / 20

Growing: a bigger ring

# grow copies the body into a ring with one more slot
func grow(body as ringbuffer.RingBuffer) {
    def size as int init ringbuffer.capacity($body) + 1;
    def bigger as ringbuffer.RingBuffer init ringbuffer.new($size);
    for (def c in ringbuffer.toList($body)) {
        $bigger = ringbuffer.push($bigger, $c);
    }
    return $bigger;
}
12 / 20

One step: walls, yourself, food

def next as string init cell($x, $y);
def eats as bool init $next == $g.food;
def others as list of string init ringbuffer.toList($g.body);
if (not $eats) {
    $others = $others[1..]; # the tail moves out of the way
}
def hitsWall as bool init $x < 0 or $x >= W or $y < 0 or $y >= H;
if ($hitsWall or lists.contains($others, $next)) {
    $g.over = true;
    return $g;
}
13 / 20

Food in a random place

func placeFood(body as ringbuffer.RingBuffer) {
    def taken as list of string init ringbuffer.toList($body);
    def spot as string init "";
    repeat {
        $spot = cell(math.randInt(0, W - 1), math.randInt(0, H - 1));
    } until (not lists.contains($taken, $spot));
    return $spot;
}

SNAKE_SEED=7 calls math.randSeed(7): the same food every game.

14 / 20

The loop

repeat {
    time.sleep(time.fromMilliseconds(TICK_MS));
    def key as screen.Key init screen.pollKey($input);
    $quit = isQuit($key);
    if (not $quit) {
        $g = step(turn($g, $key));
        def frame as screen.Buffer init draw($g, $best);
        io.printf("%s", screen.diff($shown, $frame));
        $shown = $frame;
    }
} until ($quit or $g.over);
15 / 20

Real frames, in a real terminal

----------------------------    ----------------------------
|                   *      |    |                      ooo@|
|          oo@             |    |                          |
|                          |    |                          |
|                          |    |         GAME OVER        |
----------------------------    ----------------------------
 score 0   best 0   q quits      score 1   best 0   q quits

Up, right, ... and straight into the wall.

16 / 20

End of input, and replaying a game

$ printf 'ab' | jennifer run eof-poll.j
0: char
1: char
2: eof
3: none
4: none

jennifer run snake.j < moves.txt: one letter per tick, x goes straight.

17 / 20

Saving the high score

func saveBest(best as int) {
    def text as string init MAGIC + SAVE_FORMAT + "\n";
    $text = $text + "best " + convert.toString($best) + "\n";
    $text = $text + "crc " + checksum($text) + "\n";
    fs.writeString(SAVE_FILE, $text);
}
snake-save 1.0.0
best 4
crc bc15eaa4
18 / 20

Loading it, carefully

def version as string init $lines[0][len(MAGIC)..];
if (not semver.satisfies($version, READS)) {
    throw saveError("unknown save format " + $version);
}
def text as string init $lines[0] + "\n" + $lines[1] + "\n";
if ($lines[2] != "crc " + checksum($text)) {
    throw saveError("checksum mismatch, file damaged or edited");
}
snake: checksum mismatch, file damaged or edited; best score starts at 0
snake: unknown save format 2.0.0; best score starts at 0
19 / 20

Over to you

The full game: demo-jsnake, multiplayer snake over the network, with CPU opponents.

All programs, the moves file and the capture script are in this talk's code/ folder. More talks: academy.jennifer-lang.dev

20 / 20