QR CART programming manual
QR CART is a tiny fantasy games console. Every game (a "tape") 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)
-> base64url
-> https://your-console/#2<payload> (the "2" is the ROM version)
-> QR code on a card
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 tape 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.
- Install the SDK's tools once, from the project folder:
npm install - Start a game. The id is 2 to 20 lowercase letters, numbers or dashes; the title is up to 24 characters.
This createsnpm run qrcart -- new mygame "My Game"games/mygame.js(a small working game to change) andgames/mygame.test.mjs(its tests). - Run the dev console:
Open http://localhost:8080/?dev=mygame (or addnpm run qrcart -- dev mygame--opento the command). Every time you save a file ingames/, 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. - Change something. Colours, text, speed. Save and watch it reload.
- Run the tests:
npm run qrcart -- test mygame - Build the cards:
npm run qrcart -- build --dev--devpoints the codes at your local console (devUrlinqrcart.config.json). The cards are indist/tapes/, and with the dev server running you can see them at http://localhost:8080/tapes/. - 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: alocalhostlink only works on the machine running the dev server.
The machine
Screen
- 256 x 192 pixels, like the ZX Spectrum.
ROM.Wis 256 andROM.His 192. - Every pixel is one of 16 palette colours, given as a number 0 to 15. There are no other colours.
- (0, 0) is the top-left corner. Coordinates are rounded to whole pixels; anything off-screen is clipped.
- You can also colour the border around the screen with
border(c), handy for flashes. It starts blue (1). - The console scales the screen up in whole steps to fit the phone, with crisp pixels.
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.

| # | 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.

- Capitals and digits are 6 pixels tall. Lowercase letters are 4 pixels tall (x-height), and
g j p q yhave 2-pixel descenders, so a lowercase line is 8 pixels tall in all. - Widths vary. Most capitals, digits and lowercase letters are 4 pixels wide.
M T W m w # $ & @are 5,%is 7,I f tand the space are 3,jis 2 andi l ! . : ;are 1. There is a 1-pixel gap between characters. Usetw(text)to measure. - y is the baseline.
txt(s, x, y)puts the bottom row of the capitals ony - 1, so capitals fill rowsy - 6toy - 1and descenders hang into rowsyandy + 1. In the chart, the blue line is rowy. Text aty = 7sits neatly in an 8-pixel bar at the top of the screen. - Scale with
z(rounded to a whole number): every font pixel becomes a z x z block, and the gap grows with it. - Alignment:
align0 (default) centres the text on x, -1 starts it at x, 1 ends it at x (the last pixel is atx - 1). - A few quirks:
$is drawn as a heart, the backtick is blank, and|looks the same asl. Characters outside ASCII 32 to 126 (accents,£, emoji) draw as spaces. - Link-like text is drawn as solid blocks. See Rules and security, below. The
@in the chart can never actually be shown bytxt.
Sound
The console has two sound devices. Games send it short commands; the console does the playing.
- Effects: 20 built-in presets (
sfx('coin')), or your own ZzFX sound as an array of numbers. - Music: three channels (0, 1, 2) that play tunes written in MML, a little music language like the Spectrum 128's
PLAYcommand. Square, triangle and noise waves. - Beeps:
beep(f, d, f2), a square-wave sweep, the cheapest sound in bytes.
There is no sound data in a tape, only commands. The Sound chapter, after the API reference, has the details.
Input
- Touch and mouse: each finger (and the mouse) is tracked separately, so two players can share one screen. Every press and every release calls your handler with the screen position in game pixels (0 to 255, 0 to 191).
- Keys: a key press calls the same handler with
XandYas -1 and the key'scode(for example'Space','ArrowLeft','KeyA','Digit1','Enter','ShiftLeft'). Auto-repeat is ignored: you get one press per real press. ROM.heldis true while any finger, mouse button or key is down.- There are no move events. You learn where a finger went down and where it came up, not where it travelled. Design for taps, holds and screen halves.
- Touching the border (outside the game screen) is the console's, not the game's: holding it for a second opens the pause menu.
Storage
A tape can't store anything except high scores, through hi(key, value). Scores are kept on the phone, per tape. A tape is identified by its exact contents, so changing a single byte of a game makes it a new tape, 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. Four members are not safe to copy out, because they change or because you set them: ROM.t, ROM.held, 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? |
run(step, draw) |
Start the game loop |
ROM.t |
Steps since the tape 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 |
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.
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;
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.
step()is your game logic. It runs exactly 50 times a second, like a PAL Spectrum, whatever the phone's screen rate. Move things, check collisions, count timers here.draw()paints the screen. It runs once per screen refresh, after any steps that were due. On a 60 Hz phone,draw()sometimes runs with no step in between; on a 120 Hz phone it runs more than twice per step. So don't change game state indraw(), or your game will run at different speeds on different phones.- If the phone stalls, the console catches up by at most 5 steps (a tenth of a second) per frame, then lets the game slow down rather than jump.
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 tape 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 tape 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.
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 tape on this phone. The library shows the highest value a tape 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
- Keep tunes short. A 40-note tune costs about 50 bytes. A four-note jingle and a short loop go a long way.
beepis the cheapest sound there is, and with a sweep it covers jumps, hits, coins and falls. Most of the example games use nothing else.- About 30 sounds can start per second; any more are dropped. Don't call
sfxevery step. - Sound can't start until the player has touched the screen or pressed a key (a browser rule). A title screen that waits for a tap solves this for free.
- Pausing freezes sound (music included) and resuming carries on from the same note, so a looping tune started once keeps going across pauses.
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 tape: 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 tape: the title colour in the library and pause menu, and the card's spine and title. |
Titles are usually written in capitals (new does this for you). Avoid | in a title: it is the separator inside the tape.
@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 tape 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 tape can't do
- No network. No
fetch, no web sockets, no images or scripts from anywhere. A tape is all of its game; nothing can be downloaded. - No storage, except
hi(). It can't see the tape library, other tapes' scores or anything else on the phone. - No page. No DOM, no HTML, no links, no forms, no pop-ups, no canvas. The only way to show anything is the ROM's 16-colour framebuffer.
- No links in text. Any
txtstring that looks like a link is drawn as solid blocks, all of it. "Looks like a link" means it contains the wordshttp,wwworftp, an@, a//, or a word followed by a web ending such as.com. It looks for whole words and real web endings (.com,.co.uk,.ly,.io,.ggand similar), so game text likeLIFTPASS,READY...GOorGAME.OVERis left alone. The title gets the same treatment wherever the console shows it. - No CSS colours or fonts. Palette numbers and the ROM font only.
- No
evalornew Function. The tape's code is all the code there is.
How the console enforces it
Each tape 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 tape 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), or an error message. Nothing a tape sends is ever opened, navigated to or shown as HTML.
The tape 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 qrcart -- lint (and dev, build) checks your game before the console ever sees it:
- The header: the first line is
// TITLE: ..., the title is 1 to 24 plain characters, and@tagline,@how,@controlsare present and@colouris 1 to 15. - The code parses.
- No browser globals:
document,window,globalThis,self,localStorage,fetch,navigator,location,eval,Function,Image,Audio,AudioContextand friends (unless you declared a variable with that name yourself). - No canvas drawing (
fillStyle,fillRect,fillText,getContext,drawImageand so on). - No
ROM.somethingthat isn't in ROM v2, including inconst { ... } = ROM. - No CSS colours in strings (
'#ff0','rgb(...)'). This also catches text like'#123', so write'NO. 123'instead. setInterval(not available; usesetTimeout, which counts game frames).
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 tape and shows TAPE STOPPED with a reason when:
| Reason shown | Cause |
|---|---|
| This tape crashed: error | An uncaught error, in your top-level code or in step, draw, press or release. |
| This tape stopped responding and was closed. | One frame took more than 2 seconds (usually an endless loop). |
| This tape could not start. | The top-level code didn't finish within 4 seconds. |
| This tape 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 tape 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 | URL characters | About this much packed game |
|---|---|---|
| Easy to scan (about QR version 32), from paper or a screen | 1900 | 1400 bytes |
| Absolute maximum (QR version 40, low error correction) | 2953 | 2190 bytes |
The whole URL counts, console address included. The game part is base64, so every 3 packed bytes take 4 URL characters. With a console URL of about 23 characters, a game can be about 1400 packed bytes and still scan easily. The example games are 1060 to 1410 bytes.
A shorter console URL leaves more room for games: every character saved in the address is a character 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 │ '27 (125x125)' │ 348 │ 1138 │
- source B: your file, comments and all.
- packed B: what actually goes in the code, after minifying and compressing. This is the number to watch.
- QR version: the size of the code. Up to about 32 scans easily; 40 is the largest there is. The second part is the code's size in modules (squares).
- bytes left (easy scan) and bytes left (max): how many more packed bytes fit before the address reaches 1900 characters (easy scanning) and 2953 (the QR limit). Negative means over.
The dev console's tab title shows the same thing while you work, in the form 1058 B, QR v27, 348 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:
- Write readable code. Names and comments are free. Never squash your source by hand.
- Repetition is cheap. Compression loves repeated patterns: a second call to the same function with similar arguments costs a few bytes. Unique logic, numbers and strings are what cost.
- Property names survive minifying.
obj.velocitykeeps the word "velocity". Short property names (r.x,r.v) or plain variables help. - Text is expensive. Title screens and instructions add up fast. The card's
@howlines are free (they're printed, not packed), so put the instructions there. - Sprites as strings cost their pixels. For simple shapes,
rectcalls or a pattern drawn in a loop may be cheaper. SHOWDOWN packs its cowboy as rectangles in a base-36 string. - Prefer presets and
beepover custom effects, and short tunes over long ones. - Check often. The dev tab title updates on every save, so you see the cost of each change straight away.
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 qrcart -- test mygame, or everything (SDK and all games) with npm run qrcart -- test. Paths are relative to the project folder.
load(file, options)
Loads a game and returns a handle g. Options:
expose: names of your game's own top-level variables and functions. Each becomes a property ofgthat you can read and set (g.score,g.rocks = []). Setting one changes the game's real variable, which is the easiest way to set up a situation.scores: high scores already saved, as{ key: value }, to test what happens with an existing best.
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 |
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.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:
- Test the rules, not the pixels. Exposed variables are more reliable than counting colours.
- Put things where you need them (
g.rocks = [...],g.x = 50) instead of playing until they happen. - If your game uses
Math.random, you can replace it at the top of the test with a seeded one to make runs repeatable (SIGNAL BOX's test does this). games/mygame.test.mjsfromnewis a good template: title, start, controls, game over, restart pause.
Making cards
Build
npm run qrcart -- build # codes point at consoleUrl
npm run qrcart -- build --dev # codes point at devUrl (your machine)
build lints every game (and stops if any fails), then packs each one into dist/:
<id>.svgand<id>.png: the QR code.<id>.url.txt: the full URL inside it.tapes/<id>.html: the cassette inlay card for that game, andtapes/index.html: a rack of all of them.
Screenshots
The inlay shows a screenshot of the game in play. To take them:
npm run qrcart -- build --dev(the screenshots load each game from its--devURL).- In another terminal,
npm run qrcart -- dev. npm run qrcart -- shots. This opens each game in headless Google Chrome (installed in/Applications), plays its@shotscript and savesdist/<id>-shot.png.- Build again (with or without
--dev) so the cards pick the screenshots up.
Open a card from dist/tapes/ 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 qrcart.config.json once you have a domain:
{
"consoleUrl": "https://PLACEHOLDER.example/",
"devUrl": "http://localhost:8080/",
"devPort": 8080
}
- Until
consoleUrlis real,buildprints a warning and its cards won't open anything useful when scanned with a phone's own camera. - Choose it carefully: cards printed with one address keep pointing there. The console's in-app scanner accepts tapes from any address, so old cards still play when scanned from inside QR CART, but a phone camera app follows the address on the card.
- A short address leaves more bytes for games (see Size budget).
devUrlishttp://localhost:8080/by default, which only works on the machine runningdev. To try--devcards on a phone on the same Wi-Fi, setdevUrlto your computer's local address, likehttp://192.168.1.20:8080/(the dev server listens on the whole network). The phone's camera app can open those links; the in-app scanner needs the camera, which browsers only allow on HTTPS or localhost.
Publish the console
npm run qrcart -- site
npx wrangler pages deploy dist/site
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; Cloudflare Pages via wrangler is the one set up here. Build the cards with the final consoleUrl before running site.
Playing and swapping
Install the console
Open the console's address on the phone, then:
- iPhone and iPad: in Safari, Share, then Add to Home Screen.
- Android: in Chrome, the menu, then Install app (or Add to Home screen).
Once installed, the console and every tape work with no connection at all. 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 tapes you want to keep there.
Scan a tape
Tap SCAN TAPE and point the camera at a card. Scanning works offline. If the code isn't a QR CART tape, the console says NOT A TAPE 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 tapes, most recently played first, with each one's best score (or NEW TAPE). Tap one to play it. QR shows its code, X deletes it (with its scores). The library holds up to 200 tapes.
Share phone to phone
QR in the library (or SHOW QR in the pause menu) puts the tape's code on screen. A friend scans it with their QR CART, and now they have the game too. No cards, no internet.
Pause
Tap MENU in the top corner, hold your finger on the border around the game for a second, or press Esc. The pause menu has RESUME, SHOW QR and BACK TO TAPES. The game also pauses itself when you switch away from the app.
Credits and licences
- BM mini A8 pixel font: (c) 2001 BitmapMania / COOZ. The licence is unknown and must be cleared before QR CART is released publicly.
- ZzFX (Zuper Zmall Zound Zynth) by Frank Force: MIT licence. https://github.com/KilledByAPixel/ZzFX
- zxing-wasm by Ze-Zheng Wu (the QR scanner on phones without a built-in one): MIT licence. It's built from zxing-cpp (Apache License 2.0), noted in
console/vendor/LICENSE-zxing-cpp. - qrcode-generator by Kazuhiko Arase (the on-screen share codes): MIT licence.
The palette and screen size are a tribute to Sinclair's ZX Spectrum.