Compare commits
228
Commits
d1264f3b9e
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ed23295ae | ||
|
|
ca86bfc427 | ||
|
|
09c3fc443b | ||
|
|
a0b2003c65 | ||
|
|
03db1e8a06 | ||
|
|
20993d3b72 | ||
|
|
59391c74d9 | ||
|
|
fb3c98b1ef | ||
|
|
5c1ef232fd | ||
|
|
f5df1c26dc | ||
|
|
2014162819 | ||
|
|
d932c2f5e2 | ||
|
|
1bd49c32e0 | ||
|
|
b009189b9a | ||
|
|
59b99d2042 | ||
|
|
32408c3cee | ||
|
|
23ac09ff21 | ||
|
|
e8c995f74f | ||
|
|
bbab3cc43b | ||
|
|
2e2ddebec4 | ||
|
|
0d7a84edee | ||
|
|
bedde1ef4b | ||
|
|
359e7b7485 | ||
|
|
63e55a828e | ||
|
|
8ec95cbf81 | ||
|
|
f4c96a4a72 | ||
|
|
a5e2e4888e | ||
|
|
38fd46618e | ||
|
|
72647a8268 | ||
|
|
dbbbba14e2 | ||
|
|
888b7b822d | ||
|
|
bb4528cd27 | ||
|
|
877cc9d779 | ||
|
|
2eec668851 | ||
|
|
5235ba7def | ||
|
|
6cb0626f05 | ||
|
|
270b9b744e | ||
|
|
113d240f71 | ||
|
|
0547180074 | ||
|
|
d1605a9ee3 | ||
|
|
093738cd42 | ||
|
|
97ff61985a | ||
|
|
03d367c7b0 | ||
|
|
b509284bc6 | ||
|
|
9b20f7ad6f | ||
|
|
2823089f06 | ||
|
|
f834e15412 | ||
|
|
2ec0e323c4 | ||
|
|
140b7aed86 | ||
|
|
ca9912a5f5 | ||
|
|
34cb828f60 | ||
|
|
974c1a828c | ||
|
|
b83ff28f60 | ||
|
|
0c94e6923a | ||
|
|
d5ec099540 | ||
|
|
52b6cecd64 | ||
|
|
f336a989e2 | ||
|
|
423cc7c841 | ||
|
|
88d31430a6 | ||
|
|
90cb97e0ae | ||
|
|
5e172c61bb | ||
|
|
5019bc6324 | ||
|
|
9bed2ca13e | ||
|
|
08c6a67d16 | ||
|
|
dda8f4cfe9 | ||
|
|
2f2e4e56b5 | ||
|
|
3840c3d739 | ||
|
|
43bb246ab9 | ||
|
|
25b44fd6d1 | ||
|
|
601eb0f417 | ||
|
|
a82b6b0685 | ||
|
|
1e1d04777f | ||
|
|
8142fbfa60 | ||
|
|
89d96d838b | ||
|
|
6b50e9014a | ||
|
|
39ac37b5f2 | ||
|
|
b264cea305 | ||
|
|
6577897a42 | ||
|
|
4e9e426519 | ||
|
|
4f509da373 | ||
|
|
63733bc62d | ||
|
|
3aa92b2d2a | ||
|
|
fa92b5d865 | ||
|
|
e46822b45b | ||
|
|
03add589c6 | ||
|
|
4f5747d81d | ||
|
|
0222b66bed | ||
|
|
90ca8fa761 | ||
|
|
131af2c0bb | ||
|
|
02c159f8ae | ||
|
|
e09e24e274 | ||
|
|
a80852bc59 | ||
|
|
af0906561c | ||
|
|
aedf82d264 | ||
|
|
2f085cc0b6 | ||
|
|
fb66ec55c4 | ||
|
|
8155747cac | ||
|
|
7601a97ec9 | ||
|
|
f775d51a58 | ||
|
|
aa36f3ea67 | ||
|
|
0f04af2c6e | ||
|
|
c11bceeb44 | ||
|
|
1d749f59a6 | ||
|
|
65afe6dc8f | ||
|
|
3a135a4ad1 | ||
|
|
4deebf67c3 | ||
|
|
1c238aec3a | ||
|
|
a469b4024a | ||
|
|
7d8684a16f | ||
|
|
3dc566c2fd | ||
|
|
3f3490fad8 | ||
|
|
5e55b58c43 | ||
|
|
f8c008b67d | ||
|
|
c0fa0e91b2 | ||
|
|
e3014e47a8 | ||
|
|
f7b59a1790 | ||
|
|
b28ec823a7 | ||
|
|
b18e232cc8 | ||
|
|
51da1e5308 | ||
|
|
8c783da857 | ||
|
|
a010a0bca6 | ||
|
|
693c279e0f | ||
|
|
94c7c91745 | ||
|
|
976ee43ed3 | ||
|
|
6984e54bdf | ||
|
|
7b954bb5a5 | ||
|
|
7472095822 | ||
|
|
e5da41c1cb | ||
|
|
509e121275 | ||
|
|
e77e2d0737 | ||
|
|
09148f5b13 | ||
|
|
7e98e5e546 | ||
|
|
33095d5226 | ||
|
|
726856af35 | ||
|
|
630e35ad4e | ||
|
|
5860f2a247 | ||
|
|
8f34104332 | ||
|
|
760cfc9954 | ||
|
|
4fbd65e98c | ||
|
|
204198b10f | ||
|
|
6b724df7e7 | ||
|
|
e35871accd | ||
|
|
ef9557cba7 | ||
|
|
1e5e4e9f7e | ||
|
|
c30db2f8a4 | ||
|
|
5d1dc487f8 | ||
|
|
06a2236a1d | ||
|
|
fe361dc877 | ||
|
|
17dca6303c | ||
|
|
d1aa6dbd32 | ||
|
|
88eeee6ab7 | ||
|
|
2a4383ff10 | ||
|
|
4bfc6db60f | ||
|
|
238254c4e5 | ||
|
|
6281044f14 | ||
|
|
18eae59891 | ||
|
|
6dc85b443e | ||
|
|
d5f65fa6cd | ||
|
|
6ac5ac4b9a | ||
|
|
eb4716200a | ||
|
|
547d378d50 | ||
|
|
330aa43d7b | ||
|
|
cf3123b3f1 | ||
|
|
5849c0a343 | ||
|
|
617057988d | ||
|
|
28e548d3de | ||
|
|
8b271448d2 | ||
|
|
b8e4f73126 | ||
|
|
9d6e7a75f8 | ||
|
|
3d5a484e52 | ||
|
|
244a8bb35a | ||
|
|
cbf6dce237 | ||
|
|
35df1801c5 | ||
|
|
5b310f400d | ||
|
|
98a12b9266 | ||
|
|
91c993b223 | ||
|
|
10393f45b6 | ||
|
|
6b736ab083 | ||
|
|
a5cc584121 | ||
|
|
beb8088009 | ||
|
|
b3cea805b0 | ||
|
|
4cb9f2dbd6 | ||
|
|
a84aa2426b | ||
|
|
83658c9898 | ||
|
|
6352977791 | ||
|
|
6cfb3b6df8 | ||
|
|
fe3bef0a01 | ||
|
|
111d2e69eb | ||
|
|
aa7e99bd0f | ||
|
|
a8774f34bc | ||
|
|
49109963bc | ||
|
|
1e7dbea129 | ||
|
|
b3ff589aa5 | ||
|
|
21b91edc1a | ||
|
|
e673f60657 | ||
|
|
129c58fb08 | ||
|
|
70b1ac1e43 | ||
|
|
2d5200bdb7 | ||
|
|
8c2c6dc94c | ||
|
|
c4290841e5 | ||
|
|
cc7f302677 | ||
|
|
dd73deabb0 | ||
|
|
b929a126a1 | ||
|
|
f5830ea637 | ||
|
|
bd2988902a | ||
|
|
b9105efd03 | ||
|
|
a02403d2c7 | ||
|
|
e58690c9c6 | ||
|
|
28782aaf9b | ||
|
|
b90a4bba52 | ||
|
|
8f86b88c88 | ||
|
|
9e2947a8d6 | ||
|
|
af9254603a | ||
|
|
6e1c42015f | ||
|
|
467a56bd84 | ||
|
|
de7006ef19 | ||
|
|
97ef1df4fb | ||
|
|
d4562b8534 | ||
|
|
80f0796f3c | ||
|
|
775bb00bed | ||
|
|
60a6bcad77 | ||
|
|
a0dd5c94f5 | ||
|
|
25f9992be6 | ||
|
|
d7d484e4d3 | ||
|
|
ceaf4e8ded | ||
|
|
22d40fdc50 | ||
|
|
ae98e0735a | ||
|
|
be4ff7ae08 |
@@ -0,0 +1,175 @@
|
|||||||
|
---
|
||||||
|
name: Create Game Module
|
||||||
|
description: Create a runnable logic module for a board game with 'boardgame-core', '@preact/signals' and 'mutative'
|
||||||
|
---
|
||||||
|
# 如何编写游戏模组
|
||||||
|
|
||||||
|
## 必须导出的接口
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { IGameContext, createGameCommandRegistry } from '@/index';
|
||||||
|
|
||||||
|
export type GameState = { /* 你的状态类型 */ };
|
||||||
|
export type Game = IGameContext<GameState>;
|
||||||
|
|
||||||
|
export function createInitialState(): GameState { /* ... */ }
|
||||||
|
export async function start(game: Game) { /* 游戏主循环 */ }
|
||||||
|
```
|
||||||
|
|
||||||
|
或导出为 `GameModule` 对象:
|
||||||
|
```typescript
|
||||||
|
export const gameModule: GameModule<GameState> = { registry, createInitialState, start };
|
||||||
|
```
|
||||||
|
|
||||||
|
## 流程
|
||||||
|
|
||||||
|
### 0. 确认规则
|
||||||
|
|
||||||
|
在 `rule.md` 中描述:主题、配件、布置形式、游戏流程、玩家行动、胜利条件。
|
||||||
|
|
||||||
|
### 1. 创建类型 (`types.ts`)
|
||||||
|
|
||||||
|
- 使用字符串枚举表示游戏概念(如 `PlayerType = 'X' | 'O'`)
|
||||||
|
- 使用 `Part<TMeta>` 表示配件(棋子、卡牌等)
|
||||||
|
- 使用 `Region` 表示区域(棋盘、牌堆等)
|
||||||
|
- 状态必须可序列化(不支持函数、`Map`、`Set`)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Part, Region } from '@/index';
|
||||||
|
|
||||||
|
export type Piece = Part<{ owner: 'X' | 'O' }>;
|
||||||
|
export type GameState = {
|
||||||
|
board: Region;
|
||||||
|
pieces: Record<string, Piece>;
|
||||||
|
currentPlayer: 'X' | 'O';
|
||||||
|
turn: number;
|
||||||
|
winner: 'X' | 'O' | null;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 创建配件
|
||||||
|
|
||||||
|
少量配件直接在代码创建:
|
||||||
|
```typescript
|
||||||
|
const pieces = createParts({ owner: 'X' }, (i) => `piece-${i}`, 5);
|
||||||
|
```
|
||||||
|
|
||||||
|
大量配件使用 CSV:
|
||||||
|
```csv
|
||||||
|
# parts.csv
|
||||||
|
type,player,count
|
||||||
|
string,string,int
|
||||||
|
kitten,white,8
|
||||||
|
```
|
||||||
|
```typescript
|
||||||
|
import parts from "./parts.csv";
|
||||||
|
const pieces = createPartsFromTable(parts, (item, i) => `${item.type}-${i}`, (item) => item.count);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 创建 Prompts
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export const prompts = {
|
||||||
|
play: createPromptDef<['X' | 'O', number, number]>(
|
||||||
|
'play <player> <row:number> <col:number>',
|
||||||
|
'选择下子位置'
|
||||||
|
),
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Schema 语法:`<param>` 必需,`[param]` 可选,`[param:type]` 带验证。详见 [API 参考](./references/api.md)。
|
||||||
|
|
||||||
|
### 4. 创建游戏流程
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export async function start(game: Game) {
|
||||||
|
while (!game.value.winner) {
|
||||||
|
const { row, col } = await game.prompt(
|
||||||
|
prompts.play,
|
||||||
|
(player, row, col) => {
|
||||||
|
if (player !== game.value.currentPlayer) throw '无效玩家';
|
||||||
|
if (!isValidMove(row, col)) throw '无效位置';
|
||||||
|
if (isCellOccupied(game, row, col)) throw '位置已被占用';
|
||||||
|
return { row, col };
|
||||||
|
},
|
||||||
|
game.value.currentPlayer
|
||||||
|
);
|
||||||
|
|
||||||
|
game.produce((state) => {
|
||||||
|
state.pieces[`p-${row}-${col}`] = { /* ... */ };
|
||||||
|
});
|
||||||
|
|
||||||
|
const winner = checkWinner(game);
|
||||||
|
if (winner) {
|
||||||
|
game.produce((state) => { state.winner = winner; });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
game.produce((state) => {
|
||||||
|
state.currentPlayer = state.currentPlayer === 'X' ? 'O' : 'X';
|
||||||
|
state.turn++;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return game.value;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**注意事项:**
|
||||||
|
- `game.produce(fn)` 同步更新,`game.produceAsync(fn)` 异步更新(等待动画)
|
||||||
|
- 验证器抛出字符串表示失败,返回值表示成功
|
||||||
|
- 玩家取消时 `game.prompt()` 抛出异常
|
||||||
|
- 循环必须有明确退出条件
|
||||||
|
|
||||||
|
### 5. 创建测试
|
||||||
|
|
||||||
|
位于 `tests/samples/<game-name>.test.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { createGameContext } from '@/core/game';
|
||||||
|
import { registry, createInitialState } from './my-game';
|
||||||
|
|
||||||
|
describe('My Game', () => {
|
||||||
|
function createTestContext() {
|
||||||
|
return createGameContext(registry, createInitialState());
|
||||||
|
}
|
||||||
|
|
||||||
|
it('should perform action correctly', async () => {
|
||||||
|
const game = createTestContext();
|
||||||
|
await game.run('play X 0 0');
|
||||||
|
expect(game.value.pieces['p-0-0']).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fail on invalid input', async () => {
|
||||||
|
const game = createTestContext();
|
||||||
|
const result = await game.run('invalid');
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should complete a full game cycle', async () => {
|
||||||
|
// 模拟完整游戏流程,验证胜利条件
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**要求:**
|
||||||
|
- 每种游戏结束条件、玩家行动、边界情况各至少一条测试
|
||||||
|
- 使用 `createGameContext(registry, initialState)` 创建上下文
|
||||||
|
- 使用 `game.run('command')` 执行命令,验证 `game.value` 状态
|
||||||
|
- 测试命名使用 `should...` 格式,异步测试用 `async/await`
|
||||||
|
|
||||||
|
**运行测试:**
|
||||||
|
```bash
|
||||||
|
npm run test:run # 所有测试
|
||||||
|
npx vitest run tests/samples/my-game.test.ts # 特定文件
|
||||||
|
npx vitest run -t "should perform" # 特定用例
|
||||||
|
```
|
||||||
|
|
||||||
|
## 完整示例
|
||||||
|
|
||||||
|
参考 `src/samples/boop/` 和 `src/samples/regicide/`。
|
||||||
|
|
||||||
|
## 相关资源
|
||||||
|
|
||||||
|
- [API 参考](./references/api.md) - 完整 API 文档
|
||||||
|
- [AGENTS.md](../../AGENTS.md) - 项目代码规范
|
||||||
@@ -0,0 +1,759 @@
|
|||||||
|
# API 参考
|
||||||
|
|
||||||
|
本文档记录游戏模组开发者需要使用的公共 API。
|
||||||
|
|
||||||
|
## 核心接口
|
||||||
|
|
||||||
|
### `IGameContext<TState>`
|
||||||
|
|
||||||
|
游戏运行的核心上下文,提供状态访问、随机数、命令执行和提示系统。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface IGameContext<TState extends Record<string, unknown> = {}> {
|
||||||
|
readonly value: TState; // 当前游戏状态(只读)
|
||||||
|
readonly rng: ReadonlyRNG; // 随机数生成器(只读)
|
||||||
|
|
||||||
|
// 状态更新
|
||||||
|
produce(fn: (draft: TState) => void): void; // 同步变更状态(基于 mutative)
|
||||||
|
produceAsync(fn: (draft: TState) => void): Promise<void>; // 异步变更状态(等待中断)
|
||||||
|
|
||||||
|
// 命令执行
|
||||||
|
run<T>(input: string): Promise<CommandResult<T>>; // 执行命令字符串
|
||||||
|
runParsed<T>(command: Command): Promise<CommandResult<T>>; // 执行已解析的命令
|
||||||
|
|
||||||
|
// 提示系统
|
||||||
|
prompt<TResult, TArgs>(
|
||||||
|
def: PromptDef<TArgs>,
|
||||||
|
validator: PromptValidator<TResult, TArgs>,
|
||||||
|
currentPlayer?: string | null
|
||||||
|
): Promise<TResult>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**使用示例:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 读取状态
|
||||||
|
const currentPlayer = game.value.currentPlayer;
|
||||||
|
|
||||||
|
// 同步更新状态
|
||||||
|
game.produce((state) => {
|
||||||
|
state.score += 10;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 异步更新状态(等待动画完成)
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
state.phase = 'next';
|
||||||
|
});
|
||||||
|
|
||||||
|
// 等待玩家输入
|
||||||
|
const result = await game.prompt(
|
||||||
|
prompts.move,
|
||||||
|
(from, to) => {
|
||||||
|
if (!isValidMove(from, to)) {
|
||||||
|
throw '无效移动';
|
||||||
|
}
|
||||||
|
return { from, to };
|
||||||
|
}
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `GameModule<TState, TResult>`
|
||||||
|
|
||||||
|
游戏模块的类型定义,这是开发者创建游戏时需要导出的核心结构。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type GameModule<TState extends Record<string, unknown>, TResult = unknown> = {
|
||||||
|
registry?: CommandRegistry<IGameContext<TState>>; // 可选的命令注册表
|
||||||
|
createInitialState: () => TState; // 创建初始状态
|
||||||
|
start: (ctx: IGameContext<TState>) => Promise<TResult>; // 游戏主循环
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `createGameCommandRegistry<TState>()`
|
||||||
|
|
||||||
|
创建游戏命令注册表,游戏模组用它来注册自定义命令。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function createGameCommandRegistry<TState extends Record<string, unknown> = {}>(): CommandRegistry<IGameContext<TState>>
|
||||||
|
```
|
||||||
|
|
||||||
|
**使用示例:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { createGameCommandRegistry, IGameContext } from '@/index';
|
||||||
|
|
||||||
|
export type GameState = { score: number };
|
||||||
|
export const registry = createGameCommandRegistry<GameState>();
|
||||||
|
|
||||||
|
// 注册命令
|
||||||
|
registry.register('addScore <amount:number>', async function(ctx, amount) {
|
||||||
|
ctx.produce((state) => {
|
||||||
|
state.score += amount;
|
||||||
|
});
|
||||||
|
return { success: true, result: undefined };
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 提示系统
|
||||||
|
|
||||||
|
### `createPromptDef<TArgs>(schema, hintText?)`
|
||||||
|
|
||||||
|
从字符串模式创建 `PromptDef`。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function createPromptDef<TArgs>(
|
||||||
|
schema: CommandSchema | string,
|
||||||
|
hintText?: string
|
||||||
|
): PromptDef<TArgs>
|
||||||
|
```
|
||||||
|
|
||||||
|
**使用示例:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { createPromptDef } from '@/index';
|
||||||
|
|
||||||
|
export const prompts = {
|
||||||
|
// 必需参数
|
||||||
|
play: createPromptDef<[PlayerType, number, number]>(
|
||||||
|
'play <player> <row:number> <col:number>',
|
||||||
|
'选择下子位置'
|
||||||
|
),
|
||||||
|
|
||||||
|
// 可选参数
|
||||||
|
draw: createPromptDef<[number?]>(
|
||||||
|
'draw [count:number]',
|
||||||
|
'抽牌'
|
||||||
|
),
|
||||||
|
|
||||||
|
// 带选项
|
||||||
|
trade: createPromptDef<[string, string]>(
|
||||||
|
'trade <give> <receive> [--force]',
|
||||||
|
'交易'
|
||||||
|
),
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `PromptDef<TArgs>`
|
||||||
|
|
||||||
|
提示定义,用于 `context.prompt()` 方法。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type PromptDef<TArgs extends any[] = any[]> = {
|
||||||
|
schema: CommandSchema; // 命令模式定义
|
||||||
|
hintText?: string; // 可选的提示文本
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `PromptValidator<TResult, TArgs>`
|
||||||
|
|
||||||
|
提示验证函数类型。验证器函数接收解析后的参数,应返回结果或抛出字符串错误。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type PromptValidator<TResult, TArgs extends any[] = any[]> = (...params: TArgs) => TResult;
|
||||||
|
```
|
||||||
|
|
||||||
|
**验证器规则:**
|
||||||
|
- 返回任意值表示验证成功,该值将作为 `prompt()` 的返回值
|
||||||
|
- 抛出字符串错误表示验证失败,错误消息会返回给玩家,玩家可重新输入
|
||||||
|
- 玩家取消输入时,`prompt()` 会抛出异常
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `PromptEvent`
|
||||||
|
|
||||||
|
提示事件对象,通过 `commandRunnerContext.on('prompt', handler)` 监听。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type PromptEvent = {
|
||||||
|
schema: CommandSchema;
|
||||||
|
hintText?: string;
|
||||||
|
currentPlayer: string | null;
|
||||||
|
tryCommit: (commandOrInput: Command | string) => string | null; // null=成功,string=错误消息
|
||||||
|
cancel: (reason?: string) => void;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 零件系统 (Part)
|
||||||
|
|
||||||
|
### `Part<TMeta>`
|
||||||
|
|
||||||
|
游戏中的可操作物件(棋子、卡牌、骰子等)。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type Part<TMeta = {}> = {
|
||||||
|
id: string; // 唯一标识
|
||||||
|
sides?: number; // 总面数(用于骰子/多面牌)
|
||||||
|
side?: number; // 当前面
|
||||||
|
alignments?: string[]; // 可用对齐方式
|
||||||
|
alignment?: string; // 当前对齐方式
|
||||||
|
regionId: string; // 所属区域 ID
|
||||||
|
position: number[]; // 在区域中的位置坐标
|
||||||
|
} & Immutable<TMeta>; // 自定义元数据(不可变)
|
||||||
|
```
|
||||||
|
|
||||||
|
**使用示例:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Part } from '@/index';
|
||||||
|
|
||||||
|
export type PieceMeta = {
|
||||||
|
owner: 'X' | 'O';
|
||||||
|
type: 'pawn' | 'king';
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Piece = Part<PieceMeta>;
|
||||||
|
|
||||||
|
// 访问元数据
|
||||||
|
const piece: Piece = ...;
|
||||||
|
console.log(piece.owner); // 'X'
|
||||||
|
console.log(piece.type); // 'pawn'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 零件操作函数
|
||||||
|
|
||||||
|
#### `flip<TMeta>(part)`
|
||||||
|
|
||||||
|
翻转到下一面(循环)。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function flip<TMeta>(part: Part<TMeta>): void
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `flipTo<TMeta>(part, side)`
|
||||||
|
|
||||||
|
翻转到指定面。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function flipTo<TMeta>(part: Part<TMeta>, side: number): void
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `roll<TMeta>(part, rng)`
|
||||||
|
|
||||||
|
用 RNG 随机掷骰子。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function roll<TMeta>(part: Part<TMeta>, rng: RNG): void
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 零件工厂 (Part Factory)
|
||||||
|
|
||||||
|
### `createParts<T>(item, getId, count?)`
|
||||||
|
|
||||||
|
创建多个相同类型的零件。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function createParts<T>(
|
||||||
|
item: T,
|
||||||
|
getId: (index: number) => string,
|
||||||
|
count?: number
|
||||||
|
): Record<string, Part<T>>
|
||||||
|
```
|
||||||
|
|
||||||
|
**使用示例:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { createParts } from '@/index';
|
||||||
|
|
||||||
|
const pieces = createParts(
|
||||||
|
{ owner: 'X', type: 'pawn' },
|
||||||
|
(i) => `piece-x-${i}`,
|
||||||
|
5 // 创建 5 个
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `createPartsFromTable<T>(items, getId, getCount?)`
|
||||||
|
|
||||||
|
从配置表批量创建零件。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function createPartsFromTable<T>(
|
||||||
|
items: readonly T[],
|
||||||
|
getId: (item: T, index: number) => string,
|
||||||
|
getCount?: ((item: T) => number) | number
|
||||||
|
): Record<string, Part<T>>
|
||||||
|
```
|
||||||
|
|
||||||
|
**使用示例:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { createPartsFromTable } from '@/index';
|
||||||
|
|
||||||
|
const cardTable = [
|
||||||
|
{ name: 'fireball', damage: 3 },
|
||||||
|
{ name: 'shield', defense: 2 },
|
||||||
|
];
|
||||||
|
|
||||||
|
const cards = createPartsFromTable(
|
||||||
|
cardTable,
|
||||||
|
(item) => item.name,
|
||||||
|
(item) => item.name === 'fireball' ? 4 : 2 // 每种卡牌的数量
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 区域系统 (Region)
|
||||||
|
|
||||||
|
### `Region`
|
||||||
|
|
||||||
|
游戏区域(棋盘、手牌区等)。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type Region = {
|
||||||
|
id: string; // 区域 ID
|
||||||
|
axes: RegionAxis[]; // 坐标轴定义
|
||||||
|
childIds: string[]; // 包含的零件 ID 列表
|
||||||
|
partMap: Record<string, string>; // 位置 -> 零件 ID 映射
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `RegionAxis`
|
||||||
|
|
||||||
|
区域的一个坐标轴。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type RegionAxis = {
|
||||||
|
name: string;
|
||||||
|
min?: number;
|
||||||
|
max?: number;
|
||||||
|
align?: 'start' | 'end' | 'center'; // 对齐方式
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `createRegion(id, axes)`
|
||||||
|
|
||||||
|
创建区域。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function createRegion(id: string, axes: RegionAxis[]): Region
|
||||||
|
```
|
||||||
|
|
||||||
|
**使用示例:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { createRegion, createRegionAxis } from '@/index';
|
||||||
|
|
||||||
|
// 创建 3x3 棋盘
|
||||||
|
const board = createRegion('board', [
|
||||||
|
createRegionAxis('row', 0, 2),
|
||||||
|
createRegionAxis('col', 0, 2),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 或简写
|
||||||
|
const board = createRegion('board', [
|
||||||
|
{ name: 'row', min: 0, max: 2 },
|
||||||
|
{ name: 'col', min: 0, max: 2 },
|
||||||
|
]);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `createRegionAxis(name, min?, max?, align?)`
|
||||||
|
|
||||||
|
创建坐标轴。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function createRegionAxis(
|
||||||
|
name: string,
|
||||||
|
min?: number,
|
||||||
|
max?: number,
|
||||||
|
align?: 'start' | 'end' | 'center'
|
||||||
|
): RegionAxis
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 区域操作函数
|
||||||
|
|
||||||
|
#### `applyAlign<TMeta>(region, parts)`
|
||||||
|
|
||||||
|
根据轴的 `align` 配置重新排列零件位置。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function applyAlign<TMeta>(region: Region, parts: Record<string, Part<TMeta>>): void
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `shuffle<TMeta>(region, parts, rng)`
|
||||||
|
|
||||||
|
在区域内随机打乱零件位置。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function shuffle<TMeta>(region: Region, parts: Record<string, Part<TMeta>>, rng: RNG): void
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `moveToRegion<TMeta>(part, sourceRegion, targetRegion, position?)`
|
||||||
|
|
||||||
|
将零件从一个区域移动到另一个区域。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function moveToRegion<TMeta>(
|
||||||
|
part: Part<TMeta>,
|
||||||
|
sourceRegion: Region | null,
|
||||||
|
targetRegion: Region | null,
|
||||||
|
position?: number[]
|
||||||
|
): void
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 命令系统 (Command System)
|
||||||
|
|
||||||
|
### `Command`
|
||||||
|
|
||||||
|
解析后的命令对象。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type Command = {
|
||||||
|
name: string; // 命令名
|
||||||
|
flags: Record<string, true>; // 标志(如 --verbose)
|
||||||
|
options: Record<string, unknown>; // 选项(如 --player X)
|
||||||
|
params: unknown[]; // 位置参数
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `CommandSchema`
|
||||||
|
|
||||||
|
命令模式定义,用于验证和解析。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type CommandSchema = {
|
||||||
|
name: string;
|
||||||
|
params: CommandParamSchema[];
|
||||||
|
options: Record<string, CommandOptionSchema>;
|
||||||
|
flags: Record<string, CommandFlagSchema>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `CommandResult<T>`
|
||||||
|
|
||||||
|
命令执行结果(判别联合类型)。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type CommandResult<T = unknown> =
|
||||||
|
| { success: true; result: T }
|
||||||
|
| { success: false; error: string }
|
||||||
|
```
|
||||||
|
|
||||||
|
**使用示例:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const result = await game.run('move piece1 piece2');
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
console.log('命令执行成功', result.result);
|
||||||
|
} else {
|
||||||
|
console.error('命令执行失败', result.error);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `CommandDef<TContext, TFunc>`
|
||||||
|
|
||||||
|
命令定义对象,用于 `registry.register()`。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type CommandDef<TContext, TFunc extends CommandFunction<TContext>> = {
|
||||||
|
schema: string | CommandSchema;
|
||||||
|
run: TFunc;
|
||||||
|
}
|
||||||
|
|
||||||
|
type CommandFunction<TContext> = (ctx: TContext, ...args: any[]) => Promise<unknown>;
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `CommandRegistry<TContext>`
|
||||||
|
|
||||||
|
命令注册表。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
class CommandRegistry<TContext> extends Map<string, CommandRunner<TContext>> {
|
||||||
|
register<TFunc>(
|
||||||
|
...args: [schema: CommandSchema | string, run: TFunc] | [CommandDef<TContext, TFunc>]
|
||||||
|
): (ctx, ...args) => Promise<TResult>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**注册命令的两种方式:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 方式 1:直接传入 schema 和函数
|
||||||
|
registry.register('move <from> <to>', async function(ctx, from, to) {
|
||||||
|
ctx.produce((state) => { /* 修改状态 */ });
|
||||||
|
return { success: true, result: undefined };
|
||||||
|
});
|
||||||
|
|
||||||
|
// 方式 2:使用 CommandDef 对象
|
||||||
|
registry.register({
|
||||||
|
schema: 'move <from> <to>',
|
||||||
|
run: async function(ctx, from, to) {
|
||||||
|
ctx.produce((state) => { /* 修改状态 */ });
|
||||||
|
return { success: true, result: undefined };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `parseCommand(input, schema?)`
|
||||||
|
|
||||||
|
解析命令字符串为 `Command` 对象。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function parseCommand(input: string, schema?: CommandSchema): Command
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `parseCommandSchema(schemaStr, name?)`
|
||||||
|
|
||||||
|
从字符串模式解析命令模式。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function parseCommandSchema(schemaStr: string, name?: string): CommandSchema
|
||||||
|
```
|
||||||
|
|
||||||
|
**Schema 语法:**
|
||||||
|
- `<param>` - 必需参数
|
||||||
|
- `[param]` - 可选参数
|
||||||
|
- `[param:type]` - 带类型验证的参数(如 `[count:number]`)
|
||||||
|
- `--option:value` - 必需选项
|
||||||
|
- `[-o value]` - 可选选项
|
||||||
|
- `[--flag]` - 可选标志
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 随机数生成器 (RNG)
|
||||||
|
|
||||||
|
### `ReadonlyRNG`
|
||||||
|
|
||||||
|
只读 RNG 接口(`IGameContext.rng` 返回此类型)。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface ReadonlyRNG {
|
||||||
|
next(max?: number): number; // [0,1) 随机数,或 [0,max)
|
||||||
|
nextInt(max: number): number; // [0,max) 随机整数
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `RNG`
|
||||||
|
|
||||||
|
可设置种子的 RNG 接口。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface RNG extends ReadonlyRNG {
|
||||||
|
setSeed(seed: number): void;
|
||||||
|
getSeed(): number;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**使用示例:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 在 IGameContext 中使用
|
||||||
|
const roll = game.rng.nextInt(6) + 1; // 1-6 的随机数
|
||||||
|
|
||||||
|
// 在区域操作中使用时
|
||||||
|
shuffle(region, parts, rng); // 需要传入 RNG
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 可变信号 (MutableSignal)
|
||||||
|
|
||||||
|
### `MutableSignal<T>`
|
||||||
|
|
||||||
|
扩展自 Preact Signal 的可变信号类,支持 mutative-style 的 `produce` 方法。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
class MutableSignal<T> extends Signal<T> {
|
||||||
|
produce(fn: (draft: T) => void): void;
|
||||||
|
addInterruption(promise: Promise<void>): void; // 添加中断 Promise(用于动画等待)
|
||||||
|
clearInterruptions(): void; // 清除所有中断
|
||||||
|
produceAsync(fn: (draft: T) => void): Promise<void>; // 等待中断后更新状态
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `mutableSignal<T>(initial?, options?)`
|
||||||
|
|
||||||
|
创建可变信号。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function mutableSignal<T>(initial?: T, options?: SignalOptions<T>): MutableSignal<T>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 游戏主机 (GameHost)
|
||||||
|
|
||||||
|
### `GameHost<TState, TResult>`
|
||||||
|
|
||||||
|
游戏会话的生命周期管理器。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
class GameHost<TState, TResult> {
|
||||||
|
readonly state: ReadonlySignal<TState>; // 游戏状态(响应式)
|
||||||
|
readonly status: ReadonlySignal<GameHostStatus>; // 运行状态
|
||||||
|
readonly activePromptSchema: ReadonlySignal<CommandSchema | null>; // 当前活动提示的模式
|
||||||
|
readonly activePromptPlayer: ReadonlySignal<string | null>; // 当前等待输入的玩家
|
||||||
|
readonly activePromptHint: ReadonlySignal<string | null>; // 当前提示文本
|
||||||
|
|
||||||
|
tryInput(input: string): string | null; // 尝试提交输入,返回错误信息或 null
|
||||||
|
tryAnswerPrompt<TArgs>(def: PromptDef<TArgs>, ...args: TArgs): void; // 尝试回答提示
|
||||||
|
addInterruption(promise: Promise<void>): void; // 注册中断 Promise(用于动画)
|
||||||
|
clearInterruptions(): void; // 清除所有中断
|
||||||
|
start(seed?: number): Promise<TResult>; // 启动游戏
|
||||||
|
dispose(): void; // 销毁游戏
|
||||||
|
on(event: 'start' | 'dispose', listener: () => void): () => void; // 注册事件监听
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `GameHostStatus`
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type GameHostStatus = 'created' | 'running' | 'disposed';
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `createGameHost<TState>(gameModule)`
|
||||||
|
|
||||||
|
从游戏模块创建 `GameHost` 实例。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function createGameHost<TState extends Record<string, unknown>>(
|
||||||
|
gameModule: GameModule<TState>
|
||||||
|
): GameHost<TState>
|
||||||
|
```
|
||||||
|
|
||||||
|
**使用示例:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { createGameHost } from '@/index';
|
||||||
|
import { gameModule } from './my-game';
|
||||||
|
|
||||||
|
const host = createGameHost(gameModule);
|
||||||
|
|
||||||
|
// 启动游戏
|
||||||
|
const result = await host.start(42); // 传入种子
|
||||||
|
|
||||||
|
// 提交玩家输入
|
||||||
|
const error = host.tryInput('play X 0 0');
|
||||||
|
if (error) {
|
||||||
|
console.error('输入错误:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 监听事件
|
||||||
|
host.on('start', () => console.log('游戏开始'));
|
||||||
|
host.on('dispose', () => console.log('游戏结束'));
|
||||||
|
|
||||||
|
// 销毁游戏
|
||||||
|
host.dispose();
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Preact Signals 重新导出
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export * from '@preact/signals-core';
|
||||||
|
```
|
||||||
|
|
||||||
|
开发者可直接使用 `@preact/signals-core` 的所有导出,包括:
|
||||||
|
- `Signal<T>` - 基础信号类
|
||||||
|
- `ReadonlySignal<T>` - 只读信号类型
|
||||||
|
- `signal<T>(value)` - 创建信号
|
||||||
|
- `computed<T>(fn)` - 创建计算信号
|
||||||
|
- `effect(fn)` - 创建副作用
|
||||||
|
- `batch(fn)` - 批量更新
|
||||||
|
- `untracked(fn)` - 非追踪读取
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 测试辅助函数
|
||||||
|
|
||||||
|
以下函数主要用于测试代码:
|
||||||
|
|
||||||
|
### `createGameContext(options)`
|
||||||
|
|
||||||
|
创建游戏上下文实例。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function createGameContext<TState>(options: {
|
||||||
|
initialState: TState;
|
||||||
|
registry?: CommandRegistry<IGameContext<TState>>;
|
||||||
|
rng?: RNG;
|
||||||
|
}): IGameContext<TState>
|
||||||
|
```
|
||||||
|
|
||||||
|
**使用示例:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { createGameContext } from '@/core/game';
|
||||||
|
import { createInitialState, registry } from './my-game';
|
||||||
|
|
||||||
|
const ctx = createGameContext({
|
||||||
|
initialState: createInitialState(),
|
||||||
|
registry,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 执行命令
|
||||||
|
await ctx.run('move piece1 piece2');
|
||||||
|
|
||||||
|
// 断言状态
|
||||||
|
expect(ctx.value.score).toBe(10);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `createTestContext()`
|
||||||
|
|
||||||
|
创建用于测试的游戏上下文(简化版)。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function createTestContext<TState>(initialState: TState): IGameContext<TState>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### `createTestRegion()`
|
||||||
|
|
||||||
|
创建用于测试的区域。
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function createTestRegion(): Region
|
||||||
|
```
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
!node_modules
|
||||||
@@ -2,92 +2,92 @@
|
|||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
Prefer `bash.exe`(C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps\bash.exe) over Powershell.
|
Shell environment: git bash (bash.exe) on Windows.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run build # Build ESM bundle + declarations to dist/ (via tsup)
|
npm run build # ESM bundle + declarations to dist/ (tsup)
|
||||||
npm run test # Run vitest in watch mode
|
npm run build:samples # Build samples separately (tsup.samples.config.ts)
|
||||||
npm run test:run # Run vitest once (no watch)
|
npm run test # vitest in watch mode
|
||||||
npm run typecheck # Type-check without emitting (tsc --noEmit)
|
npm run test:run # vitest once (no watch)
|
||||||
|
npm run typecheck # tsc --noEmit
|
||||||
```
|
```
|
||||||
|
|
||||||
### Running a single test file
|
Run a single test file: `npx vitest run tests/core/game.test.ts`
|
||||||
```bash
|
Run tests matching a name: `npx vitest run -t "should create"`
|
||||||
npx vitest run tests/samples/tic-tac-toe.test.ts
|
|
||||||
```
|
|
||||||
|
|
||||||
### Running a single test by name
|
`npm run prepare` runs `npm run build` on install — if `inline-schema` isn't available, installs will fail.
|
||||||
```bash
|
|
||||||
npx vitest run -t "should detect horizontal win for X"
|
## Local Dependency
|
||||||
```
|
|
||||||
|
`inline-schema` is a **local peer dependency** at `file:../inline-schema` — must exist as a sibling directory before `npm install`. Both vitest and tsup load custom plugins from it (`inline-schema/csv-loader/rollup` and `inline-schema/csv-loader/esbuild`). `yarn-spinner-loader` is also a local dependency at `file:../yarn-spinner-loader` — it can be changed and published if needed. It provides vitest and tsup/esbuild plugins for `.yarnproject` dialogue files.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
- **MutableSignal\<T\>**: extends Preact Signal — `.value` to read, `.produce(draft => ...)` to mutate (uses `mutative`). `.produceAsync()` awaits interruption promises first, then mutates.
|
||||||
|
- **GameHost**: lifecycle manager — `start(seed?)`, `tryInput(string)`, `tryAnswerPrompt(def, ...args)`, `dispose()`. Reactive signals: `state`, `status`, `activePromptSchema`, `activePromptPlayer`, `activePromptHint`.
|
||||||
|
- **GameModule**: `{ registry?, createInitialState, start }`. `registry` defaults to `createGameCommandRegistry()` if omitted.
|
||||||
|
- **Command system**: CLI-style parsing with schema validation via `inline-schema`. `CommandRunner.run()` uses `this` bound to a `CommandRunnerContext`.
|
||||||
|
- **Prompt system**: `game.prompt(def, validator, currentPlayer?)` — validator **throws a string** to reject, **returns a value** to accept. `PromptEvent.tryCommit(Command | string)` returns `null` on success, error string on failure. `promptEnd` event fires after resolve or cancel.
|
||||||
|
- **Part collections**: `Record<string, Part<TMeta>>` keyed by ID. `Object.values()` for iteration, `Object.keys()` for count/IDs.
|
||||||
|
- **Region system**: `createRegion()` factory; `partMap` maps position keys to part IDs.
|
||||||
|
- **Barrel exports**: `src/index.ts` is the single public API surface.
|
||||||
|
|
||||||
## Project Structure
|
## Project Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
src/
|
src/
|
||||||
core/ # Core game primitives (game, part, region)
|
index.ts # Barrel export (single public API)
|
||||||
samples/ # Example games (tic-tac-toe, boop)
|
core/
|
||||||
utils/ # Shared utilities (mutable-signal, command, rng, async-queue)
|
game.ts # Game core logic
|
||||||
index.ts # Single public API barrel export
|
game-host.ts # GameHost lifecycle manager
|
||||||
tests/ # Mirrors src/ structure with *.test.ts files
|
part.ts # Part entity
|
||||||
|
part-factory.ts # Part factory
|
||||||
|
region.ts # Region/space management
|
||||||
|
utils/
|
||||||
|
mutable-signal.ts # MutableSignal<T> (extends Preact Signal)
|
||||||
|
rng.ts # Mulberry32 seeded PRNG
|
||||||
|
async-queue.ts # Async queue
|
||||||
|
middleware.ts # Middleware chain
|
||||||
|
command/ # CLI-style command system (7 files)
|
||||||
|
types.ts, command-parse.ts, command-registry.ts
|
||||||
|
command-runner.ts, command-validate.ts, command-apply.ts, schema-parse.ts, index.ts
|
||||||
|
samples/
|
||||||
|
tic-tac-toe.ts # Simple sample game
|
||||||
|
boop/ # Boop board game
|
||||||
|
onitama/ # Onitama card game
|
||||||
|
regicide/ # Regicide card game
|
||||||
|
slay-the-spire-like/ # Roguelike deckbuilder (see samples/slay-the-spire-like/AGENTS.md)
|
||||||
|
tests/ # Mirrors src/ with *.test.ts (20 files)
|
||||||
|
core/ # game-host, game, part, part-factory, region
|
||||||
|
samples/ # Each sample + slay-the-spire-like submodules
|
||||||
|
utils/ # mutable-signal, rng, async-queue, middleware, command
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`src/global.d.ts` — `*.yarnproject` module declaration.
|
||||||
|
|
||||||
|
`testsgames/` and `testsrules/` — empty directories (reserved).
|
||||||
|
|
||||||
|
## Samples Build
|
||||||
|
|
||||||
|
`tsup.samples.config.ts` auto-discovers entries from `src/samples/` (directories → `index.ts`, files → direct `.ts`). It rewrites `@/core/*`, `@/utils/*`, and `@/index` imports to external `boardgame-core`.
|
||||||
|
|
||||||
## Code Style
|
## Code Style
|
||||||
|
|
||||||
### Imports
|
- Double quotes for local imports, single quotes for npm packages
|
||||||
- Use **double quotes** for local imports, **single quotes** for npm packages
|
- `@/*` alias maps to `src/*` (configured in tsconfig, vitest, and tsup)
|
||||||
- Use `@/**/*` for `./src/**/*` import alias (configured in tsconfig.json)
|
|
||||||
- Use `@/index` when importing from the public API surface in samples
|
|
||||||
- Group imports: npm packages first, then local `@/` imports, separated by blank line
|
- Group imports: npm packages first, then local `@/` imports, separated by blank line
|
||||||
|
- 4-space indentation, semicolons, trailing commas in multi-line
|
||||||
### Formatting
|
- Arrow functions for callbacks; `function` keyword for methods needing `this` (e.g. command handlers)
|
||||||
- **4-space indentation** (no tabs)
|
- Strict TypeScript — no `any`; type aliases for object shapes (not interfaces)
|
||||||
- **Semicolons** at statement ends
|
- Discriminated unions for results: `{ success: true; result: T } | { success: false; error: string }`
|
||||||
- **Arrow functions** for callbacks; `function` keyword for methods needing `this` (e.g. command handlers)
|
|
||||||
- No trailing whitespace
|
|
||||||
- Trailing commas in multi-line objects/arrays
|
|
||||||
|
|
||||||
### Naming Conventions
|
|
||||||
- **Types/Interfaces**: `PascalCase` — `Part`, `Region`, `Command`, `IGameContext`, `GameHost`
|
|
||||||
- **Classes**: `PascalCase` — `MutableSignal`, `AsyncQueue`, `Mulberry32RNG`, `GameHost`
|
|
||||||
- **Functions**: `camelCase`, verb-first — `createGameContext`, `createGameHost`, `parseCommand`, `isValidMove`
|
|
||||||
- **Variables**: `camelCase`
|
|
||||||
- **Constants**: `UPPER_SNAKE_CASE` — `BOARD_SIZE`, `WINNING_LINES`
|
|
||||||
- **Test files**: `*.test.ts` mirroring `src/` structure under `tests/`
|
|
||||||
- **Factory functions**: prefix with `create` or `mutable` — `createGameContext`, `createGameHost`, `mutableSignal`
|
|
||||||
|
|
||||||
### Types
|
|
||||||
- **Strict TypeScript** is enabled — no `any`
|
|
||||||
- Use **generics** heavily: `MutableSignal<T>`, `CommandRunner<TContext, TResult>`
|
|
||||||
- Use **type aliases** for object shapes (not interfaces)
|
|
||||||
- Use **discriminated unions** for results: `{ success: true; result: T } | { success: false; error: string }`
|
|
||||||
- Use `unknown` for untyped values, narrow with type guards or `as`
|
|
||||||
- Derive state types via `ReturnType<typeof createInitialState>`
|
- Derive state types via `ReturnType<typeof createInitialState>`
|
||||||
|
- Factory function prefix: `create` or `mutable` — `createGameHost`, `mutableSignal`
|
||||||
|
- Validation error messages in Chinese (e.g. `"参数不足"`)
|
||||||
|
|
||||||
### Error Handling
|
## Testing
|
||||||
- Prefer **result objects** over throwing: return `{ success, result/error }`
|
|
||||||
- When catching: `const error = e as Error;` then use `error.message`
|
|
||||||
- Use `throw new Error(...)` only for truly exceptional cases
|
|
||||||
- Validation error messages are in Chinese (e.g. `"参数不足"`)
|
|
||||||
- Prompt validators return `null` for valid input, `string` error message for invalid
|
|
||||||
|
|
||||||
### Testing
|
- Vitest with globals enabled, but **test files import explicitly**: `import { describe, it, expect } from 'vitest'`
|
||||||
- **Vitest** with globals enabled (`describe`, `it`, `expect` available without import)
|
- Use `@/` imports in test files (vitest resolve alias)
|
||||||
- Use `async/await` for async tests
|
- Command/prompt test pattern: `waitForPrompt(ctx)` → `promptEvent.tryCommit(Command)` → returns `null` | error string
|
||||||
- Narrow result types with `if (result.success)` before accessing `result.result`
|
- No mocking — real implementations. Define inline helpers (`createTestContext()`, `waitForPrompt()`) per file.
|
||||||
- Define inline helper functions in test files when needed (e.g. `createTestContext()`)
|
- Narrow result types: `if (result.success)` before accessing `result.result`
|
||||||
- No mocking — use real implementations
|
|
||||||
- For command tests: use `waitForPrompt()` + `promptEvent.tryCommit()` pattern
|
|
||||||
- Test helpers: `createTestContext()`, `createTestRegion()`
|
|
||||||
|
|
||||||
## Architecture Notes
|
|
||||||
|
|
||||||
- **Reactivity**: `MutableSignal<T>` extends Preact Signal — access state via `.value`, mutate via `.produce(draft => ...)`
|
|
||||||
- **Command system**: CLI-style parsing with schema validation via `inline-schema`
|
|
||||||
- **Prompt system**: Commands prompt for input via `PromptEvent` with `resolve`/`reject`; `tryCommit` accepts `Command | string` and validates against schema before custom validator; `promptEnd` event fires when prompt completes (success or cancel)
|
|
||||||
- **GameHost**: Lifecycle manager for game sessions — provides `setup()`, `onInput()`, `dispose()`, reactive `state`/`status`/`activePromptSchema` signals
|
|
||||||
- **Barrel exports**: `src/index.ts` is the single public API surface
|
|
||||||
- **Game modules**: export `registry` and `createInitialState` for use with `createGameContextFromModule` or `createGameHost`
|
|
||||||
- **Region system**: plain `Region` type with `createRegion()` factory; `parts` are stored as `Record<string, Part>` keyed by ID, with `partMap` in regions mapping position keys to part IDs
|
|
||||||
- **Part collections**: Game state uses `Record<string, Part<TMeta>>` (not arrays) for O(1) lookup by ID. Use `Object.values(parts)` when iteration is needed, `Object.keys(parts)` for count/IDs
|
|
||||||
- **Mutative**: used for immutable state updates inside `MutableSignal.produce()`
|
|
||||||
@@ -1,312 +1,51 @@
|
|||||||
# boardgame-core
|
# boardgame-core
|
||||||
|
|
||||||
A state management library for board games using [Preact Signals](https://preactjs.com/guide/v10/signals/).
|
基于 [Preact Signals](https://preactjs.com/guide/v10/signals/) 的桌游状态管理库。
|
||||||
|
|
||||||
Build turn-based board games with reactive state, entity collections, spatial regions, and a command-driven game loop.
|
使用响应式状态、实体集合、空间区域和命令驱动的游戏循环来构建回合制桌游。
|
||||||
|
|
||||||
## Features
|
## 特性
|
||||||
|
|
||||||
- **Reactive State Management**: Fine-grained reactivity powered by [@preact/signals-core](https://preactjs.com/guide/v10/signals/)
|
- **响应式状态管理**:基于 [@preact/signals-core](https://preactjs.com/guide/v10/signals/) 的细粒度响应
|
||||||
- **Type Safe**: Full TypeScript support with strict mode and generic context extension
|
- **类型安全**:完整的 TypeScript 支持,启用严格模式和泛型上下文扩展
|
||||||
- **Region System**: Spatial management with multi-axis positioning, alignment, and shuffling
|
- **区域系统**:支持多轴定位、对齐和洗牌的空间管理
|
||||||
- **Command System**: CLI-style command parsing with schema validation, type coercion, and prompt support
|
- **命令系统**:CLI 风格的命令解析,带 schema 校验、类型转换和玩家输入提示
|
||||||
- **Game Lifecycle Management**: `GameHost` class provides clean setup/reset/dispose lifecycle for game sessions
|
- **游戏生命周期管理**:`GameHost` 类提供清晰的游戏设置/重置/销毁生命周期
|
||||||
- **Deterministic RNG**: Seeded pseudo-random number generator (Mulberry32) for reproducible game states
|
- **确定性 RNG**:Mulberry32 种子伪随机数生成器,用于可复现的游戏状态
|
||||||
|
|
||||||
## Installation
|
## 快速开始
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install boardgame-core
|
npm install boardgame-core
|
||||||
```
|
```
|
||||||
|
|
||||||
## Writing a Game
|
|
||||||
|
|
||||||
### Defining a Game
|
|
||||||
|
|
||||||
Each game defines a command registry and exports a `createInitialState` function:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import {
|
|
||||||
createGameCommandRegistry,
|
|
||||||
Region,
|
|
||||||
createRegion,
|
|
||||||
} from 'boardgame-core';
|
|
||||||
|
|
||||||
// 1. Define your game-specific state
|
|
||||||
type MyGameState = {
|
|
||||||
board: Region;
|
|
||||||
parts: Record<string, { id: string; regionId: string; position: number[] }>;
|
|
||||||
score: { white: number; black: number };
|
|
||||||
currentPlayer: 'white' | 'black';
|
|
||||||
winner: 'white' | 'black' | 'draw' | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
// 2. Create initial state factory
|
|
||||||
export function createInitialState(): MyGameState {
|
|
||||||
return {
|
|
||||||
board: createRegion('board', [
|
|
||||||
{ name: 'x', min: 0, max: 5 },
|
|
||||||
{ name: 'y', min: 0, max: 5 },
|
|
||||||
]),
|
|
||||||
parts: {},
|
|
||||||
score: { white: 0, black: 0 },
|
|
||||||
currentPlayer: 'white',
|
|
||||||
winner: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Create registry and register commands
|
|
||||||
const registration = createGameCommandRegistry<MyGameState>();
|
|
||||||
export const registry = registration.registry;
|
|
||||||
|
|
||||||
registration.add('place <row:number> <col:number>', async function(cmd) {
|
|
||||||
const [row, col] = cmd.params as [number, number];
|
|
||||||
const player = this.context.value.currentPlayer;
|
|
||||||
|
|
||||||
// Mutate state via produce()
|
|
||||||
this.context.produce(state => {
|
|
||||||
state.score[player] += 1;
|
|
||||||
});
|
|
||||||
|
|
||||||
return { success: true };
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Running a Game
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import { createGameContext } from 'boardgame-core';
|
|
||||||
import { registry, createInitialState } from './my-game';
|
|
||||||
|
|
||||||
const game = createGameContext(registry, createInitialState);
|
|
||||||
|
|
||||||
// Run commands through the context
|
|
||||||
const result = await game.commands.run('place 2 3');
|
|
||||||
if (result.success) {
|
|
||||||
console.log(result.result);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Access reactive game state
|
|
||||||
console.log(game.state.value.score.white);
|
|
||||||
```
|
|
||||||
|
|
||||||
### Handling Player Input
|
|
||||||
|
|
||||||
Commands can prompt for player input using `this.prompt()`. Use `promptQueue.pop()` to wait for prompt events:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import { createGameContext } from 'boardgame-core';
|
|
||||||
import { registry, createInitialState } from './my-game';
|
|
||||||
|
|
||||||
const game = createGameContext(registry, createInitialState);
|
|
||||||
|
|
||||||
// Start a command that will prompt for input
|
|
||||||
const runPromise = game.commands.run('turn X 1');
|
|
||||||
|
|
||||||
// Wait for the prompt event
|
|
||||||
const promptEvent = await game.commands.promptQueue.pop();
|
|
||||||
console.log(promptEvent.schema.name); // e.g. 'play'
|
|
||||||
|
|
||||||
// Validate and submit player input
|
|
||||||
const error = promptEvent.tryCommit('play X 1 2');
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
console.log('Invalid move:', error);
|
|
||||||
// tryCommit can be called again with corrected input
|
|
||||||
} else {
|
|
||||||
// Input accepted, command continues
|
|
||||||
const result = await runPromise;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
If the player needs to cancel instead of committing:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
promptEvent.cancel('player quit');
|
|
||||||
```
|
|
||||||
|
|
||||||
### Managing Game Lifecycle with GameHost
|
|
||||||
|
|
||||||
For a cleaner game lifecycle (setup, reset, dispose), use `GameHost`:
|
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import { createGameHost } from 'boardgame-core';
|
import { createGameHost } from 'boardgame-core';
|
||||||
import { registry, createInitialState } from './my-game';
|
import * as tictactoe from 'boardgame-core/samples/tic-tac-toe';
|
||||||
|
|
||||||
// Create a game host with a setup command
|
const host = createGameHost(tictactoe);
|
||||||
const host = createGameHost(
|
await host.start('start');
|
||||||
{ registry, createInitialState },
|
|
||||||
'setup' // command to run when setting up/resetting the game
|
|
||||||
);
|
|
||||||
|
|
||||||
// Reactive state — use in effects or computed values
|
// 监听状态变化
|
||||||
console.log(host.state.value.currentPlayer);
|
effect(() => {
|
||||||
console.log(host.status.value); // 'created' | 'running' | 'disposed'
|
const state = host.state.value;
|
||||||
|
console.log(`${state.currentPlayer}'s turn`);
|
||||||
|
});
|
||||||
|
|
||||||
// Check if a prompt is active and what schema it expects
|
// 处理玩家输入
|
||||||
const schema = host.activePromptSchema.value;
|
|
||||||
if (schema) {
|
|
||||||
console.log('Waiting for:', schema.name, schema.params);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Submit player input to the active prompt
|
|
||||||
const error = host.onInput('play X 1 2');
|
const error = host.onInput('play X 1 2');
|
||||||
if (error) {
|
|
||||||
console.log('Invalid move:', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reset the game (cancels active prompt, resets state, runs setup)
|
|
||||||
await host.setup('setup');
|
|
||||||
|
|
||||||
// Dispose when done (cleans up listeners, cancels active prompts)
|
|
||||||
host.dispose();
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The `GameHost` provides:
|
## 文档导航
|
||||||
- **`state`**: `ReadonlySignal<TState>` — reactive game state
|
|
||||||
- **`status`**: `ReadonlySignal<'created' | 'running' | 'disposed'>` — lifecycle status
|
|
||||||
- **`activePromptSchema`**: `ReadonlySignal<CommandSchema | null>` — reactive current prompt schema
|
|
||||||
- **`onInput(input)`**: Submit input to active prompt, returns error or null
|
|
||||||
- **`setup(command)`**: Reset and reinitialize the game
|
|
||||||
- **`dispose()`**: Clean up all resources
|
|
||||||
- **`on(event, listener)`**: Listen to `'setup'` or `'dispose'` events
|
|
||||||
|
|
||||||
## Sample Games
|
| 文档 | 说明 |
|
||||||
|
|
||||||
### Tic-Tac-Toe
|
|
||||||
|
|
||||||
The simplest example. Shows the basic command loop, 2D board regions, and win detection.
|
|
||||||
|
|
||||||
See [`src/samples/tic-tac-toe.ts`](src/samples/tic-tac-toe.ts).
|
|
||||||
|
|
||||||
### Boop
|
|
||||||
|
|
||||||
A more complex game with piece types (kittens/cats), supply management, the "boop" push mechanic, and graduation rules.
|
|
||||||
|
|
||||||
See [`src/samples/boop/index.ts`](src/samples/boop/index.ts).
|
|
||||||
|
|
||||||
## Region System
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import { applyAlign, shuffle, moveToRegion } from 'boardgame-core';
|
|
||||||
|
|
||||||
// Compact cards in a hand towards the start
|
|
||||||
applyAlign(handRegion, parts);
|
|
||||||
|
|
||||||
// Shuffle positions of all parts in a region
|
|
||||||
shuffle(handRegion, parts, rng);
|
|
||||||
|
|
||||||
// Move a part from one region to another
|
|
||||||
moveToRegion(part, sourceRegion, targetRegion, [0, 0]);
|
|
||||||
```
|
|
||||||
|
|
||||||
## Command Parsing
|
|
||||||
|
|
||||||
```ts
|
|
||||||
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' } }
|
|
||||||
|
|
||||||
// Define and validate against a schema
|
|
||||||
const schema = parseCommandSchema('move <from> <to> [--force] [-x: number]');
|
|
||||||
const result = validateCommand(cmd, schema);
|
|
||||||
// { valid: true }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Random Number Generation
|
|
||||||
|
|
||||||
```ts
|
|
||||||
import { createRNG } from 'boardgame-core';
|
|
||||||
|
|
||||||
const rng = createRNG(12345);
|
|
||||||
rng.nextInt(6); // 0-5
|
|
||||||
rng.next(); // [0, 1)
|
|
||||||
rng.next(100); // [0, 100)
|
|
||||||
rng.setSeed(999); // reseed
|
|
||||||
```
|
|
||||||
|
|
||||||
## API Reference
|
|
||||||
|
|
||||||
### Core
|
|
||||||
|
|
||||||
| Export | Description |
|
|
||||||
|---|---|
|
|---|---|
|
||||||
| `IGameContext` | Base interface for the game context (state, commands) |
|
| [使用 GameHost](docs/game-host.md) | GameHost 生命周期、响应式状态、事件处理 |
|
||||||
| `createGameContext(registry, initialState?)` | Create a game context instance. `initialState` can be an object or factory function |
|
| [编写 GameModule](docs/game-module.md) | 定义状态、注册命令、prompt 系统、Part/Region 使用 |
|
||||||
| `createGameCommandRegistry<TState>()` | Create a command registry with fluent `.add()` API |
|
| [棋子、区域与 RNG](docs/parts-regions-rng.md) | Part 创建、池管理、区域操作、RNG 使用 |
|
||||||
| `GameHost<TState>` | Game lifecycle manager class with setup/reset/dispose |
|
| [动画与状态同步](docs/animation-sync.md) | produceAsync 和中断机制 |
|
||||||
| `createGameHost(module, setupCommand, options?)` | Create a GameHost instance from a game module |
|
| [API 参考](docs/api-reference.md) | 所有导出 API 的完整列表 |
|
||||||
| `GameHostStatus` | Type: `'created' \| 'running' \| 'disposed'` |
|
| [开发指南](docs/development.md) | 安装、构建脚本、测试命令 |
|
||||||
| `GameHostOptions` | Options: `{ autoStart?: boolean }` |
|
|
||||||
|
|
||||||
### Parts
|
|
||||||
|
|
||||||
| Export | Description |
|
|
||||||
|---|---|
|
|
||||||
| `Part<TMeta>` | Type representing a game piece with sides, position, and region. `TMeta` for game-specific fields |
|
|
||||||
| `PartTemplate<TMeta>` | Template type for creating parts (excludes `id`, requires metadata) |
|
|
||||||
| `PartPool<TMeta>` | Pool of parts with `draw()`, `return()`, and `remaining()` methods. `parts` field is `Record<string, Part>` |
|
|
||||||
| `createPart(template, id)` | Create a single part from a template |
|
|
||||||
| `createParts(template, count, idPrefix)` | Create multiple identical parts with auto-generated IDs |
|
|
||||||
| `createPartPool(template, count, idPrefix)` | Create a pool of parts for lazy loading |
|
|
||||||
| `mergePartPools(...pools)` | Merge multiple part pools into one |
|
|
||||||
| `findPartById(parts, id)` | Find a part by ID in a Record |
|
|
||||||
| `isCellOccupied(parts, regionId, position)` | Check if a cell is occupied |
|
|
||||||
| `getPartAtPosition(parts, regionId, position)` | Get the part at a specific position |
|
|
||||||
| `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 |
|
|
||||||
|---|---|
|
|
||||||
| `Region` | Type for spatial grouping of parts with axis-based positioning |
|
|
||||||
| `RegionAxis` | Axis definition with min/max/align |
|
|
||||||
| `createRegion(id, axes)` | Create a new region |
|
|
||||||
| `applyAlign(region, parts)` | Compact parts according to axis alignment |
|
|
||||||
| `shuffle(region, parts, rng)` | Randomize part positions |
|
|
||||||
| `moveToRegion(part, sourceRegion?, targetRegion, position?)` | Move a part to another region. `sourceRegion` is optional for first placement |
|
|
||||||
| `moveToRegionAll(parts, sourceRegion?, targetRegion, positions?)` | Move multiple parts to another region. `parts` is `Record<string, Part>`. `sourceRegion` is optional for first placement |
|
|
||||||
| `removeFromRegion(part, region)` | Remove a part from its region |
|
|
||||||
|
|
||||||
### 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 |
|
|
||||||
| `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 |
|
|
||||||
| `PromptEvent` | Event dispatched when a command prompts for input |
|
|
||||||
| `CommandRunnerEvents` | Event types: `prompt` (when prompt starts), `promptEnd` (when prompt completes) |
|
|
||||||
|
|
||||||
### Utilities
|
|
||||||
|
|
||||||
| Export | Description |
|
|
||||||
|---|---|
|
|
||||||
| `createRNG(seed?)` | Create a seeded RNG instance |
|
|
||||||
| `Mulberry32RNG` | Mulberry32 PRNG class |
|
|
||||||
|
|
||||||
## Scripts
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run build # Build ESM bundle + declarations to dist/
|
|
||||||
npm run test # Run tests in watch mode
|
|
||||||
npm run test:run # Run tests once
|
|
||||||
npm run typecheck # Type check with TypeScript
|
|
||||||
```
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
Generated
+375
-8
@@ -8,19 +8,25 @@
|
|||||||
"name": "boardgame-core",
|
"name": "boardgame-core",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"devDependencies": {
|
||||||
|
"@preact/signals-core": "^1.5.1",
|
||||||
|
"@types/node": "^25.6.0",
|
||||||
|
"inline-schema": "file:../inline-schema",
|
||||||
|
"mutative": "^1.3.0",
|
||||||
|
"tsup": "^8.0.2",
|
||||||
|
"typescript": "^5.3.3",
|
||||||
|
"vitest": "^1.3.1",
|
||||||
|
"yarn-spinner-loader": "^0.2.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
"@preact/signals-core": "^1.5.1",
|
"@preact/signals-core": "^1.5.1",
|
||||||
"inline-schema": "file:../inline-schema",
|
"inline-schema": "file:../inline-schema",
|
||||||
"mutative": "^1.3.0"
|
"mutative": "^1.3.0"
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"tsup": "^8.0.2",
|
|
||||||
"typescript": "^5.3.3",
|
|
||||||
"vitest": "^1.3.1"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"../inline-schema": {
|
"../inline-schema": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
|
"dev": true,
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"csv-parse": "^5.5.6"
|
"csv-parse": "^5.5.6"
|
||||||
@@ -30,10 +36,20 @@
|
|||||||
"@types/node": "^25.5.0",
|
"@types/node": "^25.5.0",
|
||||||
"tsup": "^8.5.1",
|
"tsup": "^8.5.1",
|
||||||
"tsx": "^4.21.0",
|
"tsx": "^4.21.0",
|
||||||
"typescript": "^5.9.3"
|
"typescript": "^5.9.3",
|
||||||
|
"vitest": "^4.1.4"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@rspack/core": "^1.x"
|
"@rspack/core": "^1.x",
|
||||||
|
"esbuild": "*"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@rspack/core": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"esbuild": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@esbuild/aix-ppc64": {
|
"node_modules/@esbuild/aix-ppc64": {
|
||||||
@@ -530,10 +546,49 @@
|
|||||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@nodelib/fs.scandir": {
|
||||||
|
"version": "2.1.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
|
||||||
|
"integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@nodelib/fs.stat": "2.0.5",
|
||||||
|
"run-parallel": "^1.1.9"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@nodelib/fs.stat": {
|
||||||
|
"version": "2.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz",
|
||||||
|
"integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@nodelib/fs.walk": {
|
||||||
|
"version": "1.2.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz",
|
||||||
|
"integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@nodelib/fs.scandir": "2.1.5",
|
||||||
|
"fastq": "^1.6.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@preact/signals-core": {
|
"node_modules/@preact/signals-core": {
|
||||||
"version": "1.14.0",
|
"version": "1.14.0",
|
||||||
"resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.14.0.tgz",
|
"resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.14.0.tgz",
|
||||||
"integrity": "sha512-AowtCcCU/33lFlh1zRFf/u+12rfrhtNakj7UpaGEsmMwUKpKWMVvcktOGcwBBNiB4lWrZWc01LhiyyzVklJyaQ==",
|
"integrity": "sha512-AowtCcCU/33lFlh1zRFf/u+12rfrhtNakj7UpaGEsmMwUKpKWMVvcktOGcwBBNiB4lWrZWc01LhiyyzVklJyaQ==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"funding": {
|
"funding": {
|
||||||
"type": "opencollective",
|
"type": "opencollective",
|
||||||
@@ -904,6 +959,16 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/node": {
|
||||||
|
"version": "25.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz",
|
||||||
|
"integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"undici-types": "~7.19.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@vitest/expect": {
|
"node_modules/@vitest/expect": {
|
||||||
"version": "1.6.1",
|
"version": "1.6.1",
|
||||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-1.6.1.tgz",
|
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-1.6.1.tgz",
|
||||||
@@ -1018,6 +1083,23 @@
|
|||||||
"node": ">=0.4.0"
|
"node": ">=0.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/ajv": {
|
||||||
|
"version": "8.18.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
|
||||||
|
"integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"fast-deep-equal": "^3.1.3",
|
||||||
|
"fast-uri": "^3.0.1",
|
||||||
|
"json-schema-traverse": "^1.0.0",
|
||||||
|
"require-from-string": "^2.0.2"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/epoberezkin"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/ansi-styles": {
|
"node_modules/ansi-styles": {
|
||||||
"version": "5.2.0",
|
"version": "5.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
|
||||||
@@ -1048,6 +1130,19 @@
|
|||||||
"node": "*"
|
"node": "*"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/braces": {
|
||||||
|
"version": "3.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
|
||||||
|
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"fill-range": "^7.1.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/bundle-require": {
|
"node_modules/bundle-require": {
|
||||||
"version": "5.1.0",
|
"version": "5.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz",
|
||||||
@@ -1281,6 +1376,57 @@
|
|||||||
"url": "https://github.com/sindresorhus/execa?sponsor=1"
|
"url": "https://github.com/sindresorhus/execa?sponsor=1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/fast-deep-equal": {
|
||||||
|
"version": "3.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||||
|
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/fast-glob": {
|
||||||
|
"version": "3.3.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
|
||||||
|
"integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@nodelib/fs.stat": "^2.0.2",
|
||||||
|
"@nodelib/fs.walk": "^1.2.3",
|
||||||
|
"glob-parent": "^5.1.2",
|
||||||
|
"merge2": "^1.3.0",
|
||||||
|
"micromatch": "^4.0.8"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8.6.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/fast-uri": {
|
||||||
|
"version": "3.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz",
|
||||||
|
"integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",
|
||||||
|
"dev": true,
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/fastify"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/fastify"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "BSD-3-Clause"
|
||||||
|
},
|
||||||
|
"node_modules/fastq": {
|
||||||
|
"version": "1.20.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",
|
||||||
|
"integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"reusify": "^1.0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/fdir": {
|
"node_modules/fdir": {
|
||||||
"version": "6.5.0",
|
"version": "6.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||||
@@ -1299,6 +1445,19 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/fill-range": {
|
||||||
|
"version": "7.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
|
||||||
|
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"to-regex-range": "^5.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/fix-dts-default-cjs-exports": {
|
"node_modules/fix-dts-default-cjs-exports": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz",
|
||||||
@@ -1349,6 +1508,19 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/glob-parent": {
|
||||||
|
"version": "5.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
|
||||||
|
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"is-glob": "^4.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 6"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/human-signals": {
|
"node_modules/human-signals": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz",
|
||||||
@@ -1363,6 +1535,39 @@
|
|||||||
"resolved": "../inline-schema",
|
"resolved": "../inline-schema",
|
||||||
"link": true
|
"link": true
|
||||||
},
|
},
|
||||||
|
"node_modules/is-extglob": {
|
||||||
|
"version": "2.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||||
|
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/is-glob": {
|
||||||
|
"version": "4.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
|
||||||
|
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"is-extglob": "^2.1.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/is-number": {
|
||||||
|
"version": "7.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
|
||||||
|
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.12.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/is-stream": {
|
"node_modules/is-stream": {
|
||||||
"version": "3.0.0",
|
"version": "3.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz",
|
||||||
@@ -1400,6 +1605,13 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/json-schema-traverse": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/lilconfig": {
|
"node_modules/lilconfig": {
|
||||||
"version": "3.1.3",
|
"version": "3.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",
|
||||||
@@ -1474,6 +1686,43 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/merge2": {
|
||||||
|
"version": "1.4.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
|
||||||
|
"integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/micromatch": {
|
||||||
|
"version": "4.0.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
|
||||||
|
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"braces": "^3.0.3",
|
||||||
|
"picomatch": "^2.3.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8.6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/micromatch/node_modules/picomatch": {
|
||||||
|
"version": "2.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
|
||||||
|
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8.6"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/jonschlinkert"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/mimic-fn": {
|
"node_modules/mimic-fn": {
|
||||||
"version": "4.0.0",
|
"version": "4.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz",
|
||||||
@@ -1511,6 +1760,7 @@
|
|||||||
"version": "1.3.0",
|
"version": "1.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/mutative/-/mutative-1.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/mutative/-/mutative-1.3.0.tgz",
|
||||||
"integrity": "sha512-8MJj6URmOZAV70dpFe1YnSppRTKC4DsMkXQiBDFayLcDI4ljGokHxmpqaBQuDWa4iAxWaJJ1PS8vAmbntjjKmQ==",
|
"integrity": "sha512-8MJj6URmOZAV70dpFe1YnSppRTKC4DsMkXQiBDFayLcDI4ljGokHxmpqaBQuDWa4iAxWaJJ1PS8vAmbntjjKmQ==",
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=14.0"
|
"node": ">=14.0"
|
||||||
@@ -1774,6 +2024,27 @@
|
|||||||
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
|
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/queue-microtask": {
|
||||||
|
"version": "1.2.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
||||||
|
"integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==",
|
||||||
|
"dev": true,
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "patreon",
|
||||||
|
"url": "https://www.patreon.com/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "consulting",
|
||||||
|
"url": "https://feross.org/support"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/react-is": {
|
"node_modules/react-is": {
|
||||||
"version": "18.3.1",
|
"version": "18.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
|
||||||
@@ -1795,6 +2066,16 @@
|
|||||||
"url": "https://paulmillr.com/funding/"
|
"url": "https://paulmillr.com/funding/"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/require-from-string": {
|
||||||
|
"version": "2.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
|
||||||
|
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/resolve-from": {
|
"node_modules/resolve-from": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz",
|
||||||
@@ -1805,6 +2086,17 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/reusify": {
|
||||||
|
"version": "1.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
|
||||||
|
"integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"iojs": ">=1.0.0",
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/rollup": {
|
"node_modules/rollup": {
|
||||||
"version": "4.60.1",
|
"version": "4.60.1",
|
||||||
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.1.tgz",
|
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.1.tgz",
|
||||||
@@ -1850,6 +2142,30 @@
|
|||||||
"fsevents": "~2.3.2"
|
"fsevents": "~2.3.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/run-parallel": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==",
|
||||||
|
"dev": true,
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "patreon",
|
||||||
|
"url": "https://www.patreon.com/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "consulting",
|
||||||
|
"url": "https://feross.org/support"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"queue-microtask": "^1.2.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/shebang-command": {
|
"node_modules/shebang-command": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||||
@@ -2050,6 +2366,19 @@
|
|||||||
"node": ">=14.0.0"
|
"node": ">=14.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/to-regex-range": {
|
||||||
|
"version": "5.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
||||||
|
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"is-number": "^7.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/tree-kill": {
|
"node_modules/tree-kill": {
|
||||||
"version": "1.2.2",
|
"version": "1.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
|
||||||
@@ -2151,6 +2480,13 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/undici-types": {
|
||||||
|
"version": "7.19.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz",
|
||||||
|
"integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "5.4.21",
|
"version": "5.4.21",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
|
||||||
@@ -2777,6 +3113,37 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/yarn-spinner-loader": {
|
||||||
|
"version": "0.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/yarn-spinner-loader/-/yarn-spinner-loader-0.2.0.tgz",
|
||||||
|
"integrity": "sha512-tWq+n7qziugn7pj+0Zf/XXWXqVxXZez1JkqQgk7JJD4yikHbY1OihYwqSvsUiNeav52j5VCrpU8vWlerwCawPw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"ajv": "^8.17.1",
|
||||||
|
"fast-glob": "^3.3.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"esbuild": ">=0.20.0",
|
||||||
|
"rollup": ">=4.0.0",
|
||||||
|
"vite": ">=5.0.0",
|
||||||
|
"webpack": ">=5.0.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"esbuild": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"rollup": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"vite": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"webpack": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/yocto-queue": {
|
"node_modules/yocto-queue": {
|
||||||
"version": "1.2.2",
|
"version": "1.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.2.tgz",
|
||||||
|
|||||||
+13
-3
@@ -9,24 +9,34 @@
|
|||||||
".": {
|
".": {
|
||||||
"types": "./dist/index.d.ts",
|
"types": "./dist/index.d.ts",
|
||||||
"import": "./dist/index.js"
|
"import": "./dist/index.js"
|
||||||
|
},
|
||||||
|
"./samples/*": {
|
||||||
|
"types": "./dist/samples/*.d.ts",
|
||||||
|
"import": "./dist/samples/*.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsup",
|
"build": "tsup",
|
||||||
"prepare": "npm run build",
|
"build:samples": "tsup --config tsup.samples.config.ts",
|
||||||
|
"prepare": "npm run build && npm run build:samples",
|
||||||
"test": "vitest",
|
"test": "vitest",
|
||||||
"test:run": "vitest run",
|
"test:run": "vitest run",
|
||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"peerDependencies": {
|
||||||
"@preact/signals-core": "^1.5.1",
|
"@preact/signals-core": "^1.5.1",
|
||||||
"inline-schema": "file:../inline-schema",
|
"inline-schema": "file:../inline-schema",
|
||||||
"mutative": "^1.3.0"
|
"mutative": "^1.3.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@preact/signals-core": "^1.5.1",
|
||||||
|
"@types/node": "^25.6.0",
|
||||||
|
"inline-schema": "file:../inline-schema",
|
||||||
|
"mutative": "^1.3.0",
|
||||||
"tsup": "^8.0.2",
|
"tsup": "^8.0.2",
|
||||||
"typescript": "^5.3.3",
|
"typescript": "^5.3.3",
|
||||||
"vitest": "^1.3.1"
|
"vitest": "^1.3.1",
|
||||||
|
"yarn-spinner-loader": "^0.2.0"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"boardgame",
|
"boardgame",
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import { createPromptContext, PromptDef } from "@/utils/command";
|
||||||
|
import { computed, effect, signal } from "@preact/signals-core";
|
||||||
|
import { createGameContext, IGameContext } from "./game";
|
||||||
|
|
||||||
|
export enum ClientStatus {
|
||||||
|
Idle = "idle",
|
||||||
|
Running = "running",
|
||||||
|
Disposed = "disposed",
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PromptInfo =
|
||||||
|
| {
|
||||||
|
hasPrompt: false;
|
||||||
|
player: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
hasPrompt: true;
|
||||||
|
player: string;
|
||||||
|
def: PromptDef<unknown[]>;
|
||||||
|
tryAnswer(...args: unknown[]): string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1. create a client instance
|
||||||
|
* 2. setStatus("running")
|
||||||
|
* 3. select("selector", t => {}) for c# to capture game state
|
||||||
|
* 4. useClient("status" | "prompt") for c# to handle prompt / game status
|
||||||
|
*/
|
||||||
|
export abstract class BaseGameClient<
|
||||||
|
T extends Record<string, unknown> = Record<string, unknown>,
|
||||||
|
R = unknown,
|
||||||
|
> {
|
||||||
|
protected _initialState: T;
|
||||||
|
protected _context: IGameContext<T>;
|
||||||
|
protected _prompts = createPromptContext();
|
||||||
|
protected _status = signal(ClientStatus.Idle);
|
||||||
|
protected _result = signal(null as null | R);
|
||||||
|
public get state() {
|
||||||
|
return this._context.value;
|
||||||
|
}
|
||||||
|
constructor(is: T) {
|
||||||
|
this._initialState = is;
|
||||||
|
this._context = createGameContext(this._prompts, is);
|
||||||
|
}
|
||||||
|
|
||||||
|
async setStatus(status: ClientStatus) {
|
||||||
|
this._status.value = status;
|
||||||
|
if (status === ClientStatus.Disposed) {
|
||||||
|
this._prompts.reset();
|
||||||
|
} else if (status === ClientStatus.Running) {
|
||||||
|
this._prompts.reset();
|
||||||
|
this._context._state.value = this._initialState;
|
||||||
|
this._result.value = null;
|
||||||
|
this._result.value = await this.start(this._context);
|
||||||
|
this.setStatus(ClientStatus.Idle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract start(ctx: IGameContext<T>): Promise<R>;
|
||||||
|
|
||||||
|
assignSelector<S>(selector: (t: T) => S, callback: (s: S) => void) {
|
||||||
|
const selected = computed(() => selector(this._context.value));
|
||||||
|
return effect(() => {
|
||||||
|
callback(selected.value);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
addInterruption() {
|
||||||
|
let resolve!: () => void;
|
||||||
|
const promise = new Promise<void>((resolver) => {
|
||||||
|
resolve = resolver;
|
||||||
|
});
|
||||||
|
this._context._state.addInterruption(promise);
|
||||||
|
return resolve;
|
||||||
|
}
|
||||||
|
|
||||||
|
selectPrompt(callback: (prompt: PromptInfo) => void) {
|
||||||
|
return this._prompts.handleCall.use(async (ctx, next) => {
|
||||||
|
function tryAnswer(...args: any[]) {
|
||||||
|
try {
|
||||||
|
const res = ctx.validator(...args);
|
||||||
|
ctx.resolve(res);
|
||||||
|
return null;
|
||||||
|
} catch (reason) {
|
||||||
|
if (typeof reason === "string") {
|
||||||
|
return reason;
|
||||||
|
}
|
||||||
|
throw reason;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
callback({
|
||||||
|
hasPrompt: true,
|
||||||
|
player: ctx.player || "global",
|
||||||
|
def: ctx.def,
|
||||||
|
tryAnswer,
|
||||||
|
});
|
||||||
|
return await next();
|
||||||
|
} finally {
|
||||||
|
callback({
|
||||||
|
hasPrompt: false,
|
||||||
|
player: ctx.player || "global",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
selectStatus(callback: (status: ClientStatus) => void) {
|
||||||
|
return effect(() => {
|
||||||
|
callback(this._status.value);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
selectResult(callback: (status: R | null) => void) {
|
||||||
|
return effect(() => {
|
||||||
|
callback(this._result.value);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+118
-144
@@ -1,150 +1,124 @@
|
|||||||
import { ReadonlySignal, signal, Signal } from '@preact/signals-core';
|
import { createPromptContext } from "@/utils/command";
|
||||||
import type { CommandSchema, CommandRegistry, CommandResult } from '@/utils/command';
|
import { PromptContext } from "@/utils/command/command-prompt";
|
||||||
import type { MutableSignal } from '@/utils/mutable-signal';
|
import { ReadonlySignal, Signal } from "@preact/signals-core";
|
||||||
import { createGameContext } from './game';
|
import { createGameContext, IGameContext } from "./game";
|
||||||
|
|
||||||
export type GameHostStatus = 'created' | 'running' | 'disposed';
|
export type GameHostStatus = "created" | "running" | "disposed";
|
||||||
|
|
||||||
export interface GameHostOptions {
|
export class GameHost<
|
||||||
autoStart?: boolean;
|
TState extends Record<string, unknown>,
|
||||||
|
TResult = unknown,
|
||||||
|
TModule extends GameModule<TState, TResult> = GameModule<TState, TResult>,
|
||||||
|
> {
|
||||||
|
readonly state: ReadonlySignal<TState>;
|
||||||
|
readonly status: ReadonlySignal<GameHostStatus>;
|
||||||
|
readonly prompts: PromptContext;
|
||||||
|
|
||||||
|
private _context: IGameContext<TState>;
|
||||||
|
private _start: (ctx: IGameContext<TState>) => Promise<TResult>;
|
||||||
|
private _status: Signal<GameHostStatus>;
|
||||||
|
private _createInitialState: () => TState;
|
||||||
|
private _eventListeners: Map<"start" | "dispose", Set<() => void>>;
|
||||||
|
private _isDisposed = false;
|
||||||
|
|
||||||
|
constructor(public readonly gameModule: TModule) {
|
||||||
|
const { createInitialState, start } = gameModule;
|
||||||
|
this._createInitialState = createInitialState;
|
||||||
|
this._eventListeners = new Map();
|
||||||
|
|
||||||
|
this.prompts = createPromptContext();
|
||||||
|
const initialState = createInitialState();
|
||||||
|
this._context = createGameContext(this.prompts, initialState);
|
||||||
|
this._start = start;
|
||||||
|
this.state = this._context._state;
|
||||||
|
|
||||||
|
this._status = new Signal<GameHostStatus>("created");
|
||||||
|
this.status = this._status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为下一个 produceAsync 注册中断 Promise(通常用于 UI 动画)。
|
||||||
|
* @see MutableSignal.addInterruption
|
||||||
|
*/
|
||||||
|
addInterruption(promise: Promise<void>): void {
|
||||||
|
this._context._state.addInterruption(promise);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除所有未完成的中断。
|
||||||
|
* @see MutableSignal.clearInterruptions
|
||||||
|
*/
|
||||||
|
clearInterruptions(): void {
|
||||||
|
this._context._state.clearInterruptions();
|
||||||
|
}
|
||||||
|
|
||||||
|
start(seed?: number): Promise<TResult> {
|
||||||
|
if (this._isDisposed) {
|
||||||
|
throw new Error("GameHost is disposed");
|
||||||
|
}
|
||||||
|
|
||||||
|
this.prompts.reset();
|
||||||
|
|
||||||
|
const initialState = this._createInitialState();
|
||||||
|
this._context._state.value = initialState as any;
|
||||||
|
|
||||||
|
seed = seed || Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
|
||||||
|
this._context._rng.setSeed(seed);
|
||||||
|
const promise = this._start(this._context);
|
||||||
|
|
||||||
|
this._status.value = "running";
|
||||||
|
this._emitEvent("start");
|
||||||
|
|
||||||
|
return promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
if (this._isDisposed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this._isDisposed = true;
|
||||||
|
this.prompts.reset();
|
||||||
|
this._status.value = "disposed";
|
||||||
|
|
||||||
|
// Emit dispose event BEFORE clearing listeners
|
||||||
|
this._emitEvent("dispose");
|
||||||
|
this._eventListeners.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
on(event: "start" | "dispose", listener: () => void): () => void {
|
||||||
|
if (!this._eventListeners.has(event)) {
|
||||||
|
this._eventListeners.set(event, new Set());
|
||||||
|
}
|
||||||
|
this._eventListeners.get(event)!.add(listener);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
this._eventListeners.get(event)?.delete(listener);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private _emitEvent(event: "start" | "dispose") {
|
||||||
|
const listeners = this._eventListeners.get(event);
|
||||||
|
if (listeners) {
|
||||||
|
for (const listener of listeners) {
|
||||||
|
listener();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class GameHost<TState extends Record<string, unknown>> {
|
export type GameModule<
|
||||||
readonly state: ReadonlySignal<TState>;
|
TState extends Record<string, unknown> = Record<string, unknown>,
|
||||||
readonly commands: ReturnType<typeof createGameContext<TState>>['commands'];
|
TResult = unknown,
|
||||||
readonly status: ReadonlySignal<GameHostStatus>;
|
> = {
|
||||||
readonly activePromptSchema: ReadonlySignal<CommandSchema | null>;
|
createInitialState: () => TState;
|
||||||
|
start: (ctx: IGameContext<TState>) => Promise<TResult>;
|
||||||
|
};
|
||||||
|
|
||||||
private _state: MutableSignal<TState>;
|
export function createGameHost<
|
||||||
private _status: Signal<GameHostStatus>;
|
TState extends Record<string, unknown> = Record<string, unknown>,
|
||||||
private _activePromptSchema: Signal<CommandSchema | null>;
|
TResult = unknown,
|
||||||
private _createInitialState: () => TState;
|
TModule extends GameModule<TState, TResult> = GameModule<TState, TResult>,
|
||||||
private _setupCommand: string;
|
>(gameModule: TModule): GameHost<TState, TResult, TModule> {
|
||||||
private _eventListeners: Map<'setup' | 'dispose', Set<() => void>>;
|
return new GameHost(gameModule);
|
||||||
private _isDisposed = false;
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
registry: CommandRegistry<MutableSignal<TState>>,
|
|
||||||
createInitialState: () => TState,
|
|
||||||
setupCommand: string,
|
|
||||||
options?: GameHostOptions
|
|
||||||
) {
|
|
||||||
this._createInitialState = createInitialState;
|
|
||||||
this._setupCommand = setupCommand;
|
|
||||||
this._eventListeners = new Map();
|
|
||||||
|
|
||||||
const initialState = createInitialState();
|
|
||||||
const context = createGameContext(registry, initialState);
|
|
||||||
|
|
||||||
this._state = context.state;
|
|
||||||
this.commands = context.commands;
|
|
||||||
|
|
||||||
this._status = new Signal<GameHostStatus>('created');
|
|
||||||
this.status = this._status;
|
|
||||||
|
|
||||||
this._activePromptSchema = new Signal<CommandSchema | null>(null);
|
|
||||||
this.activePromptSchema = this._activePromptSchema;
|
|
||||||
|
|
||||||
this.state = this._state;
|
|
||||||
|
|
||||||
this._setupPromptTracking();
|
|
||||||
|
|
||||||
if (options?.autoStart !== false) {
|
|
||||||
this._status.value = 'running';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private _setupPromptTracking() {
|
|
||||||
const updateSchema = () => {
|
|
||||||
const activePrompt = (this.commands as any)._activePrompt as { schema?: CommandSchema } | null;
|
|
||||||
this._activePromptSchema.value = activePrompt?.schema ?? null;
|
|
||||||
};
|
|
||||||
|
|
||||||
this.commands.on('prompt', () => {
|
|
||||||
updateSchema();
|
|
||||||
});
|
|
||||||
|
|
||||||
this.commands.on('promptEnd', () => {
|
|
||||||
updateSchema();
|
|
||||||
});
|
|
||||||
|
|
||||||
updateSchema();
|
|
||||||
}
|
|
||||||
|
|
||||||
onInput(input: string): string | null {
|
|
||||||
if (this._isDisposed) {
|
|
||||||
return 'GameHost is disposed';
|
|
||||||
}
|
|
||||||
return this.commands._tryCommit(input);
|
|
||||||
}
|
|
||||||
|
|
||||||
async setup(setupCommand: string): Promise<void> {
|
|
||||||
if (this._isDisposed) {
|
|
||||||
throw new Error('GameHost is disposed');
|
|
||||||
}
|
|
||||||
|
|
||||||
this.commands._cancel();
|
|
||||||
|
|
||||||
const initialState = this._createInitialState();
|
|
||||||
this._state.value = initialState as any;
|
|
||||||
|
|
||||||
// Start the setup command but don't wait for it to complete
|
|
||||||
// The command will run in the background and prompt for input
|
|
||||||
this.commands.run(setupCommand).catch(() => {
|
|
||||||
// Command may be cancelled or fail, which is expected
|
|
||||||
});
|
|
||||||
|
|
||||||
this._status.value = 'running';
|
|
||||||
this._emitEvent('setup');
|
|
||||||
}
|
|
||||||
|
|
||||||
dispose(): void {
|
|
||||||
if (this._isDisposed) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this._isDisposed = true;
|
|
||||||
this.commands._cancel();
|
|
||||||
this._status.value = 'disposed';
|
|
||||||
|
|
||||||
// Emit dispose event BEFORE clearing listeners
|
|
||||||
this._emitEvent('dispose');
|
|
||||||
this._eventListeners.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
on(event: 'setup' | 'dispose', listener: () => void): () => void {
|
|
||||||
if (!this._eventListeners.has(event)) {
|
|
||||||
this._eventListeners.set(event, new Set());
|
|
||||||
}
|
|
||||||
this._eventListeners.get(event)!.add(listener);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
this._eventListeners.get(event)?.delete(listener);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private _emitEvent(event: 'setup' | 'dispose') {
|
|
||||||
const listeners = this._eventListeners.get(event);
|
|
||||||
if (listeners) {
|
|
||||||
for (const listener of listeners) {
|
|
||||||
listener();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createGameHost<TState extends Record<string, unknown>>(
|
|
||||||
module: {
|
|
||||||
registry: CommandRegistry<MutableSignal<TState>>;
|
|
||||||
createInitialState: () => TState;
|
|
||||||
},
|
|
||||||
setupCommand: string,
|
|
||||||
options?: GameHostOptions
|
|
||||||
): GameHost<TState> {
|
|
||||||
return new GameHost(
|
|
||||||
module.registry,
|
|
||||||
module.createInitialState,
|
|
||||||
setupCommand,
|
|
||||||
options
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
+55
-63
@@ -1,72 +1,64 @@
|
|||||||
import {MutableSignal, mutableSignal} from "@/utils/mutable-signal";
|
import { MutableSignal, mutableSignal } from "@/utils/mutable-signal";
|
||||||
import {
|
import { CommandSchema, parseCommandSchema, PromptDef } from "@/utils/command";
|
||||||
Command,
|
import { PromptValidator } from "@/utils/command/command-runner";
|
||||||
CommandRegistry,
|
import { Mulberry32RNG, ReadonlyRNG, RNG } from "@/utils/rng";
|
||||||
CommandRunnerContext,
|
import { PromptContext } from "@/utils/command/command-prompt";
|
||||||
CommandRunnerContextExport,
|
|
||||||
CommandSchema,
|
|
||||||
createCommandRegistry,
|
|
||||||
createCommandRunnerContext,
|
|
||||||
parseCommandSchema,
|
|
||||||
registerCommand
|
|
||||||
} from "@/utils/command";
|
|
||||||
|
|
||||||
export interface IGameContext<TState extends Record<string, unknown> = {} > {
|
export interface IGameContext<TState extends Record<string, unknown> = {}> {
|
||||||
state: MutableSignal<TState>;
|
get value(): TState;
|
||||||
commands: CommandRunnerContextExport<MutableSignal<TState>>;
|
get rng(): ReadonlyRNG;
|
||||||
|
produce(fn: (draft: TState) => undefined): void;
|
||||||
|
produceAsync(fn: (draft: TState) => undefined): Promise<void>;
|
||||||
|
prompt: <TResult, TArgs extends any[] = any[]>(
|
||||||
|
def: PromptDef<TArgs>,
|
||||||
|
validator: PromptValidator<TResult, TArgs>,
|
||||||
|
player?: string,
|
||||||
|
) => Promise<TResult>;
|
||||||
|
|
||||||
|
// test only
|
||||||
|
_state: MutableSignal<TState>;
|
||||||
|
_rng: RNG;
|
||||||
}
|
}
|
||||||
|
export type IGameContextExport<TState extends Record<string, unknown> = {}> =
|
||||||
|
Omit<IGameContext<TState>, "_state" | "_commands" | "_rng">;
|
||||||
|
|
||||||
export function createGameContext<TState extends Record<string, unknown> = {} >(
|
export function createGameContext<TState extends Record<string, unknown> = {}>(
|
||||||
commandRegistry: CommandRegistry<MutableSignal<TState>>,
|
promptContext: PromptContext,
|
||||||
initialState?: TState | (() => TState)
|
initialState?: TState | (() => TState),
|
||||||
): IGameContext<TState> {
|
): IGameContext<TState> {
|
||||||
const stateValue = typeof initialState === 'function' ? initialState() : initialState ?? {} as TState;
|
const stateValue =
|
||||||
const state = mutableSignal(stateValue);
|
typeof initialState === "function"
|
||||||
const commands = createCommandRunnerContext(commandRegistry, state);
|
? initialState()
|
||||||
|
: (initialState ?? ({} as TState));
|
||||||
|
const state = mutableSignal(stateValue);
|
||||||
|
const { prompt } = promptContext;
|
||||||
|
|
||||||
return {
|
const context: IGameContext<TState> = {
|
||||||
state,
|
get value(): TState {
|
||||||
commands
|
return state.value;
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* so that we can do `import * as tictactoe from './tic-tac-toe.ts';\n\n createGameContextFromModule(tictactoe);`
|
|
||||||
* @param module
|
|
||||||
*/
|
|
||||||
export function createGameContextFromModule<TState extends Record<string, unknown> = {} >(
|
|
||||||
module: {
|
|
||||||
registry: CommandRegistry<MutableSignal<TState>>,
|
|
||||||
createInitialState: () => TState
|
|
||||||
},
|
},
|
||||||
): IGameContext<TState> {
|
get rng() {
|
||||||
return createGameContext(module.registry, module.createInitialState);
|
return this._rng;
|
||||||
|
},
|
||||||
|
produce(fn: (draft: TState) => undefined) {
|
||||||
|
return state.produce(fn);
|
||||||
|
},
|
||||||
|
produceAsync(fn: (draft: TState) => undefined) {
|
||||||
|
return state.produceAsync(fn);
|
||||||
|
},
|
||||||
|
prompt,
|
||||||
|
|
||||||
|
_state: state,
|
||||||
|
_rng: new Mulberry32RNG(),
|
||||||
|
};
|
||||||
|
|
||||||
|
return context;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createGameCommandRegistry<TState extends Record<string, unknown> = {} >() {
|
export function createPromptDef<TArgs extends any[] = any[]>(
|
||||||
const registry = createCommandRegistry<MutableSignal<TState>>();
|
schema: CommandSchema | string,
|
||||||
return {
|
hintText?: string,
|
||||||
registry,
|
): PromptDef<TArgs> {
|
||||||
add<TResult = unknown>(
|
schema = typeof schema === "string" ? parseCommandSchema(schema) : schema;
|
||||||
schema: CommandSchema | string,
|
return { schema, hintText };
|
||||||
run: (this: CommandRunnerContext<MutableSignal<TState>>, command: Command) => Promise<TResult>
|
|
||||||
){
|
|
||||||
createGameCommand(registry, schema, run);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createGameCommand<TState extends Record<string, unknown> = {} , TResult = unknown>(
|
|
||||||
registry: CommandRegistry<MutableSignal<TState>>,
|
|
||||||
schema: CommandSchema | string,
|
|
||||||
run: (this: CommandRunnerContext<MutableSignal<TState>>, command: Command) => Promise<TResult>
|
|
||||||
) {
|
|
||||||
registerCommand(registry, {
|
|
||||||
schema: typeof schema === 'string' ? parseCommandSchema(schema) : schema,
|
|
||||||
run,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export { GameHost, createGameHost } from './game-host';
|
|
||||||
export type { GameHostStatus, GameHostOptions } from './game-host';
|
|
||||||
+19
-105
@@ -1,113 +1,27 @@
|
|||||||
import {Part} from "./part";
|
import {Part} from "./part";
|
||||||
|
import {Immutable} from "mutative";
|
||||||
|
|
||||||
export type PartTemplate<TMeta = {}> = Omit<Partial<Part<TMeta>>, 'id'> & TMeta;
|
export function createPartsFromTable<T>(items: readonly T[], getId: (item: T, index: number) => string, getCount?: ((item: T) => number) | number){
|
||||||
|
const pool: Record<string, Part<T>> = {};
|
||||||
export type PartPool<TMeta = {}> = {
|
for (const entry of items) {
|
||||||
parts: Record<string, Part<TMeta>>;
|
const count = getCount ? (typeof getCount === 'function' ? getCount(entry) : getCount) : 1;
|
||||||
template: PartTemplate<TMeta>;
|
for (let i = 0; i < count; i++) {
|
||||||
draw(): Part<TMeta> | undefined;
|
const id = getId(entry, i);
|
||||||
return(part: Part<TMeta>): void;
|
pool[id] = createPart(id, entry);
|
||||||
remaining(): number;
|
}
|
||||||
};
|
|
||||||
|
|
||||||
export function createPart<TMeta = {}>(
|
|
||||||
template: PartTemplate<TMeta>,
|
|
||||||
id: string
|
|
||||||
): Part<TMeta> {
|
|
||||||
const part: Part<TMeta> = {
|
|
||||||
id,
|
|
||||||
regionId: template.regionId ?? '',
|
|
||||||
position: template.position ?? [],
|
|
||||||
...template,
|
|
||||||
};
|
|
||||||
return part;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createParts<TMeta = {}>(
|
|
||||||
template: PartTemplate<TMeta>,
|
|
||||||
count: number,
|
|
||||||
idPrefix: string
|
|
||||||
): Part<TMeta>[] {
|
|
||||||
const parts: Part<TMeta>[] = [];
|
|
||||||
for (let i = 0; i < count; i++) {
|
|
||||||
parts.push(createPart(template, `${idPrefix}-${i + 1}`));
|
|
||||||
}
|
}
|
||||||
return parts;
|
return pool;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createPartPool<TMeta = {}>(
|
export function createParts<T>(item: T, getId: (index: number) => string, count?: number){
|
||||||
template: PartTemplate<TMeta>,
|
return createPartsFromTable([item], (_,index) => getId(index), count);
|
||||||
count: number,
|
|
||||||
idPrefix: string
|
|
||||||
): PartPool<TMeta> {
|
|
||||||
const partsArray = createParts(template, count, idPrefix);
|
|
||||||
const parts: Record<string, Part<TMeta>> = {};
|
|
||||||
for (const part of partsArray) {
|
|
||||||
parts[part.id] = part;
|
|
||||||
}
|
|
||||||
const available = [...partsArray];
|
|
||||||
|
|
||||||
return {
|
|
||||||
parts,
|
|
||||||
template,
|
|
||||||
draw() {
|
|
||||||
return available.pop();
|
|
||||||
},
|
|
||||||
return(part: Part<TMeta>) {
|
|
||||||
part.regionId = '';
|
|
||||||
part.position = [];
|
|
||||||
available.push(part);
|
|
||||||
},
|
|
||||||
remaining() {
|
|
||||||
return available.length;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function mergePartPools<TMeta = {}>(
|
export function createPart<T>(id: string, entry: T): Part<T> {
|
||||||
...pools: PartPool<TMeta>[]
|
return {
|
||||||
): PartPool<TMeta> {
|
id,
|
||||||
if (pools.length === 0) {
|
regionId: '',
|
||||||
return createEmptyPartPool<TMeta>();
|
position: [],
|
||||||
}
|
...entry as Immutable<T>
|
||||||
|
}
|
||||||
const allPartsArray = pools.flatMap(p => Object.values(p.parts));
|
|
||||||
const allParts: Record<string, Part<TMeta>> = {};
|
|
||||||
for (const part of allPartsArray) {
|
|
||||||
allParts[part.id] = part;
|
|
||||||
}
|
|
||||||
const template = pools[0].template;
|
|
||||||
const available = allPartsArray.filter(p => p.regionId === '');
|
|
||||||
|
|
||||||
return {
|
|
||||||
parts: allParts,
|
|
||||||
template,
|
|
||||||
draw() {
|
|
||||||
return available.pop();
|
|
||||||
},
|
|
||||||
return(part: Part<TMeta>) {
|
|
||||||
part.regionId = '';
|
|
||||||
part.position = [];
|
|
||||||
available.push(part);
|
|
||||||
},
|
|
||||||
remaining() {
|
|
||||||
return available.length;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function createEmptyPartPool<TMeta>(): PartPool<TMeta> {
|
|
||||||
return {
|
|
||||||
parts: {},
|
|
||||||
template: {} as PartTemplate<TMeta>,
|
|
||||||
draw() {
|
|
||||||
return undefined;
|
|
||||||
},
|
|
||||||
return(_part: Part<TMeta>) {
|
|
||||||
// no-op for empty pool
|
|
||||||
},
|
|
||||||
remaining() {
|
|
||||||
return 0;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
+2
-33
@@ -1,5 +1,5 @@
|
|||||||
import {RNG} from '@/utils/rng';
|
import {RNG} from '@/utils/rng';
|
||||||
import {Region} from '@/core/region';
|
import {Immutable} from "mutative";
|
||||||
|
|
||||||
export type Part<TMeta = {}> = {
|
export type Part<TMeta = {}> = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -11,7 +11,7 @@ export type Part<TMeta = {}> = {
|
|||||||
alignment?: string;
|
alignment?: string;
|
||||||
regionId: string;
|
regionId: string;
|
||||||
position: number[];
|
position: number[];
|
||||||
} & TMeta;
|
} & Immutable<TMeta>;
|
||||||
|
|
||||||
export function flip<TMeta>(part: Part<TMeta>) {
|
export function flip<TMeta>(part: Part<TMeta>) {
|
||||||
if(!part.sides) return;
|
if(!part.sides) return;
|
||||||
@@ -27,34 +27,3 @@ export function roll<TMeta>(part: Part<TMeta>, rng: RNG) {
|
|||||||
if(!part.sides) return;
|
if(!part.sides) return;
|
||||||
part.side = rng.nextInt(part.sides);
|
part.side = rng.nextInt(part.sides);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function findPartById<TMeta>(parts: Record<string, Part<TMeta>>, id: string): Part<TMeta> | undefined {
|
|
||||||
return parts[id];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isCellOccupied<TMeta>(parts: Record<string, Part<TMeta>>, regionId: string, position: number[]): boolean {
|
|
||||||
const posKey = position.join(',');
|
|
||||||
return Object.values(parts).some(p => p.regionId === regionId && p.position.join(',') === posKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getPartAtPosition<TMeta>(parts: Record<string, Part<TMeta>>, regionId: string, position: number[]): Part<TMeta> | undefined {
|
|
||||||
const posKey = position.join(',');
|
|
||||||
return Object.values(parts).find(p => p.regionId === regionId && p.position.join(',') === posKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* O(1) cell occupancy check using Region.partMap
|
|
||||||
*/
|
|
||||||
export function isCellOccupiedByRegion(region: Region, position: number[]): boolean {
|
|
||||||
return position.join(',') in region.partMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* O(1) part lookup using Region.partMap and parts Record
|
|
||||||
*/
|
|
||||||
export function getPartAtPositionInRegion<TMeta>(region: Region, parts: Record<string, Part<TMeta>>, position: number[]): Part<TMeta> | undefined {
|
|
||||||
const posKey = position.join(',');
|
|
||||||
const partId = region.partMap[posKey];
|
|
||||||
if (!partId) return undefined;
|
|
||||||
return parts[partId];
|
|
||||||
}
|
|
||||||
|
|||||||
+14
-26
@@ -1,5 +1,5 @@
|
|||||||
import {Part} from "./part";
|
import {Part} from "./part";
|
||||||
import {RNG} from "@/utils/rng";
|
import {ReadonlyRNG} from "@/utils/rng";
|
||||||
|
|
||||||
export type Region = {
|
export type Region = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -24,6 +24,15 @@ export function createRegion(id: string, axes: RegionAxis[]): Region {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function createRegionAxis(name: string, min?: number, max?: number, align?: 'start' | 'end' | 'center'): RegionAxis {
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
min,
|
||||||
|
max,
|
||||||
|
align,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function buildPartMap<TMeta>(region: Region, parts: Record<string, Part<TMeta>>) {
|
function buildPartMap<TMeta>(region: Region, parts: Record<string, Part<TMeta>>) {
|
||||||
const map: Record<string, string> = {};
|
const map: Record<string, string> = {};
|
||||||
for (const childId of region.childIds) {
|
for (const childId of region.childIds) {
|
||||||
@@ -98,7 +107,7 @@ export function applyAlign<TMeta>(region: Region, parts: Record<string, Part<TMe
|
|||||||
region.partMap = buildPartMap(region, parts);
|
region.partMap = buildPartMap(region, parts);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function shuffle<TMeta>(region: Region, parts: Record<string, Part<TMeta>>, rng: RNG){
|
export function shuffle<TMeta>(region: Region, parts: Record<string, Part<TMeta>>, rng: ReadonlyRNG){
|
||||||
if (region.childIds.length <= 1) return;
|
if (region.childIds.length <= 1) return;
|
||||||
|
|
||||||
const childIds = [...region.childIds];
|
const childIds = [...region.childIds];
|
||||||
@@ -117,41 +126,20 @@ export function shuffle<TMeta>(region: Region, parts: Record<string, Part<TMeta>
|
|||||||
region.partMap = buildPartMap(region, parts);
|
region.partMap = buildPartMap(region, parts);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function moveToRegion<TMeta>(part: Part<TMeta>, sourceRegion: Region | null, targetRegion: Region, position?: number[]) {
|
export function moveToRegion<TMeta>(part: Part<TMeta>, sourceRegion: Region | null, targetRegion: Region | null, position?: number[]) {
|
||||||
if (sourceRegion && part.regionId === sourceRegion.id) {
|
if (sourceRegion && part.regionId === sourceRegion.id) {
|
||||||
sourceRegion.childIds = sourceRegion.childIds.filter(id => id !== part.id);
|
sourceRegion.childIds = sourceRegion.childIds.filter(id => id !== part.id);
|
||||||
delete sourceRegion.partMap[part.position.join(',')];
|
delete sourceRegion.partMap[part.position.join(',')];
|
||||||
}
|
}
|
||||||
|
|
||||||
targetRegion.childIds.push(part.id);
|
|
||||||
if (position) {
|
if (position) {
|
||||||
part.position = position;
|
part.position = position;
|
||||||
}
|
}
|
||||||
targetRegion.partMap[part.position.join(',')] = part.id;
|
|
||||||
|
|
||||||
part.regionId = targetRegion.id;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function moveToRegionAll<TMeta>(parts: Record<string, Part<TMeta>>, sourceRegion: Region | null, targetRegion: Region, positions?: number[][]) {
|
|
||||||
const partIds = Object.keys(parts);
|
|
||||||
for (let i = 0; i < partIds.length; i++) {
|
|
||||||
const part = parts[partIds[i]];
|
|
||||||
if (sourceRegion && part.regionId === sourceRegion.id) {
|
|
||||||
sourceRegion.childIds = sourceRegion.childIds.filter(id => id !== part.id);
|
|
||||||
delete sourceRegion.partMap[part.position.join(',')];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if(targetRegion){
|
||||||
targetRegion.childIds.push(part.id);
|
targetRegion.childIds.push(part.id);
|
||||||
if (positions && positions[i]) {
|
|
||||||
part.position = positions[i];
|
|
||||||
}
|
|
||||||
targetRegion.partMap[part.position.join(',')] = part.id;
|
targetRegion.partMap[part.position.join(',')] = part.id;
|
||||||
|
|
||||||
part.regionId = targetRegion.id;
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
export function removeFromRegion<TMeta>(part: Part<TMeta>, region: Region) {
|
part.regionId = targetRegion?.id || '';
|
||||||
region.childIds = region.childIds.filter(id => id !== part.id);
|
|
||||||
delete region.partMap[part.position.join(',')];
|
|
||||||
}
|
}
|
||||||
+63
-18
@@ -4,30 +4,75 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
// Core types
|
// Core types
|
||||||
export type { IGameContext } from './core/game';
|
export type { IGameContext } from "./core/game";
|
||||||
export { createGameContext, createGameCommandRegistry } from './core/game';
|
export { createPromptDef } from "./core/game";
|
||||||
|
|
||||||
export type { GameHost, GameHostStatus, GameHostOptions } from './core/game-host';
|
export type { GameHost, GameHostStatus, GameModule } from "./core/game-host";
|
||||||
export { createGameHost } from './core/game-host';
|
export { createGameHost } from "./core/game-host";
|
||||||
|
|
||||||
export type { Part } from './core/part';
|
export type { Part } from "./core/part";
|
||||||
export { flip, flipTo, roll, findPartById, isCellOccupied, getPartAtPosition, isCellOccupiedByRegion, getPartAtPositionInRegion } from './core/part';
|
export { flip, flipTo, roll } from "./core/part";
|
||||||
|
|
||||||
export type { PartTemplate, PartPool } from './core/part-factory';
|
export { createParts, createPartsFromTable } from "./core/part-factory";
|
||||||
export { createPart, createParts, createPartPool, mergePartPools } from './core/part-factory';
|
|
||||||
|
|
||||||
export type { Region, RegionAxis } from './core/region';
|
export type { Region, RegionAxis } from "./core/region";
|
||||||
export { createRegion, applyAlign, shuffle, moveToRegion, moveToRegionAll, removeFromRegion } from './core/region';
|
export {
|
||||||
|
createRegion,
|
||||||
|
createRegionAxis,
|
||||||
|
applyAlign,
|
||||||
|
shuffle,
|
||||||
|
moveToRegion,
|
||||||
|
} from "./core/region";
|
||||||
|
|
||||||
|
export * from "./core/game-client";
|
||||||
|
|
||||||
// Utils
|
// Utils
|
||||||
export type { Command, CommandResult, CommandSchema, CommandParamSchema, CommandOptionSchema, CommandFlagSchema } from './utils/command';
|
export type {
|
||||||
export { parseCommand, parseCommandSchema, validateCommand, parseCommandWithSchema, applyCommandSchema } from './utils/command';
|
Command,
|
||||||
|
CommandDef,
|
||||||
|
CommandResult,
|
||||||
|
CommandSchema,
|
||||||
|
CommandParamSchema,
|
||||||
|
CommandOptionSchema,
|
||||||
|
CommandFlagSchema,
|
||||||
|
} from "./utils/command";
|
||||||
|
export {
|
||||||
|
parseCommand,
|
||||||
|
parseCommandSchema,
|
||||||
|
validateCommand,
|
||||||
|
parseCommandWithSchema,
|
||||||
|
applyCommandSchema,
|
||||||
|
} from "./utils/command";
|
||||||
|
|
||||||
export type { CommandRunner, CommandRunnerHandler, CommandRunnerContext, PromptEvent, CommandRunnerEvents } from './utils/command';
|
export type {
|
||||||
export { createCommandRegistry, registerCommand, unregisterCommand, hasCommand, getCommand, runCommand, runCommandParsed, createCommandRunnerContext, type CommandRegistry, type CommandRunnerContextExport } from './utils/command';
|
CommandRunner,
|
||||||
|
CommandRunnerHandler,
|
||||||
|
CommandRunnerContext,
|
||||||
|
PromptEvent,
|
||||||
|
CommandRunnerEvents,
|
||||||
|
} from "./utils/command";
|
||||||
|
export {
|
||||||
|
createCommandRegistry,
|
||||||
|
registerCommand,
|
||||||
|
unregisterCommand,
|
||||||
|
hasCommand,
|
||||||
|
getCommand,
|
||||||
|
runCommand,
|
||||||
|
runCommandParsed,
|
||||||
|
createCommandRunnerContext,
|
||||||
|
type CommandRegistry,
|
||||||
|
type CommandRunnerContextExport,
|
||||||
|
} from "./utils/command";
|
||||||
|
|
||||||
export type { MutableSignal } from './utils/mutable-signal';
|
export type { MutableSignal } from "./utils/mutable-signal";
|
||||||
export { mutableSignal, createEntityCollection } from './utils/mutable-signal';
|
export { mutableSignal } from "./utils/mutable-signal";
|
||||||
|
|
||||||
export type { RNG } from './utils/rng';
|
export type { RNG, ReadonlyRNG } from "./utils/rng";
|
||||||
export { createRNG, Mulberry32RNG } from './utils/rng';
|
export { createRNG, Mulberry32RNG } from "./utils/rng";
|
||||||
|
|
||||||
|
export type { MiddlewareChain } from "./utils/middleware";
|
||||||
|
export { createMiddlewareChain } from "./utils/middleware";
|
||||||
|
|
||||||
|
export * from "./utils/spawner";
|
||||||
|
|
||||||
|
export * from "@preact/signals-core";
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
type,player,count
|
||||||
|
string,string,int
|
||||||
|
kitten,white,8
|
||||||
|
kitten,black,8
|
||||||
|
cat,white,8
|
||||||
|
cat,black,8
|
||||||
|
Vendored
+10
@@ -0,0 +1,10 @@
|
|||||||
|
type BoopPartTable = readonly {
|
||||||
|
readonly type: string;
|
||||||
|
readonly player: string;
|
||||||
|
readonly count: number;
|
||||||
|
}[];
|
||||||
|
|
||||||
|
export type BoopPart = BoopPartTable[number];
|
||||||
|
|
||||||
|
declare function getData(): BoopPartTable;
|
||||||
|
export default getData;
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import {BoopGame} from "@/samples/boop/types-extensions";
|
||||||
|
import {PieceType} from "@/samples/boop/types";
|
||||||
|
import {findPartAtPosition, getNeighborPositions, isCellOccupied, isInBounds} from "@/samples/boop/utils";
|
||||||
|
import {moveToRegion} from "@/core/region";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行boop - 推动周围棋子
|
||||||
|
*/
|
||||||
|
export async function boop(game: BoopGame, row: number, col: number, type: PieceType) {
|
||||||
|
const booped: string[] = [];
|
||||||
|
|
||||||
|
await game.produceAsync(state => {
|
||||||
|
// 按照远离放置位置的方向推动
|
||||||
|
for (const [dr, dc] of getNeighborPositions()) {
|
||||||
|
const nr = row + dr;
|
||||||
|
const nc = col + dc;
|
||||||
|
|
||||||
|
if (!isInBounds(nr, nc)) continue;
|
||||||
|
|
||||||
|
// 从 state 中查找,而不是 game
|
||||||
|
const part = findPartAtPosition(state, nr, nc);
|
||||||
|
if (!part) continue;
|
||||||
|
|
||||||
|
// 小猫不能推动猫
|
||||||
|
if (type === 'kitten' && part.type === 'cat') continue;
|
||||||
|
|
||||||
|
// 计算推动后的位置
|
||||||
|
const newRow = nr + dr;
|
||||||
|
const newCol = nc + dc;
|
||||||
|
|
||||||
|
// 检查新位置是否为空或在棋盘外
|
||||||
|
if (!isInBounds(newRow, newCol)) {
|
||||||
|
// 棋子被推出棋盘,返回玩家supply
|
||||||
|
booped.push(part.id);
|
||||||
|
moveToRegion(part, state.regions.board, state.regions[part.player]);
|
||||||
|
} else if (!isCellOccupied(state, newRow, newCol)) {
|
||||||
|
// 新位置为空,移动过去
|
||||||
|
booped.push(part.id);
|
||||||
|
moveToRegion(part, state.regions.board, state.regions.board, [newRow, newCol]);
|
||||||
|
}
|
||||||
|
// 如果新位置被占用,则不移动(两个棋子都保持原位)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return { booped };
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import {BoopGame} from "@/samples/boop/types-extensions";
|
||||||
|
import {PlayerType} from "@/samples/boop/types";
|
||||||
|
import {findPartAtPosition, findPartInRegion, isInBounds} from "@/samples/boop/utils";
|
||||||
|
import {MAX_PIECES_PER_PLAYER} from "@/samples/boop/constants";
|
||||||
|
import {prompts} from "@/samples/boop/prompts";
|
||||||
|
import {moveToRegion} from "@/core/region";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查并执行 8-piece 规则
|
||||||
|
*/
|
||||||
|
export async function checkFullBoard(game: BoopGame, turnPlayer: PlayerType){
|
||||||
|
// 检查8-piece规则: 如果玩家所有8个棋子都在棋盘上且没有获胜,强制升级一个小猫
|
||||||
|
const playerPieces = Object.values(game.value.pieces).filter(
|
||||||
|
p => p.player === turnPlayer && p.regionId === 'board'
|
||||||
|
);
|
||||||
|
if(playerPieces.length < MAX_PIECES_PER_PLAYER || game.value.winner !== null){
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const partId = await game.prompt(
|
||||||
|
prompts.choose,
|
||||||
|
(player, row, col) => {
|
||||||
|
if (player !== turnPlayer) {
|
||||||
|
throw `Invalid player: ${player}. Expected ${turnPlayer}.`;
|
||||||
|
}
|
||||||
|
if (!isInBounds(row, col)) {
|
||||||
|
throw `Invalid position: (${row}, ${col}). Must be between 0 and 5.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const part = findPartAtPosition(game, row, col);
|
||||||
|
if (!part || part.player !== turnPlayer) {
|
||||||
|
throw `No ${player} piece at (${row}, ${col}).`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return part.id;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
await game.produceAsync(state => {
|
||||||
|
const part = state.pieces[partId];
|
||||||
|
moveToRegion(part, state.regions.board, null);
|
||||||
|
const cat = findPartInRegion(state, '', 'cat');
|
||||||
|
moveToRegion(cat || part, null, state.regions[turnPlayer]);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import {BoopGame} from "@/samples/boop/types-extensions";
|
||||||
|
import {PlayerType} from "@/samples/boop/types";
|
||||||
|
import {findPartAtPosition, findPartInRegion, getLineCandidates} from "@/samples/boop/utils";
|
||||||
|
import {WIN_LENGTH} from "@/samples/boop/constants";
|
||||||
|
import {moveToRegion} from "@/core/region";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查并执行小猫升级(三个小猫连线变成猫)
|
||||||
|
*/
|
||||||
|
export async function checkGraduates(game: BoopGame){
|
||||||
|
const toUpgrade = new Set<string>();
|
||||||
|
for(const line of getLineCandidates()){
|
||||||
|
let whites = 0;
|
||||||
|
let blacks = 0;
|
||||||
|
for(const [row, col] of line){
|
||||||
|
const part = findPartAtPosition(game, row, col);
|
||||||
|
if (part?.player === 'white') whites++;
|
||||||
|
else if(part?.player === 'black') blacks++;
|
||||||
|
}
|
||||||
|
const player = whites >= WIN_LENGTH ? 'white' : blacks >= WIN_LENGTH ? 'black' : null;
|
||||||
|
if(!player) continue;
|
||||||
|
|
||||||
|
for(const [row, col] of line){
|
||||||
|
const part = findPartAtPosition(game, row, col);
|
||||||
|
part && toUpgrade.add(part.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await game.produceAsync(state => {
|
||||||
|
for(const partId of toUpgrade){
|
||||||
|
const part = state.pieces[partId];
|
||||||
|
const [row, col] = part.position;
|
||||||
|
const player = part.player;
|
||||||
|
moveToRegion(part, state.regions.board, null);
|
||||||
|
|
||||||
|
const newPart = findPartInRegion(state, '', 'cat', player);
|
||||||
|
moveToRegion(newPart || part, null, state.regions[player], [row, col]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { BoopGame } from "@/samples/boop/types-extensions";
|
||||||
|
import { PlayerType } from "@/samples/boop/types";
|
||||||
|
import { turn } from "@/samples/boop/commands/turn";
|
||||||
|
import { boop } from "./boop";
|
||||||
|
import { checkFullBoard } from "./full-board";
|
||||||
|
import { checkGraduates } from "./graduate";
|
||||||
|
import { place } from "./place";
|
||||||
|
import { checkWin } from "./win";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动游戏主循环
|
||||||
|
*/
|
||||||
|
export async function start(game: BoopGame) {
|
||||||
|
while (true) {
|
||||||
|
const currentPlayer = game.value.currentPlayer;
|
||||||
|
const turnOutput = await turn(game, currentPlayer);
|
||||||
|
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
state.winner = turnOutput.winner;
|
||||||
|
if (!state.winner) {
|
||||||
|
state.currentPlayer =
|
||||||
|
state.currentPlayer === "white" ? "black" : "white";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (game.value.winner) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return game.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { place, boop, checkWin, checkGraduates, checkFullBoard, turn };
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import {BoopGame} from "@/samples/boop/types-extensions";
|
||||||
|
import {PieceType, PlayerType} from "@/samples/boop/types";
|
||||||
|
import {findPartInRegion} from "@/samples/boop/utils";
|
||||||
|
import {moveToRegion} from "@/core/region";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 放置棋子到棋盘
|
||||||
|
*/
|
||||||
|
export async function place(game: BoopGame, row: number, col: number, player: PlayerType, type: PieceType) {
|
||||||
|
const value = game.value;
|
||||||
|
// 从玩家supply中找到对应类型的棋子
|
||||||
|
const part = findPartInRegion(game, player, type);
|
||||||
|
|
||||||
|
if (!part) {
|
||||||
|
throw new Error(`No ${type} available in ${player}'s supply`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const partId = part.id;
|
||||||
|
|
||||||
|
await game.produceAsync(state => {
|
||||||
|
// 将棋子从supply移动到棋盘
|
||||||
|
const part = state.pieces[partId];
|
||||||
|
moveToRegion(part, state.regions[player], state.regions.board, [row, col]);
|
||||||
|
});
|
||||||
|
|
||||||
|
return { row, col, player, type, partId };
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import {BoopGame} from "@/samples/boop/types-extensions";
|
||||||
|
import {PieceType, PlayerType, WinnerType} from "@/samples/boop/types";
|
||||||
|
import {prompts} from "@/samples/boop/prompts";
|
||||||
|
import {findPartInRegion, isCellOccupied, isInBounds} from "@/samples/boop/utils";
|
||||||
|
import {place} from "@/samples/boop/commands/place";
|
||||||
|
import {boop} from "@/samples/boop/commands/boop";
|
||||||
|
import {checkWin} from "@/samples/boop/commands/win";
|
||||||
|
import {checkGraduates} from "@/samples/boop/commands/graduate";
|
||||||
|
import {checkFullBoard} from "@/samples/boop/commands/full-board";
|
||||||
|
import {BOARD_SIZE} from "@/samples/boop/constants";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理一个回合
|
||||||
|
*/
|
||||||
|
export async function turn(game: BoopGame, turnPlayer: PlayerType) {
|
||||||
|
const {row, col, type} = await game.prompt(
|
||||||
|
prompts.play,
|
||||||
|
(player, row, col, type) => {
|
||||||
|
const pieceType = type === 'cat' ? 'cat' : 'kitten';
|
||||||
|
|
||||||
|
if (player !== turnPlayer) {
|
||||||
|
throw `Invalid player: ${player}. Expected ${turnPlayer}.`;
|
||||||
|
}
|
||||||
|
if (!isInBounds(row, col)) {
|
||||||
|
throw `Invalid position: (${row}, ${col}). Must be between 0 and ${BOARD_SIZE - 1}.`;
|
||||||
|
}
|
||||||
|
if (isCellOccupied(game, row, col)) {
|
||||||
|
throw `Cell (${row}, ${col}) is already occupied.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const found = findPartInRegion(game, player, pieceType);
|
||||||
|
if (!found) {
|
||||||
|
throw `No ${pieceType}s left in ${player}'s supply.`;
|
||||||
|
}
|
||||||
|
return {player, row,col,type};
|
||||||
|
},
|
||||||
|
game.value.currentPlayer
|
||||||
|
);
|
||||||
|
const pieceType = type === 'cat' ? 'cat' : 'kitten';
|
||||||
|
|
||||||
|
await place(game, row, col, turnPlayer, pieceType);
|
||||||
|
await boop(game, row, col, pieceType);
|
||||||
|
const winner = await checkWin(game);
|
||||||
|
if(winner) return { winner: winner };
|
||||||
|
|
||||||
|
await checkGraduates(game);
|
||||||
|
await checkFullBoard(game, turnPlayer);
|
||||||
|
return { winner: null };
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import {BoopGame} from "@/samples/boop/types-extensions";
|
||||||
|
import {PlayerType, WinnerType} from "@/samples/boop/types";
|
||||||
|
import {findPartAtPosition, getLineCandidates} from "@/samples/boop/utils";
|
||||||
|
import {WIN_LENGTH} from "@/samples/boop/constants";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查是否有玩家获胜(三个猫连线)
|
||||||
|
*/
|
||||||
|
export async function checkWin(game: BoopGame): Promise<WinnerType | null> {
|
||||||
|
for(const line of getLineCandidates()){
|
||||||
|
let whites = 0;
|
||||||
|
let blacks = 0;
|
||||||
|
for(const [row, col] of line){
|
||||||
|
const part = findPartAtPosition(game, row, col);
|
||||||
|
if(part?.type !== 'cat') continue;
|
||||||
|
if (part.player === 'white') whites++;
|
||||||
|
else blacks++;
|
||||||
|
}
|
||||||
|
if(whites >= WIN_LENGTH) {
|
||||||
|
return 'white';
|
||||||
|
}
|
||||||
|
if(blacks >= WIN_LENGTH) {
|
||||||
|
return 'black';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export const BOARD_SIZE = 6;
|
||||||
|
export const MAX_PIECES_PER_PLAYER = 8;
|
||||||
|
export const WIN_LENGTH = 3;
|
||||||
+35
-357
@@ -1,363 +1,41 @@
|
|||||||
import {
|
// Types
|
||||||
createGameCommandRegistry,
|
export type {
|
||||||
Part,
|
PlayerType,
|
||||||
MutableSignal,
|
PieceType,
|
||||||
createRegion,
|
WinnerType,
|
||||||
createPart,
|
RegionType,
|
||||||
isCellOccupied as isCellOccupiedUtil,
|
BoopPartMeta,
|
||||||
getPartAtPosition,
|
BoopPart,
|
||||||
} from '@/index';
|
} from "./types";
|
||||||
|
|
||||||
const BOARD_SIZE = 6;
|
export type { BoopGame } from "./types-extensions";
|
||||||
const MAX_PIECES_PER_PLAYER = 8;
|
|
||||||
const WIN_LENGTH = 3;
|
|
||||||
|
|
||||||
export type PlayerType = 'white' | 'black';
|
// Constants
|
||||||
export type PieceType = 'kitten' | 'cat';
|
export { BOARD_SIZE, MAX_PIECES_PER_PLAYER, WIN_LENGTH } from "./constants";
|
||||||
export type WinnerType = PlayerType | 'draw' | null;
|
|
||||||
|
|
||||||
type BoopPart = Part<{ player: PlayerType; pieceType: PieceType }>;
|
// State
|
||||||
|
export { createInitialState, type BoopState } from "./state";
|
||||||
|
|
||||||
type PieceSupply = { supply: number; placed: number };
|
// Prompts
|
||||||
|
export { prompts } from "./prompts";
|
||||||
|
|
||||||
type Player = {
|
// Commands
|
||||||
id: PlayerType;
|
export {
|
||||||
kitten: PieceSupply;
|
start,
|
||||||
cat: PieceSupply;
|
place as placeCmd,
|
||||||
};
|
boop as boopCmd,
|
||||||
|
checkWin as checkWinCmd,
|
||||||
|
checkGraduates as checkGraduatesCmd,
|
||||||
|
checkFullBoard as checkFullBoardCmd,
|
||||||
|
turn as turnCmd,
|
||||||
|
} from "./commands";
|
||||||
|
|
||||||
type PlayerData = Record<PlayerType, Player>;
|
// Utils
|
||||||
|
export {
|
||||||
export function createInitialState() {
|
getLineCandidates,
|
||||||
return {
|
isInBounds,
|
||||||
board: createRegion('board', [
|
isCellOccupied,
|
||||||
{ name: 'x', min: 0, max: BOARD_SIZE - 1 },
|
getNeighborPositions,
|
||||||
{ name: 'y', min: 0, max: BOARD_SIZE - 1 },
|
findPartInRegion,
|
||||||
]),
|
findPartAtPosition,
|
||||||
pieces: {} as Record<string, BoopPart>,
|
} from "./utils";
|
||||||
currentPlayer: 'white' as PlayerType,
|
|
||||||
winner: null as WinnerType,
|
|
||||||
players: {
|
|
||||||
white: createPlayer('white'),
|
|
||||||
black: createPlayer('black'),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function createPlayer(id: PlayerType): Player {
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
kitten: { supply: MAX_PIECES_PER_PLAYER, placed: 0 },
|
|
||||||
cat: { supply: 0, placed: 0 },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export type BoopState = ReturnType<typeof createInitialState>;
|
|
||||||
const registration = createGameCommandRegistry<BoopState>();
|
|
||||||
export const registry = registration.registry;
|
|
||||||
|
|
||||||
export function getPlayer(host: MutableSignal<BoopState>, player: PlayerType): Player {
|
|
||||||
return host.value.players[player];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decrementSupply(player: Player, pieceType: PieceType) {
|
|
||||||
player[pieceType].supply--;
|
|
||||||
player[pieceType].placed++;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function incrementSupply(player: Player, pieceType: PieceType, count?: number) {
|
|
||||||
player[pieceType].supply += count ?? 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
registration.add('setup', async function() {
|
|
||||||
const {context} = this;
|
|
||||||
while (true) {
|
|
||||||
const currentPlayer = context.value.currentPlayer;
|
|
||||||
const turnOutput = await this.run<{winner: WinnerType}>(`turn ${currentPlayer}`);
|
|
||||||
if (!turnOutput.success) throw new Error(turnOutput.error);
|
|
||||||
|
|
||||||
context.produce(state => {
|
|
||||||
state.winner = turnOutput.result.winner;
|
|
||||||
if (!state.winner) {
|
|
||||||
state.currentPlayer = state.currentPlayer === 'white' ? 'black' : 'white';
|
|
||||||
}
|
|
||||||
});
|
|
||||||
if (context.value.winner) break;
|
|
||||||
}
|
|
||||||
|
|
||||||
return context.value;
|
|
||||||
});
|
|
||||||
|
|
||||||
registration.add('turn <player>', async function(cmd) {
|
|
||||||
const [turnPlayer] = cmd.params as [PlayerType];
|
|
||||||
|
|
||||||
const playCmd = await this.prompt(
|
|
||||||
'play <player> <row:number> <col:number> [type:string]',
|
|
||||||
(command) => {
|
|
||||||
const [player, row, col, type] = command.params as [PlayerType, number, number, PieceType?];
|
|
||||||
const pieceType = type === 'cat' ? 'cat' : 'kitten';
|
|
||||||
|
|
||||||
if (player !== turnPlayer) {
|
|
||||||
return `Invalid player: ${player}. Expected ${turnPlayer}.`;
|
|
||||||
}
|
|
||||||
if (!isValidMove(row, col)) {
|
|
||||||
return `Invalid position: (${row}, ${col}). Must be between 0 and ${BOARD_SIZE - 1}.`;
|
|
||||||
}
|
|
||||||
if (isCellOccupied(this.context, row, col)) {
|
|
||||||
return `Cell (${row}, ${col}) is already occupied.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const playerData = getPlayer(this.context, player);
|
|
||||||
const supply = playerData[pieceType].supply;
|
|
||||||
if (supply <= 0) {
|
|
||||||
return `No ${pieceType}s left in ${player}'s supply.`;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
const [player, row, col, type] = playCmd.params as [PlayerType, number, number, PieceType?];
|
|
||||||
const pieceType = type === 'cat' ? 'cat' : 'kitten';
|
|
||||||
|
|
||||||
placePiece(this.context, row, col, turnPlayer, pieceType);
|
|
||||||
applyBoops(this.context, row, col, pieceType);
|
|
||||||
|
|
||||||
const graduatedLines = checkGraduation(this.context, turnPlayer);
|
|
||||||
if (graduatedLines.length > 0) {
|
|
||||||
processGraduation(this.context, turnPlayer, graduatedLines);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (countPiecesOnBoard(this.context, turnPlayer) >= MAX_PIECES_PER_PLAYER) {
|
|
||||||
const pieces = this.context.value.pieces;
|
|
||||||
const availableKittens = Object.values(pieces).filter(
|
|
||||||
p => p.player === turnPlayer && p.pieceType === 'kitten'
|
|
||||||
);
|
|
||||||
|
|
||||||
if (availableKittens.length > 0) {
|
|
||||||
const graduateCmd = await this.prompt(
|
|
||||||
'graduate <row:number> <col:number>',
|
|
||||||
(command) => {
|
|
||||||
const [row, col] = command.params as [number, number];
|
|
||||||
const posKey = `${row},${col}`;
|
|
||||||
const part = availableKittens.find(p => `${p.position[0]},${p.position[1]}` === posKey);
|
|
||||||
if (!part) return `No kitten at (${row}, ${col}).`;
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
const [row, col] = graduateCmd.params as [number, number];
|
|
||||||
const part = availableKittens.find(p => p.position[0] === row && p.position[1] === col)!;
|
|
||||||
removePieceFromBoard(this.context, part);
|
|
||||||
const playerData = getPlayer(this.context, turnPlayer);
|
|
||||||
incrementSupply(playerData, 'cat', 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const winner = checkWinner(this.context);
|
|
||||||
if (winner) return { winner };
|
|
||||||
|
|
||||||
return { winner: null };
|
|
||||||
});
|
|
||||||
|
|
||||||
function isValidMove(row: number, col: number): boolean {
|
|
||||||
return !isNaN(row) && !isNaN(col) && row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getBoardRegion(host: MutableSignal<BoopState>) {
|
|
||||||
return host.value.board;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isCellOccupied(host: MutableSignal<BoopState>, row: number, col: number): boolean {
|
|
||||||
return isCellOccupiedUtil(host.value.pieces, 'board', [row, col]);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getPartAt(host: MutableSignal<BoopState>, row: number, col: number): BoopPart | null {
|
|
||||||
return getPartAtPosition(host.value.pieces, 'board', [row, col]) || null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function placePiece(host: MutableSignal<BoopState>, row: number, col: number, player: PlayerType, pieceType: PieceType) {
|
|
||||||
const board = getBoardRegion(host);
|
|
||||||
const playerData = getPlayer(host, player);
|
|
||||||
const count = playerData[pieceType].placed + 1;
|
|
||||||
|
|
||||||
const piece = createPart<{ player: PlayerType; pieceType: PieceType }>(
|
|
||||||
{ regionId: 'board', position: [row, col], player, pieceType },
|
|
||||||
`${player}-${pieceType}-${count}`
|
|
||||||
);
|
|
||||||
host.produce(s => {
|
|
||||||
s.pieces[piece.id] = piece;
|
|
||||||
board.childIds.push(piece.id);
|
|
||||||
board.partMap[`${row},${col}`] = piece.id;
|
|
||||||
});
|
|
||||||
decrementSupply(playerData, pieceType);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function applyBoops(host: MutableSignal<BoopState>, placedRow: number, placedCol: number, placedType: PieceType) {
|
|
||||||
const board = getBoardRegion(host);
|
|
||||||
const pieces = host.value.pieces;
|
|
||||||
const piecesArray = Object.values(pieces);
|
|
||||||
|
|
||||||
const piecesToBoop: { part: BoopPart; dr: number; dc: number }[] = [];
|
|
||||||
|
|
||||||
for (const part of piecesArray) {
|
|
||||||
const [r, c] = part.position;
|
|
||||||
if (r === placedRow && c === placedCol) continue;
|
|
||||||
|
|
||||||
const dr = Math.sign(r - placedRow);
|
|
||||||
const dc = Math.sign(c - placedCol);
|
|
||||||
|
|
||||||
if (Math.abs(r - placedRow) <= 1 && Math.abs(c - placedCol) <= 1) {
|
|
||||||
const booperIsKitten = placedType === 'kitten';
|
|
||||||
const targetIsCat = part.pieceType === 'cat';
|
|
||||||
|
|
||||||
if (booperIsKitten && targetIsCat) continue;
|
|
||||||
|
|
||||||
piecesToBoop.push({ part, dr, dc });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const { part, dr, dc } of piecesToBoop) {
|
|
||||||
const [r, c] = part.position;
|
|
||||||
const newRow = r + dr;
|
|
||||||
const newCol = c + dc;
|
|
||||||
|
|
||||||
if (newRow < 0 || newRow >= BOARD_SIZE || newCol < 0 || newCol >= BOARD_SIZE) {
|
|
||||||
const pt = part.pieceType;
|
|
||||||
const pl = part.player;
|
|
||||||
const playerData = getPlayer(host, pl);
|
|
||||||
removePieceFromBoard(host, part);
|
|
||||||
incrementSupply(playerData, pt);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isCellOccupied(host, newRow, newCol)) continue;
|
|
||||||
|
|
||||||
part.position = [newRow, newCol];
|
|
||||||
board.partMap = Object.fromEntries(
|
|
||||||
board.childIds.map(id => {
|
|
||||||
const p = pieces[id];
|
|
||||||
return [p.position.join(','), id];
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function removePieceFromBoard(host: MutableSignal<BoopState>, part: BoopPart) {
|
|
||||||
const board = getBoardRegion(host);
|
|
||||||
const playerData = getPlayer(host, part.player);
|
|
||||||
board.childIds = board.childIds.filter(id => id !== part.id);
|
|
||||||
delete board.partMap[part.position.join(',')];
|
|
||||||
delete host.value.pieces[part.id];
|
|
||||||
playerData[part.pieceType].placed--;
|
|
||||||
}
|
|
||||||
|
|
||||||
const DIRECTIONS: [number, number][] = [
|
|
||||||
[0, 1],
|
|
||||||
[1, 0],
|
|
||||||
[1, 1],
|
|
||||||
[1, -1],
|
|
||||||
];
|
|
||||||
|
|
||||||
export function* linesThrough(r: number, c: number): Generator<number[][]> {
|
|
||||||
for (const [dr, dc] of DIRECTIONS) {
|
|
||||||
const minStart = -(WIN_LENGTH - 1);
|
|
||||||
for (let offset = minStart; offset <= 0; offset++) {
|
|
||||||
const startR = r + offset * dr;
|
|
||||||
const startC = c + offset * dc;
|
|
||||||
const endR = startR + (WIN_LENGTH - 1) * dr;
|
|
||||||
const endC = startC + (WIN_LENGTH - 1) * dc;
|
|
||||||
|
|
||||||
if (startR < 0 || startR >= BOARD_SIZE || startC < 0 || startC >= BOARD_SIZE) continue;
|
|
||||||
if (endR < 0 || endR >= BOARD_SIZE || endC < 0 || endC >= BOARD_SIZE) continue;
|
|
||||||
|
|
||||||
const line: number[][] = [];
|
|
||||||
for (let i = 0; i < WIN_LENGTH; i++) {
|
|
||||||
line.push([startR + i * dr, startC + i * dc]);
|
|
||||||
}
|
|
||||||
yield line;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function* allLines(): Generator<number[][]> {
|
|
||||||
const seen = new Set<string>();
|
|
||||||
for (let r = 0; r < BOARD_SIZE; r++) {
|
|
||||||
for (let c = 0; c < BOARD_SIZE; c++) {
|
|
||||||
for (const line of linesThrough(r, c)) {
|
|
||||||
const key = line.map(p => p.join(',')).join(';');
|
|
||||||
if (!seen.has(key)) {
|
|
||||||
seen.add(key);
|
|
||||||
yield line;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function hasWinningLine(positions: number[][]): boolean {
|
|
||||||
const posSet = new Set(positions.map(p => `${p[0]},${p[1]}`));
|
|
||||||
for (const line of allLines()) {
|
|
||||||
if (line.every(([lr, lc]) => posSet.has(`${lr},${lc}`))) return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function checkGraduation(host: MutableSignal<BoopState>, player: PlayerType): number[][][] {
|
|
||||||
const pieces = host.value.pieces;
|
|
||||||
const piecesArray = Object.values(pieces);
|
|
||||||
const posSet = new Set<string>();
|
|
||||||
|
|
||||||
for (const part of piecesArray) {
|
|
||||||
if (part.player === player && part.pieceType === 'kitten') {
|
|
||||||
posSet.add(`${part.position[0]},${part.position[1]}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const winningLines: number[][][] = [];
|
|
||||||
for (const line of allLines()) {
|
|
||||||
if (line.every(([lr, lc]) => posSet.has(`${lr},${lc}`))) {
|
|
||||||
winningLines.push(line);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return winningLines;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function processGraduation(host: MutableSignal<BoopState>, player: PlayerType, lines: number[][][]) {
|
|
||||||
const allPositions = new Set<string>();
|
|
||||||
for (const line of lines) {
|
|
||||||
for (const [r, c] of line) {
|
|
||||||
allPositions.add(`${r},${c}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const board = getBoardRegion(host);
|
|
||||||
const pieces = host.value.pieces;
|
|
||||||
const partsToRemove = Object.values(pieces).filter(
|
|
||||||
p => p.player === player && p.pieceType === 'kitten' && allPositions.has(`${p.position[0]},${p.position[1]}`)
|
|
||||||
);
|
|
||||||
|
|
||||||
for (const part of partsToRemove) {
|
|
||||||
removePieceFromBoard(host, part);
|
|
||||||
}
|
|
||||||
|
|
||||||
const count = partsToRemove.length;
|
|
||||||
const playerData = getPlayer(host, player);
|
|
||||||
incrementSupply(playerData, 'cat', count);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function countPiecesOnBoard(host: MutableSignal<BoopState>, player: PlayerType): number {
|
|
||||||
const pieces = host.value.pieces;
|
|
||||||
return Object.values(pieces).filter(p => p.player === player).length;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function checkWinner(host: MutableSignal<BoopState>): WinnerType {
|
|
||||||
const pieces = host.value.pieces;
|
|
||||||
const piecesArray = Object.values(pieces);
|
|
||||||
|
|
||||||
for (const player of ['white', 'black'] as PlayerType[]) {
|
|
||||||
const positions = piecesArray
|
|
||||||
.filter(p => p.player === player && p.pieceType === 'cat')
|
|
||||||
.map(p => p.position);
|
|
||||||
if (hasWinningLine(positions)) return player;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import {createPromptDef} from "@/core/game";
|
||||||
|
import {PieceType, PlayerType} from "@/samples/boop/types";
|
||||||
|
|
||||||
|
export const prompts = {
|
||||||
|
play: createPromptDef<[PlayerType, number, number, PieceType?]>(
|
||||||
|
'play <player> <row:number> <col:number> [type:string]'),
|
||||||
|
choose: createPromptDef<[PlayerType, number, number]>(
|
||||||
|
'choose <player> <row:number> <col:number>')
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import getParts from './boopPart.csv';
|
||||||
|
import {createRegion, moveToRegion, Region} from "@/core/region";
|
||||||
|
import {createPartsFromTable} from "@/core/part-factory";
|
||||||
|
import {BoopPart} from "@/samples/boop/types";
|
||||||
|
import {BOARD_SIZE} from "@/samples/boop/constants";
|
||||||
|
import {PlayerType, PieceType, RegionType} from "@/samples/boop/types";
|
||||||
|
|
||||||
|
export function createInitialState() {
|
||||||
|
const parts = getParts();
|
||||||
|
const pieces = createPartsFromTable(
|
||||||
|
parts,
|
||||||
|
(item, index) => `${item.player}-${item.type}-${index + 1}`,
|
||||||
|
(item) => item.count
|
||||||
|
) as Record<string, BoopPart>;
|
||||||
|
|
||||||
|
// Initialize region childIds
|
||||||
|
const whiteRegion = createRegion('white', []);
|
||||||
|
const blackRegion = createRegion('black', []);
|
||||||
|
const boardRegion = createRegion('board', [
|
||||||
|
{ name: 'x', min: 0, max: BOARD_SIZE - 1 },
|
||||||
|
{ name: 'y', min: 0, max: BOARD_SIZE - 1 },
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Populate region childIds based on piece regionId
|
||||||
|
for (const part of Object.values(pieces)) {
|
||||||
|
if(part.type !== 'kitten') continue;
|
||||||
|
if (part.player === 'white' ) {
|
||||||
|
moveToRegion(part, null, whiteRegion);
|
||||||
|
} else if (part.player === 'black') {
|
||||||
|
moveToRegion(part, null, blackRegion);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
regions: {
|
||||||
|
white: whiteRegion,
|
||||||
|
black: blackRegion,
|
||||||
|
board: boardRegion,
|
||||||
|
} as Record<RegionType, Region>,
|
||||||
|
pieces,
|
||||||
|
currentPlayer: 'white' as PlayerType,
|
||||||
|
winner: null as PlayerType | 'draw' | null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
export type BoopState = ReturnType<typeof createInitialState>;
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import {IGameContext} from "@/core/game";
|
||||||
|
import {BoopState} from "@/samples/boop/state";
|
||||||
|
|
||||||
|
export type BoopGame = IGameContext<BoopState>;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import {Part} from "@/core/part";
|
||||||
|
|
||||||
|
export type PlayerType = 'white' | 'black';
|
||||||
|
export type PieceType = 'kitten' | 'cat';
|
||||||
|
export type WinnerType = PlayerType | 'draw' | null;
|
||||||
|
export type RegionType = 'white' | 'black' | 'board' | '';
|
||||||
|
|
||||||
|
export type BoopPartMeta = { player: PlayerType; type: PieceType };
|
||||||
|
export type BoopPart = Part<BoopPartMeta>;
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import {BOARD_SIZE, WIN_LENGTH} from "@/samples/boop/constants";
|
||||||
|
import {BoopState} from "@/samples/boop/state";
|
||||||
|
import {BoopGame} from "@/samples/boop/types-extensions";
|
||||||
|
|
||||||
|
const DIRS = [
|
||||||
|
[0, 1],
|
||||||
|
[1, 0],
|
||||||
|
[1, 1],
|
||||||
|
[-1, 1]
|
||||||
|
]
|
||||||
|
type PT = [number, number];
|
||||||
|
type Line = PT[];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成所有可能的连线候选(用于检查胜利或升级)
|
||||||
|
*/
|
||||||
|
export function* getLineCandidates(){
|
||||||
|
for(const [dx, dy] of DIRS){
|
||||||
|
for(let x = 0; x < BOARD_SIZE; x ++)
|
||||||
|
for(let y = 0; y < BOARD_SIZE; y ++){
|
||||||
|
if(!isInBounds(x + dx * (WIN_LENGTH-1), y + dy * (WIN_LENGTH-1))) continue;
|
||||||
|
const line = [];
|
||||||
|
for(let i = 0; i < WIN_LENGTH; i ++){
|
||||||
|
line.push([x + i * dx, y + i * dy]);
|
||||||
|
}
|
||||||
|
yield line as Line;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查位置是否在棋盘范围内
|
||||||
|
*/
|
||||||
|
export function isInBounds(x: number, y: number): boolean {
|
||||||
|
return x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查单元格是否被占用
|
||||||
|
*/
|
||||||
|
export function isCellOccupied(game: BoopGame | BoopState, x: number, y: number): boolean {
|
||||||
|
const state = getState(game);
|
||||||
|
const id = `${x},${y}`;
|
||||||
|
return state.regions.board.partMap[id] !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取邻居位置生成器
|
||||||
|
*/
|
||||||
|
export function* getNeighborPositions(x: number = 0, y: number = 0){
|
||||||
|
for(let dx = -1; dx <= 1; dx ++)
|
||||||
|
for(let dy = -1; dy <= 1; dy ++)
|
||||||
|
if(dx !== 0 || dy !== 0)
|
||||||
|
yield [x + dx, y + dy] as PT;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getState(ctx: BoopGame | BoopState): BoopState {
|
||||||
|
if('value' in ctx){
|
||||||
|
return ctx.value;
|
||||||
|
}
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
export {
|
||||||
|
getLineCandidates,
|
||||||
|
isInBounds,
|
||||||
|
isCellOccupied,
|
||||||
|
getNeighborPositions
|
||||||
|
} from './board';
|
||||||
|
|
||||||
|
export {
|
||||||
|
findPartInRegion,
|
||||||
|
findPartAtPosition
|
||||||
|
} from './pieces';
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import {BoopPart, PieceType, PlayerType, RegionType} from "@/samples/boop/types";
|
||||||
|
import {BoopState} from "@/samples/boop/state";
|
||||||
|
import {BoopGame} from "@/samples/boop/types-extensions";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在区域中查找棋子
|
||||||
|
*/
|
||||||
|
export function findPartInRegion(
|
||||||
|
ctx: BoopGame | BoopState,
|
||||||
|
regionId: keyof BoopGame['value']['regions'],
|
||||||
|
type: PieceType,
|
||||||
|
player?: PlayerType
|
||||||
|
): BoopPart | null {
|
||||||
|
const state = getState(ctx);
|
||||||
|
if(!regionId){
|
||||||
|
return Object.values(state.pieces).find(part => match(regionId, part, type, player)) || null;
|
||||||
|
}
|
||||||
|
const id = state.regions[regionId].childIds.find(id => match(regionId, state.pieces[id], type, player));
|
||||||
|
return id ? state.pieces[id] || null : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在指定位置查找棋子
|
||||||
|
*/
|
||||||
|
export function findPartAtPosition(ctx: BoopGame | BoopState, row: number, col: number): BoopPart | null {
|
||||||
|
const state = getState(ctx);
|
||||||
|
const id = state.regions.board.partMap[`${row},${col}`];
|
||||||
|
return id ? state.pieces[id] || null : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function match(regionId: RegionType, part: BoopPart, type: PieceType, player?: PlayerType){
|
||||||
|
return regionId === part.regionId && part.type === type && (!player || part.player === player);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getState(ctx: BoopGame | BoopState): BoopState {
|
||||||
|
if('value' in ctx){
|
||||||
|
return ctx.value;
|
||||||
|
}
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
# pattern forms a grid of 5x5
|
||||||
|
# o is the move's starting postion
|
||||||
|
# x are move end position candidates
|
||||||
|
# . is space
|
||||||
|
|
||||||
|
# first row, first position is dx=-2 dy=2
|
||||||
|
name,startingPlayer,row,pattern
|
||||||
|
string,string,number,string
|
||||||
|
|
||||||
|
tiger,black,0,..x..
|
||||||
|
tiger,black,1,.....
|
||||||
|
tiger,black,2,..o..
|
||||||
|
tiger,black,3,..x..
|
||||||
|
tiger,black,4,.....
|
||||||
|
|
||||||
|
dragon,red,0,.....
|
||||||
|
dragon,red,1,x...x
|
||||||
|
dragon,red,2,..o..
|
||||||
|
dragon,red,3,.x.x.
|
||||||
|
dragon,red,4,.....
|
||||||
|
|
||||||
|
frog,black,0,.....
|
||||||
|
frog,black,1,.x...
|
||||||
|
frog,black,2,x.o..
|
||||||
|
frog,black,3,...x.
|
||||||
|
frog,black,4,.....
|
||||||
|
|
||||||
|
rabbit,black,0,.....
|
||||||
|
rabbit,black,1,...x.
|
||||||
|
rabbit,black,2,..o.x
|
||||||
|
rabbit,black,3,.x...
|
||||||
|
rabbit,black,4,.....
|
||||||
|
|
||||||
|
crab,black,0,.....
|
||||||
|
crab,black,1,..x..
|
||||||
|
crab,black,2,x.o.x
|
||||||
|
crab,black,3,.....
|
||||||
|
crab,black,4,.....
|
||||||
|
|
||||||
|
elephant,red,0,.....
|
||||||
|
elephant,red,1,.x.x.
|
||||||
|
elephant,red,2,.xox.
|
||||||
|
elephant,red,3,.....
|
||||||
|
elephant,red,4,.....
|
||||||
|
|
||||||
|
goose,black,0,.....
|
||||||
|
goose,black,1,.x...
|
||||||
|
goose,black,2,.xox.
|
||||||
|
goose,black,3,...x.
|
||||||
|
goose,black,4,.....
|
||||||
|
|
||||||
|
rooster,red,0,.....
|
||||||
|
rooster,red,1,...x.
|
||||||
|
rooster,red,2,.xox.
|
||||||
|
rooster,red,3,.x...
|
||||||
|
rooster,red,4,.....
|
||||||
|
|
||||||
|
monkey,black,0,.....
|
||||||
|
monkey,black,1,.x.x.
|
||||||
|
monkey,black,2,..o..
|
||||||
|
monkey,black,3,.x.x.
|
||||||
|
monkey,black,4,.....
|
||||||
|
|
||||||
|
mantis,red,0,.....
|
||||||
|
mantis,red,1,.x.x.
|
||||||
|
mantis,red,2,..o..
|
||||||
|
mantis,red,3,..x..
|
||||||
|
mantis,red,4,.....
|
||||||
|
|
||||||
|
horse,red,0,.....
|
||||||
|
horse,red,1,..x..
|
||||||
|
horse,red,2,.xo..
|
||||||
|
horse,red,3,..x..
|
||||||
|
horse,red,4,.....
|
||||||
|
|
||||||
|
ox,black,0,.....
|
||||||
|
ox,black,1,..x..
|
||||||
|
ox,black,2,..ox.
|
||||||
|
ox,black,3,..x..
|
||||||
|
ox,black,4,.....
|
||||||
|
|
||||||
|
crane,black,0,.....
|
||||||
|
crane,black,1,..x..
|
||||||
|
crane,black,2,..o..
|
||||||
|
crane,black,3,.x.x.
|
||||||
|
crane,black,4,.....
|
||||||
|
|
||||||
|
boar,red,0,.....
|
||||||
|
boar,red,1,..x..
|
||||||
|
boar,red,2,.xox.
|
||||||
|
boar,red,3,.....
|
||||||
|
boar,red,4,.....
|
||||||
|
|
||||||
|
eel,black,0,.....
|
||||||
|
eel,black,1,.x...
|
||||||
|
eel,black,2,..ox.
|
||||||
|
eel,black,3,.x...
|
||||||
|
eel,black,4,.....
|
||||||
|
|
||||||
|
cobra,red,0,.....
|
||||||
|
cobra,red,1,...x.
|
||||||
|
cobra,red,2,.xo..
|
||||||
|
cobra,red,3,...x.
|
||||||
|
cobra,red,4,.....
|
||||||
|
Vendored
+11
@@ -0,0 +1,11 @@
|
|||||||
|
type CardsTable = readonly {
|
||||||
|
readonly name: string;
|
||||||
|
readonly startingPlayer: string;
|
||||||
|
readonly row: number;
|
||||||
|
readonly pattern: string;
|
||||||
|
}[];
|
||||||
|
|
||||||
|
export type Cards = CardsTable[number];
|
||||||
|
|
||||||
|
declare function getData(): CardsTable;
|
||||||
|
export default getData;
|
||||||
@@ -0,0 +1,409 @@
|
|||||||
|
import {
|
||||||
|
OnitamaGame,
|
||||||
|
OnitamaState,
|
||||||
|
PlayerType,
|
||||||
|
prompts,
|
||||||
|
initializeCards,
|
||||||
|
} from "./types";
|
||||||
|
import { moveToRegion } from "@/core/region";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查位置是否在棋盘范围内
|
||||||
|
*/
|
||||||
|
function isInBounds(x: number, y: number): boolean {
|
||||||
|
return x >= 0 && x < 5 && y >= 0 && y < 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查位置是否有棋子
|
||||||
|
*/
|
||||||
|
function getPawnAtPosition(state: OnitamaState, x: number, y: number) {
|
||||||
|
const key = `${x},${y}`;
|
||||||
|
const pawnId = state.regions.board.partMap[key];
|
||||||
|
return pawnId ? state.pawns[pawnId] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查玩家是否拥有某张卡牌
|
||||||
|
*/
|
||||||
|
function playerHasCard(
|
||||||
|
state: OnitamaState,
|
||||||
|
player: PlayerType,
|
||||||
|
cardName: string,
|
||||||
|
): boolean {
|
||||||
|
const cardList = player === "red" ? state.redCards : state.blackCards;
|
||||||
|
return cardList.includes(cardName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取卡牌的移动候选项,根据玩家视角进行旋转
|
||||||
|
* 黑方需要将卡牌旋转180度
|
||||||
|
*/
|
||||||
|
export function getCardMoveCandidates(
|
||||||
|
state: OnitamaState,
|
||||||
|
cardName: string,
|
||||||
|
player: PlayerType,
|
||||||
|
) {
|
||||||
|
const card = state.cards[cardName];
|
||||||
|
const candidates = card.moveCandidates;
|
||||||
|
|
||||||
|
// 黑方需要将卡牌旋转180度
|
||||||
|
if (player === "black") {
|
||||||
|
return candidates.map((m) => ({ dx: -m.dx, dy: -m.dy }));
|
||||||
|
}
|
||||||
|
|
||||||
|
return candidates;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查移动是否合法
|
||||||
|
*/
|
||||||
|
export function isValidMove(
|
||||||
|
state: OnitamaState,
|
||||||
|
cardName: string,
|
||||||
|
fromX: number,
|
||||||
|
fromY: number,
|
||||||
|
toX: number,
|
||||||
|
toY: number,
|
||||||
|
player: PlayerType,
|
||||||
|
): string | null {
|
||||||
|
// 检查玩家是否拥有该卡牌
|
||||||
|
if (!playerHasCard(state, player, cardName)) {
|
||||||
|
return `玩家 ${player} 不拥有卡牌 ${cardName}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查起始位置是否有玩家的棋子
|
||||||
|
const fromPawn = getPawnAtPosition(state, fromX, fromY);
|
||||||
|
if (!fromPawn) {
|
||||||
|
return `位置 (${fromX}, ${fromY}) 没有棋子`;
|
||||||
|
}
|
||||||
|
if (fromPawn.owner !== player) {
|
||||||
|
return `位置 (${fromX}, ${fromY}) 的棋子不属于玩家 ${player}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查卡牌是否存在
|
||||||
|
const card = state.cards[cardName];
|
||||||
|
if (!card) {
|
||||||
|
return `卡牌 ${cardName} 不存在`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算移动偏移量
|
||||||
|
const dx = toX - fromX;
|
||||||
|
const dy = toY - fromY;
|
||||||
|
|
||||||
|
// 检查移动是否在卡牌的移动候选项中(黑方需要旋转180度)
|
||||||
|
const candidates = getCardMoveCandidates(state, cardName, player);
|
||||||
|
const isValid = candidates.some((m) => m.dx === dx && m.dy === dy);
|
||||||
|
if (!isValid) {
|
||||||
|
return `卡牌 ${cardName} 不支持移动 (${dx}, ${dy})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查目标位置是否在棋盘内
|
||||||
|
if (!isInBounds(toX, toY)) {
|
||||||
|
return `目标位置 (${toX}, ${toY}) 超出棋盘范围`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查目标位置是否有己方棋子
|
||||||
|
const toPawn = getPawnAtPosition(state, toX, toY);
|
||||||
|
if (toPawn && toPawn.owner === player) {
|
||||||
|
return `目标位置 (${toX}, ${toY}) 已有己方棋子`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行移动
|
||||||
|
*/
|
||||||
|
async function move(
|
||||||
|
game: OnitamaGame,
|
||||||
|
player: PlayerType,
|
||||||
|
cardName: string,
|
||||||
|
fromX: number,
|
||||||
|
fromY: number,
|
||||||
|
toX: number,
|
||||||
|
toY: number,
|
||||||
|
) {
|
||||||
|
const state = game.value;
|
||||||
|
|
||||||
|
// 验证移动
|
||||||
|
const error = isValidMove(state, cardName, fromX, fromY, toX, toY, player);
|
||||||
|
if (error) {
|
||||||
|
throw new Error(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const capturedPawnId = getPawnAtPosition(state, toX, toY)?.id || null;
|
||||||
|
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
const pawn = state.pawns[getPawnAtPosition(state, fromX, fromY)!.id];
|
||||||
|
|
||||||
|
// 如果目标位置有敌方棋子,将其移除(吃掉)
|
||||||
|
if (capturedPawnId) {
|
||||||
|
const capturedPawn = state.pawns[capturedPawnId];
|
||||||
|
moveToRegion(capturedPawn, state.regions.board, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 移动棋子到目标位置
|
||||||
|
moveToRegion(pawn, state.regions.board, state.regions.board, [toX, toY]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 交换卡牌
|
||||||
|
await swapCard(game, player, cardName);
|
||||||
|
|
||||||
|
return {
|
||||||
|
from: { x: fromX, y: fromY },
|
||||||
|
to: { x: toX, y: toY },
|
||||||
|
card: cardName,
|
||||||
|
captured: capturedPawnId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 交换卡牌:将使用的卡牌与备用卡牌交换
|
||||||
|
*/
|
||||||
|
async function swapCard(
|
||||||
|
game: OnitamaGame,
|
||||||
|
player: PlayerType,
|
||||||
|
usedCard: string,
|
||||||
|
) {
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
const spareCard = state.spareCard;
|
||||||
|
const usedCardData = state.cards[usedCard];
|
||||||
|
const spareCardData = state.cards[spareCard];
|
||||||
|
|
||||||
|
// 从玩家手牌中移除使用的卡牌
|
||||||
|
if (player === "red") {
|
||||||
|
state.redCards = state.redCards.filter((c) => c !== usedCard);
|
||||||
|
state.redCards.push(spareCard);
|
||||||
|
} else {
|
||||||
|
state.blackCards = state.blackCards.filter((c) => c !== usedCard);
|
||||||
|
state.blackCards.push(spareCard);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新卡牌区域
|
||||||
|
usedCardData.regionId = "spare";
|
||||||
|
spareCardData.regionId = player;
|
||||||
|
|
||||||
|
// 更新备用卡牌
|
||||||
|
state.spareCard = usedCard;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查占领胜利条件:玩家的师父棋子到达对手的初始位置
|
||||||
|
* 红色师父需要到达 (2, 4) - 黑色师父的初始位置
|
||||||
|
* 黑色师父需要到达 (2, 0) - 红色师父的初始位置
|
||||||
|
*/
|
||||||
|
async function checkConquestWin(game: OnitamaGame): Promise<PlayerType | null> {
|
||||||
|
const state = game.value;
|
||||||
|
|
||||||
|
// 红色师父到达 (2, 4)(黑色师父的初始位置)
|
||||||
|
const redMaster = state.pawns["red-master"];
|
||||||
|
if (
|
||||||
|
redMaster &&
|
||||||
|
redMaster.regionId === "board" &&
|
||||||
|
redMaster.position[0] === 2 &&
|
||||||
|
redMaster.position[1] === 4
|
||||||
|
) {
|
||||||
|
return "red";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 黑色师父到达 (2, 0)(红色师父的初始位置)
|
||||||
|
const blackMaster = state.pawns["black-master"];
|
||||||
|
if (
|
||||||
|
blackMaster &&
|
||||||
|
blackMaster.regionId === "board" &&
|
||||||
|
blackMaster.position[0] === 2 &&
|
||||||
|
blackMaster.position[1] === 0
|
||||||
|
) {
|
||||||
|
return "black";
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查吃掉胜利条件:对手的师父棋子被吃掉(不在棋盘上)
|
||||||
|
*/
|
||||||
|
async function checkCaptureWin(game: OnitamaGame): Promise<PlayerType | null> {
|
||||||
|
const state = game.value;
|
||||||
|
|
||||||
|
// 红色师父不在棋盘上,黑色获胜
|
||||||
|
const redMaster = state.pawns["red-master"];
|
||||||
|
if (!redMaster || redMaster.regionId !== "board") {
|
||||||
|
return "black";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 黑色师父不在棋盘上,红色获胜
|
||||||
|
const blackMaster = state.pawns["black-master"];
|
||||||
|
if (!blackMaster || blackMaster.regionId !== "board") {
|
||||||
|
return "red";
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 综合胜利检测
|
||||||
|
*/
|
||||||
|
async function checkWin(game: OnitamaGame): Promise<PlayerType | null> {
|
||||||
|
const conquestWinner = await checkConquestWin(game);
|
||||||
|
if (conquestWinner) {
|
||||||
|
return conquestWinner;
|
||||||
|
}
|
||||||
|
|
||||||
|
const captureWinner = await checkCaptureWin(game);
|
||||||
|
if (captureWinner) {
|
||||||
|
return captureWinner;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取玩家可用的移动
|
||||||
|
*/
|
||||||
|
export function getAvailableMoves(
|
||||||
|
state: OnitamaState,
|
||||||
|
player: PlayerType,
|
||||||
|
): Array<{
|
||||||
|
card: string;
|
||||||
|
fromX: number;
|
||||||
|
fromY: number;
|
||||||
|
toX: number;
|
||||||
|
toY: number;
|
||||||
|
}> {
|
||||||
|
const moves: Array<{
|
||||||
|
card: string;
|
||||||
|
fromX: number;
|
||||||
|
fromY: number;
|
||||||
|
toX: number;
|
||||||
|
toY: number;
|
||||||
|
}> = [];
|
||||||
|
|
||||||
|
// 获取玩家的所有卡牌
|
||||||
|
const cardNames = player === "red" ? state.redCards : state.blackCards;
|
||||||
|
|
||||||
|
// 获取玩家的所有棋子
|
||||||
|
const playerPawns = Object.values(state.pawns).filter(
|
||||||
|
(p) => p.owner === player && p.regionId === "board",
|
||||||
|
);
|
||||||
|
|
||||||
|
// 对于每张卡牌
|
||||||
|
for (const cardName of cardNames) {
|
||||||
|
// 获取旋转后的移动候选项(黑方需要旋转180度)
|
||||||
|
const candidates = getCardMoveCandidates(state, cardName, player);
|
||||||
|
|
||||||
|
// 对于每个棋子
|
||||||
|
for (const pawn of playerPawns) {
|
||||||
|
const [fromX, fromY] = pawn.position;
|
||||||
|
|
||||||
|
// 对于卡牌的每个移动
|
||||||
|
for (const move of candidates) {
|
||||||
|
const toX = fromX + move.dx;
|
||||||
|
const toY = fromY + move.dy;
|
||||||
|
|
||||||
|
// 检查移动是否合法
|
||||||
|
if (isInBounds(toX, toY)) {
|
||||||
|
const targetPawn = getPawnAtPosition(state, toX, toY);
|
||||||
|
// 目标位置为空或有敌方棋子
|
||||||
|
if (!targetPawn || targetPawn.owner !== player) {
|
||||||
|
moves.push({ card: cardName, fromX, fromY, toX, toY });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return moves;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理回合
|
||||||
|
*/
|
||||||
|
async function turn(game: OnitamaGame, turnPlayer: PlayerType) {
|
||||||
|
const state = game.value;
|
||||||
|
const availableMoves = getAvailableMoves(state, turnPlayer);
|
||||||
|
|
||||||
|
let moveOutput;
|
||||||
|
|
||||||
|
if (availableMoves.length === 0) {
|
||||||
|
// 没有可用移动,玩家必须交换一张卡牌
|
||||||
|
const cardToSwap = await game.prompt(
|
||||||
|
prompts.move,
|
||||||
|
(player, card, _fromX, _fromY, _toX, _toY) => {
|
||||||
|
if (player !== turnPlayer) {
|
||||||
|
throw `Invalid player: ${player}. Expected ${turnPlayer}.`;
|
||||||
|
}
|
||||||
|
if (!playerHasCard(state, player, card)) {
|
||||||
|
throw `Player ${player} does not have card ${card}.`;
|
||||||
|
}
|
||||||
|
return card;
|
||||||
|
},
|
||||||
|
turnPlayer,
|
||||||
|
);
|
||||||
|
|
||||||
|
await swapCard(game, turnPlayer, cardToSwap);
|
||||||
|
moveOutput = { swappedCard: cardToSwap, noMoves: true };
|
||||||
|
} else {
|
||||||
|
// 有可用移动,提示玩家选择
|
||||||
|
moveOutput = await game.prompt(
|
||||||
|
prompts.move,
|
||||||
|
(player, card, fromX, fromY, toX, toY) => {
|
||||||
|
if (player !== turnPlayer) {
|
||||||
|
throw `Invalid player: ${player}. Expected ${turnPlayer}.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const error = isValidMove(state, card, fromX, fromY, toX, toY, player);
|
||||||
|
if (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { player, card, fromX, fromY, toX, toY };
|
||||||
|
},
|
||||||
|
turnPlayer,
|
||||||
|
);
|
||||||
|
|
||||||
|
await move(
|
||||||
|
game,
|
||||||
|
moveOutput.player,
|
||||||
|
moveOutput.card,
|
||||||
|
moveOutput.fromX,
|
||||||
|
moveOutput.fromY,
|
||||||
|
moveOutput.toX,
|
||||||
|
moveOutput.toY,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查胜利
|
||||||
|
const winner = await checkWin(game);
|
||||||
|
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
state.winner = winner;
|
||||||
|
if (!winner) {
|
||||||
|
state.currentPlayer = state.currentPlayer === "red" ? "black" : "red";
|
||||||
|
state.turn++;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return { winner, move: moveOutput };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 开始游戏主循环
|
||||||
|
*/
|
||||||
|
export async function start(game: OnitamaGame) {
|
||||||
|
// Initialize cards with RNG at game start
|
||||||
|
initializeCards(game);
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const currentPlayer = game.value.currentPlayer;
|
||||||
|
const turnOutput = await turn(game, currentPlayer);
|
||||||
|
|
||||||
|
if (turnOutput.winner) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return game.value;
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export * from './types';
|
||||||
|
export * from './commands';
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# Onitama
|
||||||
|
|
||||||
|
## 游戏目标
|
||||||
|
|
||||||
|
玩家在棋盘上移动棋子,达成两种胜利条件当中的一种即可赢得游戏:
|
||||||
|
- 占领:将师父棋子移动到对手师父棋子的初始位置
|
||||||
|
- 吃掉:将对手的师父棋子吃掉
|
||||||
|
|
||||||
|
## 游戏配件
|
||||||
|
|
||||||
|
公共配件:
|
||||||
|
- 卡牌:16张,每张标记一位起始玩家,和一个移动方式图示
|
||||||
|
- 棋盘:1个,5x5
|
||||||
|
|
||||||
|
玩家配件:
|
||||||
|
- 师父棋子:1个
|
||||||
|
- 徒弟棋子:4个
|
||||||
|
|
||||||
|
## 游戏布置
|
||||||
|
|
||||||
|
1. 将所有玩家的棋子放在棋盘的初始位置上:
|
||||||
|
```
|
||||||
|
bbBbb
|
||||||
|
.....
|
||||||
|
.....
|
||||||
|
.....
|
||||||
|
rrRrr
|
||||||
|
```
|
||||||
|
其中b表示黑方,r表示红方,大写表示师父,小写表示徒弟。
|
||||||
|
|
||||||
|
2. 将所有卡牌洗混,每名玩家抓2张放在自己面前。
|
||||||
|
|
||||||
|
3. 翻开一张卡牌作为额外卡牌。额外卡牌标记的玩家成为起始玩家。
|
||||||
|
|
||||||
|
## 游戏进行
|
||||||
|
|
||||||
|
从起始玩家开始,轮流进行以下步骤:
|
||||||
|
- 选择一张卡牌,按照其描述移动棋子。
|
||||||
|
- 将选择的卡牌与额外卡牌交换。
|
||||||
|
|
||||||
|
移动时,可以选择自己的任意棋子。
|
||||||
|
移动落点必须是空位或者对手的棋子。
|
||||||
|
若移动到对手的棋子上,则吃掉该棋子。
|
||||||
|
|
||||||
|
若玩家没有任何能够进行的移动,可以任意选择一张卡牌与额外卡牌交换,然后直接结束回合。
|
||||||
|
|
||||||
|
之后若有玩家达成胜利条件,游戏结束。
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
import getCards from './cards.csv';
|
||||||
|
import {Part} from "@/core/part";
|
||||||
|
import {createRegion, createRegionAxis, Region} from "@/core/region";
|
||||||
|
import {createPromptDef, IGameContext} from "@/core/game";
|
||||||
|
|
||||||
|
export type PlayerType = 'red' | 'black';
|
||||||
|
export type CardData = {
|
||||||
|
moveCandidates: {
|
||||||
|
dx: number,
|
||||||
|
dy: number,
|
||||||
|
}[];
|
||||||
|
startingPlayer: PlayerType
|
||||||
|
}
|
||||||
|
export type Card = Part<CardData>;
|
||||||
|
export type Pawn = Part<{
|
||||||
|
type: 'master' | 'student',
|
||||||
|
owner: PlayerType,
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function createRegions(){
|
||||||
|
return {
|
||||||
|
board: createRegion('board', [
|
||||||
|
createRegionAxis('x', 0, 4),
|
||||||
|
createRegionAxis('y', 0, 4),
|
||||||
|
]),
|
||||||
|
red: createRegion('red', []),
|
||||||
|
black: createRegion('black', []),
|
||||||
|
spare: createRegion('spare', []),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export type RegionType = keyof ReturnType<typeof createRegions>;
|
||||||
|
|
||||||
|
export function createGameInfo(){
|
||||||
|
return {
|
||||||
|
turn: 0,
|
||||||
|
currentPlayer: 'red' as PlayerType,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createCards(){
|
||||||
|
const cards = getCards();
|
||||||
|
const dataMap = {} as Record<string, CardData>;
|
||||||
|
|
||||||
|
for(const entry of cards){
|
||||||
|
const card = dataMap[entry.name] = dataMap[entry.name] || {
|
||||||
|
moveCandidates: [],
|
||||||
|
startingPlayer: entry.startingPlayer,
|
||||||
|
}
|
||||||
|
|
||||||
|
for(let i = 0; i < entry.pattern.length; i++){
|
||||||
|
if(entry.pattern[i] !== 'x') continue;
|
||||||
|
const dx = i - 2;
|
||||||
|
const dy = 2 - entry.row;
|
||||||
|
card.moveCandidates.push({dx, dy});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const cardsMap = {} as Record<string, Card>;
|
||||||
|
for(const [name, data] of Object.entries(dataMap)){
|
||||||
|
cardsMap[name] = {
|
||||||
|
id: name,
|
||||||
|
regionId: '',
|
||||||
|
position: [],
|
||||||
|
...data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cardsMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createPawns(){
|
||||||
|
const pawns: Record<string, Pawn> = {};
|
||||||
|
|
||||||
|
// Red player: 1 master (R) at y=0, 4 students (r) at y=0
|
||||||
|
// Position: rrRrr at y=0
|
||||||
|
pawns['red-master'] = {
|
||||||
|
id: 'red-master',
|
||||||
|
regionId: 'board',
|
||||||
|
position: [2, 0],
|
||||||
|
type: 'master',
|
||||||
|
owner: 'red',
|
||||||
|
};
|
||||||
|
|
||||||
|
for(let i = 0; i < 4; i++){
|
||||||
|
const x = i < 2 ? i : i + 1; // Skip position 2 (master)
|
||||||
|
pawns[`red-student-${i+1}`] = {
|
||||||
|
id: `red-student-${i+1}`,
|
||||||
|
regionId: 'board',
|
||||||
|
position: [x, 0],
|
||||||
|
type: 'student',
|
||||||
|
owner: 'red',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Black player: 1 master (B) at y=4, 4 students (b) at y=4
|
||||||
|
// Position: bbBbb at y=4
|
||||||
|
pawns['black-master'] = {
|
||||||
|
id: 'black-master',
|
||||||
|
regionId: 'board',
|
||||||
|
position: [2, 4],
|
||||||
|
type: 'master',
|
||||||
|
owner: 'black',
|
||||||
|
};
|
||||||
|
|
||||||
|
for(let i = 0; i < 4; i++){
|
||||||
|
const x = i < 2 ? i : i + 1; // Skip position 2 (master)
|
||||||
|
pawns[`black-student-${i+1}`] = {
|
||||||
|
id: `black-student-${i+1}`,
|
||||||
|
regionId: 'board',
|
||||||
|
position: [x, 4],
|
||||||
|
type: 'student',
|
||||||
|
owner: 'black',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return pawns;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const prompts = {
|
||||||
|
move: createPromptDef<[PlayerType, string, number, number, number, number]>(
|
||||||
|
'move <player> <card> <fromX:number> <fromY:number> <toX:number> <toY:number>',
|
||||||
|
'选择卡牌并移动棋子'
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createInitialState() {
|
||||||
|
const regions = createRegions();
|
||||||
|
const pawns = createPawns();
|
||||||
|
const cards = createCards();
|
||||||
|
|
||||||
|
// Cards will be shuffled and distributed in start()
|
||||||
|
// Initialize with empty card lists
|
||||||
|
const redCards: string[] = [];
|
||||||
|
const blackCards: string[] = [];
|
||||||
|
const spareCard = '';
|
||||||
|
|
||||||
|
// Populate board region childIds
|
||||||
|
for(const pawn of Object.values(pawns)){
|
||||||
|
if(pawn.regionId === 'board'){
|
||||||
|
regions.board.childIds.push(pawn.id);
|
||||||
|
regions.board.partMap[pawn.position.join(',')] = pawn.id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
regions,
|
||||||
|
pawns,
|
||||||
|
cards,
|
||||||
|
currentPlayer: 'red' as PlayerType,
|
||||||
|
winner: null as PlayerType | null,
|
||||||
|
spareCard,
|
||||||
|
redCards,
|
||||||
|
blackCards,
|
||||||
|
turn: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 洗牌并分配卡牌,设置起始玩家
|
||||||
|
*/
|
||||||
|
export function initializeCards(game: OnitamaGame) {
|
||||||
|
const state = game.value;
|
||||||
|
const rng = game.rng;
|
||||||
|
const cardNames = Object.keys(state.cards);
|
||||||
|
|
||||||
|
// Fisher-Yates shuffle using game.rng
|
||||||
|
const shuffled = [...cardNames];
|
||||||
|
for (let i = shuffled.length - 1; i > 0; i--) {
|
||||||
|
const j = rng.nextInt(i + 1);
|
||||||
|
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
|
||||||
|
}
|
||||||
|
|
||||||
|
const redCards = shuffled.slice(0, 2);
|
||||||
|
const blackCards = shuffled.slice(2, 4);
|
||||||
|
const spareCard = shuffled[4];
|
||||||
|
|
||||||
|
game.produce(state => {
|
||||||
|
// Set card regions
|
||||||
|
for(const cardName of redCards){
|
||||||
|
state.cards[cardName].regionId = 'red';
|
||||||
|
state.regions.red.childIds.push(cardName);
|
||||||
|
}
|
||||||
|
for(const cardName of blackCards){
|
||||||
|
state.cards[cardName].regionId = 'black';
|
||||||
|
state.regions.black.childIds.push(cardName);
|
||||||
|
}
|
||||||
|
state.cards[spareCard].regionId = 'spare';
|
||||||
|
state.regions.spare.childIds.push(spareCard);
|
||||||
|
|
||||||
|
// Set card lists
|
||||||
|
state.redCards = redCards;
|
||||||
|
state.blackCards = blackCards;
|
||||||
|
state.spareCard = spareCard;
|
||||||
|
|
||||||
|
// Determine starting player from spare card
|
||||||
|
state.currentPlayer = state.cards[spareCard].startingPlayer;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export type OnitamaState = ReturnType<typeof createInitialState>;
|
||||||
|
export type OnitamaGame = IGameContext<OnitamaState>;
|
||||||
@@ -0,0 +1,417 @@
|
|||||||
|
import { IGameContext } from "@/core/game";
|
||||||
|
import { RegicideState } from "@/samples/regicide/state";
|
||||||
|
import { PlayerType, RegicideCard } from "@/samples/regicide/types";
|
||||||
|
import { CARD_VALUES, FACE_CARDS } from "@/samples/regicide/constants";
|
||||||
|
import { isEnemyDefeated } from "@/samples/regicide/utils";
|
||||||
|
|
||||||
|
export type RegicideGame = IGameContext<RegicideState>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打出一张牌(对当前敌人造成伤害)
|
||||||
|
*/
|
||||||
|
async function playCmd(game: RegicideGame, player: string, cardId: string) {
|
||||||
|
const state = game.value;
|
||||||
|
const card = state.cards[cardId];
|
||||||
|
|
||||||
|
if (!card) {
|
||||||
|
return { success: false, error: `卡牌 ${cardId} 不存在` };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查卡牌是否在玩家手牌中
|
||||||
|
const playerKey = player as PlayerType;
|
||||||
|
const playerHand = state.playerHands[playerKey];
|
||||||
|
if (!playerHand || !playerHand.includes(cardId)) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: `卡牌 ${cardId} 不在玩家 ${player} 的手牌中`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否有当前敌人
|
||||||
|
if (!state.currentEnemy) {
|
||||||
|
return { success: false, error: "没有活跃的敌人" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算伤害(基础伤害为卡牌面值)
|
||||||
|
let damage = card.value;
|
||||||
|
let attackReduction = 0;
|
||||||
|
|
||||||
|
// 梅花双倍伤害
|
||||||
|
if (card.suit === "clubs") {
|
||||||
|
damage *= 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 黑桃降低敌人攻击力
|
||||||
|
if (card.suit === "spades") {
|
||||||
|
attackReduction = card.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
const enemyHpBefore = state.currentEnemy.hp;
|
||||||
|
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
// 对敌人造成伤害
|
||||||
|
state.currentEnemy!.hp -= damage;
|
||||||
|
|
||||||
|
// 记录黑桃的攻击力降低
|
||||||
|
if (attackReduction > 0) {
|
||||||
|
state.currentEnemy!.value = Math.max(
|
||||||
|
0,
|
||||||
|
state.currentEnemy!.value - attackReduction,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从手牌移除卡牌
|
||||||
|
const hand = state.playerHands[playerKey];
|
||||||
|
const cardIndex = hand.indexOf(cardId);
|
||||||
|
if (cardIndex !== -1) {
|
||||||
|
hand.splice(cardIndex, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将卡牌移到弃牌堆
|
||||||
|
state.cards[cardId].regionId = "discardPile";
|
||||||
|
|
||||||
|
// 红心能力:将弃牌堆洗回酒馆牌堆
|
||||||
|
if (card.suit === "hearts") {
|
||||||
|
const discardIds = state.regions.discardPile.childIds.filter(
|
||||||
|
(id) => id !== state.currentEnemy!.id,
|
||||||
|
);
|
||||||
|
if (discardIds.length > 0) {
|
||||||
|
// 将弃牌堆(除当前敌人外)移回酒馆牌堆
|
||||||
|
for (const discardId of discardIds) {
|
||||||
|
state.cards[discardId].regionId = "tavernDeck";
|
||||||
|
}
|
||||||
|
state.regions.tavernDeck.childIds.push(...discardIds);
|
||||||
|
state.regions.discardPile.childIds = [state.currentEnemy!.id];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 方块能力:从酒馆牌堆抓牌
|
||||||
|
if (card.suit === "diamonds") {
|
||||||
|
const tavernDeckCount = state.regions.tavernDeck.childIds.length;
|
||||||
|
if (tavernDeckCount > 0) {
|
||||||
|
const drawCardId = state.regions.tavernDeck.childIds.shift()!;
|
||||||
|
state.cards[drawCardId].regionId = `hand_${player}`;
|
||||||
|
hand.push(drawCardId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 检查敌人是否被击败
|
||||||
|
const enemyDefeated = isEnemyDefeated(game.value.currentEnemy);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
result: {
|
||||||
|
damage,
|
||||||
|
attackReduction,
|
||||||
|
enemyHpBefore,
|
||||||
|
enemyHpAfter: game.value.currentEnemy!.hp,
|
||||||
|
enemyDefeated,
|
||||||
|
suitAbility: card.suit,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打出A配合另一张牌
|
||||||
|
*/
|
||||||
|
async function playWithACmd(
|
||||||
|
game: RegicideGame,
|
||||||
|
player: string,
|
||||||
|
aceCardId: string,
|
||||||
|
otherCardId: string,
|
||||||
|
) {
|
||||||
|
const state = game.value;
|
||||||
|
const aceCard = state.cards[aceCardId];
|
||||||
|
const otherCard = state.cards[otherCardId];
|
||||||
|
|
||||||
|
if (!aceCard || !otherCard) {
|
||||||
|
return { success: false, error: "卡牌不存在" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否是A牌
|
||||||
|
if (aceCard.rank !== "A") {
|
||||||
|
return { success: false, error: `第一张牌必须是A` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const playerKey = player as PlayerType;
|
||||||
|
const playerHand = state.playerHands[playerKey];
|
||||||
|
|
||||||
|
// 检查两张牌都在手牌中
|
||||||
|
if (!playerHand.includes(aceCardId) || !playerHand.includes(otherCardId)) {
|
||||||
|
return { success: false, error: "卡牌不在手牌中" };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!state.currentEnemy) {
|
||||||
|
return { success: false, error: "没有活跃的敌人" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算两张牌的总伤害
|
||||||
|
let totalDamage = aceCard.value + otherCard.value;
|
||||||
|
|
||||||
|
// 如果另一张牌是梅花,双倍伤害
|
||||||
|
if (otherCard.suit === "clubs") {
|
||||||
|
totalDamage *= 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
let attackReduction = 0;
|
||||||
|
if (aceCard.suit === "spades") {
|
||||||
|
attackReduction += aceCard.value;
|
||||||
|
}
|
||||||
|
if (otherCard.suit === "spades") {
|
||||||
|
attackReduction += otherCard.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
// 对敌人造成伤害
|
||||||
|
state.currentEnemy!.hp -= totalDamage;
|
||||||
|
|
||||||
|
// 记录黑桃的攻击力降低
|
||||||
|
if (attackReduction > 0) {
|
||||||
|
state.currentEnemy!.value = Math.max(
|
||||||
|
0,
|
||||||
|
state.currentEnemy!.value - attackReduction,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从手牌移除两张牌
|
||||||
|
const hand = state.playerHands[playerKey];
|
||||||
|
const aceIndex = hand.indexOf(aceCardId);
|
||||||
|
const otherIndex = hand.indexOf(otherCardId);
|
||||||
|
if (aceIndex !== -1) hand.splice(aceIndex, 1);
|
||||||
|
if (otherIndex !== -1) hand.splice(otherIndex, 1);
|
||||||
|
|
||||||
|
// 将卡牌移到弃牌堆
|
||||||
|
state.cards[aceCardId].regionId = "discardPile";
|
||||||
|
state.cards[otherCardId].regionId = "discardPile";
|
||||||
|
});
|
||||||
|
|
||||||
|
const enemyDefeated = isEnemyDefeated(state.currentEnemy);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
result: {
|
||||||
|
damage: totalDamage,
|
||||||
|
attackReduction,
|
||||||
|
enemyHp: state.currentEnemy!.hp,
|
||||||
|
enemyDefeated,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 让过(不出牌)
|
||||||
|
*/
|
||||||
|
async function passCmd(game: RegicideGame, player: string) {
|
||||||
|
// 即使让过,也会受到敌人反击(在回合结束时处理)
|
||||||
|
return { success: true, result: { message: `${player} 让过` } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 敌人反击 - 玩家必须弃掉点数和 >= 敌人攻击力的牌
|
||||||
|
*/
|
||||||
|
async function enemyCounterattackCmd(
|
||||||
|
game: RegicideGame,
|
||||||
|
player: string,
|
||||||
|
discardCards: string[],
|
||||||
|
) {
|
||||||
|
const state = game.value;
|
||||||
|
|
||||||
|
if (!state.currentEnemy) {
|
||||||
|
return { success: false, error: "没有活跃的敌人" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const playerKey = player as PlayerType;
|
||||||
|
const playerHand = state.playerHands[playerKey];
|
||||||
|
|
||||||
|
// 检查要弃的牌都在手牌中
|
||||||
|
for (const cardId of discardCards) {
|
||||||
|
if (!playerHand.includes(cardId)) {
|
||||||
|
return { success: false, error: `卡牌 ${cardId} 不在手牌中` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算弃牌的点数和
|
||||||
|
let totalValue = 0;
|
||||||
|
for (const cardId of discardCards) {
|
||||||
|
const card = state.cards[cardId];
|
||||||
|
if (card) {
|
||||||
|
totalValue += card.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const enemyAttack = state.currentEnemy.value;
|
||||||
|
|
||||||
|
// 检查点数和是否 >= 敌人攻击力
|
||||||
|
if (totalValue < enemyAttack) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: `弃牌点数和 (${totalValue}) 小于敌人攻击力 (${enemyAttack}),游戏失败`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行弃牌
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
const hand = state.playerHands[playerKey];
|
||||||
|
for (const cardId of discardCards) {
|
||||||
|
const index = hand.indexOf(cardId);
|
||||||
|
if (index !== -1) {
|
||||||
|
hand.splice(index, 1);
|
||||||
|
}
|
||||||
|
state.cards[cardId].regionId = "discardPile";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
result: {
|
||||||
|
discardedCards: discardCards,
|
||||||
|
totalValue,
|
||||||
|
enemyAttack,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查敌人是否被击败,如果击败则翻开下一个敌人
|
||||||
|
*/
|
||||||
|
async function checkEnemyDefeatedCmd(game: RegicideGame) {
|
||||||
|
const state = game.value;
|
||||||
|
|
||||||
|
if (!state.currentEnemy) {
|
||||||
|
return { success: false as const, error: "没有活跃的敌人" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const defeated = state.currentEnemy.hp <= 0;
|
||||||
|
|
||||||
|
if (defeated) {
|
||||||
|
const defeatedEnemy = { ...state.currentEnemy };
|
||||||
|
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
// 将当前敌人移到弃牌堆
|
||||||
|
state.regions.discardPile.childIds.push(state.currentEnemy!.id);
|
||||||
|
|
||||||
|
// 翻开下一个敌人
|
||||||
|
if (state.enemyDeck.length > 0) {
|
||||||
|
const nextEnemy = state.enemyDeck.shift()!;
|
||||||
|
state.currentEnemy = nextEnemy;
|
||||||
|
} else {
|
||||||
|
// 没有更多敌人了
|
||||||
|
state.currentEnemy = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 检查是否胜利(没有更多敌人)
|
||||||
|
if (!game.value.currentEnemy) {
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
state.phase = "victory";
|
||||||
|
state.winner = true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true as const,
|
||||||
|
result: {
|
||||||
|
defeated: true,
|
||||||
|
defeatedEnemy,
|
||||||
|
nextEnemy: game.value.currentEnemy,
|
||||||
|
enemiesRemaining: game.value.enemyDeck.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
result: {
|
||||||
|
defeated: false,
|
||||||
|
currentEnemy: { ...state.currentEnemy },
|
||||||
|
enemiesRemaining: state.enemyDeck.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查玩家是否有可出的牌
|
||||||
|
*/
|
||||||
|
async function checkCanPlayCmd(game: RegicideGame, player: string) {
|
||||||
|
const state = game.value;
|
||||||
|
const playerKey = player as PlayerType;
|
||||||
|
const playerHand = state.playerHands[playerKey];
|
||||||
|
|
||||||
|
const canPlay = playerHand.length > 0;
|
||||||
|
const canPlayWithA = playerHand.some((cardId) => {
|
||||||
|
const card = state.cards[cardId];
|
||||||
|
return card && card.rank === "A" && playerHand.length > 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
result: {
|
||||||
|
canPlay,
|
||||||
|
canPlayWithA,
|
||||||
|
handSize: playerHand.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查酒馆牌堆是否为空
|
||||||
|
*/
|
||||||
|
async function checkTavernDeckCmd(game: RegicideGame) {
|
||||||
|
const state = game.value;
|
||||||
|
const isEmpty = state.regions.tavernDeck.childIds.length === 0;
|
||||||
|
|
||||||
|
// 如果酒馆牌堆为空且所有玩家手牌也为空,则游戏失败
|
||||||
|
if (isEmpty) {
|
||||||
|
const allHandsEmpty = Object.values(state.playerHands).every(
|
||||||
|
(hand) => hand.length === 0,
|
||||||
|
);
|
||||||
|
if (allHandsEmpty) {
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
state.phase = "defeat";
|
||||||
|
state.winner = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
result: {
|
||||||
|
isEmpty,
|
||||||
|
cardsRemaining: state.regions.tavernDeck.childIds.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 下一个玩家回合
|
||||||
|
*/
|
||||||
|
async function nextTurnCmd(game: RegicideGame) {
|
||||||
|
const state = game.value;
|
||||||
|
await game.produce((state) => {
|
||||||
|
state.currentPlayerIndex =
|
||||||
|
(state.currentPlayerIndex + 1) % state.playerCount;
|
||||||
|
});
|
||||||
|
|
||||||
|
const players: PlayerType[] = ["player1", "player2", "player3", "player4"];
|
||||||
|
const currentPlayer = players[game.value.currentPlayerIndex];
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
result: {
|
||||||
|
currentPlayer,
|
||||||
|
currentPlayerIndex: game.value.currentPlayerIndex,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
playCmd as play,
|
||||||
|
playWithACmd as playWithA,
|
||||||
|
passCmd as pass,
|
||||||
|
enemyCounterattackCmd as enemyCounterattack,
|
||||||
|
checkEnemyDefeatedCmd as checkEnemy,
|
||||||
|
checkCanPlayCmd as checkCanPlay,
|
||||||
|
checkTavernDeckCmd as checkTavernDeck,
|
||||||
|
nextTurnCmd as nextTurn,
|
||||||
|
};
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import {CardRank, SuitType} from "@/samples/regicide/types";
|
||||||
|
|
||||||
|
// 敌人总数
|
||||||
|
export const ENEMY_COUNT = 12;
|
||||||
|
|
||||||
|
// 初始手牌数
|
||||||
|
export const INITIAL_HAND_SIZE = 6;
|
||||||
|
|
||||||
|
// 卡牌面值映射
|
||||||
|
export const CARD_VALUES: Record<CardRank, number> = {
|
||||||
|
'A': 1,
|
||||||
|
'2': 2,
|
||||||
|
'3': 3,
|
||||||
|
'4': 4,
|
||||||
|
'5': 5,
|
||||||
|
'6': 6,
|
||||||
|
'7': 7,
|
||||||
|
'8': 8,
|
||||||
|
'9': 9,
|
||||||
|
'10': 10,
|
||||||
|
'J': 10,
|
||||||
|
'Q': 15,
|
||||||
|
'K': 20,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 所有花色
|
||||||
|
export const ALL_SUITS: SuitType[] = ['spades', 'hearts', 'diamonds', 'clubs'];
|
||||||
|
|
||||||
|
// 所有牌面值(不含大小王)
|
||||||
|
export const ALL_RANKS: CardRank[] = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
|
||||||
|
|
||||||
|
// 人头牌(J/Q/K)
|
||||||
|
export const FACE_CARDS: CardRank[] = ['J', 'Q', 'K'];
|
||||||
|
|
||||||
|
// 数字牌(A-10)
|
||||||
|
export const NUMBER_CARDS: CardRank[] = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
import { IGameContext } from "@/core/game";
|
||||||
|
import { RegicideState } from "@/samples/regicide/state";
|
||||||
|
import {
|
||||||
|
buildEnemyDeck,
|
||||||
|
buildTavernDeck,
|
||||||
|
createAllCards,
|
||||||
|
getPlayerHandRegionId,
|
||||||
|
} from "@/samples/regicide/utils";
|
||||||
|
import { INITIAL_HAND_SIZE } from "@/samples/regicide/constants";
|
||||||
|
import { Enemy, PlayerType, RegicideCard } from "@/samples/regicide/types";
|
||||||
|
import { checkEnemy, nextTurn, pass, playWithA } from "./commands";
|
||||||
|
import { enemyCounterattackCmd, playCmd } from ".";
|
||||||
|
|
||||||
|
export type RegicideGame = IGameContext<RegicideState>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化游戏设置
|
||||||
|
* @param game 游戏上下文
|
||||||
|
* @param playerCount 玩家数量(1-4)
|
||||||
|
* @param seed 随机种子(可选)
|
||||||
|
*/
|
||||||
|
export async function setupGame(
|
||||||
|
game: RegicideGame,
|
||||||
|
playerCount: number,
|
||||||
|
seed?: number,
|
||||||
|
) {
|
||||||
|
if (playerCount < 1 || playerCount > 4) {
|
||||||
|
throw new Error("玩家数量必须为 1-4 人");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (seed) {
|
||||||
|
// RNG seeding handled by game context
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建所有卡牌
|
||||||
|
const allCards = createAllCards();
|
||||||
|
|
||||||
|
// 构建敌人牌堆(J/Q/K)
|
||||||
|
const enemyDeck = buildEnemyDeck(game._rng);
|
||||||
|
|
||||||
|
// 构建酒馆牌堆(A-10)
|
||||||
|
const tavernDeck = buildTavernDeck(game._rng);
|
||||||
|
|
||||||
|
// 初始化游戏状态
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
state.cards = allCards;
|
||||||
|
state.playerCount = playerCount;
|
||||||
|
state.currentPlayerIndex = 0;
|
||||||
|
state.enemyDeck = enemyDeck;
|
||||||
|
|
||||||
|
// 设置酒馆牌堆区域
|
||||||
|
for (const card of tavernDeck) {
|
||||||
|
card.regionId = "tavernDeck";
|
||||||
|
state.regions.tavernDeck.childIds.push(card.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置敌人牌堆区域(只存储ID,敌人是独立对象)
|
||||||
|
state.regions.enemyDeck.childIds = enemyDeck.map((e) => e.id);
|
||||||
|
|
||||||
|
// 给每个玩家发牌
|
||||||
|
const players: PlayerType[] = ["player1", "player2", "player3", "player4"];
|
||||||
|
for (let i = 0; i < playerCount; i++) {
|
||||||
|
const player = players[i];
|
||||||
|
const regionId = getPlayerHandRegionId(player);
|
||||||
|
|
||||||
|
for (let j = 0; j < INITIAL_HAND_SIZE; j++) {
|
||||||
|
if (tavernDeck.length === 0) break;
|
||||||
|
const card = tavernDeck.shift()!;
|
||||||
|
card.regionId = regionId;
|
||||||
|
state.playerHands[player].push(card.id);
|
||||||
|
const region = state.regions[regionId as keyof typeof state.regions];
|
||||||
|
region.childIds.push(card.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 翻开第一个敌人
|
||||||
|
if (enemyDeck.length > 0) {
|
||||||
|
const firstEnemy = enemyDeck.shift()!;
|
||||||
|
state.currentEnemy = firstEnemy;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动游戏主循环
|
||||||
|
*/
|
||||||
|
export async function start(game: RegicideGame) {
|
||||||
|
const state = game.value;
|
||||||
|
|
||||||
|
// 检查游戏是否已设置
|
||||||
|
if (!state.currentEnemy) {
|
||||||
|
throw new Error("请先调用 setupGame 初始化游戏");
|
||||||
|
}
|
||||||
|
|
||||||
|
const players: PlayerType[] = ["player1", "player2", "player3", "player4"];
|
||||||
|
|
||||||
|
// 主游戏循环
|
||||||
|
while (state.phase === "playing") {
|
||||||
|
const currentPlayerIndex = state.currentPlayerIndex;
|
||||||
|
const currentPlayer = players[currentPlayerIndex];
|
||||||
|
|
||||||
|
// 检查当前玩家是否有手牌
|
||||||
|
const currentHand = state.playerHands[currentPlayer];
|
||||||
|
if (currentHand.length === 0) {
|
||||||
|
// 玩家没有手牌,跳过回合
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
state.currentPlayerIndex =
|
||||||
|
(state.currentPlayerIndex + 1) % state.playerCount;
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 等待玩家输入(出牌或让过)
|
||||||
|
// 这里需要外部通过 prompt 系统获取输入
|
||||||
|
// 实际使用时由 UI 或测试代码提供输入
|
||||||
|
|
||||||
|
// 循环会在外部调用 play/pass 命令后继续
|
||||||
|
// 当 phase 变为 'victory' 或 'defeat' 时退出
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return game.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理完整的玩家回合
|
||||||
|
*/
|
||||||
|
export async function playTurn(
|
||||||
|
game: RegicideGame,
|
||||||
|
player: PlayerType,
|
||||||
|
action: "play" | "pass",
|
||||||
|
cardId?: string,
|
||||||
|
secondCardId?: string,
|
||||||
|
) {
|
||||||
|
const state = game.value;
|
||||||
|
|
||||||
|
if (state.phase !== "playing") {
|
||||||
|
return { success: false, error: "游戏已结束" };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!state.currentEnemy) {
|
||||||
|
return { success: false, error: "没有活跃的敌人" };
|
||||||
|
}
|
||||||
|
|
||||||
|
let playResult: any;
|
||||||
|
|
||||||
|
// 执行玩家动作
|
||||||
|
if (action === "play" && cardId) {
|
||||||
|
// 检查是否是A配合另一张牌
|
||||||
|
const card = state.cards[cardId];
|
||||||
|
if (card.rank === "A" && secondCardId) {
|
||||||
|
playResult = await playWithA(game, player, cardId, secondCardId);
|
||||||
|
} else {
|
||||||
|
playResult = await playCmd(game, player, cardId);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 让过
|
||||||
|
playResult = await pass(game, player);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!playResult.success) {
|
||||||
|
return playResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查敌人是否被击败
|
||||||
|
const checkResult = await checkEnemy(game);
|
||||||
|
if (!checkResult.success) {
|
||||||
|
return checkResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果敌人未被击败,处理反击
|
||||||
|
if (!checkResult.result.defeated) {
|
||||||
|
// 反击逻辑需要玩家选择弃牌,这里返回状态让外部处理
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
result: {
|
||||||
|
playResult: playResult.result,
|
||||||
|
enemyDefeated: false,
|
||||||
|
needsDiscard: true,
|
||||||
|
enemyAttack: state.currentEnemy.value,
|
||||||
|
playerHand: state.playerHands[player],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 敌人被击败,检查是否还有更多敌人
|
||||||
|
if (
|
||||||
|
state.enemyDeck.length === 0 &&
|
||||||
|
state.currentEnemy &&
|
||||||
|
state.currentEnemy.hp <= 0
|
||||||
|
) {
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
state.phase = "victory";
|
||||||
|
state.winner = true;
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
result: {
|
||||||
|
playResult: playResult.result,
|
||||||
|
enemyDefeated: true,
|
||||||
|
gameWon: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 切换到下一个玩家
|
||||||
|
await nextTurn(game);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
result: {
|
||||||
|
playResult: playResult.result,
|
||||||
|
enemyDefeated: true,
|
||||||
|
nextEnemy: state.currentEnemy,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理反击阶段的弃牌
|
||||||
|
*/
|
||||||
|
export async function handleCounterattack(
|
||||||
|
game: RegicideGame,
|
||||||
|
player: PlayerType,
|
||||||
|
discardCardIds: string[],
|
||||||
|
) {
|
||||||
|
const result = await enemyCounterattackCmd(game, player, discardCardIds);
|
||||||
|
if (!result.success) {
|
||||||
|
// 弃牌失败(点数和不足),游戏失败
|
||||||
|
await game.produceAsync((state) => {
|
||||||
|
state.phase = "defeat";
|
||||||
|
state.winner = false;
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 弃牌成功,切换到下一个玩家
|
||||||
|
await nextTurn(game);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前游戏状态摘要
|
||||||
|
*/
|
||||||
|
export function getGameStatus(game: RegicideGame) {
|
||||||
|
const state = game.value;
|
||||||
|
|
||||||
|
return {
|
||||||
|
phase: state.phase,
|
||||||
|
currentPlayer: ["player1", "player2", "player3", "player4"][
|
||||||
|
state.currentPlayerIndex
|
||||||
|
],
|
||||||
|
currentEnemy: state.currentEnemy
|
||||||
|
? {
|
||||||
|
...state.currentEnemy,
|
||||||
|
hpPercent: Math.round(
|
||||||
|
(state.currentEnemy.hp / state.currentEnemy.maxHp) * 100,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
enemiesRemaining: state.enemyDeck.length,
|
||||||
|
tavernDeckCount: state.regions.tavernDeck.childIds.length,
|
||||||
|
discardPileCount: state.regions.discardPile.childIds.length,
|
||||||
|
playerHands: Object.fromEntries(
|
||||||
|
Object.entries(state.playerHands).map(([player, hand]) => [
|
||||||
|
player,
|
||||||
|
hand.length,
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
winner: state.winner,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
// Types
|
||||||
|
export type {
|
||||||
|
SuitType,
|
||||||
|
CardRank,
|
||||||
|
PlayerType,
|
||||||
|
RegionType,
|
||||||
|
RegicideCardMeta,
|
||||||
|
RegicideCard,
|
||||||
|
Enemy,
|
||||||
|
GamePhase,
|
||||||
|
} from "./types";
|
||||||
|
|
||||||
|
// Constants
|
||||||
|
export {
|
||||||
|
ENEMY_COUNT,
|
||||||
|
INITIAL_HAND_SIZE,
|
||||||
|
CARD_VALUES,
|
||||||
|
ALL_SUITS,
|
||||||
|
ALL_RANKS,
|
||||||
|
FACE_CARDS,
|
||||||
|
NUMBER_CARDS,
|
||||||
|
} from "./constants";
|
||||||
|
|
||||||
|
// State
|
||||||
|
export { createInitialState, type RegicideState } from "./state";
|
||||||
|
|
||||||
|
// Prompts
|
||||||
|
export { prompts } from "./prompts";
|
||||||
|
|
||||||
|
// Commands
|
||||||
|
export {
|
||||||
|
play as playCmd,
|
||||||
|
playWithA as playWithACmd,
|
||||||
|
pass as passCmd,
|
||||||
|
enemyCounterattack as enemyCounterattackCmd,
|
||||||
|
checkEnemy as checkEnemyCmd,
|
||||||
|
checkCanPlay as checkCanPlayCmd,
|
||||||
|
checkTavernDeck as checkTavernDeckCmd,
|
||||||
|
nextTurn as nextTurnCmd,
|
||||||
|
} from "./commands";
|
||||||
|
|
||||||
|
// Game
|
||||||
|
export {
|
||||||
|
setupGame,
|
||||||
|
start,
|
||||||
|
playTurn,
|
||||||
|
handleCounterattack,
|
||||||
|
getGameStatus,
|
||||||
|
type RegicideGame,
|
||||||
|
} from "./game";
|
||||||
|
|
||||||
|
// Utils
|
||||||
|
export {
|
||||||
|
getCardValue,
|
||||||
|
createCard,
|
||||||
|
createEnemy,
|
||||||
|
createAllCards,
|
||||||
|
buildEnemyDeck,
|
||||||
|
buildTavernDeck,
|
||||||
|
drawFromDeck,
|
||||||
|
isEnemyDefeated,
|
||||||
|
getPlayerHandRegionId,
|
||||||
|
} from "./utils";
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import {createPromptDef} from "@/core/game";
|
||||||
|
|
||||||
|
export const prompts = {
|
||||||
|
playCard: createPromptDef<[string, string]>(
|
||||||
|
'play <player:string> <cardId:string>',
|
||||||
|
'选择要打出的卡牌'
|
||||||
|
),
|
||||||
|
playWithA: createPromptDef<[string, string, string]>(
|
||||||
|
'play-with-a <player:string> <aceCardId:string> <otherCardId:string>',
|
||||||
|
'打出A配合另一张牌'
|
||||||
|
),
|
||||||
|
pass: createPromptDef<[string]>(
|
||||||
|
'pass <player:string>',
|
||||||
|
'让过不出牌'
|
||||||
|
),
|
||||||
|
discard: createPromptDef<[string, string[]]>(
|
||||||
|
'counterattack <player:string> <discardCards:string[]>',
|
||||||
|
'选择要弃掉的卡牌以应对敌人反击'
|
||||||
|
),
|
||||||
|
};
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# Regicide (弑君游戏)
|
||||||
|
|
||||||
|
## 游戏概述
|
||||||
|
|
||||||
|
**Regicide** 是一个合作式奇幻主题卡牌游戏,使用标准扑克牌进行游戏。
|
||||||
|
|
||||||
|
- **玩家人数:** 1-4 人(合作)
|
||||||
|
- **年龄:** 10+
|
||||||
|
- **游戏时间:** 约30分钟
|
||||||
|
|
||||||
|
## 游戏目标
|
||||||
|
|
||||||
|
玩家们协作对抗,使用手牌击败12个强大的敌人(每个等级3个敌人)。如果成功击败所有12个敌人则获胜;如果任何敌人的生命值归零前未能击败它,或者牌库耗尽时仍有敌人存活,则游戏失败。
|
||||||
|
|
||||||
|
## 游戏配件
|
||||||
|
|
||||||
|
- **标准扑克牌:** 52张(不包含大小王)
|
||||||
|
|
||||||
|
## 卡牌说明
|
||||||
|
|
||||||
|
### 数字牌(A-10)
|
||||||
|
- 面值等于牌面数字
|
||||||
|
- 每张牌有独特的花色能力
|
||||||
|
|
||||||
|
### 人头牌(J、Q、K)
|
||||||
|
- **J(侍卫):** 面值 10
|
||||||
|
- **Q(皇后):** 面值 15
|
||||||
|
- **K(国王):** 面值 20
|
||||||
|
|
||||||
|
### 花色能力
|
||||||
|
- **黑桃(Spades):** 降低敌人的攻击力
|
||||||
|
- **红心(Hearts):** 将弃牌堆的牌洗回酒馆牌堆
|
||||||
|
- **方块(Diamonds):** 从酒馆牌堆抓牌
|
||||||
|
- **梅花(Clubs):** 造成双倍伤害
|
||||||
|
|
||||||
|
## 游戏设置
|
||||||
|
|
||||||
|
0. 将所有的J/Q/K从牌堆移出,将4张K洗混后放在最下,4张Q洗混后放在中间,4张J洗混后放在最上形成敌人牌堆
|
||||||
|
1. 将剩余的扑克牌洗匀形成酒馆牌堆,每位玩家抽取 6 张手牌
|
||||||
|
2. 翻开一张敌人牌
|
||||||
|
3. 决定起始玩家(单人模式下自动为当前玩家)
|
||||||
|
|
||||||
|
## 游戏流程
|
||||||
|
|
||||||
|
从起始玩家开始,轮流进行以下操作:
|
||||||
|
|
||||||
|
### 玩家回合
|
||||||
|
在你的回合,你可以:
|
||||||
|
1. **打出一张牌:** 选择一张手牌打出,对其目标敌人造成伤害或触发效果
|
||||||
|
2. **打出一张A和另一张牌:** A可以配合任何其他牌一起打出
|
||||||
|
3. **让过(Pass):** 不出牌,结束回合
|
||||||
|
|
||||||
|
### 出牌流程
|
||||||
|
1. 打出的牌对当前敌人造成伤害
|
||||||
|
2. 触发牌的花色能力
|
||||||
|
3. 如果敌人的生命值降至0或以下,该敌人被击败,放置到弃牌堆
|
||||||
|
4. 如果当前敌人被击败,翻开下一张敌人牌,否则受到敌人反击,必须弃掉点数和大于等于敌人攻击力的手牌
|
||||||
|
|
||||||
|
即使玩家让过,也会受到敌人的反击。
|
||||||
|
|
||||||
|
### 限制
|
||||||
|
- 玩家之间不能交流或暗示关于手牌的信息
|
||||||
|
- 每个回合只能打出一张牌(除了A配合其他牌的情况)
|
||||||
|
|
||||||
|
## 敌人机制
|
||||||
|
|
||||||
|
### 敌人属性
|
||||||
|
- **生命值:** 敌人需要承受的伤害量,为卡牌面值的两倍
|
||||||
|
- **攻击力:** 敌人的面值即敌人的攻击力
|
||||||
|
|
||||||
|
## 胜利与失败条件
|
||||||
|
|
||||||
|
### 胜利条件
|
||||||
|
- 击败所有12个敌人
|
||||||
|
|
||||||
|
### 失败条件
|
||||||
|
- 任何玩家在敌人反击后无法弃掉点数和达到敌人攻击力以上的牌
|
||||||
|
- 任何玩家无法出牌
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import {createRegion, Region} from "@/core/region";
|
||||||
|
import {Enemy, GamePhase, PlayerType, RegionType} from "@/samples/regicide/types";
|
||||||
|
import {RegicideCard} from "@/samples/regicide/types";
|
||||||
|
import {INITIAL_HAND_SIZE} from "@/samples/regicide/constants";
|
||||||
|
|
||||||
|
export function createInitialState() {
|
||||||
|
const regions: Record<RegionType, Region> = {
|
||||||
|
enemyDeck: createRegion('enemyDeck', []),
|
||||||
|
tavernDeck: createRegion('tavernDeck', []),
|
||||||
|
discardPile: createRegion('discardPile', []),
|
||||||
|
currentEnemy: createRegion('currentEnemy', []),
|
||||||
|
hand_player1: createRegion('hand_player1', []),
|
||||||
|
hand_player2: createRegion('hand_player2', []),
|
||||||
|
hand_player3: createRegion('hand_player3', []),
|
||||||
|
hand_player4: createRegion('hand_player4', []),
|
||||||
|
};
|
||||||
|
|
||||||
|
const playerHands: Record<PlayerType, string[]> = {
|
||||||
|
player1: [],
|
||||||
|
player2: [],
|
||||||
|
player3: [],
|
||||||
|
player4: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
regions,
|
||||||
|
cards: {} as Record<string, RegicideCard>,
|
||||||
|
playerHands,
|
||||||
|
currentPlayerIndex: 0,
|
||||||
|
playerCount: 1,
|
||||||
|
currentEnemy: null as Enemy | null,
|
||||||
|
enemyDeck: [] as Enemy[],
|
||||||
|
phase: 'playing' as GamePhase,
|
||||||
|
winner: null as boolean | null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RegicideState = ReturnType<typeof createInitialState>;
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import {Part} from "@/core/part";
|
||||||
|
|
||||||
|
// 花色类型
|
||||||
|
export type SuitType = 'spades' | 'hearts' | 'diamonds' | 'clubs';
|
||||||
|
|
||||||
|
// 牌面值
|
||||||
|
export type CardRank = 'A' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '10' | 'J' | 'Q' | 'K';
|
||||||
|
|
||||||
|
// 玩家类型(1-4人合作)
|
||||||
|
export type PlayerType = 'player1' | 'player2' | 'player3' | 'player4';
|
||||||
|
|
||||||
|
// 区域类型
|
||||||
|
export type RegionType =
|
||||||
|
| 'enemyDeck' // 敌人牌堆
|
||||||
|
| 'tavernDeck' // 酒馆牌堆
|
||||||
|
| 'discardPile' // 弃牌堆
|
||||||
|
| 'currentEnemy' // 当前敌人
|
||||||
|
| 'hand_player1'
|
||||||
|
| 'hand_player2'
|
||||||
|
| 'hand_player3'
|
||||||
|
| 'hand_player4';
|
||||||
|
|
||||||
|
// 卡牌元数据
|
||||||
|
export type RegicideCardMeta = {
|
||||||
|
suit: SuitType;
|
||||||
|
rank: CardRank;
|
||||||
|
value: number; // 卡牌面值
|
||||||
|
};
|
||||||
|
|
||||||
|
// 卡牌部件类型
|
||||||
|
export type RegicideCard = Part<RegicideCardMeta>;
|
||||||
|
|
||||||
|
// 敌人类型
|
||||||
|
export type Enemy = {
|
||||||
|
id: string;
|
||||||
|
rank: CardRank;
|
||||||
|
suit: SuitType;
|
||||||
|
value: number; // 敌人面值(即攻击力)
|
||||||
|
hp: number; // 当前生命值
|
||||||
|
maxHp: number; // 最大生命值(面值的2倍)
|
||||||
|
};
|
||||||
|
|
||||||
|
// 游戏阶段
|
||||||
|
export type GamePhase = 'playing' | 'victory' | 'defeat';
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import {ALL_RANKS, ALL_SUITS, CARD_VALUES, ENEMY_COUNT, FACE_CARDS} from "@/samples/regicide/constants";
|
||||||
|
import {CardRank, Enemy, RegicideCard, SuitType} from "@/samples/regicide/types";
|
||||||
|
import {RNG} from "@/utils/rng";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取卡牌面值
|
||||||
|
*/
|
||||||
|
export function getCardValue(rank: CardRank): number {
|
||||||
|
return CARD_VALUES[rank];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建卡牌部件
|
||||||
|
*/
|
||||||
|
export function createCard(id: string, suit: SuitType, rank: CardRank): RegicideCard {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
regionId: '',
|
||||||
|
position: [],
|
||||||
|
suit,
|
||||||
|
rank,
|
||||||
|
value: getCardValue(rank),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建敌人
|
||||||
|
*/
|
||||||
|
export function createEnemy(id: string, rank: CardRank, suit: SuitType): Enemy {
|
||||||
|
const value = getCardValue(rank);
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
rank,
|
||||||
|
suit,
|
||||||
|
value,
|
||||||
|
hp: value * 2,
|
||||||
|
maxHp: value * 2,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成完整卡牌列表(52张,不含大小王)
|
||||||
|
*/
|
||||||
|
export function createAllCards(): Record<string, RegicideCard> {
|
||||||
|
const cards: Record<string, RegicideCard> = {};
|
||||||
|
|
||||||
|
for (const suit of ALL_SUITS) {
|
||||||
|
for (const rank of ALL_RANKS) {
|
||||||
|
const id = `${suit}_${rank}`;
|
||||||
|
cards[id] = createCard(id, suit, rank);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return cards;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建敌人牌堆(J/Q/K 共12张)
|
||||||
|
* 规则:4张K在最下,4张Q在中间,4张J在最上
|
||||||
|
*/
|
||||||
|
export function buildEnemyDeck(rng: RNG): Enemy[] {
|
||||||
|
const enemies: Enemy[] = [];
|
||||||
|
let idCounter = 0;
|
||||||
|
|
||||||
|
// 创建所有J/Q/K敌人
|
||||||
|
for (const rank of FACE_CARDS) {
|
||||||
|
for (const suit of ALL_SUITS) {
|
||||||
|
const id = `enemy_${idCounter++}`;
|
||||||
|
enemies.push(createEnemy(id, rank, suit));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分离J、Q、K
|
||||||
|
const jEnemies = enemies.filter(e => e.rank === 'J');
|
||||||
|
const qEnemies = enemies.filter(e => e.rank === 'Q');
|
||||||
|
const kEnemies = enemies.filter(e => e.rank === 'K');
|
||||||
|
|
||||||
|
// 分别洗牌
|
||||||
|
shuffleArray(jEnemies, rng);
|
||||||
|
shuffleArray(qEnemies, rng);
|
||||||
|
shuffleArray(kEnemies, rng);
|
||||||
|
|
||||||
|
// J在最上(先遇到),Q在中间,K在最下
|
||||||
|
return [...jEnemies, ...qEnemies, ...kEnemies];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建酒馆牌堆(移除J/Q/K后的剩余牌)
|
||||||
|
*/
|
||||||
|
export function buildTavernDeck(rng: RNG): RegicideCard[] {
|
||||||
|
const allCards = createAllCards();
|
||||||
|
const numberCards = Object.values(allCards).filter(card => !FACE_CARDS.includes(card.rank));
|
||||||
|
|
||||||
|
shuffleArray(numberCards, rng);
|
||||||
|
|
||||||
|
return numberCards;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 洗牌辅助函数
|
||||||
|
*/
|
||||||
|
function shuffleArray<T>(array: T[], rng: RNG): void {
|
||||||
|
for (let i = array.length - 1; i > 0; i--) {
|
||||||
|
const j = rng.nextInt(i + 1);
|
||||||
|
[array[i], array[j]] = [array[j], array[i]];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从牌堆抽牌
|
||||||
|
*/
|
||||||
|
export function drawFromDeck(
|
||||||
|
deck: RegicideCard[],
|
||||||
|
count: number
|
||||||
|
): RegicideCard[] {
|
||||||
|
const drawn = deck.splice(0, count);
|
||||||
|
return drawn;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查敌人是否被击败
|
||||||
|
*/
|
||||||
|
export function isEnemyDefeated(enemy: Enemy | null): boolean {
|
||||||
|
return enemy !== null && enemy.hp <= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前玩家手牌区域ID
|
||||||
|
*/
|
||||||
|
export function getPlayerHandRegionId(playerId: string): string {
|
||||||
|
return `hand_${playerId}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# AGENTS.md - slay-the-spire-like
|
||||||
|
|
||||||
|
Roguelike deckbuilder combining Slay the Spire combat with Backpack Hero grid inventory.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
Three-layer design: **system** (content-agnostic) → **data** (CSV content) → **dialogues** (Yarn Spinner).
|
||||||
|
|
||||||
|
### System Layer (`system/`)
|
||||||
|
|
||||||
|
| Module | Files | Responsibility |
|
||||||
|
|---|---|---|
|
||||||
|
| `combat/` | types.ts, effects.ts, triggers.ts, prompts.ts | Combat state, effects pipeline, middleware triggers |
|
||||||
|
| `deck/` | types.ts, factory.ts, index.ts | Deck state management |
|
||||||
|
| `grid-inventory/` | types.ts, transform.ts, index.ts | Grid backpack, shape collision, adjacency |
|
||||||
|
| `map/` | types.ts, generator.ts, index.ts | Procedural node generation (point crawl) |
|
||||||
|
| `progress/` | types.ts, encounter.ts, index.ts | Adventure progress, node traversal |
|
||||||
|
| `utils/` | parse-shape.ts, shape-collision.ts | Shape parsing and collision detection |
|
||||||
|
| `types.ts` | — | `EffectData`, `EffectLifecycle`, `EnemyData`, `CardData`, `IntentData`, `EncounterData`, `ItemData` |
|
||||||
|
|
||||||
|
### Data Layer (`data/desert/`)
|
||||||
|
|
||||||
|
All content via CSV (loaded by `inline-schema`):
|
||||||
|
|
||||||
|
| File | Content |
|
||||||
|
|---|---|
|
||||||
|
| `card.csv` | Card definitions |
|
||||||
|
| `effect.csv` | Effect definitions |
|
||||||
|
| `enemy.csv` | Enemies + intents |
|
||||||
|
| `intent.csv` | Intent definitions |
|
||||||
|
| `item.csv` | Equipment items |
|
||||||
|
| `encounter.csv` | Encounter nodes |
|
||||||
|
|
||||||
|
### Triggers (`data/desert/triggers/`)
|
||||||
|
|
||||||
|
Middleware hooks extending the base trigger system:
|
||||||
|
|
||||||
|
| File | Hooks |
|
||||||
|
|---|---|
|
||||||
|
| `effect.ts` | Orchestrator — calls all sub-modules |
|
||||||
|
| `instant.ts` | `onEffectApplied` — attack, draw, gainEnergy, removeWound, summon, etc. |
|
||||||
|
| `damage.ts` | `onDamage` — block, spike, expose, aim, roll, charge, molt, tailSting, energyDrain |
|
||||||
|
| `turn-start.ts` | `onTurnStart` — discard, defendNext, energyNext, drawNext |
|
||||||
|
| `card-events.ts` | `onEnemyIntent`, `onCardPlayed`, `onCardDiscarded`, `onDamage` — storm, crossbow, burnForEnergy, sandwormKing, vulture |
|
||||||
|
|
||||||
|
### Dialogue Layer (`data/desert/dialogues/`)
|
||||||
|
|
||||||
|
`story.yarn` — branching encounter dialogues (inside `dialogues.yarnproject`). Commands resolve via `tryAnswerPrompt`.
|
||||||
|
|
||||||
|
## Key Mechanics
|
||||||
|
|
||||||
|
- **Energy**: 3/turn, spent on weapon/armor/tool cards
|
||||||
|
- **Uses**: Consumable cards use `uses` cost type instead of energy; tracked as `depletion` on `GameItemMeta`
|
||||||
|
- **Grid adjacency**: Items buff adjacent items (e.g. burnForEnergy consumes adjacent item on card play)
|
||||||
|
- **Effect lifecycles**: `instant`, `temporary`, `lingering`, `permanent`, `posture`, `item`, `itemTemporary`, `itemUntilPlay`, `itemUntilDiscard`, `itemPermanent`
|
||||||
|
- **Trigger pipeline**: `createMiddlewareChain` with `use(async (ctx, next) => ...)` pattern
|
||||||
|
- **Cards from items**: `GameCard` instances are generated from `GameItem` inventory items via deck factory
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Tests live in `tests/samples/slay-the-spire-like/`:
|
||||||
|
- `combat/effects.test.ts` — effect application, upkeep, posture damage
|
||||||
|
- `combat/triggers.test.ts` — full desert trigger integration tests
|
||||||
|
- `deck/factory.test.ts` — deck creation
|
||||||
|
- `grid-inventory.test.ts` — placement, adjacency, collision
|
||||||
|
- `map/generator.test.ts` — procedural generation
|
||||||
|
- `utils/shape-utils.test.ts` — shape parsing
|
||||||
|
- `data/index.test.ts` — data loading validation
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# cardDesert: unified card definitions for item cards and status cards
|
||||||
|
# type: 'item' = inventory item card, 'status' = status effect card
|
||||||
|
# costType: 'energy' = costs energy per turn, 'uses' = limited uses, 'none' = free
|
||||||
|
# targetType: 'single' = target one enemy, 'none' = no target
|
||||||
|
|
||||||
|
# type CardType = 'item' | 'status'
|
||||||
|
# type CardCostType = 'energy' | 'uses' | 'none'
|
||||||
|
# type CardTargetType = 'player' | 'enemy' | 'enemies'
|
||||||
|
|
||||||
|
# inject effects = ~cardEffect(card)
|
||||||
|
|
||||||
|
id,name,desc,type,costType,costCount,targetType
|
||||||
|
string,string,string,CardType,CardCostType,int,CardTargetType
|
||||||
|
sword,剑,【攻击2】【攻击2】,item,energy,1,enemy
|
||||||
|
greataxe,长斧,对全体【攻击5】,item,energy,2,enemies
|
||||||
|
spear,长枪,【攻击2】【攻击2】【攻击2】,item,energy,1,enemy
|
||||||
|
dagger,短刀,【攻击3】【攻击3】,item,energy,1,enemy
|
||||||
|
dart,飞镖,【攻击1】抓一张牌,item,energy,0,enemy
|
||||||
|
crossbow,十字弩,【攻击6】对同一目标打出其他十字弩,item,energy,2,enemy
|
||||||
|
shield,盾,【防御3】,item,energy,1,player
|
||||||
|
hat,斗笠,【防御8】,item,energy,2,player
|
||||||
|
cape,披风,【防御2】下回合【防御2】,item,energy,1,player
|
||||||
|
bracer,护腕,【防御1】抓1张牌,item,energy,0,player
|
||||||
|
greatshield,大盾,【防御5】,item,energy,1,player
|
||||||
|
chainmail,锁子甲,本回合受到伤害-3,item,energy,1,player
|
||||||
|
bandage,绷带,从牌堆或弃牌堆随机移除1张伤口,item,uses,3,player
|
||||||
|
poisonPotion,淬毒药剂,周围物品的【攻击】+2,item,uses,3,player
|
||||||
|
fortifyPotion,强固药剂,周围物品的【防御】+2,item,uses,3,player
|
||||||
|
vitalityPotion,活力药剂,获得1点能量,item,uses,3,player
|
||||||
|
focusPotion,集中药剂,抓2张牌,item,uses,3,player
|
||||||
|
healingPotion,治疗药剂,从牌堆或弃牌堆移除3张伤口,item,uses,3,player
|
||||||
|
waterBag,水袋,下回合开始时获得1能量抓2张牌,item,energy,1,player
|
||||||
|
rope,绳索,周围物品的牌【防御】+2直到打出,item,energy,1,player
|
||||||
|
belt,腰带,从牌堆周围物品的牌当中选择一张加入手牌,item,energy,0,player
|
||||||
|
torch,火把,下次打出周围物品的牌时将其消耗并获得1能量,item,energy,1,player
|
||||||
|
whetstone,磨刀石,周围物品的牌【攻击】+3直到打出,item,energy,1,player
|
||||||
|
blacksmithHammer,铁匠锤,从牌堆/弃牌堆选择一张牌随机变为一张周围物品的牌,item,energy,1,player
|
||||||
|
wound,伤口,无效果占用手牌和牌堆,status,none,0,player
|
||||||
|
venom,蛇毒,弃掉时受到3点伤害,status,none,0,player
|
||||||
|
curse,诅咒,受攻击时物品攻击-1直到弃掉一张该物品的牌,status,none,0,player
|
||||||
|
static,静电,在手里时受电击伤害+1,status,none,0,player
|
||||||
|
fatigue,疲劳,占用手牌,status,none,0,player
|
||||||
|
vultureEye,秃鹫之眼,抓到时获得3层暴露,status,none,0,player
|
||||||
|
@@ -0,0 +1,21 @@
|
|||||||
|
import type { CardEffect } from './cardEffect.csv';
|
||||||
|
|
||||||
|
export type CardType = 'item' | 'status';
|
||||||
|
export type CardCostType = 'energy' | 'uses' | 'none';
|
||||||
|
export type CardTargetType = 'player' | 'enemy' | 'enemies';
|
||||||
|
|
||||||
|
type CardTable = readonly {
|
||||||
|
readonly id: string;
|
||||||
|
readonly name: string;
|
||||||
|
readonly desc: string;
|
||||||
|
readonly type: CardType;
|
||||||
|
readonly costType: CardCostType;
|
||||||
|
readonly costCount: number;
|
||||||
|
readonly targetType: CardTargetType;
|
||||||
|
readonly effects: CardEffect[];
|
||||||
|
}[];
|
||||||
|
|
||||||
|
export type Card = CardTable[number];
|
||||||
|
|
||||||
|
declare function getData(): CardTable;
|
||||||
|
export default getData;
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# type CardEffectTrigger = 'onPlay' | 'onDraw' | 'onDiscard'
|
||||||
|
# type CardEffectTarget = 'source' | 'eachTarget' | 'eachEnemy' | 'randomEnemy' | 'player'
|
||||||
|
# type CardEffectList = [effect: @effect; stacks: number][]
|
||||||
|
|
||||||
|
id,card,trigger,target,effects
|
||||||
|
string,@card,CardEffectTrigger,CardEffectTarget,CardEffectList
|
||||||
|
sword,sword,onPlay,eachTarget,[attack;2];[attack;2]
|
||||||
|
greataxe,greataxe,onPlay,eachTarget,[attack;5]
|
||||||
|
spear,spear,onPlay,eachTarget,[attack;2];[attack;2];[attack;2]
|
||||||
|
dagger,dagger,onPlay,eachTarget,[attack;3];[attack;3]
|
||||||
|
dart,dart,onPlay,eachTarget,[attack;1]
|
||||||
|
dart-draw,dart,onPlay,source,[draw;1]
|
||||||
|
crossbow,crossbow,onPlay,eachTarget,[attack;6]
|
||||||
|
crossbow-combo,crossbow,onPlay,source,[crossbow;0]
|
||||||
|
shield,shield,onPlay,source,[defend;3]
|
||||||
|
hat,hat,onPlay,source,[defend;8]
|
||||||
|
cape,cape,onPlay,source,[defend;2];[defendNext;2]
|
||||||
|
bracer,bracer,onPlay,source,[defend;1];[draw;1]
|
||||||
|
greatshield,greatshield,onPlay,source,[defend;5]
|
||||||
|
chainmail,chainmail,onPlay,source,[damageReduce;3]
|
||||||
|
bandage,bandage,onPlay,source,[removeWound;1]
|
||||||
|
poisonPotion,poisonPotion,onPlay,source,[attackBuff;2]
|
||||||
|
fortifyPotion,fortifyPotion,onPlay,source,[defendBuff;2]
|
||||||
|
vitalityPotion,vitalityPotion,onPlay,source,[gainEnergy;1]
|
||||||
|
focusPotion,focusPotion,onPlay,source,[draw;2]
|
||||||
|
healingPotion,healingPotion,onPlay,source,[removeWound;3]
|
||||||
|
waterBag,waterBag,onPlay,source,[energyNext;1];[drawNext;2]
|
||||||
|
rope,rope,onPlay,source,[defendBuffUntilPlay;2]
|
||||||
|
belt,belt,onPlay,source,[drawChoice;1]
|
||||||
|
torch,torch,onPlay,source,[burnForEnergy;1]
|
||||||
|
whetstone,whetstone,onPlay,source,[attackBuffUntilPlay;3]
|
||||||
|
blacksmithHammer,blacksmithHammer,onPlay,source,[transformRandom;1]
|
||||||
|
venom,venom,onDiscard,source,[attack;3]
|
||||||
|
curse,curse,onDraw,source,[curse;1]
|
||||||
|
static,static,onDraw,source,[static;1]
|
||||||
|
vultureEye,vultureEye,onDraw,source,[expose;3]
|
||||||
|
@@ -0,0 +1,19 @@
|
|||||||
|
import type { Card } from './card.csv';
|
||||||
|
import type { Effect } from './effect.csv';
|
||||||
|
|
||||||
|
export type CardEffectTrigger = 'onPlay' | 'onDraw' | 'onDiscard';
|
||||||
|
export type CardEffectTarget = 'source' | 'eachTarget' | 'eachEnemy' | 'randomEnemy' | 'player';
|
||||||
|
export type CardEffectList = [effect: Effect, stacks: number][];
|
||||||
|
|
||||||
|
type CardEffectTable = readonly {
|
||||||
|
readonly id: string;
|
||||||
|
readonly card: Card;
|
||||||
|
readonly trigger: CardEffectTrigger;
|
||||||
|
readonly target: CardEffectTarget;
|
||||||
|
readonly effects: CardEffectList;
|
||||||
|
}[];
|
||||||
|
|
||||||
|
export type CardEffect = CardEffectTable[number];
|
||||||
|
|
||||||
|
declare function getData(): CardEffectTable;
|
||||||
|
export default getData;
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"projectFileVersion": 4,
|
||||||
|
"sourceFiles": [
|
||||||
|
"**/*.yarn"
|
||||||
|
],
|
||||||
|
"excludeFiles": [],
|
||||||
|
"baseLanguage": "en",
|
||||||
|
"projectName": "encounters",
|
||||||
|
"authorName": [
|
||||||
|
"hyper"
|
||||||
|
],
|
||||||
|
"editorOptions": {
|
||||||
|
"yarnScriptEditor": {
|
||||||
|
"presenter": "try"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
@@ -0,0 +1,3 @@
|
|||||||
|
import type { LoadResult } from 'yarn-spinner-loader';
|
||||||
|
const result: LoadResult;
|
||||||
|
export default result;
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
title: Start
|
||||||
|
---
|
||||||
|
// A linear story progresses from one scene to the next.
|
||||||
|
// Great for cutscenes, tutorials, or scripted sequences.
|
||||||
|
|
||||||
|
<<jump Scene1>>
|
||||||
|
===
|
||||||
|
title: Scene1
|
||||||
|
---
|
||||||
|
The sun rose over the quiet village.
|
||||||
|
|
||||||
|
Birds sang their morning chorus as the first rays of light crept through the window.
|
||||||
|
|
||||||
|
-> Continue
|
||||||
|
<<jump Scene2>>
|
||||||
|
===
|
||||||
|
title: Scene2
|
||||||
|
---
|
||||||
|
In the kitchen, a kettle began to whistle.
|
||||||
|
|
||||||
|
The smell of fresh bread filled the air.
|
||||||
|
|
||||||
|
-> Continue
|
||||||
|
<<jump Scene3>>
|
||||||
|
===
|
||||||
|
title: Scene3
|
||||||
|
---
|
||||||
|
A knock at the door broke the peaceful morning.
|
||||||
|
|
||||||
|
Who could be visiting so early?
|
||||||
|
|
||||||
|
-> Open the door
|
||||||
|
<<jump Scene4>>
|
||||||
|
===
|
||||||
|
title: Scene4
|
||||||
|
---
|
||||||
|
A messenger stood at the threshold, parchment in hand.
|
||||||
|
|
||||||
|
"News from the capital," they said breathlessly. "You must read this at once."
|
||||||
|
|
||||||
|
// Your story continues from here!
|
||||||
|
===
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# instant: 不施加buff,瞬间生效
|
||||||
|
|
||||||
|
# temporary: 施加buff,下回合开始时失效
|
||||||
|
# lingering: 施加buff,下回合开始时失去1层
|
||||||
|
# permanent: 施加buff
|
||||||
|
# posture: 施加buff,每受到1点伤害移除1层
|
||||||
|
|
||||||
|
# item: 施加buff到周围物品,永久生效
|
||||||
|
# itemTemporary: 施加buff到周围物品,持续到下次buff更新
|
||||||
|
# itemUntilPlay: 施加buff到周围物品,物品被打出后失效
|
||||||
|
# itemUntilDiscard: 施加buff到周围物品,物品被弃掉后失效
|
||||||
|
# itemPermanent: 施加buff到周围物品,持续整场冒险
|
||||||
|
|
||||||
|
# type EffectLifecycle = 'instant' | 'temporary' | 'lingering' | 'permanent' | 'posture' | 'item' | 'itemTemporary' | 'itemUntilPlay' | 'itemUntilDiscard' | 'itemPermanent'
|
||||||
|
|
||||||
|
id, name, description, lifecycle, emoji
|
||||||
|
string, string, string, EffectLifecycle, string
|
||||||
|
attack, 攻击, 对对手造成伤害, instant, ⚔️
|
||||||
|
defend, 防御, 抵消下次行动前受到的伤害, temporary, 🛡️
|
||||||
|
spike, 尖刺, 对攻击者造成X点伤害, permanent, 🌵
|
||||||
|
venom, 蛇毒, 同名状态牌/1费:打出时移除此牌。弃掉时受到3点伤害, instant, 🧪
|
||||||
|
curse, 诅咒, 受攻击时物品攻击-1,直到弃掉一张该物品的牌, lingering, 💀
|
||||||
|
aim, 瞄准, 造成双倍伤害,受伤时失去等量瞄准, posture, 🎯
|
||||||
|
roll, 滚动, 攻击时每消耗10点滚动造成等量伤害, posture, 🎲
|
||||||
|
rollDamage, 滚动攻击, 消耗滚动层数造成的伤害, instant, 💥
|
||||||
|
vultureEye, 秃鹫之眼, 抓到时获得3层暴露(临时debuff,受到的伤害+1/每层), instant, 👁️
|
||||||
|
tailSting, 尾刺, 攻击时,伤害提升X, posture, 🦂
|
||||||
|
energyDrain, 能量吸取, 受伤时,玩家失去X点能量, lingering, 🔋
|
||||||
|
molt, 脱皮, 若脱皮达到生命上限则怪物逃跑, posture, 🐚
|
||||||
|
discard, 劫掠, 回合开始时随机弃掉一张手牌, lingering, 🗑️
|
||||||
|
storm, 风暴, 攻击时给玩家塞入1张静电, permanent, ⚡
|
||||||
|
static, 静电, 在手里时受电击伤害+1, permanent, ⚡
|
||||||
|
charge, 冲锋, 受到或造成的伤害翻倍并消耗等量冲锋, lingering, 🐎
|
||||||
|
summonMummy, 召唤木乃伊, 召唤1个木乃伊, instant, 🧟
|
||||||
|
summonSandwormLarva, 召唤幼沙虫, 召唤1个幼沙虫, instant, 🐛
|
||||||
|
reviveMummy, 复活木乃伊, 复活1个已死亡的木乃伊, instant, 🌅
|
||||||
|
draw, 抓牌, 抓X张牌, instant, 🃏
|
||||||
|
crossbow, 十字弩连击, 对同一目标打出其他十字弩, instant, 🏹
|
||||||
|
defendNext, 下回合防御, 下回合开始时获得防御, temporary, 🛡️
|
||||||
|
damageReduce, 减伤, 本回合受到的伤害减少X, temporary, 📉
|
||||||
|
removeWound, 移除伤口, 从牌堆或弃牌堆移除X张伤口, instant, 🩹
|
||||||
|
attackBuff, 攻击增益, 周围物品的攻击+X, itemUntilPlay, ⬆️
|
||||||
|
defendBuff, 防御增益, 周围物品的防御+X, itemUntilPlay, ⬆️
|
||||||
|
gainEnergy, 获得能量, 获得X点能量, instant, ⚡
|
||||||
|
energyNext, 下回合获能量, 下回合开始时获得X点能量, temporary, ⚡
|
||||||
|
drawNext, 下回合抓牌, 下回合开始时抓X张牌, temporary, 🃏
|
||||||
|
defendBuffUntilPlay, 防御增益直到打出, 周围物品的牌防御+X直到打出, itemUntilPlay, 🛡️
|
||||||
|
drawChoice, 选择抓牌, 从牌堆周围物品的牌中选择一张加入手牌, instant, 🔍
|
||||||
|
burnForEnergy, 消耗获能量, 打出周围物品的牌时消耗并获得X能量, itemUntilPlay, 🔥
|
||||||
|
attackBuffUntilPlay, 攻击增益直到打出, 周围物品的牌攻击+X直到打出, itemUntilPlay, ⚔️
|
||||||
|
transformRandom, 随机变牌, 选择一张牌随机变为周围物品的牌, instant, 🌀
|
||||||
|
expose, 暴露, 受到的伤害+1/每层, temporary, 👁️
|
||||||
|
@@ -0,0 +1,14 @@
|
|||||||
|
export type EffectLifecycle = 'instant' | 'temporary' | 'lingering' | 'permanent' | 'posture' | 'item' | 'itemTemporary' | 'itemUntilPlay' | 'itemUntilDiscard' | 'itemPermanent';
|
||||||
|
|
||||||
|
type EffectTable = readonly {
|
||||||
|
readonly id: string;
|
||||||
|
readonly name: string;
|
||||||
|
readonly description: string;
|
||||||
|
readonly lifecycle: EffectLifecycle;
|
||||||
|
readonly emoji: string;
|
||||||
|
}[];
|
||||||
|
|
||||||
|
export type Effect = EffectTable[number];
|
||||||
|
|
||||||
|
declare function getData(): EffectTable;
|
||||||
|
export default getData;
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# minion (10): minor enemies
|
||||||
|
# elite (4): dangerous enemies
|
||||||
|
# event (1): random dangerous event that requires reaction
|
||||||
|
# shop (2): merchant who sells different stuff
|
||||||
|
# camp (2): consumable restock and heal
|
||||||
|
# curio (8): random pickup of treasure or resources
|
||||||
|
# enemies: array of [enemyId; initialHp; buffs[]]
|
||||||
|
|
||||||
|
# type EncounterType = 'minion' | 'elite' | 'event' | 'shop' | 'camp' | 'curio'
|
||||||
|
# type EnemyList = [data: @enemy; hp: int; effects: [effect: @effect; stacks: int][]][]
|
||||||
|
|
||||||
|
id,type,name,description,enemies,dialogue
|
||||||
|
string,EncounterType,string,string,EnemyList,string
|
||||||
|
cactus_pair,minion,仙人掌怪,概念:防+强化。【尖刺X】:对攻击者造成X点伤害。,[仙人掌怪;12;[]];[仙人掌怪;12;[]],
|
||||||
|
snake_pair,minion,蛇,概念:攻+强化。给玩家塞入蛇毒牌(1费:打出时移除此牌。弃掉时受到3点伤害)。,[蛇;10;[]],
|
||||||
|
mummy_cactus,minion,木乃伊,概念:攻+防。【诅咒】:受攻击时物品【攻击】-1,直到弃掉一张该物品的牌。,[木乃伊;14;[]];[仙人掌怪;12;[]],
|
||||||
|
gunslinger,minion,枪手,概念:单回高攻。【瞄准X】:造成双倍伤害。受伤时失去等量【瞄准】,[枪手;12;[]],
|
||||||
|
tumbleweed_pair,minion,风卷草,概念:防+强化。【滚动X】:攻击时,每消耗10点【滚动】,造成等量伤害。,[风卷草;16;[]],
|
||||||
|
vulture_cactus,minion,秃鹫,概念:攻+防。若造成伤害,玩家获得秃鹫之眼(0费状态牌:打出时移除。抓到时获得3层暴露)。,[秃鹫;12;[]];[仙人掌怪;12;[]],
|
||||||
|
scorpion_snake,minion,沙蝎,概念:攻+强化。【尾刺X】:姿态buff,攻击时,伤害提升X。,[沙蝎;10;[]];[蛇;10;[]],
|
||||||
|
sandworm_larva,minion,幼沙虫,概念:防+强化。每回合第一次受伤时,玩家失去1点能量。,[幼沙虫;18;[]],
|
||||||
|
lizard_pair,minion,蜥蜴,概念:攻+防+逃跑。【脱皮】:若脱皮达到生命上限,则怪物逃跑,玩家不能获得战斗奖励。,[蜥蜴;14;[]],
|
||||||
|
bandit_gunslinger,minion,沙匪,概念:弱化玩家。【劫掠】:对玩家施加的延时debuff。回合开始时,随机弃掉一张手牌。,[沙匪;12;[]];[枪手;12;[]],
|
||||||
|
storm_spirit,elite,风暴之灵,【风暴X】:攻击时,玩家获得1张静电。受伤时失去等量【风暴】。(静电:在手里时受【电击】伤害+1),[风暴之灵;30;[]],
|
||||||
|
mounted_gunslinger,elite,骑马枪手,【冲锋X】:受到或造成的伤害翻倍并消耗等量的冲锋。,[骑马枪手;25;[]];[枪手;12;[]],
|
||||||
|
sandworm_king,elite,沙虫王,召唤幼体沙虫;每当玩家弃掉一张牌,恢复1生命。,[沙虫王;40;[]],
|
||||||
|
desert_guard,elite,沙漠守卫,召唤木乃伊;会复活木乃伊2次。,[沙漠守卫;35;[]];[木乃伊;14;[]],
|
||||||
|
desert_merchant,shop,沙漠商人,商店:可以恢复生命、出售装备、附魔物品。,,
|
||||||
|
nomad_caravan,shop,游牧商队,商队:出售稀有物品、移除牌组中一张牌。,,
|
||||||
|
oasis_campfire,camp,绿洲篝火,篝火:可以恢复生命、补充药水使用次数、获得下次战斗Buff。,,
|
||||||
|
cave_shelter,camp,岩洞庇护所,篝火:可以恢复生命、升级一张牌。,,
|
||||||
|
desert_relic_in_sand,curio,沙中遗物,随机获得一件遗物或受到3点伤害。,,desert_relic_in_sand
|
||||||
|
desert_dry_well,curio,枯井,投入1能量:可能获得药水或什么也没有。,,desert_dry_well
|
||||||
|
desert_ancient_stele,curio,古代石碑,阅读碑文:获得随机Buff直到下次战斗结束。,,desert_ancient_stele
|
||||||
|
desert_storm_wreckage,curio,沙暴残骸,搜索残骸:随机获得一张物品牌或受到2点伤害。,,desert_storm_wreckage
|
||||||
|
desert_mirage_chest,curio,蜃景宝箱,打开宝箱:50%获得宝藏,50%为蜃景什么也没有。,,desert_mirage_chest
|
||||||
|
desert_buried_pot,curio,埋藏陶罐,挖掘:获得随机资源(金币、药水或遗物碎片)。,,desert_buried_pot
|
||||||
|
desert_weathered_statue,curio,风化雕像,献祭1生命:获得一件随机遗物。,,desert_weathered_statue
|
||||||
|
desert_oasis_fragment,curio,绿洲碎片,小型绿洲:恢复3生命并获得1张随机消耗品。,,desert_oasis_fragment
|
||||||
|
desert_mirage_event,event,海市蜃楼,随机遭遇:可能获得宝藏或遭遇陷阱,使用d6双阶段结构结算。,,desert_mirage_event
|
||||||
|
@@ -0,0 +1,19 @@
|
|||||||
|
import type { Enemy } from './enemy.csv';
|
||||||
|
import type { Effect } from './effect.csv';
|
||||||
|
|
||||||
|
export type EncounterType = 'minion' | 'elite' | 'event' | 'shop' | 'camp' | 'curio';
|
||||||
|
export type EnemyList = [data: Enemy, hp: int, effects: [effect: Effect, stacks: int][]][];
|
||||||
|
|
||||||
|
type EncounterTable = readonly {
|
||||||
|
readonly id: string;
|
||||||
|
readonly type: EncounterType;
|
||||||
|
readonly name: string;
|
||||||
|
readonly description: string;
|
||||||
|
readonly enemies: EnemyList;
|
||||||
|
readonly dialogue: string;
|
||||||
|
}[];
|
||||||
|
|
||||||
|
export type Encounter = EncounterTable[number];
|
||||||
|
|
||||||
|
declare function getData(): EncounterTable;
|
||||||
|
export default getData;
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
id,name,intents,description
|
||||||
|
string,string,@intent[],string
|
||||||
|
仙人掌怪,仙人掌怪,[仙人掌怪-boost;仙人掌怪-defend;仙人掌怪-attack],防+强化。【尖刺X】:对攻击者造成X点伤害。
|
||||||
|
蛇,蛇,[蛇-poison;蛇-attack;蛇-boost],攻+强化。给玩家塞入蛇毒牌(1费:打出时移除此牌。弃掉时受到3点伤害)。
|
||||||
|
木乃伊,木乃伊,[木乃伊-attack;木乃伊-defend;木乃伊-curse],攻+防。【诅咒】:受攻击时物品【攻击】-1,直到弃掉一张该物品的牌。
|
||||||
|
枪手,枪手,[枪手-aim;枪手-attack;枪手-defend],单回高攻。【瞄准X】:造成双倍伤害。受伤时失去等量【瞄准】。
|
||||||
|
风卷草,风卷草,[风卷草-boost;风卷草-defend;风卷草-attack],防+强化。【滚动X】:攻击时,每消耗10点【滚动】,造成等量伤害。
|
||||||
|
秃鹫,秃鹫,[秃鹫-attack;秃鹫-defend],攻+防。若造成伤害,玩家获得秃鹫之眼(0费状态牌:打出时移除。抓到时获得3层暴露)。
|
||||||
|
沙蝎,沙蝎,[沙蝎-boost;沙蝎-attack],攻+强化。【尾刺X】:姿态buff,攻击时,伤害提升X。
|
||||||
|
幼沙虫,幼沙虫,[幼沙虫-defend;幼沙虫-boost;幼沙虫-attack],防+强化。每回合第一次受伤时,玩家失去1点能量。
|
||||||
|
蜥蜴,蜥蜴,[蜥蜴-attack;蜥蜴-defend;蜥蜴-molt],攻+防+逃跑。【脱皮】:若脱皮达到生命上限,则怪物逃跑,玩家不能获得战斗奖励。
|
||||||
|
沙匪,沙匪,[沙匪-attack;沙匪-heavyAttack;沙匪-debuff],弱化玩家。【劫掠】:对玩家施加的延时debuff。回合开始时,随机弃掉一张手牌。
|
||||||
|
风暴之灵,风暴之灵,[风暴之灵-storm;风暴之灵-attack;风暴之灵-defend],【风暴X】:攻击时,玩家获得1张静电。受伤时失去等量【风暴】。(静电:在手里时受【电击】伤害+1)
|
||||||
|
骑马枪手,骑马枪手,[骑马枪手-charge;骑马枪手-attack;骑马枪手-defend],【冲锋X】:受到或造成的伤害翻倍并消耗等量的冲锋。
|
||||||
|
沙虫王,沙虫王,[沙虫王-summon;沙虫王-attack;沙虫王-defend],召唤幼体沙虫;每当玩家弃掉一张牌,恢复1生命。
|
||||||
|
沙漠守卫,沙漠守卫,[沙漠守卫-summon;沙漠守卫-attack;沙漠守卫-defend;沙漠守卫-revive],召唤木乃伊;会复活木乃伊2次。
|
||||||
|
@@ -0,0 +1,13 @@
|
|||||||
|
import type { Intent } from './intent.csv';
|
||||||
|
|
||||||
|
type EnemyTable = readonly {
|
||||||
|
readonly id: string;
|
||||||
|
readonly name: string;
|
||||||
|
readonly intents: Intent[];
|
||||||
|
readonly description: string;
|
||||||
|
}[];
|
||||||
|
|
||||||
|
export type Enemy = EnemyTable[number];
|
||||||
|
|
||||||
|
declare function getData(): EnemyTable;
|
||||||
|
export default getData;
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import getItems, { Item } from "./item.csv";
|
||||||
|
|
||||||
|
export type * from "./card.csv";
|
||||||
|
export type * from "./cardEffect.csv";
|
||||||
|
export type * from "./effect.csv";
|
||||||
|
export type * from "./encounter.csv";
|
||||||
|
export type * from "./enemy.csv";
|
||||||
|
export type * from "./intent.csv";
|
||||||
|
export type * from "./item.csv";
|
||||||
|
|
||||||
|
export { default as getCards } from "./card.csv";
|
||||||
|
export { default as getEffects } from "./effect.csv";
|
||||||
|
export { default as getEncounters } from "./encounter.csv";
|
||||||
|
export { default as getEnemies } from "./enemy.csv";
|
||||||
|
export { default as getIntents } from "./intent.csv";
|
||||||
|
export { default as getItems } from "./item.csv";
|
||||||
|
export { default as dialogues } from "./dialogues/dialogues.yarnproject";
|
||||||
|
export { addTriggers } from "./triggers";
|
||||||
|
|
||||||
|
const itemSet = ["剑", "盾", "水袋", "绷带"] as string[];
|
||||||
|
export function getStartingItems(): Item[] {
|
||||||
|
return itemSet.map(function (name): Item {
|
||||||
|
return getItems().find((item: Item) => item.name === name) as Item;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# intentId: unique intent state ID (e.g. '仙人掌怪-boost')
|
||||||
|
# enemy: enemy template this intent belongs to
|
||||||
|
# initialIntent: true if this is the enemy's starting intent
|
||||||
|
# nextIntents: possible next intent IDs after this intent resolves
|
||||||
|
# brokenIntent: possible intent IDs when defend is broken
|
||||||
|
# initBuffs: initial buffs for this intent (applied when intent becomes active)
|
||||||
|
# effects: effects executed when this intent is active
|
||||||
|
|
||||||
|
# type IntentEffectTarget = 'source' | 'eachEnemy' | 'randomEnemy' | 'player'
|
||||||
|
# type IntentEffect = [IntentEffectTarget;@effect;number]
|
||||||
|
# type IntentEffectList = IntentEffect[]
|
||||||
|
|
||||||
|
id,enemy,initialIntent,nextIntents,brokenIntent,effects
|
||||||
|
string,@enemy,boolean,@intent[],@intent[],IntentEffectList
|
||||||
|
仙人掌怪-boost,仙人掌怪,true,仙人掌怪-boost;仙人掌怪-defend,,[source;spike;1];[source;defend;4]
|
||||||
|
仙人掌怪-defend,仙人掌怪,false,仙人掌怪-attack,,[source;defend;8]
|
||||||
|
仙人掌怪-attack,仙人掌怪,false,仙人掌怪-boost,,[player;attack;5]
|
||||||
|
蛇-poison,蛇,true,蛇-attack;蛇-attack,,[player;venom;1];[player;attack;4]
|
||||||
|
蛇-attack,蛇,false,蛇-poison;蛇-boost,,[player;attack;6]
|
||||||
|
蛇-boost,蛇,false,蛇-poison;蛇-attack,,[source;defend;3];[player;venom;1]
|
||||||
|
木乃伊-attack,木乃伊,true,木乃伊-defend;木乃伊-curse,,[player;attack;6]
|
||||||
|
木乃伊-defend,木乃伊,false,木乃伊-attack,,[source;defend;6]
|
||||||
|
木乃伊-curse,木乃伊,false,木乃伊-defend;木乃伊-attack,木乃伊-attack,[player;curse;1]
|
||||||
|
枪手-aim,枪手,true,枪手-attack,,[source;aim;2]
|
||||||
|
枪手-attack,枪手,false,枪手-aim;枪手-defend,枪手-aim,[player;attack;8]
|
||||||
|
枪手-defend,枪手,false,枪手-aim,枪手-aim,[source;defend;5]
|
||||||
|
风卷草-boost,风卷草,true,风卷草-defend;风卷草-defend;风卷草-boost,,[source;roll;5];[source;defend;4]
|
||||||
|
风卷草-defend,风卷草,false,风卷草-boost;风卷草-attack,,[source;defend;8]
|
||||||
|
风卷草-attack,风卷草,false,风卷草-boost,,[player;rollDamage;0]
|
||||||
|
秃鹫-attack,秃鹫,true,秃鹫-defend;秃鹫-defend,,[player;attack;6];[player;vultureEye;1]
|
||||||
|
秃鹫-defend,秃鹫,false,秃鹫-attack;秃鹫-attack,,[source;defend;5]
|
||||||
|
沙蝎-boost,沙蝎,true,沙蝎-attack;沙蝎-attack,,[source;tailSting;2]
|
||||||
|
沙蝎-attack,沙蝎,false,沙蝎-boost;沙蝎-attack,,[player;attack;6]
|
||||||
|
幼沙虫-defend,幼沙虫,true,幼沙虫-defend;幼沙虫-boost,,[source;defend;6]
|
||||||
|
幼沙虫-boost,幼沙虫,false,幼沙虫-attack;幼沙虫-defend,,[source;energyDrain;1];[source;defend;4]
|
||||||
|
幼沙虫-attack,幼沙虫,false,幼沙虫-defend;幼沙虫-defend,,[player;attack;5]
|
||||||
|
蜥蜴-attack,蜥蜴,true,蜥蜴-defend;蜥蜴-molt,,[player;attack;5]
|
||||||
|
蜥蜴-defend,蜥蜴,false,蜥蜴-attack;蜥蜴-attack,,[source;defend;6]
|
||||||
|
蜥蜴-molt,蜥蜴,false,蜥蜴-defend;蜥蜴-attack,,[source;molt;3]
|
||||||
|
沙匪-attack,沙匪,true,沙匪-attack;沙匪-heavyAttack,,[player;attack;6]
|
||||||
|
沙匪-heavyAttack,沙匪,false,沙匪-attack;沙匪-attack;沙匪-debuff,,[player;attack;10]
|
||||||
|
沙匪-debuff,沙匪,false,沙匪-attack;沙匪-attack,,[player;discard;1]
|
||||||
|
风暴之灵-storm,风暴之灵,true,风暴之灵-attack;风暴之灵-storm,,[source;storm;2];[source;defend;3]
|
||||||
|
风暴之灵-attack,风暴之灵,false,风暴之灵-storm;风暴之灵-defend,,[player;attack;8];[player;static;1]
|
||||||
|
风暴之灵-defend,风暴之灵,false,风暴之灵-storm;风暴之灵-attack,,[source;defend;8]
|
||||||
|
骑马枪手-charge,骑马枪手,true,骑马枪手-attack,,[source;charge;2]
|
||||||
|
骑马枪手-attack,骑马枪手,false,骑马枪手-charge;骑马枪手-defend,骑马枪手-charge,[player;attack;6]
|
||||||
|
骑马枪手-defend,骑马枪手,false,骑马枪手-charge;骑马枪手-attack,骑马枪手-charge,[source;defend;5]
|
||||||
|
沙虫王-summon,沙虫王,true,沙虫王-attack;沙虫王-defend,,[source;summonSandwormLarva;18]
|
||||||
|
沙虫王-attack,沙虫王,false,沙虫王-summon;沙虫王-defend,,[player;attack;9]
|
||||||
|
沙虫王-defend,沙虫王,false,沙虫王-attack;沙虫王-summon,,[source;defend;6]
|
||||||
|
沙漠守卫-summon,沙漠守卫,true,沙漠守卫-attack;沙漠守卫-defend,,[source;summonMummy;14]
|
||||||
|
沙漠守卫-attack,沙漠守卫,false,沙漠守卫-defend;沙漠守卫-summon,,[player;attack;8]
|
||||||
|
沙漠守卫-defend,沙漠守卫,false,沙漠守卫-attack;沙漠守卫-revive,,[source;defend;8]
|
||||||
|
沙漠守卫-revive,沙漠守卫,false,沙漠守卫-attack;沙漠守卫-summon,,[source;reviveMummy;1]
|
||||||
|
@@ -0,0 +1,20 @@
|
|||||||
|
import type { Enemy } from './enemy.csv';
|
||||||
|
import type { Effect } from './effect.csv';
|
||||||
|
|
||||||
|
export type IntentEffectTarget = 'source' | 'eachEnemy' | 'randomEnemy' | 'player';
|
||||||
|
export type IntentEffect = [IntentEffectTarget, Effect, number];
|
||||||
|
export type IntentEffectList = IntentEffect[];
|
||||||
|
|
||||||
|
type IntentTable = readonly {
|
||||||
|
readonly id: string;
|
||||||
|
readonly enemy: Enemy;
|
||||||
|
readonly initialIntent: boolean;
|
||||||
|
readonly nextIntents: Intent[];
|
||||||
|
readonly brokenIntent: Intent[];
|
||||||
|
readonly effects: IntentEffectList;
|
||||||
|
}[];
|
||||||
|
|
||||||
|
export type Intent = IntentTable[number];
|
||||||
|
|
||||||
|
declare function getData(): IntentTable;
|
||||||
|
export default getData;
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
id,type,name,shape,card,price,description
|
||||||
|
string,string,string,string,@card,int,string
|
||||||
|
sword,weapon,剑,oee,sword,50,【攻击2】【攻击2】
|
||||||
|
greataxe,weapon,长斧,oees,greataxe,80,对全体【攻击5】
|
||||||
|
spear,weapon,长枪,oeee,spear,75,【攻击2】【攻击2】【攻击2】
|
||||||
|
dagger,weapon,短刀,oe,dagger,40,【攻击3】【攻击3】
|
||||||
|
dart,weapon,飞镖,o,dart,30,【攻击1】抓一张牌
|
||||||
|
crossbow,weapon,十字弩,onrersrw,crossbow,120,【攻击6】对同一目标打出其他十字弩
|
||||||
|
shield,armor,盾,oesw,shield,50,【防御3】
|
||||||
|
hat,armor,斗笠,oerwrn,hat,90,【防御8】
|
||||||
|
cape,armor,披风,oers,cape,45,【防御2】下回合【防御2】
|
||||||
|
bracer,armor,护腕,o,bracer,25,【防御1】抓1张牌
|
||||||
|
greatshield,armor,大盾,oesswn,greatshield,70,【防御5】
|
||||||
|
chainmail,armor,锁子甲,oesw,chainmail,60,本回合受到伤害-3
|
||||||
|
bandage,consumable,绷带,o,bandage,20,从牌堆或弃牌堆随机移除1张伤口
|
||||||
|
poisonPotion,consumable,淬毒药剂,o,poisonPotion,30,周围物品的【攻击】+2
|
||||||
|
fortifyPotion,consumable,强固药剂,o,fortifyPotion,30,周围物品的【防御】+2
|
||||||
|
vitalityPotion,consumable,活力药剂,o,vitalityPotion,25,获得1点能量
|
||||||
|
focusPotion,consumable,集中药剂,o,focusPotion,25,抓2张牌
|
||||||
|
healingPotion,consumable,治疗药剂,o,healingPotion,35,从牌堆或弃牌堆移除3张伤口
|
||||||
|
waterBag,tool,水袋,os,waterBag,35,下回合开始时获得1能量抓2张牌
|
||||||
|
rope,tool,绳索,ose,rope,30,周围物品的牌【防御】+2直到打出
|
||||||
|
belt,tool,腰带,owre,belt,40,从牌堆周围物品的牌当中选择一张加入手牌
|
||||||
|
torch,tool,火把,on,torch,25,下次打出周围物品的牌时将其消耗并获得1能量
|
||||||
|
whetstone,tool,磨刀石,o,whetstone,30,周围物品的牌【攻击】+3直到打出
|
||||||
|
blacksmithHammer,tool,铁匠锤,oerwrs,blacksmithHammer,45,从牌堆/弃牌堆选择一张牌随机变为一张周围物品的牌
|
||||||
|
@@ -0,0 +1,16 @@
|
|||||||
|
import type { Card } from './card.csv';
|
||||||
|
|
||||||
|
type ItemTable = readonly {
|
||||||
|
readonly id: string;
|
||||||
|
readonly type: string;
|
||||||
|
readonly name: string;
|
||||||
|
readonly shape: string;
|
||||||
|
readonly card: Card;
|
||||||
|
readonly price: number;
|
||||||
|
readonly description: string;
|
||||||
|
}[];
|
||||||
|
|
||||||
|
export type Item = ItemTable[number];
|
||||||
|
|
||||||
|
declare function getData(): ItemTable;
|
||||||
|
export default getData;
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import { Triggers } from "@/samples/slay-the-spire-like/system/combat/triggers";
|
||||||
|
import { getCombatEntity } from "@/samples/slay-the-spire-like/system/combat/effects";
|
||||||
|
import { EffectData } from "@/samples/slay-the-spire-like/system/types";
|
||||||
|
import getEffects from "../effect.csv";
|
||||||
|
import { IRunContext } from "@/samples/slay-the-spire-like/system/combat/types";
|
||||||
|
|
||||||
|
export function addCardEventTriggers(triggers: Triggers, run: IRunContext) {
|
||||||
|
const effects = getEffects();
|
||||||
|
|
||||||
|
function findEffect(id: string): EffectData {
|
||||||
|
const found = effects.find((e) => e.id === id);
|
||||||
|
if (found) return found;
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: id,
|
||||||
|
description: "",
|
||||||
|
lifecycle: "instant",
|
||||||
|
} as EffectData;
|
||||||
|
}
|
||||||
|
|
||||||
|
// storm: give static card to player when storm enemy attacks
|
||||||
|
triggers.onEnemyIntent.use(async (ctx, next) => {
|
||||||
|
await next();
|
||||||
|
|
||||||
|
const enemy = getCombatEntity(ctx.game.value, ctx.enemyId);
|
||||||
|
if (!enemy || !enemy.isAlive) return;
|
||||||
|
|
||||||
|
const storm = enemy.effects.storm?.stacks ?? 0;
|
||||||
|
if (storm > 0) {
|
||||||
|
for (let i = 0; i < storm; i++) {
|
||||||
|
await triggers.onEffectApplied.execute(ctx.game, {
|
||||||
|
effect: findEffect("static"),
|
||||||
|
entityId: "player",
|
||||||
|
stacks: 1,
|
||||||
|
sourceEntityId: ctx.enemyId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// crossbow: replay other crossbows on same target
|
||||||
|
triggers.onEffectApplied.use(async (ctx, next) => {
|
||||||
|
await next();
|
||||||
|
|
||||||
|
if (ctx.effect.id !== "crossbow" || !ctx.cardId || !ctx.targetId) return;
|
||||||
|
|
||||||
|
const { cards, regions } = ctx.game.value.player.deck;
|
||||||
|
const handIds = [...regions.hand.childIds];
|
||||||
|
for (const id of handIds) {
|
||||||
|
const card = cards[id];
|
||||||
|
if (card && card.itemId === "crossbow" && id !== ctx.cardId) {
|
||||||
|
await triggers.onCardPlayed.execute(ctx.game, {
|
||||||
|
cardId: id,
|
||||||
|
targetId: ctx.targetId,
|
||||||
|
sourceEntityId: "player",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// burnForEnergy: consume adjacent item, gain energy when its card is played
|
||||||
|
triggers.onCardPlayed.use(async (ctx, next) => {
|
||||||
|
await next();
|
||||||
|
|
||||||
|
const card = ctx.game.value.player.deck.cards[ctx.cardId];
|
||||||
|
if (!card) return;
|
||||||
|
const playedItemId = card.itemId;
|
||||||
|
|
||||||
|
const adjacent = run.getAdjacentItems(playedItemId);
|
||||||
|
for (const adjItemId of adjacent) {
|
||||||
|
const adjEffects = ctx.game.value.player.itemEffects[adjItemId];
|
||||||
|
if (!adjEffects) continue;
|
||||||
|
const burn = adjEffects.burnForEnergy;
|
||||||
|
if (!burn || burn.stacks <= 0) continue;
|
||||||
|
|
||||||
|
const item = run.getItemData(adjItemId);
|
||||||
|
const maxUses =
|
||||||
|
item?.card.costType === "energy" ? item.card.costCount : 0;
|
||||||
|
const consumed = run.getConsumedUses(adjItemId);
|
||||||
|
const toConsume = Math.min(maxUses - consumed, burn.stacks);
|
||||||
|
|
||||||
|
await run.setConsumedUsesAsync(adjItemId, consumed + toConsume);
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
draft.player.energy += burn.stacks;
|
||||||
|
delete draft.player.itemEffects[adjItemId];
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// sandwormKing: heal 10 hp when player discards fatigue
|
||||||
|
triggers.onCardDiscarded.use(async (ctx, next) => {
|
||||||
|
await next();
|
||||||
|
|
||||||
|
const card = ctx.game.value.player.deck.cards[ctx.cardId];
|
||||||
|
if (!card || card.cardData.id !== "fatigue") return;
|
||||||
|
|
||||||
|
const sandwormKing = ctx.game.value.enemies.find(
|
||||||
|
(e) => e.enemy.id === "沙虫王" && e.isAlive,
|
||||||
|
);
|
||||||
|
if (!sandwormKing) return;
|
||||||
|
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const king = draft.enemies.find((e) => e.id === sandwormKing.id);
|
||||||
|
if (king) {
|
||||||
|
king.hp = Math.min(king.hp + 10, king.maxHp);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// vulture: give vultureEye when vulture deals damage
|
||||||
|
triggers.onDamage.use(async (ctx, next) => {
|
||||||
|
await next();
|
||||||
|
|
||||||
|
const dealt = ctx.amount - (ctx.prevented ?? 0);
|
||||||
|
if (dealt <= 0 || !ctx.sourceEntityId) return;
|
||||||
|
|
||||||
|
const attacker = getCombatEntity(ctx.game.value, ctx.sourceEntityId);
|
||||||
|
if (!attacker || !("enemy" in attacker) || attacker.enemy.id !== "秃鹫")
|
||||||
|
return;
|
||||||
|
|
||||||
|
await triggers.onEffectApplied.execute(ctx.game, {
|
||||||
|
effect: findEffect("vultureEye"),
|
||||||
|
entityId: "player",
|
||||||
|
stacks: 1,
|
||||||
|
sourceEntityId: ctx.sourceEntityId,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
import { Triggers } from "@/samples/slay-the-spire-like/system/combat/triggers";
|
||||||
|
import {
|
||||||
|
addEntityEffect,
|
||||||
|
getCombatEntity,
|
||||||
|
} from "@/samples/slay-the-spire-like/system/combat/effects";
|
||||||
|
import { EffectData } from "@/samples/slay-the-spire-like/system/types";
|
||||||
|
import getEffects from "../effect.csv";
|
||||||
|
|
||||||
|
export function addDamageTriggers(triggers: Triggers) {
|
||||||
|
const effects = getEffects();
|
||||||
|
|
||||||
|
function findEffect(id: string): EffectData {
|
||||||
|
const found = effects.find((e: EffectData) => e.id === id);
|
||||||
|
if (found) return found;
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: id,
|
||||||
|
description: "",
|
||||||
|
lifecycle: "instant",
|
||||||
|
} as EffectData;
|
||||||
|
}
|
||||||
|
|
||||||
|
// block / damage prevention
|
||||||
|
triggers.onDamage.use(async (ctx, next) => {
|
||||||
|
const entity = getCombatEntity(ctx.game.value, ctx.entityId);
|
||||||
|
if (!entity) return;
|
||||||
|
|
||||||
|
let preventable = ctx.amount - (ctx.prevented ?? 0);
|
||||||
|
|
||||||
|
// 1. apply damageReduce before block
|
||||||
|
const damageReduce = entity.effects.damageReduce?.stacks ?? 0;
|
||||||
|
if (damageReduce > 0) {
|
||||||
|
const reduced = Math.min(damageReduce, preventable);
|
||||||
|
ctx.prevented = (ctx.prevented ?? 0) + reduced;
|
||||||
|
preventable -= reduced;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. consume defend for damage prevented
|
||||||
|
const blocks = entity.effects.defend?.stacks ?? 0;
|
||||||
|
const blocked = Math.min(blocks, preventable);
|
||||||
|
if (blocked > 0) {
|
||||||
|
ctx.prevented = (ctx.prevented ?? 0) + blocked;
|
||||||
|
preventable -= blocked;
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const e = getCombatEntity(draft, ctx.entityId);
|
||||||
|
if (e) addEntityEffect(e, findEffect("defend"), -blocked);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const expose = entity.effects.expose?.stacks ?? 0;
|
||||||
|
if (expose > 0) {
|
||||||
|
ctx.amount += expose;
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// energyDrain: player loses energy when enemy takes damage
|
||||||
|
triggers.onDamage.use(async (ctx, next) => {
|
||||||
|
const entity = getCombatEntity(ctx.game.value, ctx.entityId);
|
||||||
|
if (!entity) return;
|
||||||
|
|
||||||
|
const energyDrain = entity.effects.energyDrain?.stacks ?? 0;
|
||||||
|
if (energyDrain > 0 && ctx.entityId !== "player") {
|
||||||
|
const dealt = Math.min(
|
||||||
|
Math.max(0, entity.hp),
|
||||||
|
ctx.amount - (ctx.prevented ?? 0),
|
||||||
|
);
|
||||||
|
if (dealt > 0) {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
draft.player.energy = Math.max(0, draft.player.energy - energyDrain);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// molt: enemy flees if molt >= maxHp
|
||||||
|
triggers.onDamage.use(async (ctx, next) => {
|
||||||
|
const entity = getCombatEntity(ctx.game.value, ctx.entityId);
|
||||||
|
if (!entity || !entity.isAlive) {
|
||||||
|
await next();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const molt = entity.effects.molt?.stacks ?? 0;
|
||||||
|
if (molt >= entity.maxHp) {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const e = draft.enemies.find((en) => en.id === ctx.entityId);
|
||||||
|
if (e) {
|
||||||
|
e.isAlive = false;
|
||||||
|
e.hp = 0;
|
||||||
|
}
|
||||||
|
draft.result = draft.enemies.every((en) => !en.isAlive)
|
||||||
|
? "victory"
|
||||||
|
: null;
|
||||||
|
});
|
||||||
|
if (ctx.game.value.result) throw ctx.game.value;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// aim: double damage, lose aim on damage
|
||||||
|
triggers.onDamage.use(async (ctx, next) => {
|
||||||
|
if (ctx.sourceEntityId === "player") {
|
||||||
|
const player = ctx.game.value.player;
|
||||||
|
const aim = player.effects.aim?.stacks ?? 0;
|
||||||
|
if (aim > 0) {
|
||||||
|
ctx.amount *= 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// roll: consume 10 roll per 10 damage
|
||||||
|
triggers.onDamage.use(async (ctx, next) => {
|
||||||
|
if (ctx.sourceEntityId === "player") {
|
||||||
|
const player = ctx.game.value.player;
|
||||||
|
const roll = player.effects.roll?.stacks ?? 0;
|
||||||
|
if (roll >= 10) {
|
||||||
|
const rollDamage = Math.floor(roll / 10) * 10;
|
||||||
|
ctx.amount += rollDamage;
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
addEntityEffect(draft.player, findEffect("roll"), -rollDamage);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// tailSting: bonus damage on attack
|
||||||
|
triggers.onDamage.use(async (ctx, next) => {
|
||||||
|
if (ctx.sourceEntityId && ctx.sourceEntityId !== "player") {
|
||||||
|
const attacker = getCombatEntity(ctx.game.value, ctx.sourceEntityId);
|
||||||
|
if (attacker) {
|
||||||
|
const tailSting = attacker.effects.tailSting?.stacks ?? 0;
|
||||||
|
if (tailSting > 0) {
|
||||||
|
ctx.amount += tailSting;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// charge: double damage dealt/received, consume equal charge
|
||||||
|
triggers.onDamage.use(async (ctx, next) => {
|
||||||
|
const entity = getCombatEntity(ctx.game.value, ctx.entityId);
|
||||||
|
if (entity) {
|
||||||
|
const charge = entity.effects.charge?.stacks ?? 0;
|
||||||
|
if (charge > 0) {
|
||||||
|
const dealt = Math.min(
|
||||||
|
Math.max(0, entity.hp),
|
||||||
|
ctx.amount - (ctx.prevented ?? 0),
|
||||||
|
);
|
||||||
|
const consumed = Math.min(charge, dealt);
|
||||||
|
ctx.amount += dealt;
|
||||||
|
if (consumed > 0) {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const e = getCombatEntity(draft, ctx.entityId);
|
||||||
|
if (e) addEntityEffect(e, findEffect("charge"), -consumed);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx.sourceEntityId) {
|
||||||
|
const attacker = getCombatEntity(ctx.game.value, ctx.sourceEntityId);
|
||||||
|
if (attacker) {
|
||||||
|
const charge = attacker.effects.charge?.stacks ?? 0;
|
||||||
|
if (charge > 0) {
|
||||||
|
const baseAmount = ctx.amount;
|
||||||
|
const targetEntity = getCombatEntity(ctx.game.value, ctx.entityId);
|
||||||
|
const dealt = Math.min(
|
||||||
|
Math.max(0, targetEntity?.hp ?? 0),
|
||||||
|
baseAmount - (ctx.prevented ?? 0),
|
||||||
|
);
|
||||||
|
const consumed = Math.min(charge, dealt);
|
||||||
|
ctx.amount += dealt;
|
||||||
|
if (consumed > 0) {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const a = getCombatEntity(draft, ctx.sourceEntityId!);
|
||||||
|
if (a) addEntityEffect(a, findEffect("charge"), -consumed);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { addInstantEffectTriggers } from "./instant";
|
||||||
|
import { addDamageTriggers } from "./damage";
|
||||||
|
import { addTurnStartTriggers } from "./turn-start";
|
||||||
|
import { addCardEventTriggers } from "./card-events";
|
||||||
|
import {
|
||||||
|
IRunContext,
|
||||||
|
Triggers,
|
||||||
|
} from "@/samples/slay-the-spire-like/system/combat";
|
||||||
|
|
||||||
|
export function addTriggers(triggers: Triggers, run: IRunContext) {
|
||||||
|
addInstantEffectTriggers(triggers);
|
||||||
|
addDamageTriggers(triggers);
|
||||||
|
addTurnStartTriggers(triggers);
|
||||||
|
addCardEventTriggers(triggers, run);
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
import { Triggers } from "@/samples/slay-the-spire-like/system/combat/triggers";
|
||||||
|
import {
|
||||||
|
addEntityEffect,
|
||||||
|
getCombatEntity,
|
||||||
|
} from "@/samples/slay-the-spire-like/system/combat/effects";
|
||||||
|
import { moveToRegion } from "@/core/region";
|
||||||
|
import { CombatGameContext } from "@/samples/slay-the-spire-like/system/combat/types";
|
||||||
|
import { GameCard } from "@/samples/slay-the-spire-like/system/deck";
|
||||||
|
import getCards from "../card.csv";
|
||||||
|
|
||||||
|
export function addInstantEffectTriggers(triggers: Triggers) {
|
||||||
|
const cards = getCards();
|
||||||
|
|
||||||
|
function findCard(id: string) {
|
||||||
|
return cards.find((c) => c.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createStatusCard(
|
||||||
|
draft: CombatGameContext["value"],
|
||||||
|
cardId: string,
|
||||||
|
): void {
|
||||||
|
const cardData = findCard(cardId);
|
||||||
|
if (!cardData) return;
|
||||||
|
|
||||||
|
const instanceId = `${cardId}-${draft.player.deck.regions.drawPile.childIds.length}-${draft.player.deck.regions.discardPile.childIds.length}`;
|
||||||
|
const card: GameCard = {
|
||||||
|
id: instanceId,
|
||||||
|
regionId: "",
|
||||||
|
position: [],
|
||||||
|
itemId: cardId,
|
||||||
|
cardData: {
|
||||||
|
id: cardData.id,
|
||||||
|
name: cardData.name,
|
||||||
|
desc: cardData.desc,
|
||||||
|
type: cardData.type,
|
||||||
|
costType: cardData.costType,
|
||||||
|
costCount: cardData.costCount,
|
||||||
|
targetType: cardData.targetType,
|
||||||
|
effects: cardData.effects,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
draft.player.deck.cards[instanceId] = card;
|
||||||
|
moveToRegion(card, null, draft.player.deck.regions.drawPile);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAllEnemyDataFromState(state: CombatGameContext["value"]) {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const result: (typeof state.enemies)[number]["enemy"][] = [];
|
||||||
|
for (const enemy of state.enemies) {
|
||||||
|
if (!seen.has(enemy.enemy.id)) {
|
||||||
|
seen.add(enemy.enemy.id);
|
||||||
|
result.push(enemy.enemy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function summonEnemy(
|
||||||
|
draft: CombatGameContext["value"],
|
||||||
|
enemyId: string,
|
||||||
|
hp: number,
|
||||||
|
) {
|
||||||
|
for (const enemyData of getAllEnemyDataFromState(draft)) {
|
||||||
|
if (enemyData.id === enemyId) {
|
||||||
|
const existing = draft.enemies.find(
|
||||||
|
(e) => e.enemy.id === enemyId && !e.isAlive,
|
||||||
|
);
|
||||||
|
if (existing) {
|
||||||
|
existing.isAlive = true;
|
||||||
|
existing.hp = existing.maxHp;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const intent =
|
||||||
|
enemyData.intents.find((i) => i.initialIntent) ??
|
||||||
|
enemyData.intents[0];
|
||||||
|
const instanceId = `${enemyData.id}-${draft.enemies.length}`;
|
||||||
|
const intents: Record<string, typeof intent> = {};
|
||||||
|
for (const i of enemyData.intents) {
|
||||||
|
intents[i.id] = i;
|
||||||
|
}
|
||||||
|
draft.enemies.push({
|
||||||
|
id: instanceId,
|
||||||
|
enemy: enemyData,
|
||||||
|
hp,
|
||||||
|
maxHp: hp,
|
||||||
|
isAlive: true,
|
||||||
|
effects: {},
|
||||||
|
intents,
|
||||||
|
currentIntent: intent,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
triggers.onEffectApplied.use(async (ctx, next) => {
|
||||||
|
if (ctx.effect.id === "attack") {
|
||||||
|
await triggers.onDamage.execute(ctx.game, {
|
||||||
|
entityId: ctx.entityId,
|
||||||
|
amount: ctx.stacks,
|
||||||
|
sourceEntityId: ctx.sourceEntityId,
|
||||||
|
});
|
||||||
|
|
||||||
|
const entity = getCombatEntity(ctx.game.value, ctx.entityId);
|
||||||
|
const spike = entity?.effects.spike?.stacks ?? 0;
|
||||||
|
if (spike > 0 && ctx.sourceEntityId) {
|
||||||
|
await triggers.onDamage.execute(ctx.game, {
|
||||||
|
entityId: ctx.sourceEntityId,
|
||||||
|
amount: spike,
|
||||||
|
sourceEntityId: ctx.entityId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else if (ctx.effect.id === "draw") {
|
||||||
|
await triggers.onDraw.execute(ctx.game, { count: ctx.stacks });
|
||||||
|
} else if (ctx.effect.id === "gainEnergy") {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
draft.player.energy += ctx.stacks;
|
||||||
|
});
|
||||||
|
} else if (ctx.effect.id === "removeWound") {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const { cards, regions } = draft.player.deck;
|
||||||
|
let removed = 0;
|
||||||
|
const allPileIds = [
|
||||||
|
...regions.drawPile.childIds,
|
||||||
|
...regions.discardPile.childIds,
|
||||||
|
];
|
||||||
|
for (const cardId of allPileIds) {
|
||||||
|
if (removed >= ctx.stacks) break;
|
||||||
|
const card = cards[cardId];
|
||||||
|
if (card && card.cardData.id === "wound") {
|
||||||
|
const sourceRegion =
|
||||||
|
card.regionId === "drawPile"
|
||||||
|
? regions.drawPile
|
||||||
|
: regions.discardPile;
|
||||||
|
moveToRegion(card, sourceRegion, null);
|
||||||
|
delete cards[cardId];
|
||||||
|
removed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (ctx.effect.id === "venom") {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
createStatusCard(draft, "venom");
|
||||||
|
});
|
||||||
|
} else if (ctx.effect.id === "vultureEye") {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
createStatusCard(draft, "vultureEye");
|
||||||
|
});
|
||||||
|
} else if (ctx.effect.id === "static") {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
createStatusCard(draft, "static");
|
||||||
|
});
|
||||||
|
} else if (ctx.effect.id === "summonMummy") {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
summonEnemy(draft, "木乃伊", ctx.stacks);
|
||||||
|
});
|
||||||
|
} else if (ctx.effect.id === "summonSandwormLarva") {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
summonEnemy(draft, "幼沙虫", ctx.stacks);
|
||||||
|
});
|
||||||
|
} else if (ctx.effect.id === "reviveMummy") {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const deadMummy = draft.enemies.find(
|
||||||
|
(e) => e.enemy.id === "木乃伊" && !e.isAlive,
|
||||||
|
);
|
||||||
|
if (deadMummy) {
|
||||||
|
deadMummy.isAlive = true;
|
||||||
|
deadMummy.hp = deadMummy.maxHp;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (ctx.effect.id === "curse") {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
addEntityEffect(draft.player, ctx.effect, ctx.stacks);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { Triggers } from "@/samples/slay-the-spire-like/system/combat/triggers";
|
||||||
|
import { addEntityEffect } from "@/samples/slay-the-spire-like/system/combat/effects";
|
||||||
|
import { EffectData } from "@/samples/slay-the-spire-like/system/types";
|
||||||
|
import getEffects from "../effect.csv";
|
||||||
|
|
||||||
|
export function addTurnStartTriggers(triggers: Triggers) {
|
||||||
|
const effects = getEffects();
|
||||||
|
|
||||||
|
function findEffect(id: string): EffectData {
|
||||||
|
const found = effects.find((e) => e.id === id);
|
||||||
|
if (found) return found;
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: id,
|
||||||
|
description: "",
|
||||||
|
lifecycle: "instant",
|
||||||
|
} as EffectData;
|
||||||
|
}
|
||||||
|
|
||||||
|
// discard: random discard at turn start
|
||||||
|
triggers.onTurnStart.use(async (ctx, next) => {
|
||||||
|
if (ctx.entityId !== "player") {
|
||||||
|
await next();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const discard = ctx.game.value.player.effects.discard;
|
||||||
|
if (discard && discard.stacks > 0) {
|
||||||
|
const handIds = [...ctx.game.value.player.deck.regions.hand.childIds];
|
||||||
|
if (handIds.length > 0) {
|
||||||
|
const randomIndex = ctx.game.rng.nextInt(handIds.length);
|
||||||
|
const randomCardId = handIds[randomIndex];
|
||||||
|
await triggers.onCardDiscarded.execute(ctx.game, {
|
||||||
|
cardId: randomCardId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// defendNext: gain block next turn
|
||||||
|
// record how many defendNext there is, before buff update
|
||||||
|
// then apply after buff update
|
||||||
|
triggers.onTurnStart.use(async (ctx, next) => {
|
||||||
|
const defendNext = ctx.game.value.player.effects.defendNext;
|
||||||
|
if (!defendNext || defendNext.stacks <= 0) {
|
||||||
|
await next();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await next();
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
addEntityEffect(draft.player, findEffect("defend"), defendNext.stacks);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// energyNext: gain energy next turn
|
||||||
|
triggers.onTurnStart.use(async (ctx, next) => {
|
||||||
|
if (ctx.entityId !== "player") {
|
||||||
|
await next();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const energyNext = ctx.game.value.player.effects.energyNext;
|
||||||
|
if (energyNext && energyNext.stacks > 0) {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
draft.player.energy += energyNext.stacks;
|
||||||
|
addEntityEffect(draft.player, energyNext.data, -energyNext.stacks);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// drawNext: draw extra cards next turn
|
||||||
|
triggers.onTurnStart.use(async (ctx, next) => {
|
||||||
|
if (ctx.entityId !== "player") {
|
||||||
|
await next();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const drawNext = ctx.game.value.player.effects.drawNext;
|
||||||
|
if (drawNext && drawNext.stacks > 0) {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
addEntityEffect(draft.player, drawNext.data, -drawNext.stacks);
|
||||||
|
});
|
||||||
|
await triggers.onDraw.execute(ctx.game, { count: drawNext.stacks });
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import * as desert from "./desert";
|
||||||
|
export type { ContentModule } from "./types";
|
||||||
|
|
||||||
|
export default {
|
||||||
|
desert,
|
||||||
|
};
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { LoadResult as YarnDialogues } from "yarn-spinner-loader";
|
||||||
|
import { Triggers } from "../system/combat/triggers";
|
||||||
|
|
||||||
|
import type * as desert from "./desert";
|
||||||
|
import { IRunContext } from "../system/combat";
|
||||||
|
|
||||||
|
export type ContentModule = {
|
||||||
|
readonly getCards: () => readonly desert.Card[];
|
||||||
|
readonly getEffects: () => readonly desert.Effect[];
|
||||||
|
readonly getEncounters: () => readonly desert.Encounter[];
|
||||||
|
readonly getEnemies: () => readonly desert.Enemy[];
|
||||||
|
readonly getIntents: () => readonly desert.Intent[];
|
||||||
|
readonly getItems: () => readonly desert.Item[];
|
||||||
|
readonly getStartingItems: () => readonly desert.Item[];
|
||||||
|
|
||||||
|
readonly dialogues: YarnDialogues;
|
||||||
|
readonly addTriggers: (triggers: Triggers, run: IRunContext) => void;
|
||||||
|
};
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
# 杀戮尖塔 + 背包英雄
|
||||||
|
|
||||||
|
玩家有4x6的背包
|
||||||
|
|
||||||
|
装备占格子,提供同等数量的牌,并且给周围加buff,背包英雄style
|
||||||
|
|
||||||
|
战斗时玩杀戮尖塔
|
||||||
|
|
||||||
|
## 肉鸽结构
|
||||||
|
|
||||||
|
区域点到点地图
|
||||||
|
|
||||||
|
- 分4个区域,每个区域有独立的随机遭遇池,目前先考虑第一个区域
|
||||||
|
- 每区域10层,26个遭遇节点
|
||||||
|
- 荒野层6层×3节点(小怪50%/精英25%/事件25%)
|
||||||
|
- 聚落层2层×4节点(≥1篝火/≥1商店/≥1奇遇,第4随机)
|
||||||
|
- 起点→终点,终点为boss战
|
||||||
|
|
||||||
|
## 战斗(小怪、精英、boss)
|
||||||
|
|
||||||
|
基本流程
|
||||||
|
- 怪物战斗开始效应
|
||||||
|
- 玩家战斗开始效应
|
||||||
|
- 重复直至一方不剩下存活角色
|
||||||
|
- 玩家回合
|
||||||
|
- 怪物回合
|
||||||
|
|
||||||
|
怪物战斗开始
|
||||||
|
- 获得初始buff、初始血量、初始意图
|
||||||
|
|
||||||
|
玩家战斗开始
|
||||||
|
- 获得3点能量,抓5张手牌
|
||||||
|
|
||||||
|
玩家回合
|
||||||
|
- buff更新阶段:临时buff消失、延时buff-1层
|
||||||
|
- 回合开始:触发回合开始效果
|
||||||
|
- 行动:玩家可以自由出牌直至结束回合
|
||||||
|
- 回合结束:触发回合结束效果
|
||||||
|
- 重置:恢复到3点能量,弃掉剩余手牌,抓5张手牌
|
||||||
|
- 洗回牌堆:每当牌堆为空需要抓牌或与牌堆顶交互,则将弃牌堆与2张《疲劳》(没有效果,不能打出)洗回牌堆,然后再继续。
|
||||||
|
|
||||||
|
怪物回合
|
||||||
|
- buff更新阶段:每个怪物临时buff消失、延时buff-1层
|
||||||
|
- 回合开始:触发每个怪物的回合开始效果
|
||||||
|
- 行动:怪物的意图生效,然后更新意图
|
||||||
|
- 回合结束:触发每个怪物的回合结束效果
|
||||||
|
|
||||||
|
## 篝火
|
||||||
|
|
||||||
|
在篝火处可进行3次行动,每次行动可以:
|
||||||
|
- 恢复20%最大生命
|
||||||
|
- 恢复1次所有药品的使用次数
|
||||||
|
- 合成一个物品(暂未设计)
|
||||||
|
|
||||||
|
## 商店
|
||||||
|
|
||||||
|
在商店可以买/卖物品
|
||||||
|
- 有5个随机的不同物品可以买,价格为原价50%-150%随机
|
||||||
|
- 购买之后不会补充
|
||||||
|
- 可以以原价25%的价格卖出背包内的任意物品
|
||||||
|
|
||||||
|
## 奇遇
|
||||||
|
|
||||||
|
奇遇为Yarn Spinner驱动的分支对话遭遇
|
||||||
|
|
||||||
|
对玩家产生的影响根据Yarn Spinner的命令结算
|
||||||
|
|
||||||
|
在对话结束后奇遇结算结束
|
||||||
|
|
||||||
|
## 战斗内Effect
|
||||||
|
|
||||||
|
Effect分以下类型:
|
||||||
|
- 瞬间:立即生效,直接改变状态
|
||||||
|
- Buff:作为状态叠加到角色身上
|
||||||
|
- 持久Buff:持续整场战斗
|
||||||
|
- 临时Buff:持续到下次Buff更新
|
||||||
|
- 延时Buff:每次Buff更新-1层,持续到归零
|
||||||
|
- 姿态Buff:受到伤害时,移除同等数量的层数
|
||||||
|
- 卡牌:作为状态卡牌加入
|
||||||
|
- 弃牌:加入弃牌堆
|
||||||
|
- 手牌:加入手牌
|
||||||
|
- 牌堆:加入抓牌堆
|
||||||
|
- 物品:作为物品状态叠加到物品上,通常是效应来源卡牌对应的物品周围的物品,若没有上下文物品则可能无效或对玩家的随机物品生效
|
||||||
|
- 临时:持续到下次Buff更新
|
||||||
|
- 持久:持续整场战斗
|
||||||
|
- 永久:持续整个冒险
|
||||||
|
- 直到打出:持续到下次打出该物品的卡牌
|
||||||
|
- 直到弃掉:持续到下次弃掉该物品的卡牌
|
||||||
|
|
||||||
|
## 时机
|
||||||
|
|
||||||
|
产生Effect的时机包括:
|
||||||
|
- 打出卡牌/抓到卡牌/弃掉卡牌
|
||||||
|
- 敌人意图生效
|
||||||
|
- Effect侦听器需要的特定侦听事件
|
||||||
|
|
||||||
|
## 卡牌属性
|
||||||
|
|
||||||
|
- 费用:能量费用或物品使用次数费用,如果不能支付则无法打出
|
||||||
|
- 抓牌效果/打出效果/弃掉效果:包括目标(自身、选择目标、全体),效果类型,和层数,可能有复数条
|
||||||
|
|
||||||
|
能量费用以3费为准,希望大约60%牌1费,20%牌2费,20%牌0费
|
||||||
|
|
||||||
|
## 遗物
|
||||||
|
|
||||||
|
遗物不需要放在背包格里,且仅提供正面触发效果,暂未设计
|
||||||
|
|
||||||
|
## 区域设计量
|
||||||
|
|
||||||
|
每区域10小怪,4精英,8奇遇,1 boss(暂未设计)
|
||||||
|
目前仅考虑沙漠一个区域
|
||||||
|
|
||||||
|
## 角色设计量
|
||||||
|
|
||||||
|
~24 物品 每角色(4种各6个)
|
||||||
|
-8 遗物 每角色
|
||||||
|
|
||||||
|
在扩展更多区域后需添加更多内容随区域/奇遇解锁
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# Fighter
|
||||||
|
|
||||||
|
战士角色:默认的角色。
|
||||||
|
|
||||||
|
## 物品
|
||||||
|
|
||||||
|
4种物品各6个:武器、防具、耗材、工具。
|
||||||
|
|
||||||
|
玩家共24格,每种物品预算6格,每个物品尺寸1-6格。武器防具大部分在2-4格,少部分有5-6格,耗材、工具大部分在1-2格。
|
||||||
|
|
||||||
|
每种物品每格提供一张牌加入玩家牌堆。
|
||||||
|
|
||||||
|
使用武器、防具、工具的卡牌花费能量。每回合有3点能量。耗材使用不计入费用,但消耗本身的使用次数。使用次数在篝火处可以恢复。
|
||||||
|
|
||||||
|
### 初始装备
|
||||||
|
|
||||||
|
剑、短刀、绷带、水袋、治疗药剂
|
||||||
|
|
||||||
|
### 武器
|
||||||
|
|
||||||
|
武器是配合对象,不需要有邻接性检查。
|
||||||
|
|
||||||
|
剑 1x3/1费:【攻击2】【攻击2】
|
||||||
|
长斧 4格L型/2费:对全体【攻击5】
|
||||||
|
长枪 4格I型/1费:【攻击2】【攻击2】【攻击2】
|
||||||
|
短刀 1x2/1费:【攻击3】【攻击3】
|
||||||
|
飞镖 1格/0费:【攻击1】,抓一张牌
|
||||||
|
十字弩 4格X型/2费:【攻击6】。对同一目标打出其他十字弩。
|
||||||
|
|
||||||
|
### 防具
|
||||||
|
|
||||||
|
防具可以检查周围物品,每个匹配的给奖励。
|
||||||
|
|
||||||
|
物品被动:每个防具的周围每种不同防具+1最大生命。
|
||||||
|
|
||||||
|
盾 2x2/1费:【防御3】。
|
||||||
|
斗笠 4格T型/2费:【防御8】
|
||||||
|
披风 3格L型/1费:【防御2】,下回合【防御2】
|
||||||
|
护腕 1格/0费:【防御1】,抓1张牌
|
||||||
|
大盾 6格2x3/1费:【防御5】
|
||||||
|
锁子甲 4格2x2/1费:本回合受到伤害-3
|
||||||
|
|
||||||
|
### 工具
|
||||||
|
|
||||||
|
工具可以检查周围物品,给触发或者触发给强化。
|
||||||
|
|
||||||
|
水袋 1x2/1费:下回合开始时,获得1能量,抓2张牌。
|
||||||
|
绳索 3格L型/1费:生效物品的牌【防御】+2直到打出。
|
||||||
|
腰带 3格I型/0费:抓一张牌,然后从生效物品的牌当中选择一张加入手牌。
|
||||||
|
火把 2格/1费:下次打出生效物品的牌时,将其消并获得1能量。
|
||||||
|
磨刀石 1x1/1费:生效物品的牌【攻击】+3直到打出。
|
||||||
|
铁匠锤 3格T型/1费:从牌堆/弃牌堆选择一张牌,随机变为一张生效物品的牌。
|
||||||
|
|
||||||
|
### 消耗品
|
||||||
|
|
||||||
|
消耗品本身不应该给强化,但可以被防具/工具给强化。
|
||||||
|
|
||||||
|
绷带 1x1/3次:从牌堆或弃牌堆随机移除1张伤口。
|
||||||
|
淬毒药剂 1格/3次:生效物品的攻击+2。
|
||||||
|
强固药剂 1格/3次:生效物品获得的防御+2。
|
||||||
|
活力药剂 1格/3次:获得1点能量。
|
||||||
|
集中药剂 1格/3次:抓2张牌。
|
||||||
|
治疗药剂 1格/3次:移除3个随机伤口。
|
||||||
|
|
||||||
|
### 遗物
|
||||||
|
|
||||||
|
酒葫芦:使用药水后,下次攻击变为范围攻击。
|
||||||
|
净瓶:可以支付两点生命来使用剩余次数为0的药水。
|
||||||
|
熊挂坠:每打出三张攻击,获得3防御。
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# Desert
|
||||||
|
|
||||||
|
## 小怪 - 10种
|
||||||
|
|
||||||
|
### 仙人掌怪
|
||||||
|
|
||||||
|
概念:防+强化
|
||||||
|
|
||||||
|
【尖刺X】:对自己施加的持续buff,对攻击者造成X点伤害
|
||||||
|
|
||||||
|
### 蛇
|
||||||
|
|
||||||
|
概念:攻+强化
|
||||||
|
|
||||||
|
【蛇毒X】:对玩家施加的手牌状态(同名状态牌/1费:打出时移除此牌。弃掉时受到3点伤害。)
|
||||||
|
|
||||||
|
### 木乃伊
|
||||||
|
|
||||||
|
概念:攻+防
|
||||||
|
|
||||||
|
【诅咒】:对自己施加的延时buff。受玩家卡牌攻击时,卡牌对应物品【攻击】-1,直到玩家弃掉一张该物品的牌
|
||||||
|
|
||||||
|
### 枪手
|
||||||
|
|
||||||
|
概念:单回高攻
|
||||||
|
|
||||||
|
【瞄准X】:对自己施加的姿态buff。造成双倍伤害。
|
||||||
|
|
||||||
|
### 风卷草
|
||||||
|
|
||||||
|
概念:防+强化
|
||||||
|
|
||||||
|
【滚动X】:对自己施加的姿态buff。攻击时,若有至少10层滚动,则消耗10层滚动让攻击+10。
|
||||||
|
|
||||||
|
### 秃鹫
|
||||||
|
|
||||||
|
概念:攻+防
|
||||||
|
|
||||||
|
若造成伤害,玩家获得秃鹫之眼。
|
||||||
|
|
||||||
|
秃鹫之眼:对玩家施加的抓牌堆状态卡牌(同名状态牌/0费:打出时移除。抓到时获得3层【暴露】(临时debuff,受到的伤害+1/每层))
|
||||||
|
|
||||||
|
### 沙蝎
|
||||||
|
|
||||||
|
概念:攻+强化
|
||||||
|
|
||||||
|
【尾刺X】:对自己施加的姿态buff。攻击时,伤害提升X。
|
||||||
|
|
||||||
|
### 幼沙虫
|
||||||
|
|
||||||
|
防+强化
|
||||||
|
|
||||||
|
【能量吸取】:对自己施加的延时buff。受伤时,玩家失去X点能量。
|
||||||
|
|
||||||
|
### 蜥蜴
|
||||||
|
|
||||||
|
概念:攻+防+逃跑
|
||||||
|
|
||||||
|
【脱皮】:对自己施加的姿态buff。若脱皮达到生命上限,则怪物逃跑,玩家不能获得战斗奖励。
|
||||||
|
|
||||||
|
### 沙匪
|
||||||
|
|
||||||
|
概念:弱化玩家
|
||||||
|
|
||||||
|
【劫掠】:对玩家施加的延时debuff。回合开始时,随机弃掉一张手牌。
|
||||||
|
|
||||||
|
## 精英 - 4种
|
||||||
|
|
||||||
|
### 风暴之灵
|
||||||
|
|
||||||
|
静电:对玩家施加的弃牌堆状态卡牌/0费:打出时自己获得1层【暴露】并抓一张牌。(临时debuff,受到的伤害+1/每层)
|
||||||
|
|
||||||
|
【风暴X】:对自己施加的姿态buff。攻击时,玩家获得1张静电。
|
||||||
|
|
||||||
|
### 骑马枪手
|
||||||
|
|
||||||
|
【冲锋X】:对自己施加的姿态buff,受到或造成的伤害翻倍并消耗等量的冲锋。(额外伤害不会消耗姿态)
|
||||||
|
|
||||||
|
### 沙虫王
|
||||||
|
|
||||||
|
召唤幼体沙虫
|
||||||
|
|
||||||
|
玩家弃掉疲劳时,恢复10生命
|
||||||
|
|
||||||
|
### 沙漠守卫
|
||||||
|
|
||||||
|
召唤木乃伊
|
||||||
|
|
||||||
|
会复活木乃伊2次
|
||||||
|
|
||||||
|
## boss - 法老之灵
|
||||||
|
|
||||||
|
Boss在区域终点节点触发,不属于遭遇类型池。
|
||||||
|
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# 文件结构
|
||||||
|
|
||||||
|
## 系统实现
|
||||||
|
|
||||||
|
- `system/`:系统实现。
|
||||||
|
- `combat/`:管理一次战斗内的战斗状态、流程、触发。
|
||||||
|
- `progress/`:管理一次冒险的进度。
|
||||||
|
- `map/`:管理地图生成。
|
||||||
|
- `grid-inventory/`:管理背包状态。
|
||||||
|
- `deck/`:管理卡组状态。
|
||||||
|
|
||||||
|
## 数据
|
||||||
|
|
||||||
|
- `data/`:所有的数据文件
|
||||||
|
- `desert/`:游戏的测试模组,沙漠区域的内容。
|
||||||
|
- `card.csv`:所有的卡牌定义。
|
||||||
|
- `effect.csv`:所有的效应定义。
|
||||||
|
- `encounter.csv`:所有的遭遇定义。
|
||||||
|
- `enemy.csv`:所有的敌人和意图定义。
|
||||||
|
- `item.csv`:所有的玩家物品定义。
|
||||||
|
- `dialogues/`:yarn对话项目目录
|
||||||
|
- `dialogues.yarnproject`:yarn对话项目入口
|
||||||
|
- `**.yarn`:具体的yarn对话文件,代码不关心
|
||||||
|
- `index.ts`:统一导出所有的数据。
|
||||||
|
- `trigger.ts`:额外的触发器脚本,用于实现测试模组中涉及的效果。
|
||||||
|
|
||||||
|
## 开发流程
|
||||||
|
|
||||||
|
### SRD / 系统设计
|
||||||
|
|
||||||
|
首先编写srd文档。srd文档描述游戏系统和规则,并提供少量内联的基础游戏数据。
|
||||||
|
|
||||||
|
SRD是系统实现的基础,系统实现只能基于SRD,不能依赖具体的游戏内容。
|
||||||
|
|
||||||
|
### Setting / 环境设定
|
||||||
|
|
||||||
|
使用SRD提供的特性来设计环境内容:
|
||||||
|
- 效应:效应在技术上不依赖其他类型内容,可以首先确定。但在创意上可能不会直接设计效应,而是从若干创意中提取共性,并创建一个效应来作为主题。
|
||||||
|
- 卡牌:部分效应会创建卡牌或修改卡牌。在设计时需要注意。
|
||||||
|
- 敌人和意图:结合效应与主题表达设计敌人。通常需要为每个敌人设计独特的效应。
|
||||||
|
- 玩家物品:结合效应与主题表达设计物品。常见物品的效应容易找到替代,不常见物品则有特殊的效应。
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
export * from "./system/combat";
|
||||||
|
export * from "./system/deck";
|
||||||
|
export * from "./system/encounter";
|
||||||
|
export * from "./system/grid-inventory";
|
||||||
|
export * from "./system/map";
|
||||||
|
export * from "./system/utils";
|
||||||
|
export * from "./system/types";
|
||||||
|
export { default as data } from "./data";
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
import {
|
||||||
|
CombatEntity,
|
||||||
|
CombatGameContext,
|
||||||
|
CombatState,
|
||||||
|
EffectTable,
|
||||||
|
IRunContext,
|
||||||
|
PlayerEntity,
|
||||||
|
} from "./types";
|
||||||
|
import {
|
||||||
|
CardData,
|
||||||
|
CardEffectTarget,
|
||||||
|
EffectData,
|
||||||
|
IntentEffectTarget,
|
||||||
|
} from "@/samples/slay-the-spire-like/system/types";
|
||||||
|
|
||||||
|
export function addEffect(
|
||||||
|
effects: EffectTable,
|
||||||
|
effect: EffectData,
|
||||||
|
stacks: number,
|
||||||
|
) {
|
||||||
|
let current = effects[effect.id];
|
||||||
|
|
||||||
|
if (!current) current = { data: effect, stacks };
|
||||||
|
else current.stacks += stacks;
|
||||||
|
|
||||||
|
if (current.stacks === 0 && effects[effect.id]) delete effects[effect.id];
|
||||||
|
else if (current.stacks !== 0 && !effects[effect.id])
|
||||||
|
effects[effect.id] = current;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addEntityEffect(
|
||||||
|
entity: CombatEntity,
|
||||||
|
effect: EffectData,
|
||||||
|
stacks: number,
|
||||||
|
) {
|
||||||
|
addEffect(entity.effects, effect, stacks);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addItemEffect(
|
||||||
|
entity: PlayerEntity,
|
||||||
|
itemKey: string,
|
||||||
|
effect: EffectData,
|
||||||
|
stacks: number,
|
||||||
|
) {
|
||||||
|
entity.itemEffects[itemKey] = entity.itemEffects[itemKey] || {};
|
||||||
|
addEffect(entity.itemEffects[itemKey], effect, stacks);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onEntityEffectUpkeep(entity: CombatEntity) {
|
||||||
|
for (const effect of Object.values(entity.effects)) {
|
||||||
|
const lifecycle = effect.data.lifecycle;
|
||||||
|
if (lifecycle === "temporary")
|
||||||
|
addEntityEffect(entity, effect.data, -effect.stacks);
|
||||||
|
else if (lifecycle === "lingering")
|
||||||
|
addEntityEffect(entity, effect.data, effect.stacks >= 0 ? -1 : 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onEntityPostureDamage(entity: CombatEntity, damage: number) {
|
||||||
|
for (const effect of Object.values(entity.effects)) {
|
||||||
|
const lifecycle = effect.data.lifecycle;
|
||||||
|
if (lifecycle === "posture")
|
||||||
|
addEntityEffect(entity, effect.data, -Math.min(damage, effect.stacks));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onPlayerItemEffectUpkeep(entity: PlayerEntity) {
|
||||||
|
for (const [itemKey, itemEffects] of Object.entries(entity.itemEffects)) {
|
||||||
|
for (const effect of Object.values(itemEffects)) {
|
||||||
|
const lifecycle = effect.data.lifecycle;
|
||||||
|
if (lifecycle === "itemTemporary")
|
||||||
|
addItemEffect(entity, itemKey, effect.data, -effect.stacks);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onItemPlay(entity: PlayerEntity, itemKey: string) {
|
||||||
|
const effects = entity.itemEffects[itemKey];
|
||||||
|
if (!effects) return;
|
||||||
|
for (const effect of Object.values(effects)) {
|
||||||
|
if (effect.data.lifecycle === "itemUntilPlay") {
|
||||||
|
addItemEffect(entity, itemKey, effect.data, -effect.stacks);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onItemDiscard(entity: PlayerEntity, itemKey: string) {
|
||||||
|
const effects = entity.itemEffects[itemKey];
|
||||||
|
if (!effects) return;
|
||||||
|
for (const effect of Object.values(effects)) {
|
||||||
|
if (effect.data.lifecycle === "itemUntilDiscard") {
|
||||||
|
addItemEffect(entity, itemKey, effect.data, -effect.stacks);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function* getAliveEnemies(state: CombatState) {
|
||||||
|
for (let enemy of state.enemies) {
|
||||||
|
if (enemy.isAlive) {
|
||||||
|
yield enemy;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function* getEffectTargets(
|
||||||
|
target: CardEffectTarget | IntentEffectTarget,
|
||||||
|
game: CombatGameContext,
|
||||||
|
targetId?: string,
|
||||||
|
sourceEntityKey: "player" | string = "player",
|
||||||
|
) {
|
||||||
|
if (target === "eachEnemy") {
|
||||||
|
for (const enemy of getAliveEnemies(game.value)) {
|
||||||
|
yield enemy;
|
||||||
|
}
|
||||||
|
} else if (target === "source") {
|
||||||
|
const entity = getCombatEntity(game.value, sourceEntityKey);
|
||||||
|
if (entity) yield entity;
|
||||||
|
} else if (target === "player") {
|
||||||
|
yield game.value.player;
|
||||||
|
} else if (target === "eachTarget") {
|
||||||
|
if (!targetId) return;
|
||||||
|
const entity = getCombatEntity(game.value, targetId);
|
||||||
|
if (entity) yield entity;
|
||||||
|
} else if (target === "randomEnemy") {
|
||||||
|
const aliveEnemies = [...getAliveEnemies(game.value)];
|
||||||
|
if (aliveEnemies.length === 0) return;
|
||||||
|
const index = game.rng.nextInt(aliveEnemies.length);
|
||||||
|
yield aliveEnemies[index];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCombatEntity(state: CombatState, entityKey: string) {
|
||||||
|
return entityKey === "player"
|
||||||
|
? state.player
|
||||||
|
: state.enemies.find((e) => e.id === entityKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function canPlayCard(
|
||||||
|
player: PlayerEntity,
|
||||||
|
costType: CardData["costType"],
|
||||||
|
costCount: number,
|
||||||
|
itemId: string,
|
||||||
|
run: IRunContext,
|
||||||
|
): boolean {
|
||||||
|
if (costType === "energy") {
|
||||||
|
return player.energy >= costCount;
|
||||||
|
}
|
||||||
|
if (costType === "uses") {
|
||||||
|
const item = run.getItemData(itemId);
|
||||||
|
if (!item) return false;
|
||||||
|
const maxUses = item?.card.costType === "uses" ? item.card.costCount : 0;
|
||||||
|
const consumed = run.getConsumedUses(itemId);
|
||||||
|
return consumed < maxUses;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function payCardCost(
|
||||||
|
player: PlayerEntity,
|
||||||
|
costType: CardData["costType"],
|
||||||
|
costCount: number,
|
||||||
|
itemId: string,
|
||||||
|
run: IRunContext,
|
||||||
|
): Promise<void> {
|
||||||
|
if (costType === "energy") {
|
||||||
|
player.energy -= costCount;
|
||||||
|
} else if (costType === "uses") {
|
||||||
|
const consumed = run.getConsumedUses(itemId);
|
||||||
|
await run.setConsumedUsesAsync(itemId, consumed + costCount);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import {
|
||||||
|
CombatState,
|
||||||
|
EffectTable,
|
||||||
|
EnemyEntity,
|
||||||
|
IPlayerDeck,
|
||||||
|
IPlayerState,
|
||||||
|
PlayerEntity,
|
||||||
|
} from "./types";
|
||||||
|
import { EffectData, EncounterData, EnemyData, IntentData } from "../types";
|
||||||
|
|
||||||
|
export function buildCombatState(
|
||||||
|
playerState: IPlayerState,
|
||||||
|
deck: IPlayerDeck,
|
||||||
|
encounter: EncounterData,
|
||||||
|
): CombatState {
|
||||||
|
const player = createPlayerEntity(playerState, deck);
|
||||||
|
const enemies = createEnemyEntities(encounter);
|
||||||
|
|
||||||
|
return {
|
||||||
|
enemies,
|
||||||
|
player,
|
||||||
|
phase: "playerTurn",
|
||||||
|
turnNumber: 1,
|
||||||
|
result: null,
|
||||||
|
loot: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createEnemyEntities(encounter: EncounterData): EnemyEntity[] {
|
||||||
|
const enemies: EnemyEntity[] = [];
|
||||||
|
let instanceCounter = 0;
|
||||||
|
|
||||||
|
for (const [enemyData, hp, encounterBuffs] of encounter.enemies) {
|
||||||
|
const instanceId = `${enemyData.id}-${instanceCounter++}`;
|
||||||
|
const intents = buildIntentMap(enemyData);
|
||||||
|
const initialIntent = findInitialIntent(enemyData);
|
||||||
|
const effects = buildEffectTable(encounterBuffs);
|
||||||
|
|
||||||
|
const entity: EnemyEntity = {
|
||||||
|
id: instanceId,
|
||||||
|
enemy: enemyData,
|
||||||
|
hp,
|
||||||
|
maxHp: hp,
|
||||||
|
isAlive: true,
|
||||||
|
effects,
|
||||||
|
intents,
|
||||||
|
currentIntent: initialIntent,
|
||||||
|
};
|
||||||
|
enemies.push(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
return enemies;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a map of intent ID -> IntentData for an enemy.
|
||||||
|
*/
|
||||||
|
function buildIntentMap(enemy: EnemyData): Record<string, IntentData> {
|
||||||
|
const intents: Record<string, IntentData> = {};
|
||||||
|
for (const intent of enemy.intents) {
|
||||||
|
intents[intent.id] = intent;
|
||||||
|
}
|
||||||
|
return intents;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds the initial intent ID for an enemy.
|
||||||
|
*/
|
||||||
|
function findInitialIntent(enemy: EnemyData): IntentData {
|
||||||
|
for (const intent of enemy.intents) {
|
||||||
|
if (intent.initialIntent) {
|
||||||
|
return intent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (enemy.intents.length === 0) {
|
||||||
|
throw new Error(`Enemy "${enemy.id}" has no intents`);
|
||||||
|
}
|
||||||
|
return enemy.intents[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildEffectTable(buffs: readonly [EffectData, number][]): EffectTable {
|
||||||
|
const table: EffectTable = {};
|
||||||
|
for (const [effect, stacks] of buffs) {
|
||||||
|
table[effect.id] = { data: effect, stacks };
|
||||||
|
}
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createPlayerEntity(
|
||||||
|
playerState: IPlayerState,
|
||||||
|
deck: IPlayerDeck,
|
||||||
|
): PlayerEntity {
|
||||||
|
return {
|
||||||
|
id: "player",
|
||||||
|
hp: playerState.hp,
|
||||||
|
maxHp: playerState.maxHp,
|
||||||
|
isAlive: playerState.hp > 0,
|
||||||
|
energy: 3,
|
||||||
|
maxEnergy: 3,
|
||||||
|
deck,
|
||||||
|
itemEffects: playerState.itemEffects,
|
||||||
|
effects: {},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
export * from "./effects";
|
||||||
|
export * from "./factory";
|
||||||
|
export * from "./prompts";
|
||||||
|
export * from "./triggers";
|
||||||
|
export * from "./types";
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { createPromptDef } from "@/core/game";
|
||||||
|
import { CombatGameContext, IRunContext } from "./types";
|
||||||
|
import { canPlayCard } from "@/samples/slay-the-spire-like/system/combat/effects";
|
||||||
|
|
||||||
|
export const prompts = {
|
||||||
|
mainAction: createPromptDef<[string, string?]>(
|
||||||
|
"main-action <cardId:string> [targetId:string]",
|
||||||
|
"选择卡牌并指定目标",
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function promptMainAction(
|
||||||
|
game: CombatGameContext,
|
||||||
|
run: IRunContext,
|
||||||
|
) {
|
||||||
|
return await game.prompt(prompts.mainAction, (cardId, targetId) => {
|
||||||
|
if (cardId === "end-turn")
|
||||||
|
return {
|
||||||
|
action: "end-turn" as "end-turn",
|
||||||
|
};
|
||||||
|
|
||||||
|
const exists =
|
||||||
|
game.value.player.deck.regions.hand.childIds.includes(cardId);
|
||||||
|
if (!exists) throw `卡牌"${cardId}"不在手牌中`;
|
||||||
|
|
||||||
|
const card = game.value.player.deck.cards[cardId];
|
||||||
|
const { cardData, itemId } = card;
|
||||||
|
if (
|
||||||
|
!canPlayCard(
|
||||||
|
game.value.player,
|
||||||
|
cardData.costType,
|
||||||
|
cardData.costCount,
|
||||||
|
itemId,
|
||||||
|
run,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw `无法支付卡牌"${cardId}"的费用`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { targetType } = cardData;
|
||||||
|
if (targetType === "enemy") {
|
||||||
|
if (!targetId) throw `请指定目标`;
|
||||||
|
const target = game.value.enemies.find((e) => e.id === targetId);
|
||||||
|
if (!target) throw `目标"${targetId}"不存在`;
|
||||||
|
if (!target.isAlive) throw `目标"${targetId}"已死亡`;
|
||||||
|
} else if (targetType === "enemies" || targetType === "player") {
|
||||||
|
if (targetId) throw `目标"${targetId}"无效`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
action: "play" as "play",
|
||||||
|
cardId,
|
||||||
|
targetId,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,343 @@
|
|||||||
|
import { CombatGameContext, IRunContext } from "./types";
|
||||||
|
import {
|
||||||
|
addEntityEffect,
|
||||||
|
addItemEffect,
|
||||||
|
getAliveEnemies,
|
||||||
|
onEntityPostureDamage,
|
||||||
|
onEntityEffectUpkeep,
|
||||||
|
onPlayerItemEffectUpkeep,
|
||||||
|
onItemDiscard,
|
||||||
|
onItemPlay,
|
||||||
|
payCardCost,
|
||||||
|
getCombatEntity,
|
||||||
|
getEffectTargets,
|
||||||
|
} from "@/samples/slay-the-spire-like/system/combat/effects";
|
||||||
|
import { promptMainAction } from "@/samples/slay-the-spire-like/system/combat/prompts";
|
||||||
|
import { moveToRegion, shuffle } from "@/core/region";
|
||||||
|
import { createMiddlewareChain } from "@/utils/middleware";
|
||||||
|
import { EffectData } from "@/samples/slay-the-spire-like/system/types";
|
||||||
|
|
||||||
|
type TriggerTypes = {
|
||||||
|
onCombatStart: {};
|
||||||
|
onTurnStart: { entityId: "player" | string };
|
||||||
|
onTurnEnd: { entityId: "player" | string };
|
||||||
|
onShuffle: {};
|
||||||
|
onCardPlayed: {
|
||||||
|
cardId: string;
|
||||||
|
targetId?: string;
|
||||||
|
sourceEntityId?: "player" | string;
|
||||||
|
};
|
||||||
|
onCardDiscarded: { cardId: string; sourceEntityId?: "player" | string };
|
||||||
|
onCardDrawn: { cardId: string; sourceEntityId?: "player" | string };
|
||||||
|
onDraw: { count: number };
|
||||||
|
onEffectApplied: {
|
||||||
|
effect: EffectData;
|
||||||
|
entityId: "player" | string;
|
||||||
|
stacks: number;
|
||||||
|
cardId?: string;
|
||||||
|
sourceEntityId?: "player" | string;
|
||||||
|
targetId?: string;
|
||||||
|
};
|
||||||
|
onHpChange: { entityId: "player" | string; amount: number };
|
||||||
|
onDamage: {
|
||||||
|
entityId: "player" | string;
|
||||||
|
amount: number;
|
||||||
|
prevented?: number;
|
||||||
|
sourceEntityId?: "player" | string;
|
||||||
|
};
|
||||||
|
onEnemyIntent: { enemyId: string; sourceEntityId?: "player" | string };
|
||||||
|
onIntentUpdate: { enemyId: string };
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createTriggers(run: IRunContext) {
|
||||||
|
const triggers = {
|
||||||
|
onCombatStart: createTrigger("onCombatStart", async (ctx) => {
|
||||||
|
await triggers.onShuffle.execute(ctx.game, {});
|
||||||
|
await triggers.onDraw.execute(ctx.game, { count: 5 });
|
||||||
|
}),
|
||||||
|
onTurnStart: createTrigger("onTurnStart", async (ctx) => {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const entity = getCombatEntity(draft, ctx.entityId);
|
||||||
|
if (entity) onEntityEffectUpkeep(entity);
|
||||||
|
if (entity === draft.player) onPlayerItemEffectUpkeep(draft.player);
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
onTurnEnd: createTrigger("onTurnEnd", async (ctx) => {
|
||||||
|
if (ctx.entityId !== "player") return;
|
||||||
|
const { regions } = ctx.game.value.player.deck;
|
||||||
|
for (const cardId of Object.values(regions.hand.childIds)) {
|
||||||
|
await triggers.onCardDiscarded.execute(ctx.game, { cardId });
|
||||||
|
}
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
draft.player.energy = draft.player.maxEnergy;
|
||||||
|
});
|
||||||
|
await triggers.onDraw.execute(ctx.game, { count: 5 });
|
||||||
|
}),
|
||||||
|
onShuffle: createTrigger("onShuffle", async (ctx) => {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const { cards, regions } = draft.player.deck;
|
||||||
|
for (const cardId of Object.values(regions.discardPile.childIds))
|
||||||
|
moveToRegion(cards[cardId], regions.discardPile, regions.drawPile);
|
||||||
|
shuffle(regions.drawPile, cards, ctx.game.rng);
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
onCardPlayed: createTrigger("onCardPlayed", async (ctx) => {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const { cards, regions } = draft.player.deck;
|
||||||
|
const card = cards[ctx.cardId];
|
||||||
|
payCardCost(
|
||||||
|
draft.player,
|
||||||
|
card.cardData.costType,
|
||||||
|
card.cardData.costCount,
|
||||||
|
card.itemId,
|
||||||
|
run,
|
||||||
|
);
|
||||||
|
moveToRegion(card, regions.hand, regions.discardPile);
|
||||||
|
onItemPlay(draft.player, card.itemId);
|
||||||
|
});
|
||||||
|
const { cards, regions } = ctx.game.value.player.deck;
|
||||||
|
const card = cards[ctx.cardId];
|
||||||
|
const source = ctx.sourceEntityId ?? "player";
|
||||||
|
for (const { trigger, target, effects } of card.cardData.effects) {
|
||||||
|
if (trigger !== "onPlay") continue;
|
||||||
|
for (const [effect, stacks] of effects)
|
||||||
|
for (const entity of getEffectTargets(
|
||||||
|
target,
|
||||||
|
ctx.game,
|
||||||
|
ctx.targetId,
|
||||||
|
source,
|
||||||
|
))
|
||||||
|
await triggers.onEffectApplied.execute(ctx.game, {
|
||||||
|
effect,
|
||||||
|
entityId: entity.id,
|
||||||
|
stacks,
|
||||||
|
cardId: ctx.cardId,
|
||||||
|
sourceEntityId: source,
|
||||||
|
targetId: ctx.targetId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
onCardDiscarded: createTrigger("onCardDiscarded", async (ctx) => {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const { cards, regions } = draft.player.deck;
|
||||||
|
moveToRegion(cards[ctx.cardId], regions.hand, regions.discardPile);
|
||||||
|
onItemDiscard(draft.player, cards[ctx.cardId].itemId);
|
||||||
|
});
|
||||||
|
const { cards, regions } = ctx.game.value.player.deck;
|
||||||
|
const card = cards[ctx.cardId];
|
||||||
|
const source = ctx.sourceEntityId ?? "player";
|
||||||
|
for (const { trigger, target, effects } of card.cardData.effects) {
|
||||||
|
if (trigger !== "onDiscard") continue;
|
||||||
|
for (const [effect, stacks] of effects)
|
||||||
|
for (const entity of getEffectTargets(
|
||||||
|
target,
|
||||||
|
ctx.game,
|
||||||
|
undefined,
|
||||||
|
source,
|
||||||
|
))
|
||||||
|
await triggers.onEffectApplied.execute(ctx.game, {
|
||||||
|
effect,
|
||||||
|
entityId: entity.id,
|
||||||
|
stacks,
|
||||||
|
cardId: ctx.cardId,
|
||||||
|
sourceEntityId: source,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
onCardDrawn: createTrigger("onCardDrawn", async (ctx) => {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const { cards, regions } = draft.player.deck;
|
||||||
|
moveToRegion(cards[ctx.cardId], regions.drawPile, regions.hand);
|
||||||
|
});
|
||||||
|
const { cards, regions } = ctx.game.value.player.deck;
|
||||||
|
const card = cards[ctx.cardId];
|
||||||
|
const source = ctx.sourceEntityId ?? "player";
|
||||||
|
for (const { trigger, target, effects } of card.cardData.effects) {
|
||||||
|
if (trigger !== "onDraw") continue;
|
||||||
|
for (const [effect, stacks] of effects)
|
||||||
|
for (const entity of getEffectTargets(
|
||||||
|
target,
|
||||||
|
ctx.game,
|
||||||
|
undefined,
|
||||||
|
source,
|
||||||
|
))
|
||||||
|
await triggers.onEffectApplied.execute(ctx.game, {
|
||||||
|
effect,
|
||||||
|
entityId: entity.id,
|
||||||
|
stacks,
|
||||||
|
cardId: ctx.cardId,
|
||||||
|
sourceEntityId: source,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
onDraw: createTrigger("onDraw", async (ctx) => {
|
||||||
|
let toDraw = ctx.count;
|
||||||
|
while (toDraw > 0) {
|
||||||
|
let inDraw =
|
||||||
|
ctx.game.value.player.deck.regions.drawPile.childIds.length;
|
||||||
|
if (inDraw <= 0) await triggers.onShuffle.execute(ctx.game, {});
|
||||||
|
|
||||||
|
inDraw = ctx.game.value.player.deck.regions.drawPile.childIds.length;
|
||||||
|
if (inDraw <= 0) break;
|
||||||
|
|
||||||
|
const children = ctx.game.value.player.deck.regions.drawPile.childIds;
|
||||||
|
const cardId = children[children.length - 1];
|
||||||
|
await triggers.onCardDrawn.execute(ctx.game, { cardId });
|
||||||
|
toDraw--;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
onEffectApplied: createTrigger("onEffectApplied", async (ctx) => {
|
||||||
|
if (ctx.effect.lifecycle === "instant") return;
|
||||||
|
|
||||||
|
if (ctx.effect.lifecycle.startsWith("item")) {
|
||||||
|
if (ctx.cardId) {
|
||||||
|
const card = ctx.game.value.player.deck.cards[ctx.cardId];
|
||||||
|
const nearby = run.getAdjacentItems(card.itemId);
|
||||||
|
for (const itemId of nearby) {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
addItemEffect(draft.player, itemId, ctx.effect, ctx.stacks);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const entity =
|
||||||
|
ctx.entityId === "player"
|
||||||
|
? draft.player
|
||||||
|
: draft.enemies.find((e) => e.id === ctx.entityId);
|
||||||
|
if (entity) addEntityEffect(entity, ctx.effect, ctx.stacks);
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
onHpChange: createTrigger("onHpChange", async (ctx) => {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const entity =
|
||||||
|
ctx.entityId === "player"
|
||||||
|
? draft.player
|
||||||
|
: draft.enemies.find((e) => e.id === ctx.entityId);
|
||||||
|
if (!entity) return;
|
||||||
|
entity.hp += ctx.amount;
|
||||||
|
entity.isAlive = entity.hp > 0;
|
||||||
|
draft.result = !draft.player.isAlive
|
||||||
|
? "defeat"
|
||||||
|
: draft.enemies.every((e) => !e.isAlive)
|
||||||
|
? "victory"
|
||||||
|
: null;
|
||||||
|
});
|
||||||
|
if (ctx.game.value.result) throw ctx.game.value;
|
||||||
|
}),
|
||||||
|
onDamage: createTrigger("onDamage", async (ctx) => {
|
||||||
|
const entity =
|
||||||
|
ctx.entityId === "player"
|
||||||
|
? ctx.game.value.player
|
||||||
|
: ctx.game.value.enemies.find((e) => e.id === ctx.entityId);
|
||||||
|
if (!entity || !entity.isAlive) return;
|
||||||
|
const dealt = Math.min(
|
||||||
|
Math.max(0, entity.hp),
|
||||||
|
ctx.amount - (ctx.prevented || 0),
|
||||||
|
);
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
onEntityPostureDamage(entity, dealt);
|
||||||
|
});
|
||||||
|
await triggers.onHpChange.execute(ctx.game, {
|
||||||
|
entityId: ctx.entityId,
|
||||||
|
amount: -dealt,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
onEnemyIntent: createTrigger("onEnemyIntent", async (ctx) => {
|
||||||
|
const enemy = ctx.game.value.enemies.find((e) => e.id === ctx.enemyId);
|
||||||
|
if (!enemy || !enemy.isAlive) return;
|
||||||
|
|
||||||
|
const intent = enemy.currentIntent;
|
||||||
|
if (!intent) return;
|
||||||
|
|
||||||
|
const source = ctx.sourceEntityId ?? enemy.id;
|
||||||
|
for (const [target, effect, stacks] of intent.effects) {
|
||||||
|
for (const entity of getEffectTargets(
|
||||||
|
target,
|
||||||
|
ctx.game,
|
||||||
|
undefined,
|
||||||
|
source,
|
||||||
|
))
|
||||||
|
await triggers.onEffectApplied.execute(ctx.game, {
|
||||||
|
effect,
|
||||||
|
entityId: entity.id,
|
||||||
|
stacks,
|
||||||
|
sourceEntityId: source,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
onIntentUpdate: createTrigger("onIntentUpdate", async (ctx) => {
|
||||||
|
await ctx.game.produceAsync((draft) => {
|
||||||
|
const enemy = draft.enemies.find((e) => e.id === ctx.enemyId);
|
||||||
|
if (!enemy) return;
|
||||||
|
|
||||||
|
const intent = enemy.currentIntent;
|
||||||
|
if (!intent) return;
|
||||||
|
|
||||||
|
const nextIntents = intent.nextIntents;
|
||||||
|
if (nextIntents.length > 0) {
|
||||||
|
const nextIndex = ctx.game.rng.nextInt(nextIntents.length);
|
||||||
|
enemy.currentIntent = nextIntents[nextIndex];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
return triggers;
|
||||||
|
}
|
||||||
|
export type Triggers = ReturnType<typeof createTriggers>;
|
||||||
|
export function createStart(triggers: Triggers, run: IRunContext) {
|
||||||
|
return async function (game: CombatGameContext) {
|
||||||
|
await triggers.onCombatStart.execute(game, {});
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
await triggers.onTurnStart.execute(game, { entityId: "player" });
|
||||||
|
while (true) {
|
||||||
|
const action = await promptMainAction(game, run);
|
||||||
|
if (action.action === "end-turn") break;
|
||||||
|
if (action.action === "play") {
|
||||||
|
await triggers.onCardPlayed.execute(game, action);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await triggers.onTurnEnd.execute(game, { entityId: "player" });
|
||||||
|
|
||||||
|
for (const enemy of getAliveEnemies(game.value)) {
|
||||||
|
await triggers.onTurnStart.execute(game, { entityId: enemy.id });
|
||||||
|
}
|
||||||
|
for (const enemy of getAliveEnemies(game.value)) {
|
||||||
|
await triggers.onEnemyIntent.execute(game, { enemyId: enemy.id });
|
||||||
|
await triggers.onIntentUpdate.execute(game, { enemyId: enemy.id });
|
||||||
|
}
|
||||||
|
for (const enemy of getAliveEnemies(game.value)) {
|
||||||
|
await triggers.onTurnEnd.execute(game, { entityId: enemy.id });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (e === game.value) return game.value.result;
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
type TriggerContext<TKey extends keyof TriggerTypes> = TriggerTypes[TKey] & {
|
||||||
|
event: TKey;
|
||||||
|
game: CombatGameContext;
|
||||||
|
};
|
||||||
|
function createTrigger<TKey extends keyof TriggerTypes>(
|
||||||
|
event: TKey,
|
||||||
|
fallback?: (ctx: TriggerContext<TKey>) => Promise<void>,
|
||||||
|
) {
|
||||||
|
const { use, execute } = createMiddlewareChain<TriggerContext<TKey>, void>(
|
||||||
|
fallback,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
use,
|
||||||
|
execute: async (game: CombatGameContext, ctx: TriggerTypes[TKey]) => {
|
||||||
|
const param = { ...ctx, game, event };
|
||||||
|
await execute(param);
|
||||||
|
return param;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { Part } from "@/core/part";
|
||||||
|
import { Region } from "@/core/region";
|
||||||
|
import {
|
||||||
|
CardData,
|
||||||
|
EnemyData,
|
||||||
|
IntentData,
|
||||||
|
ItemData,
|
||||||
|
} from "@/samples/slay-the-spire-like/system/types";
|
||||||
|
import { EffectData } from "@/samples/slay-the-spire-like/system/types";
|
||||||
|
|
||||||
|
export type EffectTable = Record<string, { data: EffectData; stacks: number }>;
|
||||||
|
|
||||||
|
export type CombatEntity = {
|
||||||
|
id: string; // player is just "player"
|
||||||
|
effects: EffectTable;
|
||||||
|
hp: number;
|
||||||
|
maxHp: number;
|
||||||
|
isAlive: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface IPlayerState {
|
||||||
|
hp: number;
|
||||||
|
maxHp: number;
|
||||||
|
itemEffects: Record<string, EffectTable>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IPlayerDeck {
|
||||||
|
cards: Record<string, Part<{ cardData: CardData; itemId: string }>>;
|
||||||
|
regions: {
|
||||||
|
hand: Region;
|
||||||
|
discardPile: Region;
|
||||||
|
drawPile: Region;
|
||||||
|
exhaustPile: Region;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PlayerEntity = CombatEntity & {
|
||||||
|
energy: number;
|
||||||
|
maxEnergy: number;
|
||||||
|
deck: IPlayerDeck;
|
||||||
|
itemEffects: Record<string, EffectTable>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type EnemyEntity = CombatEntity & {
|
||||||
|
enemy: EnemyData;
|
||||||
|
intents: Record<string, IntentData>;
|
||||||
|
currentIntent: IntentData;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CombatPhase = "playerTurn" | "enemyTurn" | "combatEnd";
|
||||||
|
export type CombatResult = "victory" | "defeat";
|
||||||
|
|
||||||
|
export type LootEntry =
|
||||||
|
| {
|
||||||
|
type: "gold";
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
type: "item";
|
||||||
|
itemId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CombatState = {
|
||||||
|
enemies: EnemyEntity[];
|
||||||
|
player: PlayerEntity;
|
||||||
|
|
||||||
|
phase: CombatPhase;
|
||||||
|
turnNumber: number;
|
||||||
|
result: CombatResult | null;
|
||||||
|
|
||||||
|
loot: LootEntry[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface IRunContext {
|
||||||
|
getItemData(id: string): ItemData | null;
|
||||||
|
getAdjacentItems(id: string): Iterable<string>;
|
||||||
|
|
||||||
|
getConsumedUses(id: string): number;
|
||||||
|
setConsumedUsesAsync(id: string, uses: number): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CombatGameContext =
|
||||||
|
import("@/core/game").IGameContextExport<CombatState>;
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { moveToRegion } from "@/core/region";
|
||||||
|
import { createRegion } from "@/core/region";
|
||||||
|
import type { CardData } from "../types";
|
||||||
|
import type { DeckRegions, GameCard, IInventory, PlayerDeck } from "./types";
|
||||||
|
|
||||||
|
function generateCardId(itemId: string, cellIndex: number): string {
|
||||||
|
return `card-${itemId}-${cellIndex}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createCard(
|
||||||
|
itemId: string,
|
||||||
|
cardData: CardData,
|
||||||
|
cellIndex: number,
|
||||||
|
): GameCard {
|
||||||
|
return {
|
||||||
|
id: generateCardId(itemId, cellIndex),
|
||||||
|
regionId: "",
|
||||||
|
position: [],
|
||||||
|
itemId,
|
||||||
|
cardData,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDeckRegions(): DeckRegions {
|
||||||
|
return {
|
||||||
|
drawPile: createRegion("drawPile", []),
|
||||||
|
hand: createRegion("hand", []),
|
||||||
|
discardPile: createRegion("discardPile", []),
|
||||||
|
exhaustPile: createRegion("exhaustPile", []),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateDeckFromInventory(inventory: IInventory): PlayerDeck {
|
||||||
|
const cards: Record<string, GameCard> = {};
|
||||||
|
const regions = createDeckRegions();
|
||||||
|
|
||||||
|
for (const item of inventory.items.values()) {
|
||||||
|
const itemData = item.meta?.itemData;
|
||||||
|
if (!itemData) continue;
|
||||||
|
|
||||||
|
const count = item.shape.count;
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
const card = createCard(item.id, itemData.card, i);
|
||||||
|
cards[card.id] = card;
|
||||||
|
moveToRegion(card, null, regions.drawPile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
cards,
|
||||||
|
regions,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createPlayerDeck(): PlayerDeck {
|
||||||
|
return {
|
||||||
|
cards: {},
|
||||||
|
regions: createDeckRegions(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
generateDeckFromInventory,
|
||||||
|
createCard,
|
||||||
|
createPlayerDeck,
|
||||||
|
createDeckRegions,
|
||||||
|
generateCardId,
|
||||||
|
};
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export * from "./factory";
|
||||||
|
export * from "./types";
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import type { Part } from "@/core/part";
|
||||||
|
import { CardData, ItemData } from "@/samples/slay-the-spire-like/system/types";
|
||||||
|
import { Region } from "@/core/region";
|
||||||
|
import { ParsedShape } from "../utils/parse-shape";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Metadata for a game card.
|
||||||
|
* Bridges inventory item data with the card system.
|
||||||
|
*/
|
||||||
|
export interface GameCardMeta {
|
||||||
|
cardData: CardData;
|
||||||
|
itemId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IInventory {
|
||||||
|
items: Map<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
id: string;
|
||||||
|
meta?: { itemData: ItemData };
|
||||||
|
shape: ParsedShape;
|
||||||
|
}
|
||||||
|
>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A card instance in the game.
|
||||||
|
* Cards are generated from inventory items or created as status effects.
|
||||||
|
*/
|
||||||
|
export type GameCard = Part<GameCardMeta>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Player deck structure containing card pools.
|
||||||
|
*/
|
||||||
|
export interface PlayerDeck {
|
||||||
|
/** All cards indexed by ID */
|
||||||
|
cards: Record<string, GameCard>;
|
||||||
|
|
||||||
|
regions: DeckRegions;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeckRegions {
|
||||||
|
/** Card IDs in the draw pile */
|
||||||
|
drawPile: Region;
|
||||||
|
/** Card IDs in the player's hand */
|
||||||
|
hand: Region;
|
||||||
|
/** Card IDs in the discard pile */
|
||||||
|
discardPile: Region;
|
||||||
|
/** Card IDs in the exhaust pile (removed from combat) */
|
||||||
|
exhaustPile: Region;
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export * from "./types";
|
||||||
|
export * from "./run";
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { RunState } from "./types";
|
||||||
|
|
||||||
|
const DEFAULT_MAX_HP = 50;
|
||||||
|
const DEFAULT_GOLD = 50;
|
||||||
|
|
||||||
|
export function createRunState(): RunState {
|
||||||
|
return {
|
||||||
|
maxHp: DEFAULT_MAX_HP,
|
||||||
|
currentHp: DEFAULT_MAX_HP,
|
||||||
|
gold: DEFAULT_GOLD,
|
||||||
|
_idCounter: { value: 0 },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function damagePlayer(runState: RunState, amount: number): void {
|
||||||
|
runState.currentHp = Math.max(0, runState.currentHp - amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function healPlayer(runState: RunState, amount: number): void {
|
||||||
|
runState.currentHp = Math.min(runState.maxHp, runState.currentHp + amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setMaxHp(runState: RunState, newMax: number): void {
|
||||||
|
const diff = Math.max(0, newMax - runState.maxHp);
|
||||||
|
runState.maxHp = newMax;
|
||||||
|
runState.currentHp = Math.max(0, Math.min(newMax, runState.currentHp + diff));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds gold to the player.
|
||||||
|
*/
|
||||||
|
export function addGold(runState: RunState, amount: number): void {
|
||||||
|
runState.gold += amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Spends gold. Returns false if the player doesn't have enough gold.
|
||||||
|
*/
|
||||||
|
export function spendGold(
|
||||||
|
runState: RunState,
|
||||||
|
amount: number,
|
||||||
|
): { success: true } | { success: false; reason: string } {
|
||||||
|
if (amount <= 0) {
|
||||||
|
return { success: false, reason: "金额必须大于零" };
|
||||||
|
}
|
||||||
|
if (runState.gold < amount) {
|
||||||
|
return { success: false, reason: "金币不足" };
|
||||||
|
}
|
||||||
|
|
||||||
|
runState.gold -= amount;
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { GridInventory } from "../grid-inventory";
|
||||||
|
import { GameItemMeta } from "../grid-inventory/types";
|
||||||
|
import { EncounterData } from "../types";
|
||||||
|
|
||||||
|
export interface RunState {
|
||||||
|
_idCounter: { value: number };
|
||||||
|
|
||||||
|
currentHp: number;
|
||||||
|
maxHp: number;
|
||||||
|
gold: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EncounterState =
|
||||||
|
| CombatEncounterState
|
||||||
|
| ShopEncounterState
|
||||||
|
| CurioEncounterState
|
||||||
|
| CampEncounterState
|
||||||
|
| DialogueEncounterState;
|
||||||
|
|
||||||
|
export type CombatEncounterState = {
|
||||||
|
data: EncounterData<"minion" | "elite">;
|
||||||
|
blocked: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ShopEncounterState = {
|
||||||
|
data: EncounterData<"shop">;
|
||||||
|
items: GridInventory<GameItemMeta & { sellPrice: number }>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CurioEncounterState = {
|
||||||
|
data: EncounterData<"curio">;
|
||||||
|
items: GridInventory<GameItemMeta>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CampEncounterState = {
|
||||||
|
data: EncounterData<"camp">;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DialogueEncounterState = {
|
||||||
|
data: EncounterData<"event">;
|
||||||
|
blocked: boolean;
|
||||||
|
};
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { parseShapeString } from "../utils/parse-shape";
|
||||||
|
import type { ParsedShape } from "../utils/parse-shape";
|
||||||
|
import { IDENTITY_TRANSFORM, type Transform2D } from "../utils/shape-collision";
|
||||||
|
import { createGridInventory, placeItem, validatePlacement } from "./transform";
|
||||||
|
import type { GameItemMeta, GridInventory, MutationResult } from "./types";
|
||||||
|
import type { ItemData } from "../types";
|
||||||
|
import { ReadonlyRNG, RNG } from "@/utils/rng";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates and places a GameItemMeta item into the grid inventory.
|
||||||
|
* Parses the shape from itemData.shape and finds the first valid placement automatically.
|
||||||
|
* **Mutates directly** — call inside a `.produce()` callback.
|
||||||
|
*/
|
||||||
|
export function createItemIn(
|
||||||
|
inventory: GridInventory<GameItemMeta>,
|
||||||
|
id: string,
|
||||||
|
item: ItemData | GameItemMeta,
|
||||||
|
): MutationResult {
|
||||||
|
const itemData = "itemData" in item ? item.itemData : item;
|
||||||
|
const shape = parseShapeString(itemData.shape);
|
||||||
|
const transform = findFirstValidPlacement(inventory, shape);
|
||||||
|
if (!transform) {
|
||||||
|
return { success: false, reason: "无可用位置" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const meta: GameItemMeta = "itemData" in item ? item : { itemData, shape };
|
||||||
|
placeItem(inventory, { id, shape, transform, meta });
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Searches for the first valid placement in the grid (row by row, left to right).
|
||||||
|
* Returns the transform or null if no valid placement exists.
|
||||||
|
*/
|
||||||
|
function findFirstValidPlacement(
|
||||||
|
inventory: GridInventory<GameItemMeta>,
|
||||||
|
shape: ParsedShape,
|
||||||
|
): Transform2D | null {
|
||||||
|
for (let y = 0; y <= inventory.height - shape.height; y++) {
|
||||||
|
for (let x = 0; x <= inventory.width - shape.width; x++) {
|
||||||
|
const transform: Transform2D = {
|
||||||
|
offset: { x, y },
|
||||||
|
rotation: 0,
|
||||||
|
flipX: false,
|
||||||
|
flipY: false,
|
||||||
|
};
|
||||||
|
const result = validatePlacement(inventory, shape, transform);
|
||||||
|
if (result.valid) {
|
||||||
|
return transform;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateInstanceId(counter: { value: number }): string {
|
||||||
|
counter.value++;
|
||||||
|
return `item-${counter.value}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createShopInventory(
|
||||||
|
allItems: ItemData[],
|
||||||
|
rng: ReadonlyRNG,
|
||||||
|
counter: { value: number },
|
||||||
|
) {
|
||||||
|
const shopItems: GameItemMeta[] = [];
|
||||||
|
const rolledIndices = new Set<number>();
|
||||||
|
|
||||||
|
for (let i = 0; i < 5 && rolledIndices.size < allItems.length; i++) {
|
||||||
|
let index: number;
|
||||||
|
do {
|
||||||
|
index = rng.nextInt(allItems.length);
|
||||||
|
} while (rolledIndices.has(index));
|
||||||
|
rolledIndices.add(index);
|
||||||
|
|
||||||
|
const itemData = allItems[index];
|
||||||
|
const shape = parseShapeString(itemData.shape);
|
||||||
|
const tradePrice = Math.floor(
|
||||||
|
(rng.nextInt(5) + rng.nextInt(5) + 1) * 0.2 * itemData.price,
|
||||||
|
);
|
||||||
|
|
||||||
|
shopItems.push({ itemData, shape, tradePrice });
|
||||||
|
}
|
||||||
|
|
||||||
|
const inventory = createGridInventory<GameItemMeta>(6, 4);
|
||||||
|
|
||||||
|
for (let i = 0; i < shopItems.length; i++) {
|
||||||
|
createItemIn(inventory, generateInstanceId(counter), shopItems[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return inventory;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createCurioItems(
|
||||||
|
allItems: ItemData[],
|
||||||
|
rng: RNG,
|
||||||
|
counter: { value: number },
|
||||||
|
) {
|
||||||
|
const curioItems: GameItemMeta[] = [];
|
||||||
|
const rolledIndices = new Set<number>();
|
||||||
|
|
||||||
|
for (let i = 0; i < 2 && rolledIndices.size < allItems.length; i++) {
|
||||||
|
let index: number;
|
||||||
|
do {
|
||||||
|
index = rng.nextInt(allItems.length);
|
||||||
|
} while (rolledIndices.has(index));
|
||||||
|
rolledIndices.add(index);
|
||||||
|
|
||||||
|
const itemData = allItems[index];
|
||||||
|
const shape = parseShapeString(itemData.shape);
|
||||||
|
curioItems.push({ itemData, shape });
|
||||||
|
}
|
||||||
|
|
||||||
|
const inventory = createGridInventory<GameItemMeta>(4, 3);
|
||||||
|
|
||||||
|
for (let i = 0; i < curioItems.length; i++) {
|
||||||
|
createItemIn(inventory, generateInstanceId(counter), curioItems[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return inventory;
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export * from "./types";
|
||||||
|
export * from "./transform";
|
||||||
|
export * from "./factory";
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
import { EffectData } from "../types";
|
||||||
|
import type { ParsedShape } from "../utils/parse-shape";
|
||||||
|
import type { Transform2D } from "../utils/shape-collision";
|
||||||
|
import {
|
||||||
|
checkBoardCollision,
|
||||||
|
checkBounds,
|
||||||
|
flipXTransform,
|
||||||
|
flipYTransform,
|
||||||
|
rotateTransform,
|
||||||
|
transformShape,
|
||||||
|
} from "../utils/shape-collision";
|
||||||
|
import type {
|
||||||
|
CellKey,
|
||||||
|
GameItemMeta,
|
||||||
|
GridInventory,
|
||||||
|
InventoryItem,
|
||||||
|
MutationResult,
|
||||||
|
PlacementResult,
|
||||||
|
} from "./types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new empty grid inventory.
|
||||||
|
* Note: When used inside `.produce()`, call this before returning the draft.
|
||||||
|
*/
|
||||||
|
export function createGridInventory<TMeta = Record<string, unknown>>(
|
||||||
|
width: number,
|
||||||
|
height: number,
|
||||||
|
): GridInventory<TMeta> {
|
||||||
|
return {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
items: new Map<string, InventoryItem<TMeta>>(),
|
||||||
|
occupiedCells: new Set<CellKey>(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a Set of occupied cell keys from a shape and transform.
|
||||||
|
*/
|
||||||
|
function getShapeCellKeys(
|
||||||
|
shape: ParsedShape,
|
||||||
|
transform: Transform2D,
|
||||||
|
): Set<CellKey> {
|
||||||
|
const cells = transformShape(shape, transform);
|
||||||
|
return new Set(cells.map((c) => `${c.x},${c.y}` as CellKey));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates whether an item can be placed at the given transform.
|
||||||
|
* Checks bounds and collision with all other items.
|
||||||
|
*/
|
||||||
|
export function validatePlacement<TMeta = Record<string, unknown>>(
|
||||||
|
inventory: GridInventory<TMeta>,
|
||||||
|
shape: InventoryItem<TMeta>["shape"],
|
||||||
|
transform: Transform2D,
|
||||||
|
): PlacementResult {
|
||||||
|
if (!checkBounds(shape, transform, inventory.width, inventory.height)) {
|
||||||
|
return { valid: false, reason: "超出边界" };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (checkBoardCollision(shape, transform, inventory.occupiedCells)) {
|
||||||
|
return { valid: false, reason: "与已有物品重叠" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Places an item onto the grid.
|
||||||
|
* **Mutates directly** — call inside a `.produce()` callback.
|
||||||
|
* Does not validate; call `validatePlacement` first.
|
||||||
|
*/
|
||||||
|
export function placeItem<TMeta = Record<string, unknown>>(
|
||||||
|
inventory: GridInventory<TMeta>,
|
||||||
|
item: InventoryItem<TMeta>,
|
||||||
|
): void {
|
||||||
|
const cells = getShapeCellKeys(item.shape, item.transform);
|
||||||
|
for (const cellKey of cells) {
|
||||||
|
inventory.occupiedCells.add(cellKey);
|
||||||
|
}
|
||||||
|
inventory.items.set(item.id, item);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes an item from the grid by its ID.
|
||||||
|
* **Mutates directly** — call inside a `.produce()` callback.
|
||||||
|
*/
|
||||||
|
export function removeItem<TMeta = Record<string, unknown>>(
|
||||||
|
inventory: GridInventory<TMeta>,
|
||||||
|
itemId: string,
|
||||||
|
): void {
|
||||||
|
const item = inventory.items.get(itemId);
|
||||||
|
if (!item) return;
|
||||||
|
|
||||||
|
const cells = getShapeCellKeys(item.shape, item.transform);
|
||||||
|
for (const cellKey of cells) {
|
||||||
|
inventory.occupiedCells.delete(cellKey);
|
||||||
|
}
|
||||||
|
inventory.items.delete(itemId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves an item to a new position with a new transform.
|
||||||
|
* **Mutates directly** — call inside a `.produce()` callback.
|
||||||
|
* Validates before applying; returns result indicating success.
|
||||||
|
*/
|
||||||
|
export function moveItem<TMeta = Record<string, unknown>>(
|
||||||
|
inventory: GridInventory<TMeta>,
|
||||||
|
itemId: string,
|
||||||
|
newTransform: Transform2D,
|
||||||
|
): MutationResult {
|
||||||
|
const item = inventory.items.get(itemId);
|
||||||
|
if (!item) {
|
||||||
|
return { success: false, reason: "物品不存在" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Temporarily remove item's cells for validation
|
||||||
|
const oldCells = getShapeCellKeys(item.shape, item.transform);
|
||||||
|
for (const cellKey of oldCells) {
|
||||||
|
inventory.occupiedCells.delete(cellKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate new position
|
||||||
|
const validation = validatePlacement(inventory, item.shape, newTransform);
|
||||||
|
if (!validation.valid) {
|
||||||
|
// Restore old cells
|
||||||
|
for (const cellKey of oldCells) {
|
||||||
|
inventory.occupiedCells.add(cellKey);
|
||||||
|
}
|
||||||
|
return { success: false, reason: validation.reason };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply new transform
|
||||||
|
item.transform = newTransform;
|
||||||
|
|
||||||
|
// Add new cells
|
||||||
|
const newCells = getShapeCellKeys(item.shape, item.transform);
|
||||||
|
for (const cellKey of newCells) {
|
||||||
|
inventory.occupiedCells.add(cellKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rotates an item by the given degrees (typically 90, 180, or 270).
|
||||||
|
* **Mutates directly** — call inside a `.produce()` callback.
|
||||||
|
* Validates before applying; returns result indicating success.
|
||||||
|
*/
|
||||||
|
export function rotateItem<TMeta = Record<string, unknown>>(
|
||||||
|
inventory: GridInventory<TMeta>,
|
||||||
|
itemId: string,
|
||||||
|
degrees: number,
|
||||||
|
): MutationResult {
|
||||||
|
const item = inventory.items.get(itemId);
|
||||||
|
if (!item) {
|
||||||
|
return { success: false, reason: "物品不存在" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const rotatedTransform = rotateTransform(item.transform, degrees);
|
||||||
|
return moveItem(inventory, itemId, rotatedTransform);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flips an item horizontally or vertically.
|
||||||
|
* **Mutates directly** — call inside a `.produce()` callback.
|
||||||
|
* Validates before applying; returns result indicating success.
|
||||||
|
*/
|
||||||
|
export function flipItem<TMeta = Record<string, unknown>>(
|
||||||
|
inventory: GridInventory<TMeta>,
|
||||||
|
itemId: string,
|
||||||
|
axis: "x" | "y",
|
||||||
|
): MutationResult {
|
||||||
|
const item = inventory.items.get(itemId);
|
||||||
|
if (!item) {
|
||||||
|
return { success: false, reason: "物品不存在" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const flippedTransform =
|
||||||
|
axis === "x"
|
||||||
|
? flipXTransform(item.transform)
|
||||||
|
: flipYTransform(item.transform);
|
||||||
|
|
||||||
|
return moveItem(inventory, itemId, flippedTransform);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a copy of the occupied cells set.
|
||||||
|
*/
|
||||||
|
export function getOccupiedCellSet<TMeta = Record<string, unknown>>(
|
||||||
|
inventory: GridInventory<TMeta>,
|
||||||
|
): Set<CellKey> {
|
||||||
|
return new Set(inventory.occupiedCells);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds the item occupying the given cell, if any.
|
||||||
|
*/
|
||||||
|
export function getItemAtCell<TMeta = Record<string, unknown>>(
|
||||||
|
inventory: GridInventory<TMeta>,
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
): InventoryItem<TMeta> | undefined {
|
||||||
|
const cellKey = `${x},${y}` as CellKey;
|
||||||
|
if (!inventory.occupiedCells.has(cellKey)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const item of inventory.items.values()) {
|
||||||
|
const cells = getShapeCellKeys(item.shape, item.transform);
|
||||||
|
if (cells.has(cellKey)) {
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets all items adjacent to the given item (orthogonally, not diagonally).
|
||||||
|
* Returns a Map of itemId -> item for deduplication.
|
||||||
|
*/
|
||||||
|
export function getAdjacentItems<TMeta>(
|
||||||
|
inventory: GridInventory<TMeta>,
|
||||||
|
itemId: string,
|
||||||
|
): Map<string, InventoryItem<TMeta>> {
|
||||||
|
const item = inventory.items.get(itemId);
|
||||||
|
if (!item) {
|
||||||
|
return new Map();
|
||||||
|
}
|
||||||
|
|
||||||
|
const ownCells = getShapeCellKeys(item.shape, item.transform);
|
||||||
|
const adjacent = new Map<string, InventoryItem<TMeta>>();
|
||||||
|
|
||||||
|
for (const cellKey of ownCells) {
|
||||||
|
const [cx, cy] = cellKey.split(",").map(Number);
|
||||||
|
const neighbors: CellKey[] = [
|
||||||
|
`${cx + 1},${cy}` as CellKey,
|
||||||
|
`${cx - 1},${cy}` as CellKey,
|
||||||
|
`${cx},${cy + 1}` as CellKey,
|
||||||
|
`${cx},${cy - 1}` as CellKey,
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const neighborKey of neighbors) {
|
||||||
|
if (
|
||||||
|
inventory.occupiedCells.has(neighborKey) &&
|
||||||
|
!ownCells.has(neighborKey)
|
||||||
|
) {
|
||||||
|
const [nx, ny] = neighborKey.split(",").map(Number);
|
||||||
|
const neighborItem = getItemAtCell(inventory, nx, ny);
|
||||||
|
if (neighborItem) {
|
||||||
|
adjacent.set(neighborItem.id, neighborItem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return adjacent;
|
||||||
|
}
|
||||||
|
|
||||||
|
// export type EffectTable = Record<string, { data: EffectData; stacks: number }>;
|
||||||
|
export function getItemEffects(inv: GridInventory<GameItemMeta>) {
|
||||||
|
const effects = {} as Record<
|
||||||
|
string,
|
||||||
|
Record<string, { data: EffectData; stacks: number }>
|
||||||
|
>;
|
||||||
|
|
||||||
|
for (const item of inv.items.values()) {
|
||||||
|
if (!item.meta) continue;
|
||||||
|
const { startEffects } = item.meta;
|
||||||
|
if (!startEffects) continue;
|
||||||
|
|
||||||
|
effects[item.id] = startEffects;
|
||||||
|
}
|
||||||
|
|
||||||
|
return effects;
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { EffectData, ItemData } from "../types";
|
||||||
|
import type { ParsedShape } from "../utils/parse-shape";
|
||||||
|
import type { Transform2D } from "../utils/shape-collision";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* String key representing a grid cell in "x,y" format.
|
||||||
|
*/
|
||||||
|
export type CellKey = `${number},${number}`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Simple 2D coordinate for grid cells.
|
||||||
|
*/
|
||||||
|
export interface CellCoordinate {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An item placed on the grid inventory.
|
||||||
|
* @template TMeta - Optional metadata type for game-specific data
|
||||||
|
*/
|
||||||
|
export interface InventoryItem<TMeta> {
|
||||||
|
/** Unique item identifier */
|
||||||
|
id: string;
|
||||||
|
/** Reference to the item's shape definition */
|
||||||
|
shape: ParsedShape;
|
||||||
|
/** Current transformation (position, rotation, flips) */
|
||||||
|
transform: Transform2D;
|
||||||
|
/** Optional metadata for game-specific data */
|
||||||
|
meta?: TMeta;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Result of a placement validation check.
|
||||||
|
*/
|
||||||
|
export type PlacementResult =
|
||||||
|
| { valid: true }
|
||||||
|
| { valid: false; reason: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Result of a mutation operation (move, rotate, flip).
|
||||||
|
*/
|
||||||
|
export type MutationResult =
|
||||||
|
| { success: true }
|
||||||
|
| { success: false; reason: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Grid inventory state.
|
||||||
|
* Designed to be mutated directly inside a `mutative .produce()` callback.
|
||||||
|
* @template TMeta - Optional metadata type for items
|
||||||
|
*/
|
||||||
|
export interface GridInventory<TMeta> {
|
||||||
|
/** Board width in cells */
|
||||||
|
width: number;
|
||||||
|
/** Board height in cells */
|
||||||
|
height: number;
|
||||||
|
/** Map of itemId -> InventoryItem for all placed items */
|
||||||
|
items: Map<string, InventoryItem<TMeta>>;
|
||||||
|
/** Set of occupied cells in "x,y" format for O(1) collision lookups */
|
||||||
|
occupiedCells: Set<CellKey>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GameItemMeta {
|
||||||
|
itemData: ItemData;
|
||||||
|
shape: ParsedShape;
|
||||||
|
consumedUses?: number;
|
||||||
|
startEffects?: Record<string, { data: EffectData; stacks: number }>;
|
||||||
|
tradePrice?: number;
|
||||||
|
}
|
||||||
|
export type GameItem = InventoryItem<GameItemMeta>;
|
||||||
@@ -0,0 +1,531 @@
|
|||||||
|
import { ReadonlyRNG } from '@/utils/rng';
|
||||||
|
import { MapNodeType, MapLayerType } from './types';
|
||||||
|
import type { MapLayer, MapNode, PointCrawlMap, MapGenerationConfig } from './types';
|
||||||
|
import {EncounterData} from "@/samples/slay-the-spire-like/system/types";
|
||||||
|
|
||||||
|
function buildEncounterIndex(src: Iterable<EncounterData>): Map<string, EncounterData[]> {
|
||||||
|
const index = new Map<string, EncounterData[]>();
|
||||||
|
for (const encounter of src) {
|
||||||
|
const type = encounter.type;
|
||||||
|
if (!index.has(type)) {
|
||||||
|
index.set(type, []);
|
||||||
|
}
|
||||||
|
index.get(type)!.push(encounter);
|
||||||
|
}
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Map from MapNodeType to encounter type key */
|
||||||
|
const NODE_TYPE_TO_ENCOUNTER: Partial<Record<MapNodeType, string>> = {
|
||||||
|
[MapNodeType.Minion]: 'minion',
|
||||||
|
[MapNodeType.Elite]: 'elite',
|
||||||
|
[MapNodeType.Event]: 'event',
|
||||||
|
[MapNodeType.Camp]: 'camp',
|
||||||
|
[MapNodeType.Shop]: 'shop',
|
||||||
|
[MapNodeType.Curio]: 'curio',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Default map generation configuration */
|
||||||
|
const DEFAULT_CONFIG: MapGenerationConfig = {
|
||||||
|
totalLayers: 10,
|
||||||
|
wildLayerNodeCount: 3,
|
||||||
|
settlementLayerNodeCount: 4,
|
||||||
|
wildNodeTypeWeights: {
|
||||||
|
[MapNodeType.Minion]: 50,
|
||||||
|
[MapNodeType.Elite]: 25,
|
||||||
|
[MapNodeType.Event]: 25,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Layer structure definition.
|
||||||
|
* Pattern: Start → Wild → Wild → Settlement → Wild → Wild → Settlement → Wild → Wild → End
|
||||||
|
*/
|
||||||
|
const LAYER_STRUCTURE: Array<{ layerType: MapLayerType | 'start' | 'end'; count: number }> = [
|
||||||
|
{ layerType: 'start', count: 1 },
|
||||||
|
{ layerType: MapLayerType.Wild, count: 3 },
|
||||||
|
{ layerType: MapLayerType.Wild, count: 3 },
|
||||||
|
{ layerType: MapLayerType.Settlement, count: 4 },
|
||||||
|
{ layerType: MapLayerType.Wild, count: 3 },
|
||||||
|
{ layerType: MapLayerType.Wild, count: 3 },
|
||||||
|
{ layerType: MapLayerType.Settlement, count: 4 },
|
||||||
|
{ layerType: MapLayerType.Wild, count: 3 },
|
||||||
|
{ layerType: MapLayerType.Wild, count: 3 },
|
||||||
|
{ layerType: 'end', count: 1 },
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fisher-Yates shuffle algorithm for unbiased random permutation.
|
||||||
|
* Mutates the array in place and returns it.
|
||||||
|
*/
|
||||||
|
function fisherYatesShuffle<T>(array: T[], rng: ReadonlyRNG): T[] {
|
||||||
|
for (let i = array.length - 1; i > 0; i--) {
|
||||||
|
const j = rng.nextInt(i + 1);
|
||||||
|
[array[i], array[j]] = [array[j], array[i]];
|
||||||
|
}
|
||||||
|
return array;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Picks a random encounter for the given node type.
|
||||||
|
* Returns undefined if no matching encounter exists.
|
||||||
|
*/
|
||||||
|
function pickEncounterForNode(pool: EncounterData[] | undefined, rng: ReadonlyRNG): EncounterData | undefined {
|
||||||
|
if (!pool || pool.length === 0) return undefined;
|
||||||
|
|
||||||
|
return pool[rng.nextInt(pool.length)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Total number of layers */
|
||||||
|
const TOTAL_LAYERS = 10;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a random point crawl map with layered directional graph.
|
||||||
|
*
|
||||||
|
* Structure:
|
||||||
|
* - 10 layers: Start → Wild×2 → Settlement → Wild×2 → Settlement → Wild×2 → End
|
||||||
|
* - Wild layers have exactly 3 nodes (minion/elite/event)
|
||||||
|
* - Settlement layers have exactly 4 nodes (camp/shop/curio + 1 random)
|
||||||
|
* - Each settlement layer has at least 1 of each: camp, shop, curio
|
||||||
|
* - Wild nodes connect to 1 wild node or 2 settlement nodes
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
export function generatePointCrawlMap(rng: ReadonlyRNG, src: Iterable<EncounterData>): PointCrawlMap {
|
||||||
|
const encounters = buildEncounterIndex(src);
|
||||||
|
const layers: MapLayer[] = [];
|
||||||
|
const nodes = new Map<string, MapNode>();
|
||||||
|
|
||||||
|
// Pre-generate optimal types for wild layer pairs (layers 1-2, 4-5, 7-8)
|
||||||
|
const wildPairTypes = new Map<number, MapNodeType[]>();
|
||||||
|
const wildPairs = [
|
||||||
|
{ layer1: 1, layer2: 2 },
|
||||||
|
{ layer1: 4, layer2: 5 },
|
||||||
|
{ layer1: 7, layer2: 8 },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const pair of wildPairs) {
|
||||||
|
const [types1, types2] = generateOptimalWildPair(rng);
|
||||||
|
wildPairTypes.set(pair.layer1, types1);
|
||||||
|
wildPairTypes.set(pair.layer2, types2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 1: create layers and nodes
|
||||||
|
for (let i = 0; i < TOTAL_LAYERS; i++) {
|
||||||
|
const structure = LAYER_STRUCTURE[i];
|
||||||
|
const nodeIds: string[] = [];
|
||||||
|
const layerNodes: MapNode[] = [];
|
||||||
|
|
||||||
|
// Pre-generate settlement types if this is a settlement layer
|
||||||
|
let settlementTypes: MapNodeType[] | undefined;
|
||||||
|
if (structure.layerType === MapLayerType.Settlement) {
|
||||||
|
settlementTypes = generateSettlementTypes(rng);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let j = 0; j < structure.count; j++) {
|
||||||
|
const id = `node-${i}-${j}`;
|
||||||
|
const type = resolveNodeType(structure.layerType, j, structure.count, rng, wildPairTypes.get(i), j, settlementTypes, j);
|
||||||
|
const encounter = pickEncounterForNode(encounters.get(NODE_TYPE_TO_ENCOUNTER[type]!), rng);
|
||||||
|
const node: MapNode = {
|
||||||
|
id,
|
||||||
|
layerIndex: i,
|
||||||
|
type,
|
||||||
|
childIds: [],
|
||||||
|
encounter
|
||||||
|
};
|
||||||
|
nodes.set(id, node);
|
||||||
|
nodeIds.push(id);
|
||||||
|
layerNodes.push(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
layers.push({ index: i, nodeIds, layerType: structure.layerType, nodes: layerNodes });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: generate edges between consecutive layers
|
||||||
|
const parentIndex = new Map<string, string[]>();
|
||||||
|
|
||||||
|
for (let i = 0; i < TOTAL_LAYERS - 1; i++) {
|
||||||
|
const sourceLayer = layers[i];
|
||||||
|
const targetLayer = layers[i + 1];
|
||||||
|
generateLayerEdges(sourceLayer, targetLayer, nodes, rng);
|
||||||
|
|
||||||
|
// Build reverse index: for each target node, record its parents
|
||||||
|
for (const srcNode of sourceLayer.nodes) {
|
||||||
|
for (const childId of srcNode.childIds) {
|
||||||
|
if (!parentIndex.has(childId)) {
|
||||||
|
parentIndex.set(childId, []);
|
||||||
|
}
|
||||||
|
parentIndex.get(childId)!.push(srcNode.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { layers, nodes, parentIndex };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the node type based on layer type and position.
|
||||||
|
*/
|
||||||
|
function resolveNodeType(
|
||||||
|
layerType: MapLayerType | 'start' | 'end',
|
||||||
|
_nodeIndex: number,
|
||||||
|
_layerCount: number,
|
||||||
|
rng: ReadonlyRNG,
|
||||||
|
preGeneratedTypes?: MapNodeType[],
|
||||||
|
nodeIndex?: number,
|
||||||
|
settlementTypes?: MapNodeType[],
|
||||||
|
settlementIndex?: number
|
||||||
|
): MapNodeType {
|
||||||
|
switch (layerType) {
|
||||||
|
case 'start':
|
||||||
|
return MapNodeType.Start;
|
||||||
|
case 'end':
|
||||||
|
return MapNodeType.End;
|
||||||
|
case MapLayerType.Wild:
|
||||||
|
// Use pre-generated types if available (from optimal pair generation)
|
||||||
|
if (preGeneratedTypes && nodeIndex !== undefined) {
|
||||||
|
return preGeneratedTypes[nodeIndex];
|
||||||
|
}
|
||||||
|
return pickWildNodeType(rng);
|
||||||
|
case MapLayerType.Settlement:
|
||||||
|
// Use pre-generated settlement types if available
|
||||||
|
if (settlementTypes && settlementIndex !== undefined) {
|
||||||
|
return settlementTypes[settlementIndex];
|
||||||
|
}
|
||||||
|
return MapNodeType.Camp; // fallback
|
||||||
|
default:
|
||||||
|
return MapNodeType.Minion;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Picks a random type for a wild node based on configured weights.
|
||||||
|
* Default: minion: 50%, elite: 25%, event: 25%
|
||||||
|
*/
|
||||||
|
function pickWildNodeType(rng: ReadonlyRNG): MapNodeType {
|
||||||
|
const weights = DEFAULT_CONFIG.wildNodeTypeWeights;
|
||||||
|
const roll = rng.nextInt(100);
|
||||||
|
|
||||||
|
if (roll < weights[MapNodeType.Minion]) return MapNodeType.Minion;
|
||||||
|
if (roll < weights[MapNodeType.Minion] + weights[MapNodeType.Elite]) return MapNodeType.Elite;
|
||||||
|
return MapNodeType.Event;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates random types for a pair of wild layers (3 nodes each).
|
||||||
|
* Returns two arrays of 3 node types each.
|
||||||
|
*/
|
||||||
|
function generateWildPair(rng: ReadonlyRNG): [MapNodeType[], MapNodeType[]] {
|
||||||
|
const layer1Types: MapNodeType[] = [];
|
||||||
|
const layer2Types: MapNodeType[] = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
layer1Types.push(pickWildNodeType(rng));
|
||||||
|
layer2Types.push(pickWildNodeType(rng));
|
||||||
|
}
|
||||||
|
|
||||||
|
return [layer1Types, layer2Types];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Counts repetitions in a wild layer pair.
|
||||||
|
* - sameLayer: number of duplicate types within each layer
|
||||||
|
* - adjacent: number of positions where layer1[i] === layer2[i]
|
||||||
|
* - total: sum of both
|
||||||
|
*/
|
||||||
|
function countRepetitions(
|
||||||
|
layer1Types: MapNodeType[],
|
||||||
|
layer2Types: MapNodeType[]
|
||||||
|
): { sameLayer: number; adjacent: number; total: number } {
|
||||||
|
// Count same-layer repetitions
|
||||||
|
let sameLayer = 0;
|
||||||
|
|
||||||
|
// For layer 1: count duplicates
|
||||||
|
const layer1Count = new Map<MapNodeType, number>();
|
||||||
|
for (const type of layer1Types) {
|
||||||
|
layer1Count.set(type, (layer1Count.get(type) || 0) + 1);
|
||||||
|
}
|
||||||
|
for (const count of layer1Count.values()) {
|
||||||
|
if (count > 1) sameLayer += count - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// For layer 2: count duplicates
|
||||||
|
const layer2Count = new Map<MapNodeType, number>();
|
||||||
|
for (const type of layer2Types) {
|
||||||
|
layer2Count.set(type, (layer2Count.get(type) || 0) + 1);
|
||||||
|
}
|
||||||
|
for (const count of layer2Count.values()) {
|
||||||
|
if (count > 1) sameLayer += count - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Count adjacent repetitions (wild[i] → wild[i] connection)
|
||||||
|
let adjacent = 0;
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
if (layer1Types[i] === layer2Types[i]) {
|
||||||
|
adjacent++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { sameLayer, adjacent, total: sameLayer + adjacent };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates optimal wild layer pair by trying multiple attempts and selecting the one with fewest repetitions.
|
||||||
|
*/
|
||||||
|
function generateOptimalWildPair(
|
||||||
|
rng: ReadonlyRNG,
|
||||||
|
attempts = 3
|
||||||
|
): [MapNodeType[], MapNodeType[]] {
|
||||||
|
let bestLayer1: MapNodeType[] = [];
|
||||||
|
let bestLayer2: MapNodeType[] = [];
|
||||||
|
let bestScore = Infinity;
|
||||||
|
|
||||||
|
for (let i = 0; i < attempts; i++) {
|
||||||
|
const [layer1, layer2] = generateWildPair(rng);
|
||||||
|
const score = countRepetitions(layer1, layer2);
|
||||||
|
|
||||||
|
if (score.total < bestScore) {
|
||||||
|
bestScore = score.total;
|
||||||
|
bestLayer1 = layer1;
|
||||||
|
bestLayer2 = layer2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Perfect score is 0, no need to continue
|
||||||
|
if (bestScore === 0) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [bestLayer1, bestLayer2];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates settlement node types ensuring at least 1 of each: camp, shop, curio.
|
||||||
|
* The 4th node is randomly chosen from the three.
|
||||||
|
* Returns shuffled array of 4 node types.
|
||||||
|
*/
|
||||||
|
function generateSettlementTypes(rng: ReadonlyRNG): MapNodeType[] {
|
||||||
|
const requiredTypes = [MapNodeType.Camp, MapNodeType.Shop, MapNodeType.Curio];
|
||||||
|
const randomType = requiredTypes[rng.nextInt(3)];
|
||||||
|
const types = [...requiredTypes, randomType];
|
||||||
|
return fisherYatesShuffle(types, rng);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Assigns settlement node types ensuring at least 1 of each: camp, shop, curio.
|
||||||
|
* The 4th node is randomly chosen from the three.
|
||||||
|
* @deprecated Use generateSettlementTypes() during node creation instead.
|
||||||
|
*/
|
||||||
|
function assignSettlementTypes(nodeIds: string[], nodes: MapNode[], rng: ReadonlyRNG): void {
|
||||||
|
// Shuffle node order to randomize which position gets which type
|
||||||
|
const shuffledIndices = fisherYatesShuffle([0, 1, 2, 3], rng);
|
||||||
|
|
||||||
|
// Assign camp, shop, curio to first 3 shuffled positions
|
||||||
|
const requiredTypes = [MapNodeType.Camp, MapNodeType.Shop, MapNodeType.Curio];
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
nodes[shuffledIndices[i]].type = requiredTypes[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assign random type to 4th position
|
||||||
|
const randomType = requiredTypes[rng.nextInt(3)];
|
||||||
|
nodes[shuffledIndices[3]].type = randomType;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates edges between two consecutive layers based on layer types.
|
||||||
|
*/
|
||||||
|
function generateLayerEdges(
|
||||||
|
sourceLayer: MapLayer,
|
||||||
|
targetLayer: MapLayer,
|
||||||
|
nodes: Map<string, MapNode>,
|
||||||
|
rng: ReadonlyRNG
|
||||||
|
): void {
|
||||||
|
// Settlement types are now pre-generated during node creation
|
||||||
|
// No need to assign them here anymore
|
||||||
|
|
||||||
|
const sourceType = sourceLayer.layerType;
|
||||||
|
const targetType = targetLayer.layerType;
|
||||||
|
|
||||||
|
if (sourceType === 'start' && targetType === MapLayerType.Wild) {
|
||||||
|
connectStartToWild(sourceLayer, targetLayer);
|
||||||
|
} else if (sourceType === MapLayerType.Wild && targetType === MapLayerType.Wild) {
|
||||||
|
connectWildToWild(sourceLayer, targetLayer);
|
||||||
|
} else if (sourceType === MapLayerType.Wild && targetType === MapLayerType.Settlement) {
|
||||||
|
connectWildToSettlement(sourceLayer, targetLayer, rng);
|
||||||
|
} else if (sourceType === MapLayerType.Settlement && targetType === MapLayerType.Wild) {
|
||||||
|
connectSettlementToWild(sourceLayer, targetLayer, rng);
|
||||||
|
} else if (sourceType === MapLayerType.Wild && targetType === 'end') {
|
||||||
|
connectWildToEnd(sourceLayer, targetLayer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start connects to all 3 wild nodes in the first wild layer.
|
||||||
|
*/
|
||||||
|
function connectStartToWild(
|
||||||
|
startLayer: MapLayer,
|
||||||
|
wildLayer: MapLayer
|
||||||
|
): void {
|
||||||
|
const startNode = startLayer.nodes[0];
|
||||||
|
startNode.childIds = [...wildLayer.nodeIds];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Each wild node connects to exactly 1 wild node in the next layer (1-to-1 mapping).
|
||||||
|
* Uses direct ordering to avoid crossing edges.
|
||||||
|
*/
|
||||||
|
function connectWildToWild(
|
||||||
|
sourceLayer: MapLayer,
|
||||||
|
targetLayer: MapLayer
|
||||||
|
): void {
|
||||||
|
// Direct 1-to-1 mapping: wild[i] → wild[i]
|
||||||
|
// This guarantees no crossings since order is preserved
|
||||||
|
for (let i = 0; i < sourceLayer.nodes.length; i++) {
|
||||||
|
sourceLayer.nodes[i].childIds = [targetLayer.nodeIds[i]];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Each wild node connects to 2 settlement nodes.
|
||||||
|
* Ensures all 4 settlement nodes are covered.
|
||||||
|
* Total: 3 wilds × 2 = 6 edges, 4 settlements to cover
|
||||||
|
*/
|
||||||
|
function connectWildToSettlement(
|
||||||
|
wildLayer: MapLayer,
|
||||||
|
settlementLayer: MapLayer,
|
||||||
|
_rng: ReadonlyRNG
|
||||||
|
): void {
|
||||||
|
// Non-crossing connection pattern: each wild connects to 2 adjacent settlements.
|
||||||
|
// Pattern: w[0]→{s[0],s[1]}, w[1]→{s[1],s[2]}, w[2]→{s[2],s[3]}
|
||||||
|
// This creates a "chain" where middle settlements are shared.
|
||||||
|
// This pattern guarantees no crossings because target indices are always
|
||||||
|
// non-decreasing when sorted by source indices.
|
||||||
|
|
||||||
|
wildLayer.nodes[0].childIds = [settlementLayer.nodeIds[0], settlementLayer.nodeIds[1]];
|
||||||
|
wildLayer.nodes[1].childIds = [settlementLayer.nodeIds[1], settlementLayer.nodeIds[2]];
|
||||||
|
wildLayer.nodes[2].childIds = [settlementLayer.nodeIds[2], settlementLayer.nodeIds[3]];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settlement nodes connect to wild nodes:
|
||||||
|
* - First and last settlement connect to 1 wild each
|
||||||
|
* - Middle two settlements connect to 2 wilds each
|
||||||
|
* Total: 1 + 2 + 2 + 1 = 6 edges, 3 wild nodes to cover
|
||||||
|
*
|
||||||
|
* Uses a non-crossing pattern: settlements and wilds are connected
|
||||||
|
* in order to avoid edge crossings.
|
||||||
|
*/
|
||||||
|
function connectSettlementToWild(
|
||||||
|
settlementLayer: MapLayer,
|
||||||
|
wildLayer: MapLayer,
|
||||||
|
_rng: ReadonlyRNG
|
||||||
|
): void {
|
||||||
|
// Non-crossing pattern: s0→w0, s1→w0,w1, s2→w1,w2, s3→w2
|
||||||
|
// This pattern guarantees no crossings because when edges are sorted by
|
||||||
|
// source index, the minimum target index is non-decreasing.
|
||||||
|
|
||||||
|
settlementLayer.nodes[0].childIds = [wildLayer.nodeIds[0]];
|
||||||
|
settlementLayer.nodes[1].childIds = [wildLayer.nodeIds[0], wildLayer.nodeIds[1]];
|
||||||
|
settlementLayer.nodes[2].childIds = [wildLayer.nodeIds[1], wildLayer.nodeIds[2]];
|
||||||
|
settlementLayer.nodes[3].childIds = [wildLayer.nodeIds[2]];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* All 3 wild nodes in the last wild layer connect to End.
|
||||||
|
*/
|
||||||
|
function connectWildToEnd(
|
||||||
|
wildLayer: MapLayer,
|
||||||
|
endLayer: MapLayer
|
||||||
|
): void {
|
||||||
|
const endNode = endLayer.nodes[0];
|
||||||
|
for (let i = 0; i < wildLayer.nodes.length; i++) {
|
||||||
|
wildLayer.nodes[i].childIds = [endNode.id];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- Query helpers --
|
||||||
|
|
||||||
|
/** Returns the node with the given ID, or undefined. */
|
||||||
|
export function getNode(map: PointCrawlMap, nodeId: string): MapNode | undefined {
|
||||||
|
return map.nodes.get(nodeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns child nodes of the given node. */
|
||||||
|
export function getChildren(map: PointCrawlMap, node: MapNode): MapNode[] {
|
||||||
|
return node.childIds
|
||||||
|
.map(id => map.nodes.get(id))
|
||||||
|
.filter((n): n is MapNode => n !== undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns parent nodes of the given node (reverse lookup). */
|
||||||
|
export function getParents(map: PointCrawlMap, node: MapNode): MapNode[] {
|
||||||
|
// Use pre-built reverse index if available
|
||||||
|
if (map.parentIndex) {
|
||||||
|
const parentIds = map.parentIndex.get(node.id);
|
||||||
|
if (!parentIds) return [];
|
||||||
|
|
||||||
|
return parentIds
|
||||||
|
.map(id => map.nodes.get(id))
|
||||||
|
.filter((n): n is MapNode => n !== undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: scan parent layer (legacy support)
|
||||||
|
const parents: MapNode[] = [];
|
||||||
|
const parentLayer = map.layers[node.layerIndex - 1];
|
||||||
|
if (!parentLayer) return parents;
|
||||||
|
|
||||||
|
for (const parentId of parentLayer.nodeIds) {
|
||||||
|
const parent = map.nodes.get(parentId);
|
||||||
|
if (parent?.childIds.includes(node.id)) {
|
||||||
|
parents.push(parent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return parents;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns true if there is a directed path from `fromId` to `toId`.
|
||||||
|
*/
|
||||||
|
export function hasPath(map: PointCrawlMap, fromId: string, toId: string): boolean {
|
||||||
|
const visited = new Set<string>();
|
||||||
|
const stack = [fromId];
|
||||||
|
|
||||||
|
while (stack.length > 0) {
|
||||||
|
const current = stack.pop()!;
|
||||||
|
if (current === toId) return true;
|
||||||
|
if (visited.has(current)) continue;
|
||||||
|
visited.add(current);
|
||||||
|
|
||||||
|
const node = map.nodes.get(current);
|
||||||
|
if (node) {
|
||||||
|
for (const childId of node.childIds) {
|
||||||
|
if (!visited.has(childId)) stack.push(childId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds all directed paths from `fromId` to `toId`.
|
||||||
|
* Returns arrays of node IDs representing each path.
|
||||||
|
* Beware: can be exponential in large maps.
|
||||||
|
*/
|
||||||
|
export function findAllPaths(map: PointCrawlMap, fromId: string, toId: string): string[][] {
|
||||||
|
const paths: string[][] = [];
|
||||||
|
const dfs = (current: string, path: string[]) => {
|
||||||
|
if (current === toId) {
|
||||||
|
paths.push([...path, current]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const node = map.nodes.get(current);
|
||||||
|
if (!node) return;
|
||||||
|
|
||||||
|
path.push(current);
|
||||||
|
for (const childId of node.childIds) {
|
||||||
|
dfs(childId, path);
|
||||||
|
}
|
||||||
|
path.pop();
|
||||||
|
};
|
||||||
|
|
||||||
|
dfs(fromId, []);
|
||||||
|
return paths;
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export * from "./generator";
|
||||||
|
export * from "./navigation";
|
||||||
|
export * from "./types";
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { getNode } from "./generator";
|
||||||
|
import { PointCrawlMap, PointCrawlMapNavigator } from "./types";
|
||||||
|
|
||||||
|
export function canMoveTo(
|
||||||
|
navigator: PointCrawlMapNavigator,
|
||||||
|
map: PointCrawlMap,
|
||||||
|
targetNodeId: string,
|
||||||
|
): boolean {
|
||||||
|
const currentNode = getNode(map, navigator.currentNodeId);
|
||||||
|
if (!currentNode) return false;
|
||||||
|
|
||||||
|
return currentNode.childIds.includes(targetNodeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function moveToNode(
|
||||||
|
navigator: PointCrawlMapNavigator,
|
||||||
|
map: PointCrawlMap,
|
||||||
|
targetNodeId: string,
|
||||||
|
): boolean {
|
||||||
|
if (!canMoveTo(navigator, map, targetNodeId)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetNode = getNode(map, targetNodeId);
|
||||||
|
if (!targetNode) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update current position
|
||||||
|
navigator.currentNodeId = targetNodeId;
|
||||||
|
navigator.visitedNodes.add(targetNodeId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function* getReachableChildren(
|
||||||
|
map: PointCrawlMap,
|
||||||
|
navigator: PointCrawlMapNavigator,
|
||||||
|
) {
|
||||||
|
const currentNode = getNode(map, navigator.currentNodeId);
|
||||||
|
if (!currentNode) return;
|
||||||
|
|
||||||
|
for (const id of currentNode.childIds) {
|
||||||
|
const node = getNode(map, id);
|
||||||
|
if (!node) continue;
|
||||||
|
yield node;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isAtStartNode(
|
||||||
|
map: PointCrawlMap,
|
||||||
|
navigator: PointCrawlMapNavigator,
|
||||||
|
): boolean {
|
||||||
|
return navigator.currentNodeId === map.layers[0]?.nodes[0]?.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if the current encounter is the end node.
|
||||||
|
*/
|
||||||
|
export function isAtEndNode(
|
||||||
|
map: PointCrawlMap,
|
||||||
|
navigator: PointCrawlMapNavigator,
|
||||||
|
): boolean {
|
||||||
|
const endLayer = map.layers[map.layers.length - 1];
|
||||||
|
return endLayer?.nodes[0]?.id === navigator.currentNodeId;
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { EncounterData } from "@/samples/slay-the-spire-like/system/types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Types of nodes that can appear on the point crawl map.
|
||||||
|
*/
|
||||||
|
export enum MapNodeType {
|
||||||
|
Start = "start",
|
||||||
|
End = "end",
|
||||||
|
Minion = "minion",
|
||||||
|
Elite = "elite",
|
||||||
|
Event = "event",
|
||||||
|
Camp = "camp",
|
||||||
|
Shop = "shop",
|
||||||
|
Curio = "curio",
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Semantic type of a layer.
|
||||||
|
*/
|
||||||
|
export enum MapLayerType {
|
||||||
|
Wild = "wild",
|
||||||
|
Settlement = "settlement",
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A single node on the map.
|
||||||
|
*/
|
||||||
|
export interface MapNode {
|
||||||
|
/** Unique identifier */
|
||||||
|
id: string;
|
||||||
|
/** Which layer this node belongs to */
|
||||||
|
layerIndex: number;
|
||||||
|
/** Semantic type of the node */
|
||||||
|
type: MapNodeType;
|
||||||
|
/** IDs of nodes in the next layer this node connects to */
|
||||||
|
childIds: string[];
|
||||||
|
/** Encounter data assigned to this node (from encounter CSV) */
|
||||||
|
encounter?: EncounterData;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A horizontal layer of nodes at the same progression stage.
|
||||||
|
*/
|
||||||
|
export interface MapLayer {
|
||||||
|
/** Layer index (0 = start, last = end) */
|
||||||
|
index: number;
|
||||||
|
/** Ordered IDs of nodes in this layer */
|
||||||
|
nodeIds: string[];
|
||||||
|
/** Semantic type of the layer */
|
||||||
|
layerType: MapLayerType | "start" | "end";
|
||||||
|
/** Direct references to nodes in this layer (for performance) */
|
||||||
|
nodes: MapNode[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A fully generated point crawl map.
|
||||||
|
*/
|
||||||
|
export interface PointCrawlMap {
|
||||||
|
/** Layers from start to end */
|
||||||
|
layers: MapLayer[];
|
||||||
|
/** All nodes keyed by ID */
|
||||||
|
nodes: Map<string, MapNode>;
|
||||||
|
/** Reverse index: nodeId → parent node IDs (for fast getParent lookup) */
|
||||||
|
parentIndex?: Map<string, string[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PointCrawlMapNavigator {
|
||||||
|
currentNodeId: string;
|
||||||
|
visitedNodes: Set<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration for map generation.
|
||||||
|
*/
|
||||||
|
export interface MapGenerationConfig {
|
||||||
|
/** Total number of layers (including start and end) */
|
||||||
|
totalLayers: number;
|
||||||
|
/** Number of nodes in each wild layer */
|
||||||
|
wildLayerNodeCount: number;
|
||||||
|
/** Number of nodes in each settlement layer */
|
||||||
|
settlementLayerNodeCount: number;
|
||||||
|
/** Probability weights for wild node types (should sum to 100) */
|
||||||
|
wildNodeTypeWeights: {
|
||||||
|
[MapNodeType.Minion]: number;
|
||||||
|
[MapNodeType.Elite]: number;
|
||||||
|
[MapNodeType.Event]: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import {
|
||||||
|
Card,
|
||||||
|
Effect,
|
||||||
|
Encounter,
|
||||||
|
EncounterType,
|
||||||
|
Enemy,
|
||||||
|
Intent,
|
||||||
|
Item,
|
||||||
|
} from "../data/desert";
|
||||||
|
|
||||||
|
export type CardData = Card;
|
||||||
|
export type ItemData = Item;
|
||||||
|
export type EffectData = Effect;
|
||||||
|
export type IntentData = Intent;
|
||||||
|
export type EnemyData = Enemy;
|
||||||
|
export type EncounterData<T extends EncounterType = EncounterType> =
|
||||||
|
Encounter & { type: T };
|
||||||
|
|
||||||
|
export {
|
||||||
|
CardTargetType,
|
||||||
|
CardEffectTarget,
|
||||||
|
IntentEffectTarget,
|
||||||
|
} from "../data/desert";
|
||||||
|
|
||||||
|
export { ContentModule } from "../data";
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export * from "./parse-shape";
|
||||||
|
export * from "./shape-collision";
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user