96 lines
2.0 KiB
Markdown
96 lines
2.0 KiB
Markdown
# 棋子、区域与 RNG
|
|
|
|
## 创建和放置 Part
|
|
|
|
```ts
|
|
import { createPart, createRegion } from 'boardgame-core';
|
|
|
|
const board = createRegion('board', [
|
|
{ name: 'row', min: 0, max: 2 },
|
|
{ name: 'col', min: 0, max: 2 },
|
|
]);
|
|
|
|
const piece = createPart<{ owner: string }>(
|
|
{ regionId: 'board', position: [1, 1], owner: 'white' },
|
|
'piece-1'
|
|
);
|
|
|
|
state.produce(draft => {
|
|
draft.parts[piece.id] = piece;
|
|
draft.board.childIds.push(piece.id);
|
|
draft.board.partMap['1,1'] = piece.id;
|
|
});
|
|
```
|
|
|
|
## Part 池
|
|
|
|
```ts
|
|
const pool = createPartPool<{ type: string }>(
|
|
{ regionId: 'supply', type: 'kitten' },
|
|
10,
|
|
'kitten'
|
|
);
|
|
|
|
const piece = pool.draw(); // 取出一个
|
|
pool.return(piece); // 放回
|
|
pool.remaining(); // 剩余数量
|
|
```
|
|
|
|
## 从表格数据创建 Part
|
|
|
|
```ts
|
|
const parts = createPartsFromTable(
|
|
{ regionId: 'board', owner: 'white' },
|
|
[
|
|
{ id: 'p1', position: [0, 0] },
|
|
{ id: 'p2', position: [1, 1] },
|
|
],
|
|
'id'
|
|
);
|
|
```
|
|
|
|
## 查询棋子
|
|
|
|
```ts
|
|
// O(n) 遍历查找
|
|
findPartById(state.parts, 'piece-1');
|
|
getPartAtPosition(state.parts, 'board', [1, 1]);
|
|
isCellOccupied(state.parts, 'board', [1, 1]);
|
|
|
|
// O(1) 使用 Region.partMap 查找
|
|
getPartAtPositionInRegion(board, state.parts, [1, 1]);
|
|
isCellOccupiedByRegion(board, [1, 1]);
|
|
```
|
|
|
|
## 区域操作
|
|
|
|
```ts
|
|
import { applyAlign, shuffle, moveToRegion } from 'boardgame-core';
|
|
|
|
applyAlign(handRegion, state.parts); // 紧凑排列
|
|
shuffle(deckRegion, state.parts, rng); // 打乱
|
|
moveToRegion(piece, sourceRegion, targetRegion, [0, 0]);
|
|
```
|
|
|
|
## 翻面与掷骰
|
|
|
|
```ts
|
|
import { flip, flipTo, roll } from 'boardgame-core';
|
|
|
|
flip(piece); // 翻到下一面
|
|
flipTo(piece, 2); // 翻到指定面
|
|
roll(piece, rng); // 随机面
|
|
```
|
|
|
|
## RNG
|
|
|
|
```ts
|
|
import { createRNG } from 'boardgame-core';
|
|
|
|
const rng = createRNG(12345);
|
|
rng.nextInt(6); // 0-5
|
|
rng.next(); // [0, 1)
|
|
```
|
|
|
|
完整 API 列表详见 [API 参考](./api-reference.md)。
|