Skip to content

Latest commit

 

History

History
165 lines (121 loc) · 17.3 KB

guide.md

File metadata and controls

165 lines (121 loc) · 17.3 KB

Your first co-op browser game

From an empty folder to a game you and a friend play in the same room, using the Amber Game Kit as it is today.

Note

amber new my_game --type game will write all of this for you; it arrives with the generator (card GK6). Until then you start from the kit's sample game.

1. Get the kit at its release commit

Every new game starts from the kit's v0.1.0 release. A tag can be moved, so check out the tag, then check that its commit is the one the v0.1.0 release notes publish on their Commit: line, and stop if it is not: then the block prints STOP and leaves kit_commit empty, and step 2 refuses to run. The commit is written below as kit_commit. Keep this shell open: the later steps use kit_commit.

mkdir my_game
cd my_game
git clone https://github.com/amberframework/amber_game_kit.git ../amber_game_kit
git -C ../amber_game_kit checkout --quiet v0.1.0
kit_commit="$(git -C ../amber_game_kit rev-parse HEAD)"
release_commit="$(curl -fsSL https://api.github.com/repos/amberframework/amber_game_kit/releases/tags/v0.1.0 | /usr/bin/ruby -rjson -e 'puts JSON.parse(STDIN.read)["body"].to_s[/^Commit: (\h{40})\s*$/, 1]')"
if [ -n "$release_commit" ] && [ "$kit_commit" = "$release_commit" ]; then echo "v0.1.0 is $kit_commit, as the release notes publish"; else echo "STOP: v0.1.0 checked out $kit_commit, the release notes publish '$release_commit'"; kit_commit=""; fi

2. Install the pinned toolchain

The kit builds only with the exact tools in toolchain.lock.json: crystal-alpha from crimson-knight/agent-crystal at tap commit e8907f0 (1.22.3-incremental-9), minecart from amberframework/amber_cli at 049471b (2025.11.25.10, revision 6), and the Homebrew libraries both run with. Install them in the order the kit's CI uses, reading each pin from the lock of the commit you checked out:

(
  [ -n "$kit_commit" ] || { echo "STOP: step 1 did not confirm the v0.1.0 commit"; exit 1; }
  cd ../amber_game_kit
  export HOMEBREW_NO_AUTO_UPDATE=1
  read_lock() { /usr/bin/ruby -rjson -e 'puts JSON.parse(File.read("toolchain.lock.json")).dig(*ARGV)' "$@"; }
  pin_tap() { brew tap "$1" && git -C "$(brew --repo "$1")" fetch --quiet origin "$2" && git -C "$(brew --repo "$1")" checkout --quiet --detach "$2"; }
  /usr/bin/ruby tooling/install_homebrew_dependencies.rb
  pin_tap crimson-knight/agent-crystal "$(read_lock crystal_alpha tap_commit)"
  pin_tap amberframework/amber_cli "$(read_lock minecart tap_commit)"
  brew install "$(read_lock crystal_alpha formula)" "$(read_lock minecart formula)"
  /usr/bin/ruby tooling/fetch_wasm_toolchain.rb --chrome
)

install_homebrew_dependencies.rb replaces any other installed version of llvm@21, lld@21, zstd, xz, lz4 or pkgconf with the locked bottle. lld@21 is needed only to cross-build the relay for a Linux server (build_linux_relay.rb, deploy.rb).

3. Start from the sample game, depending on the kit by commit

cp -R ../amber_game_kit/sample_game/. .

You now have a whole game: Crystal rules in src/, the page in web/, an Amber V2 relay in relay/, settings in config/, and playtest steps and a soak bot in tooling/.

The sample game points at the kit by folder. Point both manifests at kit_commit instead, then let minecart write the lockfiles:

(
  [ -n "$kit_commit" ] || { echo "STOP: step 1 did not confirm the v0.1.0 commit; the manifests are left as they are"; exit 1; }
  KIT_COMMIT="$kit_commit" /usr/bin/ruby -i -pe 'sub(%r{^    path: \.\.(/\.\.)?$}, "    github: amberframework/amber_game_kit\n    commit: " + ENV.fetch("KIT_COMMIT"))' shard.yml relay/shard.yml
  rm shard.lock relay/shard.lock
  minecart install
  cd relay && minecart install
)

Both shard.lock files now pin the same kit commit with its checksum. Commit them, and use minecart install --frozen from here on.

4. Build

/usr/bin/ruby lib/amber_game_kit/tooling/build_wasm.rb
/usr/bin/ruby lib/amber_game_kit/tooling/build_web.rb
cd relay
mkdir -p bin
crystal-alpha build src/relay.cr -o bin/relay
cd ..

build_wasm.rb checks the toolchain first and stops on any mismatch; it also refuses a build that lacks the --spill-pointers pass the wasm32 collector needs.

5. Play with a friend

(cd relay && ./bin/relay)

Open http://127.0.0.1:4232/sample_game/. Your page opens a room and becomes its host. Press Invite: the panel shows the room code, the join link and its QR code. Open that link in a second browser window and you have a guest in the same room; press Use or Space on either one and both see the lamp change.

Note

On one computer, two browser windows are the way to play together: each window of one browser is its own player. A friend's phone joins by scanning the QR code once the page and the relay are reachable from that phone over HTTPS, which today means a deployed game (tooling/deploy.rb). Joining from a phone on your own network during development arrives with the amber new --type game generator; tooling/dev_server.rb --phones loads the page on a phone, but the phone cannot open or join a room through it yet.

6. Check it against the budget

/usr/bin/ruby lib/amber_game_kit/tooling/playtest.rb --minutes 3 --runner local --serve --run first
/usr/bin/ruby lib/amber_game_kit/tooling/budget_check.rb build/playtest/first.json

The playtest drives every action kind on the reference phone profile, has a guest join by the invite link, saves and reloads, and drops the relay link; the budget check prints each measure, its value and its budget, and exits 1 on a miss.

7. Make it yours

  • Rules: src/sample_game/world.cr, player_action.cr and room.cr; actions are declared once and the page reads them.
  • Page: web/js/sample_game.js, web/css/, and web/game_config.js for the game id, save keys, bindings and invite text.
  • Relay messages: relay/config/initializers/game_kit.cr. A kind for screens the relay still feeds uses Delivery::ToEveryoneElseTheRelayFeeds; add watcher_delivery: WatcherDelivery::LikeGuests when TVs should get it too.
  • TV screens: a page that sends {"kind":"watch","code":"BCDF"} watches the room as a TV. Its welcome has role watcher, a relay-made id starting tv-, the latest world and its world_order; the host hears watcher_joined and watcher_left. Set how many TVs one room takes with game_limits.max_watchers_per_room (4 by default).
  • Host sends over direct links: web/kit/snapshot_pacer.js (SnapshotPacer decides when the world goes to the relay and to each link, with an isMilestone hook for changes the relay copy must not miss; WorldOrder stamps worlds so a screen drops older ones) and web/kit/position_hub.js (PositionHub gives each link, and the relay, only the positions that changed). The sample game sends on a plain timer and does not use them yet.
  • Party copies: web/kit/party_copy_pacer.js (PartyCopyPacer) keeps the relay's per-room party_copy allowance (one per 30 s, burst 2) on the page, counting each copy as reaching the relay up to 500 ms late, so the relay never drops a copy it sends: ask isCopyDue(now) before an ordinary copy, call copySent(now) after it goes, send a held copy once isCopyWaiting() and isCopyDue agree, send a final copy on pagehide when pagehideMaySpendReserve() answers true, and call tookOverRoom(now) when the page is promoted to host of a room another host was playing in (the relay counts the allowance per room; a second call changes nothing). A host that reopens or rejoins its own room sends at once, and the relay may drop that first copy if the room's allowance was still spent. DeviceSaves#putPartyCopy keeps copies by descent (an older copy or a branch is stored beside the newer one), a joining phone reports the newest of its saves and its party copies, and a reported party copy the host declines becomes an other-branch save.
  • Leaving the page: RelayLink lets go of the room when the browser keeps the page in its back/forward cache, after the page's own pagehide listeners have run (so a final party copy still goes out), and connects again with the page's hello when the page is shown again.
  • Health: a game's health controller answers AmberGameKit::Relay::HealthSummary.of_request(registry, "my_game", request).text, which ends with , seen as ADDRESS, so a check after a deploy proves the proxy passes the visitor's address.
  • Deploy: tooling/deploy.rb --preflight, --dry-run and the deploy itself read the live Caddy site file over ssh and refuse unless every route of the game's path sits inside exactly one # BEGIN amber-game-kit <game> / # END amber-game-kit <game> block (wrap an older hand-written route by hand once, with a backup); after the switch the live wasm is fetched over TLS 1.3 with Ruby's Net::HTTP, so the check works from a Mac.
  • Budget: lower any number in config/performance_budget.json.
  • The name sample_game appears in each of these; grep -rn sample_game --exclude-dir=lib . lists them all.

8. A Mac app from the same rules

The kit carries a native Mac shell: an AppKit window with a Metal renderer, the keyboard and game controllers feeding the game's declared actions, and a device save in the kit's SaveEnvelope format. Apple Silicon, macOS 26.0 or later.

  • Config: config/mac_app.json names everything game-specific: bundle_identifier, display_name, executable_name, crystal_module (the game's top module, e.g. SampleGame), version, build_number, minimum_macos, category, window_scale, frames_per_second; optionally entry_point (default src/<executable_name>_mac.cr), copyright, icon_file, signing_identity and notary_profile.
  • Entry point: src/sample_game_mac.cr requires the rules, require "amber_game_kit/mac", the generated ../build/mac/mac_app_settings, and the game's Mac files in mac/sample_game/ (its draw code through AmberGameKit::Mac::DrawList and its playtest script). The rules entry never requires amber_game_kit/mac, so the wasm build is unchanged.
  • Build: /usr/bin/ruby lib/amber_game_kit/tooling/build_mac_app.rb --unsigned (the kit's sample: ../tooling/build_mac_app.rb --unsigned from sample_game/) writes build/mac/<display_name>.app and build/mac/BUILD_RECEIPT.json (compiler, compiler_keg (the Homebrew keg path, version and compiler sha256, refused unless it is the lock's pkg_version), kit_commit (the kit actually built: its git HEAD in a kit checkout, or the game's pin when the tool runs from lib/amber_game_kit/tooling/) with kit_commit_pinned (the game's shard.lock pin) beside it, the game commit, linked libraries, binary sha256). The tree must be committed, untracked files included, so the receipt names the code that was built. The shim comes from the kit the tool belongs to and the Crystal bindings from the game's lib/amber_game_kit, so the build refuses two different kits: it goes ahead only when they are the same folder, or the same commit with every mac/native/ source and lib_game_shell.cr hashing the same. A kit checkout with uncommitted changes is refused too. With a signing_identity and notary_profile, build_mac_app.rb all also signs, notarizes and staples.
  • Playtest: /usr/bin/ruby lib/amber_game_kit/tooling/mac_playtest.rb "build/mac/<display_name>.app" on a Mac mini (it opens a window), through cluster-pool dispatch. It plays the game's script, records a movie with three stills, relaunches to check the save, and holds the report to tooling/budgets/mac.json through budget_check.rb. Tighten a Mac number in config/mac_performance_budget.json.
  • Crash-fix proof builds (diagnostic, never signed): --release-unplugged-controllers-at-once and --address-sanitizer.

Key bindings, shared by the page and the Mac app

With no bindings file both builds use the kit's defaults: arrows and WASD for an axis2, Up and W for throttle, Left/A and Right/D for any other axis1, Space and Enter for the first button, Escape for menu. To change them, add config/bindings.json, naming keys by KeyboardEvent.code:

{
  "actions": {
    "steer":    { "negative": ["ArrowLeft", "KeyA"], "positive": ["ArrowRight", "KeyD"] },
    "throttle": { "positive": ["ArrowUp", "KeyW"] },
    "move":     { "left": ["KeyJ"], "right": ["KeyL"], "up": ["KeyI"], "down": ["KeyK"] },
    "honk":     { "keys": ["Space", "Enter"] }
  }
}

Each action the file names gets exactly the keys listed; every other action keeps its defaults. Directions: negative/positive for an axis1, left/right/up/down for an axis2, keys for a button.

  • Mac: build_mac_app.rb writes the file into build/mac/mac_app_settings.cr; a key name AmberGameKit::Mac::MacKeyCode does not know stops the compile with the name in the message, and the app refuses an action the game does not declare or a direction its kind lacks.
  • Page: pass the same object to defaultKeyboardBindings(manifest, bindings) from web/kit/input/keyboard.js (for example by fetching config/bindings.json copied beside the page, or by putting the object in web/game_config.js as keyboardBindings); it throws on the same mistakes.

Relay co-op on the Mac

  • Players on one Mac: AmberGameKit::Mac::SeatMacDevices.new(slots, keyboard_player) seats the keyboard as keyboard_player (in a room, pass RoomLink#player_identifier_in_room; alone, the default mac-keyboard) and controller slot n as <keyboard_player>.p<n + 1> (DeviceSeat::PAD_PLAYER_SEPARATOR). A relay player identifier is 1 to 32 of [a-z0-9-], so no phone can claim a pad's identifier; DeviceSeat.played_on_this_mac?(id, keyboard_player) tells a Mac's own players from phones. Saves and room worlds written before the .p<n> scheme name pads mac-pad-N; those players are neither local nor seated now, so their cars are parked on the next welcome.
  • Party copies: RoomLink paces a host's copies with AmberGameKit::Mac::PartyCopyPacer, the Crystal port of web/kit/party_copy_pacer.js: ordinary copies (each party_copy_every_ms, each player joining) keep one copy of the room's allowance in reserve, a held copy goes once the allowance refills, and a promotion to host counts the room's allowance as spent. In the game's will_quit, while hosting, call room_link.send_final_party_copy(now_ms) (it may spend the reserve), then opener.wait_for_sends(500) on the ShellRelaySocketOpener, so the copy is written before the app exits.
  • Deploy route check: when public_url's path differs from base_path (players use /rally/, the relay serves /pocket_rally/), the marker block may map one onto the other: handle_path /rally/* { rewrite * /pocket_rally{path} reverse_proxy 127.0.0.1:<plain_port> }. deploy.rb --preflight and the host script both accept that block, and refuse a public-path route outside it.

Playtesting co-op against a relay on the same Mac

A co-op playtest can run on one Mac mini with no production relay: the game's relay serves its TLS 1.3 listener on loopback with a certificate from the kit's local authority (the one tooling/dev_server.rb makes in ~/.amber_game_kit/dev_certs/), and the Mac app trusts that authority for this run only.

  1. Build the relay (cd relay && minecart install --frozen && mkdir -p bin && crystal-alpha build src/relay.cr -o bin/relay, or whatever config/tooling.json serve_command runs).

  2. From the game's root, start it with its TLS listener on 127.0.0.1:

    /usr/bin/ruby lib/amber_game_kit/tooling/local_tls_relay.rb --tls-port 8443 [--plain-port 4300] [--print-only]
    

    It sets AMBER_TLS_LISTENER_HOST, _PORT, _KEY_FILE and _CERT_FILE (and AMBER_SERVER_PORT with --plain-port) for serve_command, and prints, and writes to build/local_tls_relay/relay.json: relay_url (wss://127.0.0.1:8443/<game>/ws), authority_path, chrome_trusted_spki and mac_app_arguments. Ctrl-C stops the relay; --print-only starts nothing.

  3. Launch the Mac app with --playtest --relay-url wss://127.0.0.1:8443/<game>/ws --relay-trust-anchor ~/.amber_game_kit/dev_certs/authority.crt. ReadRoomLaunchArguments hands the anchor over only with --playtest (relay_trust_anchor_path; without --playtest it lands in refused_relay_trust_anchor and the system trust decides), and the game passes it on: ShellRelaySocketOpener.new(room_arguments.relay_trust_anchor_path). The shim then trusts that authority and nothing else for every handshake (a DER or PEM certificate; host name and dates are still checked; TLS 1.3 stays the floor) and counts refused servers in RelayCounters#server_trust_refusals. Every other run keeps the system trust.

The anchor is honored in signed, notarized builds too, on purpose. The GK8 playtest runs on the exact stapled app that ships, so a playtest-only build would test a different binary. Launch arguments and the anchor file come from someone already running code as the player's user, who can already read the app's saves and tokens, so --playtest --relay-trust-anchor is not a trust boundary; and with an anchor the shim trusts that authority only, so the app refuses every other server. 4. Headless Chrome through tooling/chrome_pipe.rb trusts the same server with AMBER_GAME_KIT_CHROME_TRUSTED_SPKI=<chrome_trusted_spki>.

The kit's own proof: spec/mac/live/relay_socket_smoke.cr connects with --playtest --relay-trust-anchor, negotiates TLS 1.3 and gets no_room, and with --expect-refused (no anchor) checks the handshake is refused.