Tutorial · Chapter 3 of 23

Keep state and handle input

Write a small sector survey that remembers the current selection and counts visits.

Jump to a section

Choose what the program remembers

The first version remembers a sector number and a total visit count. Four sectors fit in a byte. Use a word for the counter so it can hold more than 255 visits. Keep both fields in one record because the input loop and display operate on the same state.

Space moves to the next sector. Return adds a visit. Q exits. Decide what happens at the end of the sector list before writing the loop. This program wraps from sector 3 to sector 0. The visit counter continues across sector changes.

Give input, updates, and drawing separate jobs

The loop reads one buffered key at a time. switch selects a state change. After changing state, redraw the display. An empty buffer produces zero and falls into the empty default branch. This keeps the loop ready for future work between keys, such as animation.

survey-console.zp64
const c64 = @import("c64");

const Survey = struct { sector: u8, visits: u16 };

fn advance(survey: *Survey) void {
    if (survey.sector == 3) {
        survey.sector = 0;
    } else {
        survey.sector += 1;
    }
}

fn show(survey: *Survey) void {
    const sector: u8 = survey.sector;
    const visits: u16 = survey.visits;
    c64.console.clear();
    c64.console.print("SECTOR {x} VISITS {x16}\n", .{ sector, visits });
    c64.console.print("SPACE NEXT  RETURN MARK  Q QUIT\n", .{});
}

export fn main() void {
    var survey = Survey{ .sector = 0, .visits = 0 };
    show(&survey);
    var running = true;
    while (running) {
        const key = c64.keyboard.readPetscii();
        switch (key) {
            c64.key.space => {
                advance(&survey);
                show(&survey);
            },
            c64.key.return_ => {
                survey.visits += 1;
                show(&survey);
            },
            0x51 => { running = false; },
            else => {},
        }
    }
    c64.vic.border = 5;
}

Open the complete source

advance takes a pointer because it changes the caller's survey. show reads the current record and copies its fields into typed locals for printing. The sector is a byte printed with {x}. The visit total is a word printed with {x16}. Use the record chapter if you want a separate snapshot for undo or replay.

Predict the screen before pressing keys

  1. On startup expect SECTOR 00 VISITS 0000.
  2. Press Space, then Return. Expect SECTOR 01 VISITS 0001.
  3. Press Space three more times. The sector wraps to 00 while the visit count stays 0001.
  4. Press Q. The border turns green and the program returns.

This version counts visits for the whole session. The REU exercise later stores visits in each sector record, which lets you change and inspect only the page you need.