Back to DINKY

DINKY programming manual

DINKY is a tiny fantasy games console. Every game lives entirely inside one QR code: no download, no game server, no account. You print the code on a card, a friend scans it, and the game is on their phone, working offline. The machine is deliberately small, in the spirit of the ZX Spectrum: a 256 x 192 screen, 16 colours, one pixel font, a little sound chip, and about 1.4 KB of compressed code per game.

This manual is for people writing games for it. It covers the machine, every ROM call, sound, the rules, the byte budget, testing, and making and sharing cards.

How a game travels

games/mygame.js
  -> minify (terser: comments gone, names shortened)
  -> deflate (zopfli, raw deflate)
  -> base43 (two bytes in three characters, capitals, digits and $*+-./: only)
  -> https://your-console/#3<payload>      (the "3" is the link format)
  -> QR code on a card: the address in byte mode, the game in alphanumeric mode

Why base43: a QR code stores capitals, digits and a few symbols ("alphanumeric" characters) in 5.5 bits each, but anything with lowercase in 8. base43 sticks to those characters, so the game part of the code costs about 8.3 bits per byte instead of the 10.7 base64 would, and each code comes out about four QR versions smaller. Cards from before this change start with #2 and hold the same bytes as base64; the console still reads them, and a game keeps its high scores whichever format its card uses.

The console is a web app (a PWA) that you install once. When it reads a card, it takes everything after the #, unpacks it and runs it. The part after # never leaves the phone (browsers don't send it to servers), so a game plays with no connection at all once the console is installed.

What goes into the link is just the game's title, its spine colour and its minified code. The rest of the header block (tagline, how to play and so on) is only used for the printed card.

Quickstart

Five minutes from nothing to a game on your phone.

  1. Install the SDK's tools once, from the project folder:
    npm install
    
  2. Start a game. The id is 2 to 20 lowercase letters, numbers or dashes; the title is up to 24 characters.
    npm run dinky -- new mygame "My Game"
    
    This creates games/mygame.js (a small working game to change) and games/mygame.test.mjs (its tests). For a game you steer by tilting the phone, add --tilt to start from the tilt template instead (see Tilt, under Input).
  3. Run the dev console:
    npm run dinky -- dev mygame
    
    Open http://localhost:8080/?dev=mygame (or add --open to the command). Every time you save a file in games/, the game reloads and the terminal shows any lint errors. The browser tab's title shows the current size, the QR version and how many bytes you have left.
  4. Change something. Colours, text, speed. Save and watch it reload.
  5. Run the tests:
    npm run dinky -- test mygame
    
  6. Build the cards:
    npm run dinky -- build --dev
    
    --dev points the codes at your local console (devUrl in dinky.config.json). The cards are in dist/games/, and with the dev server running you can see them at http://localhost:8080/games/.
  7. Play it from the code. On the computer, open the link in dist/mygame.url.txt. On a phone, see "The console's address" under Making cards: a localhost link only works on the machine running the dev server.

The machine

Screen

Palette

The ZX Spectrum palette. Colours 8 to 15 are the bright versions of 0 to 7, so c - 8 is the darker version of a bright colour. 8 is the same black as 0.

The 16 palette colours with their numbers

# Name Hex # Name Hex
0 black #000000 8 bright black #000000
1 blue #0000d7 9 bright blue #0000ff
2 red #d70000 10 bright red #ff0000
3 magenta #d700d7 11 bright magenta #ff00ff
4 green #00d700 12 bright green #00ff00
5 cyan #00d7d7 13 bright cyan #00ffff
6 yellow #d7d700 14 bright yellow #ffff00
7 white #d7d7d7 15 bright white #ffffff

Colour numbers are wrapped into range with c & 15, so 16 is 0 and -1 is 15. A missing colour in rect and friends is 0 (black).

Font

The console has one built-in pixel font, BM mini, covering ASCII 32 to 126.

Every character of the BM mini font, ASCII 32 to 126; the blue line is the row txt's y points at

Sound

The console has two sound devices. Games send it short commands; the console does the playing.

There is no sound data in a game, only commands. The Sound chapter, after the API reference, has the details.

Input

Tilt

ROM.tilt is the phone's tilt, { x, y, r, on, off }, for games you steer by tipping the phone. It is phones only; there is no keyboard stand-in.

Starting a tilt game

npm run dinky -- new mygame "My Game" --tilt creates a small working tilt game (roll a ball over coins for thirty seconds) and its tests. It already does the things every tilt game needs:

If your game has walls, cap the ball's speed below the wall thickness plus the ball's radius per step, so it can't pass through a wall in one step. TILT MAZE (games/tiltmaze.js) is a fuller example: a maze, pits, level times and rotation handling.

The card's screenshot is taken in headless Chrome, which has no motion sensor, so a tilt game can only be shot on its title or waiting screen. Keep the @shot wait under a second (the template uses 128,96 w700): after that the console decides there is no sensor and your game shows its blocked message.

Storage

A game can't store anything except high scores, through hi(key, value). Scores are kept on the phone, per game. A game is identified by its exact contents, so changing a single byte of a game makes it a new game, with its own library entry and empty scores.

The ROM API

ROM is the only thing a game can talk to. It is the same object in the console and in the tests. Most games start by pulling out what they need:

const { W, H, cls, rect, txt, spr, sfx, beep, border, hi, rnd, run } = ROM;

That's fine for functions and constants. Five members are not safe to copy out, because they change or because you set them: ROM.t, ROM.held, ROM.tilt, and the handlers ROM.press and ROM.release. Always write those with ROM. in front.

Quick list

Member What it does
W, H Screen width (256) and height (192)
cls(c) Fill the whole screen
rect(x, y, w, h, c) Filled rectangle
box(x, y, w, h, c) Rectangle outline
pset(x, y, c) Set one pixel
pget(x, y) Read one pixel's colour
line(x0, y0, x1, y1, c) Straight line
txt(s, x, y, c, z, align) Text in the ROM font
tw(s, z) Width of some text in pixels
spr(s, x, y, z) Draw a sprite from a string
cam(x, y) Scroll everything drawn after it
flip(on) Turn drawing round 180 degrees
border(c) Border colour
ROM.press, ROM.release Your input handlers
ROM.held Is anything held down?
ROM.tilt The phone's tilt: { x, y, r, on, off }
ROM.phys Physics: gravity, bouncing balls and boxes, solid pixel walls
run(step, draw) Start the game loop
ROM.t Steps since the game started
sfx(name or array) Sound effect
play(mml, ch, loop) Play a tune on channel 0 to 2
stop(ch) Stop a channel, or all sound
beep(f, d, f2) Square-wave beep or sweep
ROM.music / ROM.m Music Chip V2 songs (games with // @sound 2 only)
hi(key, value) Read or save a high score
rnd(n) Random number
FONT The font data itself

Screen

cls(c = 0) fills the whole screen with colour c. It ignores cam and flip.

cls(1);                        // blue background

rect(x, y, w, h, c) fills a rectangle. Everything is rounded to whole pixels and clipped to the screen.

rect(0, H - 8, W, 8, 4);       // green ground along the bottom

box(x, y, w, h, c) draws a 1-pixel outline of the same rectangle.

box(60, 64, 136, 48, 10);      // red frame round a message

pset(x, y, c) sets one pixel. pget(x, y) returns the colour of one pixel (0 if it is off-screen). Both follow cam and flip, so pget reads back what you drew at those coordinates.

pset(rnd(W), rnd(H), 7);        // a star
if (pget(px, py + 8) == 4) onGround = true;   // standing on green?

line(x0, y0, x1, y1, c) draws a straight line between two points (up to 2000 pixels long).

line(0, 0, W - 1, H - 1, 6);

Text

txt(s, x, y, c = 15, z = 1, align = 0) draws text in the ROM font. s can be a string or a number. y is the baseline (see Font, above); align is 0 centred on x, -1 starting at x, 1 ending at x.

txt(`SCORE ${score}`, 4, 7, 7, 1, -1);    // top-left, grey
txt('GAME OVER', 128, 96, 10, 2);           // centred, red, double size

tw(s, z = 1) returns the width of s in pixels at scale z, gap between characters included.

rect(128 - tw('PAUSED') / 2 - 2, 88, tw('PAUSED') + 4, 10, 1);

Sprites

spr(s, x, y, z = 1) draws a picture written as a string. Rows are separated by /. Each character is one pixel: a hex digit 0 to f is a palette colour, and . or a space is see-through (in fact anything that isn't a hex digit is). z scales each pixel to a z x z block. 0 is solid black, not see-through.

spr('..d../.ddd./ddfdd/d.d.d', x, y, 3);   // a little cyan ship, 3x size

Sprite strings cost bytes (see Size budget). For blocky shapes, a few rect calls are often cheaper.

Drawing sprites

With npm run dev running, click Draw at the top right of the dev console (?dev=<id>), or open http://localhost:8080/draw?game=mygame. It finds every sprite in the file (named ones like const RAT = '...' or [...rows].join('/'), and unnamed ones inside a call) and shows them in a strip along the bottom. Pick colours with 0-9/a-f, draw with the left button, erase with the right. ⌘Z undoes.

Save (⌘S) writes the pixels straight back into games/<id>.js, changing only the sprites you touched, and the open game reloads. It also writes art/<id>.png and art/<id>.json, a picture of every sprite you can open elsewhere and bring back with Import PNG. If the file changed on disk since the editor loaded it, nothing is saved.

The byte figures are estimates: ~N B once used is what the sprite adds when the game draws it, and the build packs a little smaller. Art the game doesn't use yet isn't always free: the build drops an unused '...' string sprite and unused hit and anchor consts, but keeps an unused [...].join('/') sprite, which is how the editor writes new sprites and frame 2, so those cost their bytes from the first save.

View: cam and flip

cam(x = 0, y = 0) moves the camera: anything drawn after it at world position (x, y) appears at the top-left of the screen. It affects rect, box, pset, pget, line, txt and spr, but not cls. Call cam() with no arguments to go back to screen coordinates (for a score bar, say).

cam(playerX - 128, 0);  drawWorld();
cam();                  txt(score, 128, 7);

flip(on) turns all following drawing round by 180 degrees: what you draw at the top-left lands at the bottom-right, upside down. It is made for two-player games on a phone lying flat between the players: draw one player's half, flip, draw the other's with the same code. flip(0) turns it off. Input coordinates are never flipped: a tap is always reported in real screen pixels.

for (let p = 0; p < 2; p++) { flip(p); drawHalf(p) }
flip(0);

Both reset after every frame. After each draw(), the console puts cam back to (0, 0) and flip off, so each frame starts clean. Set them in draw(), not step().

Input

ROM.press = (X, Y, key) => { ... } is called once whenever a finger, mouse button or key goes down. For touch and mouse, X and Y are the game pixel and key is null. For keys, X and Y are -1 and key is the key's code, like 'Space' or 'ArrowLeft'.

ROM.press = (X, Y, key) => {
  if (key == 'ArrowLeft' || (key == null && X < 128)) dir = -1;
  else dir = 1;
};

ROM.release = (X, Y, key) => { ... } is called when it comes up again, with the same kind of arguments. A finger can slide off the screen before it lifts, so the release position can be outside 0 to 255 / 0 to 191.

ROM.release = () => { dir = 0 };

ROM.held is true while at least one finger, button or key is down. Good for one-button "hold to rise" games.

v += ROM.held ? -0.3 : 0.2;

ROM.tilt is { x, y, r, on, off }: x, y from -1 to 1 (x > 0 right side lower, y > 0 bottom lower), r the screen angle / 90, on when readings are arriving, off when denied or no sensor. See Input, under The machine, for how and when the phone asks. Reading it for the first time is what makes the console ask for the motion sensor.

const t = ROM.tilt;
if (t.on) ball.x += t.x * 2;

Holding is easy to time by counting steps between press and release (MINEFIELD MOLE digs on a short tap and plants a flag after a 20-step hold). For two players on one screen, split by screen half: Y < 96 is the top player (see SHOWDOWN).

Time and the game loop

run(step, draw) starts the game. Call it once, at the end of your file.

function step() { x += dx }
function draw() { cls(0); rect(x, 90, 8, 8, 14) }
run(step, draw);

ROM.t is the number of steps since the game started. Read it as ROM.t each time; copying it out with const { t } = ROM gives you a number that never changes. Many games keep their own counter in step() instead (t++), which is also free to reset.

if (ROM.t % 50 == 0) beep(880, .05);       // once a second

Timing in steps keeps everything in time with pausing and testing: 50 steps is one second. setTimeout(fn, ms) works too: inside a game it counts game frames (ms / 20, rounded up), so it pauses with the game and runs the same way in tests. setInterval isn't available; use setTimeout again from inside the callback, or count steps.

Physics

ROM.phys is a small physics engine built into the console: gravity, balls and boxes that bounce, slide and come to rest, and walls you simply draw. It lives on the console, so a game pays only for the calls it makes.

const P = ROM.phys;
cls(); rect(0, 180, 256, 4, 5);              // draw the floor in colour 5
P.world({ gy: .15, walls: [5] });            // gravity down; colour 5 is solid
const ball = P.add({ x: 128, y: 20, r: 3, e: .6 });
function step() { P.step() }                 // advance the physics once per step
function draw() { cls(); rect(0, 180, 256, 4, 5); rect(ball.x - 2, ball.y - 2, 5, 5, 14) }
ROM.press = () => ball.vy = -4;              // tap to throw it up
run(step, draw);
Field Meaning (default)
x, y centre, in pixels
vx, vy speed in pixels per step (0)
r radius: makes a ball (4)
w, h width and height: makes a box instead (no rotation)
m mass (from its size); 0 makes it fixed: it never moves, and things bounce off it
e bounciness, 0 to 1 (.3)
f friction, 0 to 1 (.2)
d drag per step, 0 to 1 (0): its speed is multiplied by 1 - d each step
g how much gravity pulls it (1); 0 to float
walls bumps into pixel walls (true)
hits read only: what it touched during the last P.step()

Sound

sfx(name) plays a preset effect; sfx([...]) plays a custom ZzFX sound.

sfx('coin');
sfx([.5, 0, 988, , .04, .18, 5, 1, , , 331, .05]);

play(mml, ch = 0, loop = false) plays a tune on channel 0, 1 or 2, replacing whatever that channel was playing.

play('T200 O5 L16 C E G > C', 1);

stop(ch) stops one channel; stop() with no argument stops all sound.

stop(2);

beep(f, d, f2 = f) plays a square wave starting at f Hz and sliding to f2 Hz over d seconds (0.01 to 1).

beep(440, .1, 880);            // a rising blip

Scores

hi(key) returns the saved score for key (0 if there isn't one). hi(key, value) saves value (rounded to a whole number) and returns it. Keys are cut to 16 characters.

hi doesn't compare for you: it always saves what you give it. Check first:

let best = hi('best');
// later, at game over:
if (score > best) best = hi('best', score);

Scores belong to this game on this phone. The library shows the highest value a game has saved under any key as its "BEST". For "lower is better" scores, like a reaction time, store the time anyway: it is your game that decides what counts as better (SHOWDOWN and MINEFIELD MOLE both do this).

Misc

rnd(n) returns a whole number from 0 to n - 1. rnd() returns a fraction from 0 up to (not including) 1, like Math.random().

const lane = rnd(4);           // 0, 1, 2 or 3

W and H are 256 and 192.

FONT is the font data: one array per character from ASCII 32, one number per pixel column, bit 0 at the top. You won't normally need it.

Math, String, arrays, objects, classes and the rest of plain JavaScript are all there. performance.now() works too (SHOWDOWN uses it to time reactions to the millisecond).

Sound

Presets

Name Sounds like
coin two-tone pickup, B5 to E6
jump square sweep up
hit gritty thud
boom crunchy explosion
shoot pew
laser thin falling zap
power rising staircase
blip menu blip
select two quick notes up
hurt falling buzz
step footstep tick
win bugle arpeggio, C4 up to C6
lose sad steps down
tick clock tick
whoosh airy sweep
alarm whoop whoop
splash hiss
pickup quick bloop up
door low grind
warp wobbling rise

You can hear them all in console/sound-test.html (open it through the dev server: http://localhost:8080/sound-test.html).

Custom effects (ZzFX)

sfx([...]) takes a ZzFX parameter list of up to 21 numbers. Design one in Frank Force's ZzFX designer at https://killedbyapixel.github.io/ZzFX/ and paste the numbers in (just the array, not the zzfx(...) call). Empty slots (, ,) use ZzFX's defaults.

The console clamps every value to a safe range, and stretches nothing beyond 2 seconds: an effect with longer attack, sustain, release, delay and decay is squashed to fit. So a sound may come out slightly different from the designer if you push it to extremes.

A custom array costs bytes (around 17 for a typical one); a preset name costs almost nothing. Try the presets first.

MML cheat sheet

Tunes are strings, at most 512 characters each (longer ones are ignored). Case and spaces don't matter.

Write Means
C D E F G A B notes. Add # or + for sharp, - for flat, then an optional length and dots: C#8, E-16, G4.
R rest, with a length the same way: R4, R8
L<n> default length: 1 whole, 2 half, 4 quarter (default), 8, 16, 32 (1 to 64)
. dot: half as long again (C4. is three eighths)
O<n> octave 1 to 8 (default 4). O4 C is middle C, O4 A is 440 Hz
< > octave down / up
T<n> tempo, in quarter notes per minute, 32 to 255 (default 120)
V<n> volume 0 to 15 (default 15)
W<n> wave: 0 square (default), 1 triangle, 2 noise (the note sets the colour of the noise)
& or _ tie: join the next note on (the same pitch becomes one long note)
[ ... ]<n> repeat n times (default 2, up to 99). Can be nested

Settings carry on through repeats, and each channel keeps its own. A tune stops after 2000 notes or 120 seconds.

A start jingle (half a second):

play('T180 L16 O5 C E G > C4', 1);

A looping triangle-wave bassline on channel 2, with a melody on channel 0:

play('T120 O2 L8 W1 [C C > C < C  E- E- > E- < E-]2', 2, true);
play('T120 L8 O5 V10 E D C D E E E4 D D D4 E G G4', 0);

A noise drum loop:

play('T160 O3 L8 W2 [C R C C]', 1, true);

Sound tips

Music Chip V2

A second sound chip for games that want proper music. Put // @sound 2 in the header and the game gets ROM.music: up to six channels in one MML string, all on one clock, with instruments, effects and drums. Everything from the first chip (sfx, beep, play) still works alongside it, unchanged, on its own three channels.

The chip lives in the console, like the first one, so it costs a game nothing: a song is one string and one call.

// @sound 2
ROM.press = () => ROM.music.play('T140 L8 I2 O5 C E G >C< G E C4 | I4 O2 [C G]4 | [K0 K2 K1 K2]2');

Calls

Call Short Does
ROM.music.play(song, loop = true) ROM.m.p Play a song. It loops unless loop is false. A new song replaces the old one.
ROM.music.stop() ROM.m.s Stop the song.
ROM.music.pause() / resume() ROM.m.h / ROM.m.r Pause the song and carry on from the same place.
ROM.music.volume(v) ROM.m.v Music volume, 0 to 1 (default 0.8). Effects aren't affected.
ROM.music.tempo(n) ROM.m.t Change the tempo while it plays, 32 to 255.
ROM.music.mute(ch, on = true) ROM.m.u Mute or unmute channel 0 to 5.
ROM.music.transpose(n) ROM.m.x Shift every note by n semitones, -24 to 24.

Write the long names. The build turns ROM.music.play(...) (and const { music } = ROM; music.play(...)) into ROM.m.p(...) before packing, so readable code costs nothing. Measured on a busy fixture with 14 music calls: 283 packed bytes written long without the rewrite, 253 with it, the same as writing ROM.m.p by hand (node sdk/measure-api.mjs). If you copy ROM.music into another variable (const mu = ROM.music), the build can't follow it and leaves it alone; it still works, it just costs the long names.

A song sent before the player has touched the screen waits and starts on the first touch (browsers don't allow sound before one).

MML for the V2 chip

Everything in the first chip's MML works the same (notes, R, lengths and dots, L O < > V & _ [ ]n). New:

Write Means
| Next channel, up to 6. All channels share one clock and loop together on the longest one.
T<n> The song's tempo: the first T anywhere counts.
L<n> An L before channel 0's first note is every channel's default length, so 'T140L8 CEG|O2 C' gives both channels eighths.
W0-W5 Wave: 0 square, 1 triangle, 2 noise, 3 sine, 4 saw, 5 pulse
I0-I31 Instrument preset: sets the wave, envelope, pulse width, vibrato, arpeggio and gate in one go. Commands after it change them.
P1-P15 Pulse width, in sixteenths (P8 is square, P2 is thin and nasal)
Q1-Q8 Gate: how many eighths of each note sound (Q4 is staccato)
@a,d,s,r Envelope: attack, decay, sustain, release, each 0 to 15 (@0,6,0,4 is a pluck). Not E, which is a note.
M0-M15 Vibrato preset (0 off)
S0-S15 Glide into each note from the one before (0 off)
X0-X15 Arpeggio preset, the classic chiptune chord: 1 major, 2 minor, 3 octave, 4 fifth, 5 major with octave (0 off)
N-8-N8 Pan the channel, left to right
K0-K7 A drum hit at the current length: kick, snare, closed hat, open hat, low tom, high tom, clap, crash

A song is at most 2048 characters, 4000 notes and 240 seconds a pass; anything past that is cut off.

Instruments

Hear them all on the sound test page (npm run dev, then http://localhost:8080/sound-test.html). The sounds may still be tuned, but the numbers won't change.

# # # #
0 square lead 8 saw lead 16 square pluck 24 chip brass
1 soft square 9 flute 17 harp 25 staccato
2 pulse lead 10 vibrato square 18 bell 26 noise snare
3 thin pulse 11 pwm lead 19 organ 27 noise hat
4 triangle bass 12 soft pad 20 major arp 28 surf
5 saw bass 13 saw pad 21 minor arp 29 zap
6 punch bass 14 pwm pad 22 octave arp 30 tri kick
7 sub bass 15 sine pad 23 power arp 31 drone

Music tips

The header block

Every game starts with a block of comments. The first line is required; the @ lines feed the printed card and the library.

// STACK ATTACK: tap to drop the sliding block. Whatever overhangs gets sliced off.
// @tagline How high can you build before it all comes down?
// @how Tap to drop the sliding block onto the tower.
// @how Anything hanging over the edge is sliced off and falls.
// @how Miss the tower completely and it's game over.
// @controls Tap screen / click / any key to drop
// @players 1
// @shot 128,96 w1000 128,96 w900
// @colour 14
Line Required Used for
// TITLE: note yes, first line of the file The title goes into the link: loading screen, library, pause menu, share screen, card. 1 to 24 plain ASCII characters, no : (the colon ends the title). The note after the colon is for people reading the code; nothing uses it.
// @tagline ... yes The strapline on the inlay card.
// @how ... yes, at least one One line each of the "How to play" list on the card. Repeat as needed.
// @controls ... yes The controls line on the card.
// @players 1 no (default 1) 2 prints "Two players, one phone" on the card.
// @shot ... no The script shots plays before taking the card's screenshot (below). Default 128,96 w1200.
// @colour 14 yes Palette number 1 to 15. Goes into the link: the title colour in the library and pause menu, and the card's spine and title.
// @sound 2 no (default 1) The sound chip the game needs. 2 is Music Chip V2 (ROM.music). Goes into the link (see Hardware versions).
// @graphics 1 no (default 1) The graphics chip the game needs. There is only 1 so far.

Titles are usually written in capitals (new does this for you). Avoid | in a title: it is the separator inside the game's link.

Hardware versions

The console's sound and graphics are versioned hardware, so the console can grow without old games changing. A game says what it needs with // @sound N and // @graphics N; anything it doesn't say is version 1, the hardware every game was made for before versions existed.

@shot syntax

A space-separated list of steps, run in the real console in a headless browser:

Step Does
X,Y tap the screen at game pixel X, Y
w500 wait 500 ms
kSpace press and release a key, by its code (kEnter, kArrowLeft, kKeyA)

So 128,96 w1000 128,96 w900 taps the middle, waits a second, taps again, waits 0.9 s, then takes the picture.

Rules and security

Why there are rules

Cards get swapped between strangers. Whoever scans one is trusting a picture on a bit of card. So a game must never be able to phish, spam, track or advertise. The console makes that impossible rather than just discouraged, and the rules below are what that means for you.

What a game can't do

How the console enforces it

Each game runs in a Web Worker started from a hidden, sandboxed iframe with no origin and a strict security policy. That alone blocks the network, storage and the page. On top, the console checks every message a game sends: a frame of exactly 256 x 192 palette numbers plus a border colour, a sound command (cleaned up and clamped), a high-score save (a whole number with a short key), an error message, or one request for tilt (the only other thing a game may say). Nothing a game sends is ever opened, navigated to or shown as HTML.

The game itself is checked when it's unpacked: the code must unpack to 64 KB or less (a real QR code can't hold anything that would legitimately grow bigger), and the title must be 1 to 24 printable ASCII characters.

What lint checks

npm run dinky -- lint (and dev, build) checks your game before the console ever sees it:

Lint can't catch everything. const { t, held } = ROM passes, but gives you values that never update.

When things go wrong

The console stops a game and shows GAME STOPPED with a reason when:

Reason shown Cause
This game crashed: error An uncaught error, in your top-level code or in step, draw, press or release.
This game stopped responding and was closed. One frame took more than 2 seconds (usually an endless loop).
This game could not start. The top-level code didn't finish within 4 seconds.
This game was flooding the console and was stopped. More than 400 messages in a second. Frames, sounds and score saves are all messages, so a loop that calls sfx or hi hundreds of times will trip it.
This game tried to leave the console and was stopped. The sandbox was asked to navigate away.

Separately, more than 10 hi() saves in a second are ignored by the console (your game will still think it saved). Save once, at game over.

In the dev console, a crash shows the same screen; save a fix and it reloads.

Size budget

The numbers

Limit About this much packed game
Easy to scan (QR version 32 or less), from paper or a screen 1850 bytes
Absolute maximum (QR version 40, low error correction) 2820 bytes

The whole code counts, console address included, so these are for an address of about 29 characters like https://console.konoha.co.uk/. The address is stored at 8 bits a character and the game at about 8.3 bits a byte. The example games are 1060 to 1430 bytes, QR versions 24 to 28.

A shorter console URL leaves more room for games: every character saved in the address is about a byte for the game.

Reading the build table

│ (index)        │ source B │ packed B │ QR version     │ bytes left (easy scan) │ bytes left (max) │
│ STACK ATTACK   │ 4048     │ 1058     │ '24 (113x113)' │ 796                    │ 1766             │

The dev console's tab title shows the same thing while you work, in the form 1058 B, QR v24, 796 B left (packed bytes, QR version, bytes left for easy scanning). It compresses a little less hard than build and measures against consoleUrl, so treat it as a close estimate.

What costs bytes and what doesn't

Measured on a small game (about 330 packed bytes):

Change Cost
All comments free (minifying removes them)
Long, readable variable and function names free (minifying shortens them)
A second sfx('coin') call 4 bytes
beep(988, .1, 1300) instead of sfx('coin') 9 bytes more
A custom ZzFX array instead of sfx('coin') 17 bytes more
An object property name used twice (game.scoreValue) 20 bytes
An 8 x 8 spr string 24 bytes
A 45-character line of text 38 bytes
A 40-note tune 49 bytes

So:

Testing with the testkit

Tests run your game on the real ROM, in Node, with no browser. A test file is a plain script:

import { load, ok, done } from '../sdk/testkit.mjs';
const g = load('games/mygame.js', { expose: ['st', 'score'] });
g.run(10);
ok(g.st == 0, 'starts on the title screen');
done();

Run one game's tests with npm run dinky -- test mygame, or everything (SDK and all games) with npm run dinky -- test. Paths are relative to the project folder.

load(file, options)

Loads a game and returns a handle g. Options:

Driving the game

Call Does
g.step(n = 1) run n steps of game logic, no drawing (fast)
g.draw() run your draw() once
g.run(n = 1) exactly n steps then one draw, through the same loop as the console
g.tap(x, y, id) press and release at a game pixel
g.press(x, y, id), g.release(x, y, id) press and release separately, to hold. id (default 'finger') lets you use two fingers at once
g.key(code) press and release a key, like g.key('Space')
g.keyDown(code), g.keyUp(code) hold a key down, let it go
g.tilt(x, y, r = 0) readings arriving: the phone tipped by x, y (each -1 to 1), screen angle r (0 to 3). Stays until you change it
g.tilt(null) waiting: no readings yet (the start, or just after a resume)
g.tilt(false) blocked: the player said no, or there is no sensor

All of them return g, so they chain: g.press(250, 180).step(20).release(250, 180).

step and run both advance g.t and any setTimeout timers by one frame per step.

Looking at the result

Property Gives
g.screen.at(x, y) colour of one pixel
g.screen.count(c) how many pixels are colour c
g.screen.colours() the colours on screen, sorted
g.screen.has(c, x, y, w, h) true if any pixel in the rectangle is colour c (whole screen if you leave out the rectangle)
g.sounds every sound command so far, like { t: 'sfx', n: 'coin' }, { t: 'beep', f: 440, d: .1, f2: 880 }, { t: 'play', m: '...', c: 1, l: false }
g.saved scores saved with hi(), as { key: value }
g.wantsTilt true once the game has read ROM.tilt (which is what makes the console ask for the motion sensor)
g.border the border colour of the last frame
g.frames how many frames have been drawn by run
g.t ROM.t
g.rom the ROM itself

The screen reflects the last draw(); call g.draw() after stepping if you want to check pixels.

ok and done

ok(condition, message) prints PASS message or FAIL message. done() prints the totals and makes the test fail if anything did. Call it at the end.

A worked example

A whole tiny game, PIP: tap the dot as often as you can in ten seconds.

// PIP: tap the dot before it moves.
// @tagline One dot. Ten seconds. How quick are you?
// @how Tap the yellow dot. Each hit scores a point and moves it.
// @how You have ten seconds.
// @controls Tap the dot
// @players 1
// @shot 128,96 w500
// @colour 14
const { W, H, cls, rect, txt, sfx, border, hi, rnd, run } = ROM;
let st = 0, score = 0, best = hi('pip'), x = 120, y = 90, left = 0;

ROM.press = (X, Y) => {
  if (st == 0) { st = 1; score = 0; left = 500; border(1); return sfx('select') }
  if (X >= x && X < x + 16 && Y >= y && Y < y + 16) {
    score++; sfx('coin');
    x = rnd(W - 16); y = 16 + rnd(H - 32);
  }
};

function step() {
  if (st == 1 && --left == 0) {
    st = 0; sfx('lose'); border(2);
    if (score > best) best = hi('pip', score);
  }
}

function draw() {
  cls(0);
  txt(`SCORE ${score}  BEST ${best}`, 128, 7, 7);
  if (st == 1) {
    rect(x, y, 16, 16, 14);
    rect(0, H - 4, left * W / 500, 4, 5);
  } else txt('TAP TO PLAY', 128, 100, 15, 2);
}

run(step, draw);

And its test, games/pip.test.mjs:

import { load, ok, done } from '../sdk/testkit.mjs';

const g = load('games/pip.js', { expose: ['st', 'score', 'x', 'y', 'left'], scores: { pip: 3 } });

g.run(1);
ok(g.st == 0, 'starts on the title');
ok(g.screen.has(15, 0, 80, 256, 30), 'TAP TO PLAY is drawn');

g.tap(10, 10);
ok(g.st == 1 && g.left == 500, 'a tap starts a round');

g.x = 50; g.y = 60;                // put the dot somewhere known
g.tap(55, 65);
ok(g.score == 1, 'tapping the dot scores');
ok(g.sounds.some(s => s.n == 'coin'), 'and plays the coin sound');

g.step(500);                       // ten seconds of play
ok(g.st == 0, 'the round ends after ten seconds');
ok(g.saved.pip == undefined, 'a score of 1 does not beat the saved best of 3');
g.draw();
ok(g.screen.at(255, 191) != 5, 'timer bar is gone');

done();

Tips:

Making cards

Build

npm run dinky -- build          # codes point at consoleUrl
npm run dinky -- build --dev    # codes point at devUrl (your machine)

build lints every game (and stops if any fails), then packs each one into dist/:

Screenshots

The inlay shows a screenshot of the game in play. To take them:

  1. npm run dinky -- build --dev (the screenshots load each game from its --dev URL).
  2. In another terminal, npm run dinky -- dev.
  3. npm run dinky -- shots. This opens each game in headless Google Chrome (installed in /Applications), plays its @shot script and saves dist/<id>-shot.png.
  4. Build again (with or without --dev) so the cards pick the screenshots up.

Print

Open a card from dist/games/ and use its Print inlay button. The print layout is A4 landscape and draws the card at real size (one card unit is 1 mm), so print at 100% scale, not "fit to page". Cut it out and fold it into a cassette case, or just stick it on a card.

The console's address

Every card has the console's address baked in. Set it in dinky.config.json once you have a domain:

{
  "consoleUrl": "https://PLACEHOLDER.example/",
  "devUrl": "http://localhost:8080/",
  "devPort": 8080
}

Publish the console

npm run dinky -- site
npx wrangler deploy

site refreshes the console (its security policy hash, offline file list, icons and this manual, as console/manual.html) and copies it to dist/site/, with the built cards and codes under it. Upload that folder to any static host over HTTPS. The one set up here is a Cloudflare Worker called dinky that serves dist/site/ as static files (wrangler.jsonc); npx wrangler deploy publishes it. Build the cards with the final consoleUrl before running site.

Console versions. Every time the console's files change, site (and console) moves the console version up by one: a plain number kept in console/version.json and committed with the change. Rebuilding with no changes keeps the same number, and building cards never changes it.

Playing and swapping

Install the console

Open the console's address on the phone, then:

Once installed, the console and every game work with no connection at all. The console's version shows under the logo (v12). When the phone is online and a newer console has been published, a yellow refresh mark and UPDATE appear next to it: tap them to switch to the new console. Offline you just see the number. On iPhone, the installed app keeps its own library, separate from Safari's, so use the app's scanner rather than the camera app for games you want to keep there.

Scan a game

Tap SCAN GAME and point the camera at a card. Scanning works offline. If the code isn't a DINKY game, the console says NOT A GAME and does nothing else: it never opens a scanned link. The game plays after a short Spectrum-style loading screen and is saved to the library.

The library

The home screen lists your games, most recently played first, with each one's best score (or NEW GAME). Tap one to play it. QR shows its code, X deletes it (with its scores). The library holds up to 200 games.

Share phone to phone

QR in the library (or SHOW QR in the pause menu) puts the game's code on screen. A friend scans it with their DINKY, and now they have the game too. No cards, no internet.

Pause

Tap MENU in the top corner or press Esc. The pause menu has RESUME, SHOW QR and BACK TO GAMES. The game also pauses itself when you switch away from the app.

Credits and licences

The palette and screen size are a tribute to Sinclair's ZX Spectrum.