Draw a line and read a key

This page adds what most programs need besides text: drawing, and keys that change what is drawn. The program draws one line; Left and Right swing its top end, and Esc quits. In C here, and in Rust on the next page.

The program

line.c:

#include "terse.h"

static uint8_t list[64];

int main(void)
{
    int x = 320;
    terse_event e;
    for (;;) {
        while (terse_event_pop(&e)) {
            if (e.type != EV_KEY_DOWN)
                continue;
            if (e.a == KEY_LEFT)
                x -= 10;
            if (e.a == KEY_RIGHT)
                x += 10;
            if (e.a == KEY_ESCAPE)
                return 0;
        }
        vec_begin(list, sizeof list);
        vec_move(320 * 16, 400 * 16);
        vec_line(x * 16, 80 * 16);
        vec_end();
        vec_submit_list(list);
        terse_wait_frame();
    }
}

Build it with terse build line.c and run it with terse-host line.terse.

Drawing

The 2D vector display draws from a display list: a few bytes of drawing commands that the program builds in its own memory and hands over with vec_submit_list. The display shows that list every frame until the program submits another. The list must be in RAM, which is why it is a variable: a const array, in the program's read-only memory, is refused.

The screen is 640 by 480 units, (0, 0) at the top left, and a list's coordinates are in sixteenths of a unit: hence the * 16. vec_move moves the pen without drawing, and vec_line draws a line from it. There are also circles, discs, rectangles and triangles, colours and widths.

Reading keys

terse_event_pop takes the next event, as in hello. A key down event carries the key in e.a, and terse.h names the common ones: KEY_LEFT, KEY_ENTER, KEY_ESCAPE and so on. Typed text comes as separate text events, one per character, so a program that wants words reads those instead.

Test it without a window

Save two presses of Left as keys.txt:

5 press left
6 press left

and run

terse run line.terse --frames 10 --events keys.txt \
    --dump --dump-vectors

After the text grid (empty here) it prints the display list as the host draws it, one shape per line:

-- vectors: 11 list bytes --
line 5120 6400 4800 1280 w 16 c ffffffff

A line from (320, 400) to (300, 80) in screen units, written in sixteenths, one unit wide (16 sixteenths), in white: its top end has moved 20 units left.

What you have now

A program that draws and reacts to keys: the shape of most games and tools. It is examples/program/c/line.c in the Tersenet sources. Next, the same in Rust, or, staying with C, a small game: Make a small game.

Every drawing command is in The 2D vector display, and every event and key in Events and input.