boardgame-core/README.md

218 lines
6.8 KiB
Markdown
Raw Normal View History

# boardgame-core
2026-04-01 22:00:10 +08:00
A state management library for board games using [Preact Signals](https://preactjs.com/guide/v10/signals/).
2026-04-02 21:58:11 +08:00
Build turn-based board games with reactive state, entity collections, spatial regions, and a command-driven game loop.
2026-04-01 22:00:10 +08:00
## Features
2026-04-01 22:00:10 +08:00
- **Reactive State Management**: Fine-grained reactivity powered by [@preact/signals-core](https://preactjs.com/guide/v10/signals/)
2026-04-03 10:07:12 +08:00
- **Type Safe**: Full TypeScript support with strict mode and generic context extension
2026-04-01 22:00:10 +08:00
- **Entity Collections**: Signal-backed collections for managing game pieces (cards, dice, tokens, meeples, etc.)
- **Region System**: Spatial management with multi-axis positioning, alignment, and shuffling
2026-04-03 10:07:12 +08:00
- **Command System**: CLI-style command parsing with schema validation, type coercion, and prompt support
2026-04-01 22:00:10 +08:00
- **Deterministic RNG**: Seeded pseudo-random number generator (Mulberry32) for reproducible game states
## Installation
```bash
npm install boardgame-core
```
2026-04-02 21:58:11 +08:00
## Writing a Game
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
### Defining a Game
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
Each game defines its own context type by extending `IGameContext`, creates a command registry, and exports helper functions:
2026-04-01 22:00:10 +08:00
```ts
2026-04-03 10:07:12 +08:00
import { IGameContext, createGameCommand, createGameContext, createCommandRegistry, registerCommand } from 'boardgame-core';
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
// 1. Define your game-specific state
type MyGameState = {
score: number;
round: number;
};
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
// 2. Extend IGameContext with your state
type MyGameContext = IGameContext & {
state: MyGameState;
2026-04-02 21:58:11 +08:00
};
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
// 3. Define typed commands
const addScore = createGameCommand<MyGameContext, number>(
'add-score <amount:number>',
async function(cmd) {
this.context.state.score += cmd.params[0] as number;
return this.context.state.score;
}
);
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
// 4. Create and populate a registry
const registry = createCommandRegistry<MyGameContext>();
registerCommand(registry, addScore);
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
// 5. Export a context factory with initial state
export function createMyGameContext() {
return createGameContext<MyGameContext>(registry, () => ({
state: { score: 0, round: 1 },
}));
}
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
// 6. Export helper functions for your game logic
export function getScore(ctx: MyGameContext) {
return ctx.state.score;
}
2026-04-01 22:00:10 +08:00
```
2026-04-03 10:07:12 +08:00
### Running a Game
2026-04-01 22:00:10 +08:00
```ts
2026-04-03 10:07:12 +08:00
import { createMyGameContext } from './my-game';
2026-04-02 21:58:11 +08:00
2026-04-03 10:07:12 +08:00
const game = createMyGameContext();
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
// Run commands through the context
const result = await game.commands.run('add-score 10');
if (result.success) {
console.log(result.result); // 10
}
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
// Access game state
console.log(game.state.score); // 10
2026-04-01 22:00:10 +08:00
```
2026-04-03 10:07:12 +08:00
## Sample Games
2026-04-02 21:58:11 +08:00
2026-04-03 10:07:12 +08:00
### Tic-Tac-Toe
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
The simplest example. Shows the basic command loop, 2D board regions, and win detection.
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
See [`src/samples/tic-tac-toe.ts`](src/samples/tic-tac-toe.ts).
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
### Boop
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
A more complex game with piece types (kittens/cats), supply management, the "boop" push mechanic, and graduation rules.
2026-04-02 21:58:11 +08:00
2026-04-03 10:07:12 +08:00
// Compact cards in a hand towards the start
applyAlign(handRegion);
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
// Shuffle positions of all parts in a region
shuffle(handRegion, rng);
2026-04-02 21:58:11 +08:00
```
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
### Command Parsing
2026-04-02 21:58:11 +08:00
```ts
2026-04-03 10:07:12 +08:00
import { parseCommand, parseCommandSchema, validateCommand } from 'boardgame-core';
// Parse a command string
const cmd = parseCommand('move card1 hand --force -x 10');
// { name: 'move', params: ['card1', 'hand'], flags: { force: true }, options: { x: '10' } }
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
// Define and validate against a schema
const schema = parseCommandSchema('move <from> <to> [--force] [-x: number]');
const result = validateCommand(cmd, schema);
// { valid: true }
2026-04-01 22:00:10 +08:00
```
2026-04-03 10:07:12 +08:00
### Entity Collections
2026-04-01 22:00:10 +08:00
```ts
2026-04-03 10:07:12 +08:00
import { createEntityCollection } from 'boardgame-core';
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
const collection = createEntityCollection();
collection.add({ id: 'a', name: 'Item A' }, { id: 'b', name: 'Item B' });
2026-04-01 22:00:10 +08:00
2026-04-03 10:07:12 +08:00
const accessor = collection.get('a');
console.log(accessor.value); // reactive access
2026-04-02 21:58:11 +08:00
2026-04-03 10:07:12 +08:00
collection.remove('a');
```
2026-04-02 21:58:11 +08:00
2026-04-03 10:07:12 +08:00
### Random Number Generation
2026-04-02 21:58:11 +08:00
2026-04-03 10:07:12 +08:00
```ts
import { createRNG } from 'boardgame-core';
2026-04-02 21:58:11 +08:00
2026-04-03 10:07:12 +08:00
const rng = createRNG(12345);
rng.nextInt(6); // 0-5
rng.next(); // [0, 1)
rng.next(100); // [0, 100)
rng.setSeed(999); // reseed
```
2026-04-02 21:58:11 +08:00
2026-04-01 22:00:10 +08:00
## API Reference
### Core
| Export | Description |
|---|---|
2026-04-03 10:07:12 +08:00
| `IGameContext` | Base interface for the game context (parts, regions, commands, prompts) |
| `createGameContext<TContext>(registry, initialState?)` | Create a game context instance. `initialState` can be an object or factory function for custom properties |
| `createGameCommand<TContext, TResult>(schema, handler)` | Create a typed command with access to `this.context` |
2026-04-01 22:00:10 +08:00
### Parts
| Export | Description |
|---|---|
2026-04-02 21:58:11 +08:00
| `Part` | Entity type representing a game piece |
| `entity(id, data)` | Create a reactive entity |
2026-04-01 22:00:10 +08:00
| `flip(part)` | Cycle to the next side |
| `flipTo(part, side)` | Set to a specific side |
| `roll(part, rng)` | Randomize side using RNG |
### Regions
| Export | Description |
|---|---|
2026-04-02 21:58:11 +08:00
| `RegionEntity` | Entity type for spatial grouping of parts |
2026-04-01 22:00:10 +08:00
| `RegionAxis` | Axis definition with min/max/align |
| `applyAlign(region)` | Compact parts according to axis alignment |
| `shuffle(region, rng)` | Randomize part positions |
2026-04-02 21:58:11 +08:00
| `moveToRegion(part, targetRegion, position?)` | Move a part to another region |
| `moveToRegionAll(parts, targetRegion, positions?)` | Move multiple parts to another region |
| `removeFromRegion(part)` | Remove a part from its region |
2026-04-01 22:00:10 +08:00
### Commands
| Export | Description |
|---|---|
| `parseCommand(input)` | Parse a command string into a `Command` object |
| `parseCommandSchema(schema)` | Parse a schema string into a `CommandSchema` |
| `validateCommand(cmd, schema)` | Validate a command against a schema |
2026-04-03 10:07:12 +08:00
| `parseCommandWithSchema(cmd, schema)` | Parse and validate in one step |
| `applyCommandSchema(cmd, schema)` | Apply schema validation and return validated command |
| `createCommandRegistry<TContext>()` | Create a new command registry |
| `registerCommand(registry, runner)` | Register a command runner |
| `unregisterCommand(registry, name)` | Remove a command from the registry |
| `hasCommand(registry, name)` | Check if a command exists |
| `getCommand(registry, name)` | Get a command runner by name |
| `runCommand(registry, context, input)` | Parse and run a command string |
| `runCommandParsed(registry, context, command)` | Run a pre-parsed command |
| `createCommandRunnerContext(registry, context)` | Create a command runner context |
| `CommandRunner` | Command runner type with schema and run function |
| `CommandRunnerContext` | Context available inside command handlers |
| `PromptEvent` | Event dispatched when a command prompts for input |
2026-04-01 22:00:10 +08:00
### Utilities
| Export | Description |
|---|---|
| `createEntityCollection<T>()` | Create a reactive entity collection |
| `createRNG(seed?)` | Create a seeded RNG instance |
| `Mulberry32RNG` | Mulberry32 PRNG class |
## Scripts
```bash
npm run build # Build with tsup
npm run test # Run tests in watch mode
npm run test:run # Run tests once
npm run typecheck # Type check with TypeScript
```
## License
MIT