Writing card code by hand
Everything the assistant writes, you can write yourself. This page is for programmers: where the code lives, the editor, and the full reference for multiplayer games. The card's interface API (useYumina()) is in the API reference; building interfaces is in Custom UI in depth.
Where the code is
A card's code is a set of files: .tsx, .ts, .jsx or .js. index.tsx is the entry: its default export is the card's screen. Files import each other with relative paths (import * as game from "./game"). React and useYumina are already there; nothing else is installed.
Open the code from:
- the Code button (
</>) on the Player interface block on the canvas; - a file name in the Multiplayer block (it opens that file);
- the search (
Ctrl+K): type "code"; - on a phone: More → Interface code.
The editor
- Highlighting, line numbers, folding, bracket matching, and autocomplete for
api.(typeapi.room.to see the room's calls). Ctrl+Fsearches and replaces;Ctrl+Z/Ctrl+Yundo and redo.- A compile error is marked at its line; click the red bar under the toolbar to jump there. The badge says OK when the card compiles.
- Import → Import folder or Import files: your own
.tsx/.ts/.jsx/.jsfiles from your computer (dotfiles,node_modulesanddistare skipped; up to 300 files, 1 MB each). It says how many files are new and how many replace one with the same name before anything changes. - Export: the card's code as a
.zip, to work on in your own editor and import back. - Check: on a multiplayer game's file, plays it on Yumina's game server (see below).
- Changes save by themselves. Someone editing with you sees your typing as you type.
Multiplayer: start from a game that works
In the Multiplayer block, choose Custom, then click Turn-based or Realtime → Write it myself. Yumina puts a small whole game into the card, names its file in the settings and opens it:
- Turn-based: Race to 21.
rules.js(the rules, on the server) andindex.tsx(the table). - Realtime: Star Grab.
game.ts(the game, run by the server and every browser) andindex.tsx(the screen).
Both already play with AI seats. Press Test it yourself in the block to play it in two windows side by side, then change it into your game. A card's own index.tsx is never thrown away: it is kept as index-old.tsx.
Which kind? If things keep moving while nobody presses anything (a ball, a car, a bullet), it is realtime. If the game waits for someone to act, it is turn-based. Turn-based can hide things (a hand of cards); realtime cannot, since every browser has the whole state.
Turn-based: the rules file
One plain JavaScript file (rules.js) that Yumina's game server runs in a sandbox for every room. It is the only judge: each seat sees only what view gives it, and AI seats are played on the server.
module.exports = { // or: export default { ... }
minSeats: 2, maxSeats: 4,
setup(seats, opts, rng) { return state; }, // seats: [{ id, name, ai }] in seat order
turn(state) { return { seats: ["<seat id>"], deadlineMs: 30000 }; }, // or null: the game is over
legal(state, seat) { return ["keep", "swap"]; }, // the moves this seat has now
apply(state, seat, action, rng) { return { state, events: [] }; }, // or { error: "bad-move" }
timeout(state, seat, rng) { return "keep"; }, // the move made when time runs out
view(state, seat) { return {}; }, // what this seat may see; seat null = watching
result(state) { return { winners: ["<seat id>"], summary: "..." }; }, // or null while playing
aiPrompt(view, seat) { return "How to play well, in a few lines"; },
// Optional
takeOver: true, // a watcher may take an AI seat
canTake(state, seat, who) { return true; },
onSeat(state, change, rng) { return { state }; }, // someone joined, left, took a seat
onTimer(state, name, payload, rng) { return { state }; },
onAi(state, id, result, rng) { return { state }; }, // the answer to an `ai` request
};Required: minSeats, maxSeats, setup, turn, apply, view. Without timeout, a deadline plays a random move from legal (which must then be a list); without result, the end screen has no winner.
The rules
- Pure: no timers,
fetch, DOM,consoleor clock. State in, state out.stateis plain JSON, under 1 MB. - Random only through
rng(Math.randomis the same seeded stream). - Each call has 250 ms; the file is at most 256 KB.
applyvalidates everything (the seat, the phase, the move's shape): anything can be sent. Refuse with{ error }and leave the state as it was.turn()names who may move: one seat for turn order, several for votes or sealed bids. GivedeadlineMs(1 s to 1 h) whenever a person is on turn. Addclock: "talk-3"to keep one deadline for a whole phase while people keep acting.- Seat ids: a person's id is their player id on this card (
pand 12 letters or digits); AI seats areai-1,ai-2. Never show ids; showname. - Secrets live in
stateand reach a seat only throughview(state, seat).eventswithto: [seat ids]reach only those seats; withoutto, everyone.
What apply (and onSeat, onTimer, onAi) may return: { state, events?, timers?, ai?, notify? } or { error }.
events: [{ to?, name, body }]: one-off happenings for sounds and effects.timers: { tick: 25000, bell: { ms: 5000, payload: {} }, old: null }: server timers, 200 ms to 1 h, at most 16;nullclears one. When due,onTimer(state, name, payload)runs.ai: [{ id, prompt, maxTokens? }]: asks the card's AI for a text (a narrator, a game master). The answer comes toonAi(state, id, { text }), or{ error }(always have a fallback line). The host pays; it counts toward the room's spending limit.notify: [{ seat, kind: "mention", text }]: a notification to a player who is away. "Your turn" goes out by itself.
AI seats. For an AI seat on turn, the server sends the model the seat's view, legal(state, seat) and aiPrompt(view, seat), and expects {"action": <move>}; with a list from legal, the move must be one of its items. A failed move falls back to timeout, then to a random legal move. Keep a seat's view under 24,000 characters. In aiPrompt, say the rules in a few lines, what the view's fields mean, and a good strategy.
The table (index.tsx). The platform has already seated the player; the card draws and acts:
const api = useYumina();
const [table, setTable] = React.useState(null);
React.useEffect(() => api.room.onFrame((f) => {
if (f.t === "snap") setTable(f.body); // the table now
if (f.t === "event") play(f.name, f.body); // events from apply
}), []);
const v = table?.view; // view(state, you)
const myTurn = !!table?.turn?.seats.includes(table.you);
<button disabled={!myTurn} onClick={() => api.room.act("keep")}>Keep</button>table has view, seats ([{ id, name, ai }]), turn ({ seats, deadlineAt }), you and result. api.room.act(move) answers { ok: false, body: { reason } } when apply refused: show the reason. The platform draws the room, AI seats, Start, who won and Play again.
Realtime: the realtime rules file
One file (game.ts) that the server runs 10 to 60 times a second and every player's browser runs a little ahead for that player's own keys. It may import other plain files of the card, nothing from the interface. It must be pure: no DOM, no api, no timers, no Date.now(), nothing remembered outside state.
export const config = { tickRate: 30, smooth: ["x", "y"], angles: ["a"] };
export function setup({ players, options, random }) { return { p: {} }; } // the state: plain JSON
export function step(state, inputs, { dt, tick, random, players, emit }) { // every step: change state
for (const id in state.p) { const inp = inputs[id] || {}; /* move by what they hold */ }
}
export function join(state, player) {} // optional: came in mid-game
export function leave(state, player) {} // optional: left for good
export function result(state) { return null; } // optional: not null ends the game ({ winners, scores })
export function bot(state, id, { tick, random }) { return {}; } // optional: an AI seat's keys nowinputs[id]is what that player sent withrt.input(...): what they hold ({ up: true, fire: true }), at most 1 KB. It is held, not pressed: for "pressed once" compare with the last step (inp.fire && !me.was).- Chance from
random(); time by counting steps (tick;dt= 1 / tickRate). Players:{ id, name, bot? }, idsp1,p2; AI seatsb1,b2. config.tickRate: 10 to 60 (30 by default).smoothnames number fields to draw smoothly (positions),anglesthe same for angles in radians. Give things in lists a lastingid.emit(name, data): a one-off happening for sound and effects; it reachesrt.on("event").bot: the host's browser asks it about 20 times a second for each AI seat; it answers with the same shape asrt.input. Withbotexported, the room offers Add an AI.- Limits: state 64 KB; a step over 60 ms stops the game. Every browser receives the whole state, so nothing can be hidden.
The screen (index.tsx).
import * as game from "./game";
const api = useYumina();
const rt = api.room.realtime("game.ts", game); // the same handle every render; rt.me is your id
rt.input({ up: keys.w, left: keys.a }); // on every change of what is held
function draw() { const s = rt.state(); if (s) paint(s, rt.me); requestAnimationFrame(draw); }
rt.on("event", (name, data) => { /* sounds */ });rt.state() is the game now, your own moves already in it, movement smoothed (null before a game). rt.confirmed() is the server's last word (use it for scores). Also rt.running, rt.players, rt.ping. Listen for keys on window; on phones draw touch buttons that call rt.input too. The platform does the room, start, end screen and rematch, and reconnects a dropped player into the same seat.
Check, then test
- Check (in the editor, on the rules file or the realtime file):
- turn-based: plays 200 random games on the server, from 2 seats up to the most, with some AI seats. It reports errors and where they happened, games that never end, junk moves
applyaccepted (null,7,"x"), and hidden data that shows in another seat's view. - realtime: runs the file for 20 seconds with players pressing keys. It reports what a step costs, the state's size, data per second, whether
step()repeats exactly, and numbers that became NaN.
- turn-based: plays 200 random games on the server, from 2 seats up to the most, with some AI seats. It reports errors and where they happened, games that never end, junk moves
- Test it yourself (the Multiplayer block): the card twice side by side, both seats you. Add an AI seat and play to the end. On a phone the two windows are tabs.
- Then Open a room and play with a friend.
The assistant has the same reference: if you work with your own AI through Connect your AI, have it load the multiplayer skill.
