@vanilla-bean/web-game-framework
v0.2.6
Published
Lightweight framework for building multiplayer web games with Bun and WebSockets
Maintainers
Readme
web-game-framework
Multiplayer web games on Bun and WebSockets: a server that holds each game's state and sends every page its own view of it, the client kits a game's pages are built from, and a lobby. Built on @vanilla-bean/components.

How a game on the framework is written, its kits in a page, and what makes one feel good is GAME_RULES.md, shipped with the package: a game's CLAUDE.md imports it, so it is as current as the version the game pins. This README is the reference.
Contents
- Installation
- A new game
- The server
- The page
- The lobby
- A TV and an open table
- UI
- Hosting: status and builds
- Advanced: EventRouter and broadcasts
- Development
Installation
bun add @vanilla-bean/web-game-framework @vanilla-bean/componentsThe component library is a peer: a game has it at least at the version in the framework's peerDependencies. Bun runs the server; the pages target the last two versions of Chrome, Edge, Firefox and Safari.
A new game
bunx new-game ~/Projects/moon-game --title "Moon Game"
cd ~/Projects/moon-game && bun install && bun run devscaffold/ is a small real-time game, catch the stars, written the way a game on the framework should be: its rules in one file shared by server and page, a Game with a loop, actions and versioned saves, a Play view on a full-screen Stage with createInput and createSound, a watch view, a join card, a test, an icon, and a CLAUDE.md that imports GAME_RULES.md. new-game copies it into an empty folder and fills in its face: --title, --description and --color go into its page title, web manifest, icon and README, which are what a browser, a phone's home screen and web-game-mother-hub's card show; --framework and --vbc set the dependency specs, --name the package name.
Two more commands keep games current:
rename-game "<title>" [folder]gives a game a new title everywhere it shows: its page, manifest, README, CLAUDE.md andpackage.json'swebGame.upgrade-game [folder]brings a game made from an older scaffold up to how a new one is made (the GAME_RULES import, thewebGameentry,--watch, the component library's floor), each only when missing, so it can run on every game at each release.
The server
import { Server, Game, basicGameRoutes, refuse } from '@vanilla-bean/web-game-framework';
class Catch extends Game {
static version = 2; // saves from version 1 are migrated before the constructor reads them
static migrations = { 2: save => (save.state.stars ??= []) };
static transient = ['headings']; // never saved
static events = ['caught']; // what it broadcasts; in development another is said
constructor(options) {
super(options);
this.state = options.saveState?.state ?? { stars: [], headings: {} };
this.every(50, () => this.tick()); // stopped when the game is deleted
}
actions = {
steer(player, { x, y } = {}) {
if (!Number.isFinite(x) || !Number.isFinite(y)) refuse('Steer with a direction');
this.state.headings[player.id] = { x, y };
},
};
viewFor(playerId, { first }) {
return { state: this.savedState(), players: this.toClient().players, watchers: this.watchers };
}
toSaveState() {
return { ...super.toSaveState(), state: this.savedState() };
}
}
const routes = basicGameRoutes();
new Server({
port: 'auto',
Game: Catch,
database: './data/games.json',
router: server => request => routes(request, server),
static: true,
});Actions and views. A page acts with act(name, data); the server runs actions[name](player, data) as the page's player (a page can't claim another) and then publish()es: every page open on the game is sent its own viewFor(playerId, { first }). first is the view a page gets as it opens or comes back after a lost connection, the place for what's too big to send on every change. refuse('why') turns an action down and the page is told why; what an action returns comes back to the page as result.
Time. every(ms, tick) is a loop and after(ms, then) a one-shot delay; both stop when the game is removed, and a removed game broadcasts and publishes nothing.
Who's here. A page announces its game and player; onPresence(id, online) hears the last page of a player close (after Server.LEFT_AFTER_MS, so a reload comes back within it) and people() is who's here. addPlayer(name, { bot: true }) is a computer player, always here and left out of people(). Every view carries watchers, the pages watching without playing, and onWatchers(count) hears it change.
Saves. With a database (a file path), each game is saved soon after a change and no later than Game.SAVE_WITHIN_MS, and written at once on the way out. dataPath('file.json') is where a game keeps a file of its own; a working copy run beside the live one (GAME_DATA, GAME_DATABASE and GAME_BUILD) keeps its files, saves and page apart.
Routes. basicGameRoutes() is GET /games (a game made with private: true only when ?include= names it), GET /games/:id, POST /games, POST /games/:id/join, POST /games/:gameId/:playerId/exit and DELETE /games/:id (deleteOnlyEmpty: true keeps a game someone is in).
The dev console. In development the terminal takes b (build), stop, games, inspect <id>, stats, and the game's own commands (devConsole: (line, server) => ...).
The page
From @vanilla-bean/web-game-framework/client:
| Kit | What it does |
| --- | --- |
| enterGame(gameId, { onState, onUpdate, watch, owner, gone, home }) | Opens a game on the page as this browser's seat (or to watch), with each view the server sends; a gone game forgets the seat and, without gone, says so and goes home; an owner view that's destroyed stops it |
| act(name, data, { quiet }) | Sends an action; resolves to { ok, result } or { ok: false, error }, a refusal shown unless quiet |
| joinAndPlay(gameId, { name, body }) | Joins as this browser's seat or a new player and goes to play |
| seatOf, forgetSeat, seatedGames, lastName | This browser's seat in each game, and the name it joined with last |
| createInput({ keys, onPress }) | The keyboard, on-screen buttons (hold) and the pointer over a play area (pointer), let go when the window loses focus |
| isTouch(), inputBlocked(event) | Whether to show touch controls; whether a key or press belongs to a dialog or a field rather than the game |
| createSound({ effects, music, channels }) | play, loop, playUrl (resolves with how long it plays), music(name, { cut }), hush, volumes and mute kept, nothing lost to the first-tap rule; an effect can be a function given the AudioContext |
| stayFresh({ isBusy }) | Moves a page left open onto the server's newest build, when it loses nothing |
| stayAwake(), nudge({ pattern, color }) | Keeps a phone's screen on; buzzes it and flashes the screen |
| joinUrl(gameId) | The address a phone on the network opens to join (never localhost) |
| paths, href, pathsWith | Every screen's path, and links built from them: href(paths.play, { gameId }) |
The lobby
watchGames(onChange) is the lobby's list without its drawing: it hears loading, each list (kept current as games and players come and go), or a failure with retry, and each game carries seat, this browser's player in it. The private games this browser sits in are listed beside everyone's. randomName() names a player who joins without typing.
The UI draws it two ways: GameTiles (picture first: each game a card with who's in it, play or join with no form, watch, and a bin pressed twice; tile(game) adds a game's own content) and the Hub (a list; tiles: true draws GameTiles instead). Join (quick: true joins with no form) and Create complete it. Import them and pass options; a game whose lobby is its own shape builds it on watchGames and joinAndPlay.
A TV and an open table
watchAll(gameIds, { onState }) watches several games on one page; followGame(pick, { onState, onSwitch }) keeps a TV on the game pick(games) chooses and moves on when it ends. While a page watches, every view's watchers is above 0: a phone can turn into a remote and sound.hush the show.
An open table is one shared state anyone's page changes, with no seats (a library, a scoreboard, a tool):
// shared/ops.js, imported by both sides
export const apply = (state, op) => ({ ...state, [op.who]: (state[op.who] ?? 0) + op.by });
// server.js
new Server({ Game: createTable({ apply, initial: () => ({}) }), table: true, database: './data/games.json' });
// a page
const table = await openTable({ apply, onState: state => draw(state) });
table.change({ who: 'Ana', by: 1 }); // shown at once, sent, taken back if refused, kept if offlineUI
From @vanilla-bean/web-game-framework/ui: Stage (the play area, filling the screen), JoinCard (a QR code and address a phone can open), SoundToggle (icons for a game's own), ExitDialog (beforeExit, endLabel to end the game for everyone), GameTiles, Hub, Join, Create, GameInfoPopover, and the layout View, Toolbar and Body. See ui/README.md.
Hosting: status and builds
Every game answers GET /.well-known/web-game with its status: connections, games and players, uptime and memory, the game's own status metrics, and each listed room with where to watch it. The shape is core/status.js's WebGameStatus, with sampleStatus and isStatus for a watcher's tests. GET /.well-known/web-game-build says which build of its page it serves, for stayFresh. A game's package.json names what a host needs to run it:
"webGame": { "title": "Moon Game", "entry": "server.js", "portVia": "env", "database": "data/games.json" }Advanced: EventRouter and broadcasts
Actions and views cover what most games need. A game that streams changes (a world too big to send whole on every tick) broadcasts them: broadcast(key, data) goes to every page on the game, and the page routes them with createClientEventRouter({ gameId, events }) and router.on(key, handler) (wildcards like 'player:*' match too). Declare the keys once, in static events on the Game and events on the router, and in development a broadcast not declared, or an event no handler hears, is said; router.unhandled() names the declared events nothing handles, for a test to expect none. Such a game puts its whole world in viewFor's first view, which a page is sent again after a lost connection, so what it missed while away is never lost.
Development
bun install
bun test
bun run check:scaffold # a game made from the scaffold installs, tests and builds on this checkoutA push lints, tests, checks the formatting, checks that the component library's peer floor is the one the framework is tested on, and runs the scaffold check. examples/clicker-game is an older example built on broadcasts and the EventRouter.
License
MIT
