---
name: open-game-console
description: Make a game for the Open Game Console, a Raspberry Pi 4 that plays on a TV with phones as its controllers, and install it on one. Use when making, porting or packing a game for an Open Game Console, writing its game.json, or putting a game on a console.
---

# Make a game for the Open Game Console

The Open Game Console is a Raspberry Pi 4 behind a TV that starts straight into a menu
of games. It ships with no controller: each player's phone is one. A game is a folder
holding a `game.json`, a cover and the game's files, and the menu lists every such
folder in `~/games` on the console.

Work through the six steps in order. The reference after them holds the console's
rules; each step names the parts it needs.

The newest version of this file is published at
https://opengameconsole.org/make-a-game/SKILL.md.

## The console

| | |
|---|---|
| Board | Raspberry Pi 4 with 4 GB, ARM64 (aarch64). 512 MB of it is the graphics memory, shared with everything else |
| System | Raspberry Pi OS Lite, 64-bit, on Debian 13. No desktop and no web browser. The menu and the game run under `cage`, a Wayland compositor, with Xwayland for X11 programs |
| Engine | Godot 4.7.2 for Linux arm64, at `~/godot/godot`. A game's command calls it `$GODOT` |
| Graphics | Mesa's V3D driver: OpenGL ES 3.1, and Vulkan (V3DV) |
| Screen | 1080p, or 720p where the owner chose it |
| Sound | ALSA. Its default device is the output chosen in the menu. No PulseAudio server |
| Libraries | SDL2 (with SDL_mixer and SDL_net), OpenAL, GLU, FluidSynth, and Python 3 with its standard library only |
| Controls | Phones, as gamepads or on a page the game serves; USB and Bluetooth gamepads; a keyboard; the TV's own remote |

The menu quits while a game runs, so the game has the whole machine. When the game
exits, the menu comes back. "Menu" below is the console's system menu: Start on a
gamepad, Esc on a keyboard, or Menu on a phone that is the menu's remote.

## 1. Choose how it is played

`game.json` says how in `input`, a list, and that decides what phones get:

- **`pad`, a game controller.** The easy way, and the one to choose unless the game
  needs more than a gamepad's buttons. The console serves each phone a gamepad, and the
  game sees each as an Xbox 360 controller, up to four. The game needs nothing more for
  phones: no page, no server, no way to quit. Read [Gamepads](#gamepads).
- **A game that reads only keys.** List `["pad", "keyboard"]` and add a `keys` map to
  `game.json`: the phones' gamepad buttons, and a pad plugged in, then press the keys
  the game reads, and the game sees only keys. For a game already made for a keyboard.
  Leave `pad` out and the menu marks the game as needing a keyboard.
- **A game that reads a pad and keys both** lists `["pad", "keyboard"]` with no `keys`
  map: a `keys` map turns the phones' gamepad into a keyboard.
- **`mouse`, a game played with a pointer.** Phones get a touchpad beside the gamepad.
  Of `mouse` and `pad`, the one named first is what phones open on.
- **`phones`, a page of the game's own.** The game serves its own controller page to
  phones on port 8080. Only for a game that needs what a gamepad cannot give: cards in
  a hand, typed words, a drawing, a picture for each player. It is far more work: read
  [A page of its own](#a-page-of-its-own) before choosing it.
- `hands`, the camera, is for games made with the console's motion library, which this
  skill does not cover.

Without `phones` in the list, the console's gamepad has port 8080 while the game runs.

Done when: you hold the `input` list, and for a game that reads only keys, the key each
gamepad button presses.

## 2. Make it

Make it in **Godot 4.7.2**, the console's own engine. A project from an earlier Godot 4
opens in 4.7.2; export it from 4.7.2, so the pack matches the engine that runs it.

- Use the **Compatibility** renderer, and start the game on OpenGL ES (the command in
  step 3). Draw at 960×540 and let Godot scale it up to the TV. In `project.godot`:

  ```ini
  [display]
  window/size/viewport_width=960
  window/size/viewport_height=540
  window/stretch/mode="viewport"

  [rendering]
  renderer/rendering_method="gl_compatibility"
  renderer/rendering_method.mobile="gl_compatibility"
  ```

- For a game that shows a whole 3D world, make the size 640×360 instead, and size its
  words for that: a 3D world costs by the pixel ([Running well on a Pi 4](#running-well-on-a-pi-4)).
- Read the controllers as they come, as [Gamepads](#gamepads) shows.
- Render every letter before the first screen with many words: [Letters](#letters).
- Follow [Running well on a Pi 4](#running-well-on-a-pi-4) and
  [Keep words inside the TV's margin](#keep-words-inside-the-tvs-margin).

Another engine or language works when the result is a program built for Linux on ARM64
(aarch64) that draws through Wayland or X11 with OpenGL ES or Vulkan, plays sound
through ALSA or SDL2, and reads gamepads through SDL2 or evdev. Carry in the game's
folder every library the console lacks, and set `LD_LIBRARY_PATH` in its command. A web
build has no browser to run in.

Play it on your own computer first, with a gamepad, at the size it draws at.

Done when: the game is played from its start to its end and back to its start with
only what `input` names: for `pad`, a gamepad's D-pad, A, B, X, Y, Start and Select,
with no key and no mouse.

## 3. Pack it

The game's folder, as the console holds it:

```
comet-herder/        the game's id: lower-case letters, digits and dashes
  game.json
  cover.png
  game.pck           the Godot project, packed
```

Keep `game.json` and `cover.png` in a `console/` folder in the project, with an empty
`console/.gdignore` so Godot leaves them out of the pack. Add the export preset to
`export_presets.cfg` in the project's folder, numbered after any presets already there
(Godot's editor writes the same from Project, Export, Add, Linux):

```ini
[preset.0]

name="Console"
platform="Linux"
runnable=false
export_filter="all_resources"
include_filter=""
exclude_filter=""
export_path=""

[preset.0.options]

binary_format/embed_pck=false
binary_format/architecture="arm64"
```

A pack needs no export templates. Then, in the project's folder, with your computer's
Godot 4.7.2 as `godot`:

```sh
mkdir -p build/comet-herder && touch build/.gdignore
godot --headless --editor --path . --import --quit
godot --headless --path . --export-pack "Console" build/comet-herder/game.pck
cp console/game.json console/cover.png build/comet-herder/
```

`build/.gdignore` keeps Godot from importing what is built, or packing it into the next
pack. Files that are not Godot resources (a page for phones, a JSON file read with
`FileAccess`) go into the pack only when the preset's `include_filter` names them, such
as `include_filter="pad/*,data/*.json"`.

`console/game.json`, for a Godot game played with gamepads:

```json
{
  "title": "Comet Herder",
  "description": "Steer the comets home before the sun wakes.",
  "info": "1 to 4 players, a phone or a gamepad each",
  "input": ["pad"],
  "command": "$GODOT --display-driver wayland --rendering-method gl_compatibility --rendering-driver opengl3_es --main-pack game.pck"
}
```

Every field is in [game.json](#gamejson). `cover.png` is the label of the game's
cartridge in the menu: the middle square of it is used, so make it square, 512 pixels
a side.

Check the folder:

```sh
python3 - build/comet-herder <<'EOF'
import json, pathlib, re, sys
folder = pathlib.Path(sys.argv[1]).resolve()
wrong = []
if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,62}", folder.name):
    wrong.append(f"the folder's name {folder.name!r} is not an id: lower-case letters, digits and dashes")
try:
    entry = json.loads((folder / "game.json").read_text(encoding="utf-8"))
except (OSError, ValueError) as error:
    sys.exit(f"game.json: {error}")
if not isinstance(entry, dict):
    sys.exit("game.json must hold one object")
if not isinstance(entry.get("title"), str) or not entry["title"]:
    wrong.append("no title")
command = entry.get("command")
if not isinstance(command, str) or not command:
    wrong.append("no command")
    command = ""
ways = entry.get("input")
if not (isinstance(ways, list) and ways and all(w in ("phones", "pad", "mouse", "keyboard", "hands") for w in ways)):
    wrong.append('input must be a list of "phones", "pad", "mouse", "keyboard", "hands"')
    ways = []
if "keyboard" in ways and not {"pad", "mouse", "phones"} & set(ways):
    wrong.append('phones cannot play a game that reads only keys: add "pad" to input, and a keys map')
if entry.get("keys") and "pad" not in ways:
    wrong.append('a game with a keys map lists "pad" in input, or the menu says it needs a keyboard')
buttons = set("a b x y lb rb select start dup ddown dleft dright".split())
keys = set(("esc backspace tab enter ctrl shift alt space up left right down home pageup end pagedown insert delete "
            "minus equal leftbrace rightbrace semicolon apostrophe grave backslash comma dot slash").split())
keys |= set("abcdefghijklmnopqrstuvwxyz0123456789") | {f"f{n}" for n in range(1, 13)}
mapped = entry.get("keys") or {}
if not isinstance(mapped, dict):
    wrong.append("keys must be an object: a gamepad button to a key")
    mapped = {}
for button, key in mapped.items():
    if button not in buttons or not isinstance(key, str) or key not in keys:
        wrong.append(f"keys: {button!r} -> {key!r} is not a gamepad button and a key")
if not (folder / str(entry.get("cover", "cover.png"))).is_file():
    wrong.append("no cover")
for pack in re.findall(r"--main-pack\s+['\"]?([^'\"\s]+)", command):
    if not (folder / pack).is_file():
        wrong.append(f"the command's pack {pack} is not in the folder")
print("\n".join(wrong) or "OK")
EOF
```

Done when: the check prints `OK`.

## 4. Install it

### From a USB stick, on any console

1. On a stick formatted FAT32, exFAT, NTFS or ext4, make a folder named
   `console-games` at its top, and copy the game's folder into it:
   `console-games/comet-herder/game.json`.
2. Plug the stick into the console while the menu shows. The menu says "Found 1 game
   on the USB stick" and warns that a game can do anything on the console: OK goes
   on. Choose the game, and OK installs it. A phone the console does not trust yet is
   first asked for a code shown on the TV.
3. The game is in the menu at once. The console keeps it as `~/games/usb-comet-herder`.

- To install a newer copy, open Menu, then USB stick, with the stick in: the game is
  listed "(installed)", OK removes it, and OK on it again installs the stick's copy.
- A stick holds many games, one folder each in `console-games`.
- FAT32 keeps no file over 4 GB, and gives no file its execute bit: a program copied
  from FAT32 is started with `chmod +x ./comet-herder && exec ./comet-herder` in the
  command. A Godot pack is run by `$GODOT` and needs neither.

### Over SSH, while working on a game

A console has no way in over the network unless it was given one as its card was
written: Raspberry Pi Imager's OS customisation, with the user `pi`, SSH on, and your
public key. Writing a card erases it, so that is for a console being set up, never one
already in use; on a console without a key, install from a USB stick. On the console,
Menu, then SSH, turns the SSH server on and off; that row shows while a keyboard is
plugged into the console. Menu, then About, shows the console's addresses. Its name on
the network is `open-game-console.local`.

```sh
rsync -a --delete build/comet-herder/ pi@open-game-console.local:games/comet-herder/
ssh pi@open-game-console.local 'sudo systemctl restart console'   # the menu reads ~/games as it opens
ssh pi@open-game-console.local 'tail -f ~/console/console.log'    # what the game prints
```

- Both paths end in the game's own folder. `--delete` removes everything in the
  destination that the source lacks: given `games/` alone, it deletes every other
  game on the console.
- `systemctl restart console` restarts the menu's service, not the Pi. It stops any
  game running and plays the menu's opening again; any button skips it.
- A game copied over SSH is `~/games/comet-herder`, and the same game from a stick
  `~/games/usb-comet-herder`: two cartridges in the menu. Remove one.
- Use the console's address in place of `open-game-console.local` if that name does
  not answer.

Done when: the game's cartridge is in the menu, and choosing it starts the game on the
TV.

## 5. Check it on the console

On the TV, with the game started from the menu. Switch the TV on first: a TV that is
off reads as unplugged, and a game then draws one frame a second.

1. Every screen of the game reached once. A game that dies as a screen of many words
   first appears has missed [Letters](#letters).
2. The frame rate read for each screen and each number of players: add `--print-fps`
   to the command, and over SSH run `grep -a "Project FPS" ~/console/console.log`.
3. A round begun, finished and begun again from phones alone.
4. The game left from a phone, and the menu back: Home held for a second on the
   console's gamepad, or the game's own way out for `phones`.
5. Memory steady over a few minutes of play: over SSH, `free -m` read a few minutes
   apart, and the graphics driver's buffers,
   `sudo cat /sys/kernel/debug/dri/fec00000.v3d/bo_stats`, staying in the hundreds or
   low thousands.

- A screenshot costs the game a frame. Judge how even the frames are from a run with
  none.
- For scale, on this board: a 2D Godot game drawn at 960×540 made 60 frames a second
  with one view, about 45 split two ways and 33 to 40 four ways; a 3D world drawn at
  640×360, 27 to 30.

Done when: all five are seen on the console's own TV, and the frame rates are written
down with the game (in its README, if it has one).

## 6. Share it

- **As a folder.** The game's folder is the whole of it. Zip it, and anyone puts it on
  a stick as step 4 says.
- **On itch.io.** Get Games, the console's store, signed in to a player's itch.io
  account, installs any game on that account that has a Linux build: one they bought, or a free one they claimed
  or put in a collection. It is marked Not tested, phones play it as gamepads
  (`"input": ["pad"]`), and a game made with Godot 4.2 or later starts on OpenGL ES.
  Upload an ARM64 Linux build with `arm64` in the file's name, which Get Games picks
  over an x86 build. For Godot that is a full Linux export for `arm64`, which needs
  Godot's export templates. Get Games starts the program itself, with no `game.json`
  of yours, so it runs through Xwayland. An `.itch.toml` beside the program names the
  program to start, if the folder holds more than one.

## Reference

### game.json

| Field | |
|---|---|
| `title` | The game's name, under the row of cartridges, and what a search looks in. |
| `description` | One line. Longer text is cut short. Optional. |
| `info` | One short line under that, for players or controls. Optional. |
| `input` | How the game is played: a list of `phones`, `pad`, `mouse`, `keyboard`, `hands` (step 1). A value outside these gives the game a tile that says so, and it will not start. |
| `command` | Run by `sh` in the game's folder. `$GODOT` is the console's Godot. |
| `keys` | For a game that reads only a keyboard: the key each gamepad button presses, such as `{"a": "z", "b": "x", "dup": "up", "start": "esc"}`. Buttons: `a b x y select start dup ddown dleft dright`, and `lb rb` for a pad plugged in (a phone's gamepad has none). Keys: the letters and digits, `f1` to `f12`, `up down left right enter space esc tab shift ctrl alt backspace home end pageup pagedown insert delete`, and `minus equal comma dot slash semicolon apostrophe grave backslash leftbrace rightbrace`. A phone's gamepad is then a keyboard to the game. Optional. |
| `cover` | The cover's file name, `cover.png` if left out. Any size: the middle square is used. Optional. |

A broken `game.json` still gets a tile in the menu, which says what is wrong with it.

### What the console gives a game

- The command runs in the game's folder, in a process group of its own. When a player
  holds Home, the console stops the whole group: asked first (TERM), then killed three
  seconds later.
- `ALSA_CARD` is the sound output chosen in the menu. Play through ALSA's default
  device, as Godot and SDL2 do, and the sound goes there.
- `CONSOLE_SAFE_AREA` is the TV's margin (below).
- `SDL_GAMECONTROLLERCONFIG` holds the layouts of any pads set up in the menu.
- `DISPLAY` is Xwayland's. A Godot game is started with `--display-driver wayland`,
  or it picks X11.
- What the game prints goes to `~/console/console.log`.
- Godot keeps a game's `user://` files in `~/.local/share/godot/app_userdata/`, which
  outlasts a new copy of the game. A factory reset erases it.

### Gamepads

What a game with `pad` in its `input` is given:

- Each phone is an Xbox 360 controller to the game, up to four. One appears when its
  phone joins, after the game has started, so take controllers as they come and let
  a new player join at any time.
- A controller plugged into the console is there before any phone. A game that gives
  player 1 the first pad it finds gives it to that controller.
- The phone's gamepad has a D-pad, A, B, X, Y, Start and Select. It has no sticks,
  triggers or shoulder buttons. Put every action on those seven, and read a real
  pad's left stick as its D-pad as well.
- Home is the console's: held for a second, it ends the game and brings the menu
  back. A game needs no way out for phones, and one that exits by itself goes back to
  the menu too.
- A phone that drops keeps its controller, with every button let go. The game sees
  nothing unplugged.
- A press reaches the game about 30 ms after it leaves the phone, with the console on
  a cable to the router. On Wi-Fi it is about 60 ms, with stalls.
- Under Start, the phone has a Keyboard, which types into the game as a keyboard, for
  a game that asks for a name. Players can also remap any button to a key or a mouse
  button (Remap, on the phone), kept for that game.

In Godot, a player for each controller as it comes:

```gdscript
var players := {}  # a controller's device number -> its player number, from 0

func _ready() -> void:
	Input.joy_connection_changed.connect(_on_joy)
	for device in Input.get_connected_joypads():
		_on_joy(device, true)

func _on_joy(device: int, connected: bool) -> void:
	if connected and not players.has(device) and players.size() < 4:
		players[device] = players.size()

func _unhandled_input(event: InputEvent) -> void:
	if event is InputEventJoypadButton and event.pressed and players.has(event.device):
		var player: int = players[event.device]
		match event.button_index:
			JOY_BUTTON_A: pass       # the main action
			JOY_BUTTON_START: pass   # pause
			JOY_BUTTON_DPAD_LEFT: pass
```

An Input Map action matches every device, so for more than one player read
`event.device`, or `Input.is_joy_button_pressed(device, JOY_BUTTON_A)` each frame.
Keep the player's number when a controller is lost and comes back.

### Letters

Godot renders a letter the first time it is drawn, then sends that font size's whole
sheet of letters to the graphics card again, and the Pi's driver sets memory aside
each time. A screen that brought a few hundred new letters at once took 20,000 of the
driver's buffers within a second, and the Pi killed the game.

- Before the first screen with many words, render every letter of every font, size and
  outline the game uses. Add a size here whenever a screen uses a new one. Pass each
  `Font` the game draws with: its theme's, or `ThemeDB.fallback_font` for Godot's own.
  32 to 126 are the ASCII letters; add the ranges of any others the game shows.

  ```gdscript
  func warm_letters(font: Font, sizes: Array[int], outline := 0) -> void:
  	var server := TextServerManager.get_primary_interface()
  	for rid in font.get_rids():
  		for size in sizes:
  			server.font_render_range(rid, Vector2i(size, outline), 32, 126)
  ```

- Warmed, the same screen took 700 buffers.
- How it looks when missed: the game dies as a wordy screen first appears, with exit
  code 137, 134 or 1, and `MESA: error: Failed to allocate device memory for BO` in
  the log. A screen with few words survives, which hides it until a lobby or a menu.

### Running well on a Pi 4

- **OpenGL ES, not Vulkan.** Start Godot with `--rendering-method gl_compatibility
  --rendering-driver opengl3_es`. A 3D game on Godot's Vulkan renderer never drew a
  frame: compiling its shaders kept every core busy for over a minute. Another drew
  53 to 57 frames a second on OpenGL ES, with 936 of the driver's buffers, against 43
  to 46 frames and 7,985 buffers on its own Vulkan renderer.
- **Count the pixels.** A pixel costs about the same whatever is drawn in it. Draw at
  960×540 and scale up (step 2). A whole 3D world drew 8 frames a second at 1080p, 25
  at 960×540 and 37 at 640×360.
- **Count the full-screen layers.** A frame with nothing drawn already takes 11 to
  13 ms. On OpenGL ES at 1080p, each full-screen layer (a backdrop, a full-screen
  rectangle, a SubViewport drawn onto the screen) cost about 9 ms more.
- **Draw with rects, lines and textures.** On the Vulkan driver each `draw_circle`,
  `draw_arc`, `draw_colored_polygon` or `draw_polyline` built its own buffer every
  frame, 115 to 343 µs a call, against 1 µs for `draw_rect` or `draw_texture_rect`.
  OpenGL ES was not measured, so keep to the cheap ones there too. Draw a circle as a
  disc texture, an arc or polyline with `draw_line`, and a polygon as triangles with
  `draw_primitive` (three points each; `Geometry2D.triangulate_polygon` cuts one up).
- **Keep loops out of full-screen shaders.** A level lit per pixel from up to 32
  lights drew 15 to 25 frames a second, where the same game's other levels drew 60.
- **In 3D:** turn the depth pre-pass off (`rendering/driver/depth_prepass/enable=false`),
  leave MSAA off, prefer unlit materials with each face's shade in the vertex colours,
  and draw what is in front first: give the material of what is nearest the lowest
  `render_priority` (0), and what is behind it higher numbers. Drawn in that order, a
  row of cartridges took 1.4 ms a frame less than the other way round.
- **Split screen:** one world, and a SubViewport for each pane looking into it through
  its own camera. Put an overlay for one player (a gun in hand, a score) inside that
  pane's SubViewport, not over the whole screen. Show less ground the more panes there
  are: a frame costs about as much as the ground it shows.
- **Say so before a long wait.** Put the words on the TV before the wait begins.
  Work that would stop the game for more than a frame goes on a `Thread`, reading a
  copy of what it needs, and its result is swapped in when ready. In GDScript, several
  threads were no quicker than one.
- **Read big files on a thread.** A 5 MB song read as it was chosen stopped the game
  for a moment and ran the sound dry.
- **Memory:** the 512 MB of graphics memory is shared with the compositor and the
  rest of the system. Textures and the letters' sheets are what fill it.

### Keep words inside the TV's margin

Some TVs cut the edges off the picture. The owner sets a margin in the menu, from 0 to
10% of each side, and the game is told it in `CONSOLE_SAFE_AREA`: a whole number, the
percentage of the screen's width and height to keep clear on each side. Keep words,
scores and controls that far in; backgrounds still fill the screen.

```gdscript
var margin := int(OS.get_environment("CONSOLE_SAFE_AREA")) / 100.0
var screen := get_viewport().get_visible_rect().size
var safe := Rect2(screen * margin, screen * (1.0 - 2.0 * margin))  # lay the HUD out inside this
```

### A page of its own

A game with `phones` in its `input` serves phones its own controller page. No one can
press anything on the TV, so every choice is on a phone: joining, settings, starting,
pausing, playing again, leaving. The TV only shows.

- Serve the page and a WebSocket on one port, **8080**, with the page at `/`. Keep the
  socket off `/remote`, which is the menu's.
- Show the address on the TV as a QR code, with the console's IP address in it, not
  its `.local` name, which some phones cannot look up. Phones install nothing.
- A phone on the menu's remote is told a game is starting, looks at `/` once a second,
  and opens whatever page answers there that is not the remote. So players need not
  scan anything when the game starts.
- Hand the phones back when the game ends. Tell every phone the game is closing, then
  quit a moment later so the word goes out. The page then says so, and looks at `/`
  once a second, loading it when the menu's remote answers: the remote's page carries
  `<meta name="console-remote">`. The page also does this after a couple of seconds
  out of touch with no goodbye, since a game that dies says nothing.
- Write those words in two pieces in the page's own script
  (`'name="console-' + 'remote"'`). The remote opens whatever page at `/` lacks
  `name="console-remote"` anywhere in its text, so a page that holds the words whole
  is taken for the remote and never opened.
- Close from a phone. The console's own way out of a game needs a keyboard, a gamepad
  or the TV's remote, and the game's page has taken the place of the console's gamepad.
- Keep a player's seat when their phone drops. Phones lock and browsers reload: the
  page keeps a token, gets its seat back with it, and the game covers for the player
  meanwhile.
- Send a phone only what it should show, and read its input in the game. The page
  carries no rules.
- Lay the page out for a phone held sideways, and turn it yourself when the phone is
  upright: many phones have rotation locked.
- The page is plain `http`. What a browser gives only to `https` pages is out: tilt
  and motion, keeping the screen awake.
- Before a long wait, send the phones their message, and give the page twenty seconds
  of quiet at those moments before it takes the game for lost.
- In Godot, `WebSocketPeer` cannot share a port with a plain page, so read each request
  on a `TCPServer` yourself: answer a plain `GET` with the page, and answer an
  `Upgrade: websocket` request with the handshake (`Sec-WebSocket-Accept` is the base64
  of the SHA-1 of the key followed by `258EAFA5-E914-47DA-95CA-C5AB0DC85B11`), then
  read and write the frames yourself (RFC 6455: a phone's frames are masked, the
  game's are not). Answer or quietly drop any other request.
- Check the page in Safari as well as Chrome: every iPhone browser is WebKit.

### Not tried yet

- A real USB stick: installing from one was tried only with a folder standing in for
  a stick.
- Raspberry Pi Imager's customisation on the console's card, for SSH.
