Adder · a reactive language for the Commodore 64 · Language v0.60.0 · Lab & Guide v0.26.13

Adder Quickstart

In the next ten minutes, you'll build a playable Commodore 64 Jupiter Lander arcade game, starting with one line of Adder.

The Commodore 64 (1982) has 64 kilobytes of memory, a video chip with sixteen colors and eight hardware sprites, a three-voice SID synthesizer, and a 1 MHz processor in one keyboard case. In Adder, live <- bindings control the screen, sprites, and sound chip. when event handlers update game state. The compiler proves your number ranges and frame timing before the program runs.

Light Up the Border

This single line is a complete Adder program:

System.screen.border <- Color(System.screen.frames % 16)
// The border steps through its sixteen colors, one a frame.

The video chip paints a complete television picture called a frame fifty times a second on European (PAL) machines and sixty times a second on North American (NTSC) machines.

  • System.screen.frames counts up by one on every frame.
  • System.screen.frames % 16 wraps that count from 0 to 15, matching the sixteen built-in C64 colors.
  • The binding arrow <- works like a live formula in a spreadsheet: whenever System.screen.frames changes, System.screen.border updates automatically. You need no main function, no manual redraw loop, and no hardware register addresses.

You can also step through all sixteen colors at your own pace with .every(n) and .cycle(Color) on the frame event:

System.screen.border <- System.screen.frame.every(8).cycle(Color)
// The border steps to the next color every 8th frame.

Types and Helpful Compiler Checks

Every value in Adder has a type. System.screen.border expects a Color, while System.screen.frames is a number. Write Color(...) to convert a number to a color. If you forget it, the compiler shows the fix:

RefusedwrongType
System.screen.border <- System.screen.frames
Compiler says
This is a Number<u16>, but a Color is needed here.
Color codes run from 0 to 15. Write Color(value) to convert a number explicitly.
Fix: border <- Color(System.screen.frames % 16)

When you want a specific color, note, or key by name, use its dot member (Color.cyan, Note.c4, Key.space). Wherever Adder already knows the expected type, you can drop the type name and write the leading dot: System.screen.border <- .cyan.

Keep Score with State, Events, and Text

A game needs remembered state that changes when something happens, and a heads-up display on the 40-by-25 character screen:

const step = 1
var score: Number<0...99> = 0
when System.keyboard.space.pressed
  score = score +| step
end
System.screen.content <- (Text("LANDINGS ") ++ Text(score.digits(2)).ink(.white)).at(row: 0, col: 2).ink(.cyan)

Look at the three ways a name is introduced:

  1. A constant (const step = 1) never changes. The compiler bakes 1 straight into the machine instructions.
  2. State (var score: Number<0...99> = 0) is remembered across frames. It changes only when a when event handler assigns it a new value with =. Here, when System.keyboard.space.pressed runs in the exact frame the space bar goes down, and score = score +| step adds 1 (clamping at 99).
  3. A binding (<-) stays wired up continuously. Text("LANDINGS ") and Text(score.digits(2)) join with ++ into one line, .at(row: 0, col: 2) places it at row 0, column 2, and .ink(.cyan) colors it, except for the two-digit score, which .ink(.white) makes white. Whenever score changes, those two digits update on the very same frame.

For a whole screen row, write System.screen.text[10] <- "Ready". Adder fills the remaining cells with spaces, so you never need to count trailing spaces. The same rule fills a typed destination such as message: [40 of Char] <- "Ready". Changing Strings use copy and space-fill loops too, so a short name can fill a whole row without a character-by-character loop in your program. The cost report includes the padding work.

Numbers Have Edges

In Jupiter Lander, the pilot has three reserve ships (lives), fuel runs from 0 to 99, and both horizontal drift vx (Number<-1.5...1.5>) and vertical speed vy (Number<-1.5...2.0>) hold fractions as gravity pulls the ship down and the thrusters push it back. Giving numbers explicit ranges lets Adder pack them tightly on the 8-bit processor (Number<0...3> or Number<0...99> takes 1 byte; Number<24...296> or a fractional Number<-1.5...2.0> takes 2 bytes) and lets you choose what happens at the boundaries:

  • + and - check: stepping past either end stops the program and prints the line number on screen.
  • +% and -% wrap: stepping past one end loops around to the other end.
  • +| and -| clamp: stepping past an end stops cleanly at that boundary.

For whole-number scaling, write a * b / c: 30000 * 2 / 2 gives 30000, even though the product exceeds an ordinary number's range. Each input must fit -32768...32767; Adder keeps the product privately and checks the final quotient against its destination. Division drops any remainder toward zero, and a zero divisor stops the program.

Compare checked subtraction - with a guarded subtraction on our three lives:

var lives: Number<0...3> = 3
when System.keyboard.space.pressed
  lives = lives - 1
end
System.screen.text[0][0..<1] <- lives.digits(1)
// Pressing space four times steps 3, 2, 1, 0, then stops with
// "out of range at line 3".

To stop at 0 without halting, either clamp with lives = lives -| 1 or check if lives > 0 then first:

var lives: Number<0...3> = 3
when System.keyboard.space.pressed
  if lives > 0 then
    lives = lives - 1
  end
end
System.screen.text[0][0..<1] <- lives.digits(1)
// The count goes 3, 2, 1, 0 and stays at 0.

Because if lives > 0 then guarantees lives is at least 1 inside the block, the compiler proves lives - 1 can never dip below 0 and omits the runtime overflow check!

You can also clamp or wrap any whole-number expression inline with .clamp(lo...hi) and .wrap(lo..<hi), or pass an inline range to .cycle(0..<width):

const width = 40
column <- System.screen.frame.cycle(0..<width)
System.screen.text[0][0..<2] <- column.digits(2)

Steer the Lander with the Joystick

The Commodore 64's video chip draws eight independent sprites. These movable 24-by-21 pixel shapes appear over the character screen without erasing the text beneath them.

You draw a sprite right in your source file with Shape([...]), using X for lit pixels and . for transparent ones. Adder can reuse a packed art copy's memory after startup when a screen buffer or cleared storage can hold it. For level changes, load art companions with System.drive[8].load, as the Lab's Art by level example shows.

To steer a sprite across the screen with the joystick in Control Port 2 (System.joystick[2].dx, which reads -1 left, 0 center, 1 right), use .sum(from:, in:):

const lander = Shape([
  "...X...............X..X.",
  "....X....XXXXXX....XXX..",
  ".....X.XXXXXXXXXXX..XX..",
  ".....XX....X......XX.XX.",
  "....XXXXX..XXXXXXXXX....",
  "....X...X..X..X....X....",
  "....X...XXXX..XXXXXX....",
  "....X...XXXX..X....X....",
  "....X...XXXX.X......X...",
  "...XXXXXXXXXXXX....XX...",
  "..X............XXXXX.X..",
  "..X.............X.X..X..",
  "..X..XXXX.......X.XXXX..",
  "..X..XXXXX......X.X..X..",
  "...XXXXXXXXXXXXXXXXXXX..",
  "....XX.X..XXXX..X.XX....",
  "...XX..XXX....XXX..XX...",
  "..XX...X........X...XX..",
  "..XX................XX..",
  ".XXXX..............XXXX.",
  "XXXXXX............XXXXXX"
])

lander_x <- (System.joystick[2].dx * 2).sum(from: 148, in: 24...296)
System.screen.sprite[0] <- (x: lander_x, y: 120, shape: lander, color: .white)
// The lander glides left and right at 2 pixels a frame and stops
// cleanly inside the 24...296 flight corridor.

Because the C64 has eight sprites, stacking a second sprite at the exact same (x, y) coordinates lets us add gray cabin windows and deck trim (lander_trim), while a third sprite below the nozzle (lander_plume) draws the flickering yellow-and-orange rocket exhaust whenever the thruster fires!

Line Up with the Landing Pad

When our descending lander reaches the height of the landing pad (y = 166), how do we check whether its landing gear is squarely over the pad? By testing whether lander_x and pad_x are within 12 pixels of each other!

We write that check as a reusable function (fn):

fn on_pad(a, b)
  if a > b then a - b < 12 else b - a < 12 end
end

lander_x <- (System.joystick[2].dx * 2).sum(from: 148, in: 24...296)
pad_x <- System.screen.frame.cycle(64...256)
System.screen.border <- if on_pad(lander_x, pad_x) then .light_green else .black end
System.screen.sprite[0] <- (x: lander_x, y: 120, color: .white)
System.screen.sprite[1] <- (x: pad_x, y: 136, color: .light_gray)

Notice that fn on_pad(a, b) needs no type annotations: Adder infers the parameter ranges and bool return type directly from the call site on_pad(lander_x, pad_x)! (You can always write explicit types like fn on_pad(a: Number<24...296>, b: Number<64...256>): bool whenever you want to document a boundary.)

Play Sound Effects and Switch Scenes

Two last building blocks complete our game:

1. Sound Effects on the SID Chip

The C64's synthesizer has three voices (System.sound[1].voice[1] through voice[3]). Bind a voice with <- to a .noise waveform for a continuous rocket thruster roar while holding fire, or call .play(...) inside a when handler for one-shot landing and crash sounds:

const chime = Tone(.c6, decay: .short)
const boom = Tone(.c2, waveform: .noise, decay: .long)
const thrust = Tone(.c3, waveform: .noise)
System.sound[1].voice[2] <- if System.joystick[2].fire then thrust else .silence end
when System.keyboard.space.pressed
  System.sound[1].voice[1].play(chime)
end
when System.keyboard.return.pressed
  System.sound[1].voice[1].play(boom)
end

2. Game Scenes with Enums and Match

Enums can also give their cases values: enum Ink: Color might declare case mark = .white. A pixel field stores .mark; a handler can assign Ink.mark = .red to recolor every use. The enum chapter explains identity and values, and canvas pixels shows an editable picture. The scene enum below needs only its case names.

Try Lava lamp in Learn Adder for a larger picture. One work calculation returns all 42 rows through a <- binding, and a small fn builds its color table at compile time. Guards such as if col >= 0 and col < 32 let Adder keep an index small without repeated conversions. The maintained observation completes a new picture in about 8 PAL or 10 NTSC refreshes, using an 8,856-byte program; these are measured examples, not a deadline for every pose.

Our game moves through three scenes: title, playing, and over. By writing a match scene block at the top level of the program, each scene gets its own screen text, border color, sprites, state variables, and when handlers. They exist and run only while that scene is active:

enum Scene
  case title, playing, over
end
var scene: Scene = .title

match scene
  title ->
    System.screen.border <- .black
    System.screen.content <- Text(" PRESS FIRE ").at(row: 12, col: 14).ink(.white)
    when System.joystick[2].fire.pressed
      scene = .playing
    end
  playing ->
    System.screen.border <- .black
    System.screen.content <- Text(" DESCENDING ").at(row: 12, col: 14).ink(.light_green)
    when System.joystick[2].fire.pressed
      scene = .over
    end
  over ->
    System.screen.border <- .red
    System.screen.content <- Text(" MISSION END").at(row: 12, col: 14).ink(.yellow)
    when System.joystick[2].fire.pressed
      scene = .title
    end
end

Whenever scene switches to .playing, every var declared inside playing -> (ships, fuel, lander_x, lander_y, vx, vy, gravity) starts fresh from its initial value automatically!

Add an Independent Debug Line

A match or an if among declarations follows one rule: what a case declares exists only while it matches. Blocks beside each other choose independently, so a debug line need not be copied into every part of the game. Their active cases must bind different cells, parts and voices.

This example also bundles two colors in an output declared above the cases. Fire ends or restarts playing; space toggles the separate debug line.

output frame_color(c: Color)
  System.screen.border <- c
  System.screen.background <- c
end
var playing = true
var debug = false
frame_color <- .blue
if playing then
  frame_color <- .red
  System.screen.columns <- 38
  const inbox = Queue(of: Number<u8>, capacity: 3)
  when start
    inbox.add(7)
  end
end
if debug then
  System.screen.text[0][0..<5] <- "DEBUG"
end
when System.keyboard.space.pressed
  debug = not debug
end
when System.joystick[2].fire.pressed
  playing = not playing
end

While playing matches, its output shows instead of the usual blue colors and its window narrows to 38 columns. When it ends, blue and 40 columns return. Its queue starts empty each time, before start adds 7. A place declared with at can be bound the same way; without an outer binding, it keeps its last value.

A job queue or spare-time work result in a case stops when its case ends and starts from the top when the case starts again; declare the work function above the block. A nested case can show instead of an outer border or background, including its raster bands. If composing the new picture takes several frames, the previous whole picture stays visible until every starting case is ready, while handlers and input service continue. Shared scrolling keeps moving, and the deepest case's scroll and window join its picture at the frame border.

Fields and Functions Together

A struct groups fields and functions. A member declared mut fn changes its own value, such as score.clear(). Every function reads its parameters, its own fields and constants; pass a changing input at the call.

Use a guard to return a fallback before the rest of a value function or op:

fn visible(n: Number<u8>): Number<u8>?
  guard n > 0 else nil
  guard n < 100 else nil
  n
end

Each false test returns nil; true tests continue to the final value. To unwrap an optional, write guard item = maybe else nil and use item below it. Keep the final expression, and make each fallback fit the result type. A handler's guard has no else and ends only that handler's current run.

Share a Helper Through a Protocol

A protocol names fields and functions that a type promises. Put the protocol after the struct's colon, then use its name as a helper's parameter type:

protocol Positioned
  x: Number
end
struct Marker: Positioned
  x: Number<0...319>
end
fn ahead(view: Positioned, step: Number): Number
  view.x + step
end
const marker = Marker(x: 10)
System.screen.border <- Color(ahead(marker, 2))

The compiler checks the promise and makes each call use its concrete type. Calls need no runtime member lookup. A protocol can also require a member signature such as fn distance(target: Number): Number, written without a body. An enum with associated values puts their type first, as in enum Ink: Color, Scored. See Protocols for the rules.

Views share Scrollable, which requires scroll: (x: Number, y: Number) in whole pixels. Bind world.scroll <- (x: camera, y: 0) to move right through terrain as the camera increases; zero shows its original position. Open Scrollable world in the Lab to ride a monorail around a city four screens wide, above a fixed HUD. Its ahead(view: Scrollable) helper finds the next stop for an author Camera, which brakes there, and for the city region, whose HUD names the stop and its distance. The city uses 38 columns while the HUD keeps all 40; ordinary glyphs work at their boundary. The scroll reference explains backing cells, preparation and the proved row boundary.

Change Two Things in One Call

A mut parameter lets a function change a place for the length of its call. Mark the argument too, so the call shows what can change:

struct Player(points: Number<u8>)
fn award(mut player: Player, mut remaining: Number<u8>)
  player.points = player.points +% 1
  remaining = remaining -| 1
end
var hero = Player(points: 0)
var prizes: Number<u8> = 10
when System.keyboard.space.pressed
  award(mut hero, mut prizes)
end
System.screen.content <- Text(hero.points.digits(3)).at(row: 0, col: 0)

Pass a var, a field, an element or a slice of one. The types must match exactly. Each path is checked once before the function starts; changing an index later does not move the selected place. Two changing arguments must be different places. For swap(mut cells[i], mut cells[j]), check if i != j then first, or pass the list once with both indices. Ordinary arguments keep their values from before the call. Functions return values, and a returned slice is a copy that cannot change the original list. A binding cannot call a function with mut parameters. A work body may pass its own local var to a helper between turns.

For a calculation that needs several frames, declare work name(inputs): Result and call it like a function. Its bounded loops can live in a pure helper function or method: store the result in a local value, such as const part = scan(input), before combining it with another value. Several work declarations can share that helper; each job keeps its own inputs and paused loop position.

Bind its answer with answer: ResultType? <- scan(input). The answer starts at nil. Each run captures its arguments once in written order, finishes with those inputs, then reruns with the newest inputs if they changed. The binding keeps its last finished answer during later runs, even when inputs change every frame. With no inputs, as in work calculate(): Number<u16>, a bound job runs once. answer.running tells you whether a run is in progress.

To show progress, write publish value inside the work loop. The value must have the same type as the final answer. Changing a local or returning the answer does not offer progress. Reading answer.progress from work with no publish is refused.

work tally(count: Number<u8>): Number<u16>
  var total: Number<u16> = 0
  for i in 1...200
    total = total + count
    publish total
  end
  total
end
const count: Number<u8> = 2
answer: Number<u16>? <- tally(count)
System.screen.text[0][0..<5] <- (answer ?? 0).digits(5)
System.screen.text[1][0..<5] <- (answer.progress ?? 0).digits(5)

answer.progress starts at nil and offers the latest complete progress value at each frame opening. Several publications between frames share one visible value; a short calculation can finish before a frame shows an intermediate one.

Starting a run may use more of that frame to capture its inputs. The job can pause there and use the time left in later frames, keeping that same capture.

Several bound jobs take turns in the order you write them. If a job's next part does not fit, it keeps its turn for the next frame; later jobs can use the leftover time without taking that turn away.

Work that belongs to a value can also be a member. Build a struct in the bound call to pass several changing values together:

struct View(x: Number<0...9>, y: Number<0...9>)
work View.total(view: View): Number<u8>
  var sum: Number<u8> = 0
  for turn in 0..<4
    sum = sum + view.x + view.y
  end
  sum
end
var a: Number<0...9> = 1
var b: Number<0...9> = 2
when System.screen.frame
  a = (a + 1) % 10
  b = (b + 2) % 10
end
answer: Number<u8>? <- View(x: a, y: b).total()
System.screen.text[0][0..<3] <- (answer ?? 0).digits(3)

Each run keeps the complete View it captured. Adder evaluates the receiver first, then any explicit work arguments once in written order, checking each before starting the next.

To drive a captured job yourself, keep it in a var and call job.resume() from a handler. It returns nil until the complete answer is ready. Use job.finish() to finish all remaining work in that handler turn; the complete calculation must fit the frame.

When an input changes in the middle of a run, a bound job finishes that run first, then starts again with the newest inputs. Add .latest() to drop the out-of-date run and start again right away:

work route_to(target: Number<u8>): Number<u16>
  var steps: Number<u16> = 0
  for turn in 0..<200
    steps = steps +% Number<u16>(target)
  end
  steps
end
var target: Number<u8> = 1
when System.joystick[2].fire.pressed
  target = target +% 1
end
route: Number<u16>? <- route_to(target).latest()
System.screen.text[0][0..<5] <- (route ?? 0).digits(5)

The binding keeps its last finished answer. When an input changes during a run, the job drops the run and starts again with the newest inputs on that frame. So that answers keep arriving, it also counts how long it has been waiting: once the wait reaches one run's length, the run in progress finishes even if the inputs keep changing. For a run that takes 60 frames:

InputsPlain <-With .latest()
Change once, at frame 20Old answer at 60, new answer at 120New answer at about 80 (the new run starts at 20)
Change at frames 30, 34 and 38Out-of-date answer at 60, right one at 120Right answer at about 98 (the last run starts at 38)
Change every frameAn answer every 60 framesFirst answer at about 120 (dropping stops after 60 frames), then every 60

A bound call's .within(frames: n) promises that each captured run finishes within n frames; without .latest(), a changed input may first wait for the unfinished run. Dropping Stale Runs gives the complete rule. To drive a job entirely yourself, keep it in a var and assign a new job when you want to start over.

For a large picture, draw the answer directly with pixels(image ?? blank, ...), where blank is a constant empty picture of the same type. You can also name it with shown <- image ?? blank and draw shown, as the Work section explains. Adder refuses a deadline when a rerunning binding and another job compete for the time left in each frame.

Build a Calculation in Steps

A pure fn turns a value into another value. Collection functions apply those small calculations to a fixed list, and a pipe lets you read the steps from left to right:

type Level = Number<0...99>
fn calibrate(value: Level): Level
  value +| 3
end
fn is_high(value: Level): bool
  value >= 50
end
var readings: [4 of Level] = [12, 34, 58, 77]
high_levels <- readings |> map(calibrate) :> filter(is_high)
System.screen.content <- (Text("HIGH ") ++ Text(count(high_levels).digits(1))).at(row: 0, col: 0)

readings |> map(calibrate) means map(readings, calibrate). Both |> and :> spell the same operation; :> is convenient on a Commodore keyboard. filter keeps the original four positions, leaving nil where a reading does not qualify. count counts the present positions. This makes it easy to keep matching sensor, player or sprite slots aligned.

A list that should shrink and grow is [up to N of T]. It holds from none to N items, xs.append(item) and xs.remove(at: i) change it, and filter on it keeps only what passes, with no nil holes: count is just xs.length. Strings, slices (xs[a..<b]), ==, save and load work on it too.

To go through what a String or a list that grows holds, name it after for. for c in line visits the characters of a String one by one and for item in xs the items of a list that grows, leaving out the empty places. The loop's body cannot change what it walks; for i in 0..<line.length gives the position instead, and allows it.

var line: String<38> = "abba cabbage"
var bees: Number<0...38> = 0
when System.keyboard.space.pressed
  bees = 0
  for c in line
    if c == Char(98) then bees = bees +| 1 end
  end
end
System.screen.content <- Text(bees.digits(2)).at(row: 0, col: 0)

Try Sensor desk in Learn Adder for named transforms, filtering, original indexes and a seeded reduce. Use pure functions for calculations, and handlers for actions that happen in response to an event. A handler can call a changing assembly function when it needs a small machine routine that updates a variable or a struct.

Check What Every Line Costs

On a 1 MHz Commodore 64, a PAL frame has 19,656 cycles and an NTSC frame has 17,095 (16,768 on early NTSC chips). Adder counts the exact bytes of every line and proves an upper bound on your frame cycles with adder costs:

Terminal
adder costs border.adder
Cost report
source  bytes  cycles
border.adder:1     23     31+  System.screen.border <- Color(System.screen.frames % 16)
                    3 bytes of mutable data, including variables and scratch
frame work, worst case: PAL 70 of 19,656 cycles, NTSC 70 of 17,095, early NTSC 70 of 16,768
trusted: 0 bytes under 0 hand-written blocks; compiled: 23 bytes in the program's lines
runtime and shared tables (line 0): 217 bytes (205 code, 12 data and padding); startup worst case 12,413 cycles; program file: 242 bytes including the load address
file data (initial values, tables, constants, padding): 12 bytes; resident RAM while running: 249 bytes (the file without its load address, reserved runs and zero page cells)

This line becomes 23 bytes of instructions and takes at most 31 cycles a frame, leaving over 99% of the processor free.

In the Lab, hover or focus a cycle figure for a short summary, then activate it to inspect costs, exact writes and generated instructions in 6502. Program bytes here and Working storage here belong to that line; shared routines and deferred screen work have their own annotations.

The cost report also shows why guarding a range with if saves both bytes and cycles. Compare the two lives programs from earlier:

Cost report
   3     36     28+  lives = lives - 1
Cost report
   3      6      8+  if lives > 0 then
   4      6      10  lives = lives - 1

With if lives > 0 then, the compiler proves lives - 1 cannot underflow and emits a plain 6-byte, 10-cycle subtraction. The guard's own cost appears on the preceding row.

Put It All Together: Jupiter Lander

Here is the complete Jupiter Lander arcade game! Just like HAL Laboratory's 1982 original, each descent starts in low orbit drifting right (vx = 0.5) while gentle gravity (0.015625 pixels/frame², stepping up slightly after each landing) pulls the ship down. Nudge joystick 2 left and right to fire the side thrusters (vx = vx -| 0.03125 / +| 0.03125) and hold fire to burn the main rocket thruster (vy = vy -| 0.046875). Watch the landing pad's approach beacons: they glow green when both your descent rate (vy <= 0.625) and lateral drift (vx within -0.5...0.5) are safe for touchdown, and turn red when you are coming in too fast!

enum Scene
  case title, playing, over
end
var scene: Scene = .title
var score: Number<0...99> = 0

const chime = Tone(.c6, decay: .short)
const boom = Tone(.c2, waveform: .noise, decay: .long)
const thrust = Tone(.c3, waveform: .noise)
const rcs = Tone(.c4, waveform: .noise)
const touchdown_y = 166

const lander = Shape([
  "...X...............X..X.",
  "....X....XXXXXX....XXX..",
  ".....X.XXXXXXXXXXX..XX..",
  ".....XX....X......XX.XX.",
  "....XXXXX..XXXXXXXXX....",
  "....X...X..X..X....X....",
  "....X...XXXX..XXXXXX....",
  "....X...XXXX..X....X....",
  "....X...XXXX.X......X...",
  "...XXXXXXXXXXXX....XX...",
  "..X............XXXXX.X..",
  "..X.............X.X..X..",
  "..X..XXXX.......X.XXXX..",
  "..X..XXXXX......X.X..X..",
  "...XXXXXXXXXXXXXXXXXXX..",
  "....XX.X..XXXX..X.XX....",
  "...XX..XXX....XXX..XX...",
  "..XX...X........X...XX..",
  "..XX................XX..",
  ".XXXX..............XXXX.",
  "XXXXXX............XXXXXX"
])

const lander_trim = Shape([
  "........................",
  ".........XXXXXX.........",
  ".......XXXXXXXXXXX......",
  "........................",
  "........................",
  "........X..X..X.........",
  "........XXXX..XXXXXX....",
  "........XXXX..X.........",
  "........XXXX.X..........",
  "........................",
  "....XXXXXXXXXXXX........",
  "....XXXXXXXXXXXX........",
  ".........XXXXXXX........",
  ".........XXXXXXX........",
  "........................",
  ".........XXXXXX.........",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................"
])

const lander_plume = Shape([
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  ".........XXXXXX.........",
  "........XXXXXXXX........",
  "........XXXXXXXX........",
  ".........XXXXXX.........",
  ".........XXXXXX.........",
  "..........XXXX..........",
  "..........XXXX..........",
  "...........XX...........",
  "...........XX..........."
])

const pad = Shape([
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "XXXXXXXXXXXXXXXXXXXXXXXX",
  ".XXXXXXXXXXXXXXXXXXXXXX.",
  "..XX..XX..XXXX..XX..XX..",
  "..XX..XX...XX...XX..XX..",
  ".XXX..XX...XX...XX..XXX.",
  "XXXX................XXXX",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................"
])

const pad_beacons = Shape([
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "XX........XXXX........XX",
  "..XX....XX....XX....XX..",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................",
  "........................"
])

fn on_pad(a, b)
  if a > b then a - b < 12 else b - a < 12 end
end

preview_x <- (System.joystick[2].dx * 2).sum(from: 148, in: 24...296)

System.screen.background <- .black
System.screen.text[0][0..<2] <- score.digits(2)
System.screen.text[0][3..<38] <- "LANDINGS // FUEL:     SHIPS:       "
System.screen.color[0][3..<38] <- .cyan
System.screen.text[23][3..<37] <- "====[ JUPITER LANDING SECTOR ]===="
System.screen.color[23][3..<37] <- .dark_gray

match scene
  title ->
    System.screen.border <- .black
    System.screen.text[10][9..<31] <- "JUPITER LANDER // 1982"
    System.screen.text[12][14..<26] <- " PRESS FIRE "
    System.screen.sprite[0] <- (x: preview_x, y: 86, shape: lander, color: .white)
    System.screen.sprite[1] <- (x: preview_x, y: 86, shape: lander_trim, color: .gray)
    when System.joystick[2].fire.pressed
      score = 0
      scene = .playing
    end
  playing ->
    var ships: Number<0...3> = 3
    var fuel: Number<0...99> = 99
    var pad_x: Number<64...256> = 160
    var lander_x: Number<24.0...296.0> = 64.0
    var lander_y: Number<44.0...166.0> = 48.0
    var vx: Number<-1.5...1.5> = 0.5
    var vy: Number<-1.5...2.0> = 0.0
    var gravity: Number<0.015625...0.03125> = 0.015625
    burning <- System.joystick[2].fire and fuel > 0
    steering <- System.joystick[2].dx != 0 and fuel > 0
    safe_speed <- vy <= 0.625 and vx >= -0.5 and vx <= 0.5
    System.screen.border <- .black
    System.screen.text[0][21..<23] <- fuel.digits(2)
    System.screen.text[0][32..<33] <- ships.digits(1)
    System.screen.sprite[0] <- (x: lander_x.floor(), y: lander_y.floor(), shape: lander, color: .white)
    System.screen.sprite[1] <- (x: lander_x.floor(), y: lander_y.floor(), shape: lander_trim, color: .gray)
    System.screen.sprite[2] <- (
      x: lander_x.floor(),
      y: if burning then lander_y.floor() + 6 else -30 end,
      shape: lander_plume,
      color: if System.screen.frames % 2 == 0 then .yellow else .orange end
    )
    System.screen.sprite[3] <- (x: pad_x, y: 170, shape: pad, color: .light_gray)
    System.screen.sprite[4] <- (
      x: pad_x,
      y: 170,
      shape: pad_beacons,
      color: if safe_speed then .light_green else .light_red end
    )
    System.sound[1].voice[2] <- if burning then thrust else .silence end
    System.sound[1].voice[3] <- if steering then rcs else .silence end
    when System.screen.frame
      if System.joystick[2].dx < 0 and fuel > 0 then
        vx = vx -| 0.03125
      end
      if System.joystick[2].dx > 0 and fuel > 0 then
        vx = vx +| 0.03125
      end
      if System.joystick[2].fire and fuel > 0 then
        vy = vy -| 0.046875
        if System.screen.frames % 6 == 0 then
          fuel = fuel -| 1
        end
      else
        vy = vy +| gravity
      end
      lander_x = lander_x +| vx
      lander_y = lander_y +| vy
      guard lander_y >= touchdown_y
      if on_pad(lander_x.floor(), pad_x) and vy <= 0.625 and vx >= -0.5 and vx <= 0.5 then
        score = score +| 1
        fuel = fuel +| 25
        gravity = gravity +| 0.00390625
        System.sound[1].voice[1].play(chime)
      else
        ships = ships -| 1
        System.sound[1].voice[1].play(boom)
      end
      pad_x = Number.random(64...256)
      lander_x = 64.0
      lander_y = 48.0
      vx = 0.5
      vy = 0.0
      if ships == 0 then scene = .over end
    end
  over ->
    System.screen.border <- .red
    System.screen.text[10][11..<29] <- "ALL LANDERS LOST  "
    System.screen.text[12][14..<26] <- " MISSION END"
    when start
      wait(seconds: 3)
      scene = .title
    end
end

Where Next

Now that you have built a complete game, explore the Adder Language Reference whenever you want to reach for more of the machine:

For moving line drawings on a canvas, bind the lines with picture.drawings <- edges.lines() and advance them in when picture.shown. When every line moves, Adder clears the old area once if that costs less than erasing each line, even for small drawings. Your handlers keep running while the picture draws. The Wireframe example turns a 24-edge object in perspective. Its measured 6.00 PAL and 7.06 NTSC refreshes per picture are within 1.5 times a hand-written renderer of the same scene.

  • Types & Expressions — lists, structs, optionals (T?), map / filter pipelines, .clamp / .wrap, bit flags (bit_is_set, toggle_bit), and sliding list windows (xs[left..<(left + 40)]).
  • Declarations — struct methods (fn and mut fn), stateful op declarations (.previous()), and multi-file projects (include).
  • Events and Handlers & Statements — .hold, .cooldown, .rising / .falling, guard, wait, forever, and for loops.
  • The System Device Tree — raster color bands, scrolling text regions (System.screen.region), bitmap pixel canvases (System.screen.canvas), custom fonts, mouse, and 3-voice SID synthesis.
  • Costs and the Frame & Assembly — fast / small marks, multi-frame work functions, Queue buffers, and inline 6510 asm.