feat: Module 12, Combat (attack as one Sequence, Taunt, defender-first as a queue priority, end of turn; Bonechewer Brawler as the Expansion Drop)
Adds course/12-combat: lesson, scenarios, nine test_12 tests in both tracks, the cumulative reference (Module 11's plus combat) and the drop. The Damage action carries per-target hits with a priority; react stable-sorts its Queue by priority before order of play, so the triggers answering the defender's Damage Event go first. orderAttack/canAttack/endTurn join the harness (orderAttack because attack(id) already reads Attack). endOfTurn triggers fire, so Drakkari Enchanter's data is live. Test Bell is scoped to Module 12's cards. Harness contract, catalog, research notes and earlier lessons' forward pointers follow. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c8fff05ccb
commit
fb9d0a4eb4
89 files changed
+11852
-6
No files matched your search
@@ -0,0 +1 @@
|
||||
{ "track": "ts", "engineDirs": ["src/engine"], "contentDirs": ["src/content", "cards"], "module": "12" }
|
||||
@@ -0,0 +1 @@
|
||||
node_modules/
|
||||
@@ -0,0 +1,14 @@
|
||||
# Module 12 reference engine (TypeScript)
|
||||
|
||||
The course's own engine as of the end of Module 12: Module 11's engine (Part I's card engine, Part II's grid engine with conditions, and SpellGrid joining them), with combat and the end of a turn in Part I. Every test from Modules 1–11 still passes. Module 11's reference was the starting point, so a diff between the two shows what this module adds. `course/11-conditions/reference/ts/README.md` and the READMEs it points to describe everything else.
|
||||
|
||||
- `cards/` and `levels/` (at the package root; not in this directory): staged by `tools/verify-references.mjs` as for Module 11, plus `course/12-combat/cards/` (`Test Bell`).
|
||||
- Part I (`src/engine/`):
|
||||
- `combat.ts` (new): `attackError(world, attacker, defender)`, the legality rules (a minion in play attacks an enemy character in play, with more than 0 Attack, and a Taunt minion if the defender's side has one), and `TAUNT`.
|
||||
- `card.ts`: `Card.keywords`, compiled from keyword clauses. `"endOfTurn"` now fires.
|
||||
- `event.ts`: `{ type: "TurnEnded", player }`, which end of turn triggers answer. The course's log doesn't show it.
|
||||
- `queue.ts`: the `damage` action carries `hits`, each a target, an amount and a `Priority` (`hits(targets, amount)` builds the usual one-amount list). `react` takes the priority of each event's entries and sorts its Queue by priority, highest first, keeping the order it was filled in within one priority. The `attack` action builds one Damage action: the attacker's Attack to the defender at priority `DEFENDER`, and the defender's Attack (if more than 0) to the attacker at `NORMAL`. The `endTurn` action records `TurnEnded` and resolves the triggers that answer it.
|
||||
- `src/harness.ts`: `orderAttack(attacker, defender)` (throws an `Error` with the reason if the attack is illegal), `canAttack(attacker, defender): string | null` and `endTurn(player)` on `Game`.
|
||||
- Part II, Part III and `src/cli.ts`: unchanged from Module 11. SpellGrid doesn't attack. `tools/diff-tracks.mjs` uses this module's CLIs by default.
|
||||
|
||||
Run it with the module's tests: `node tools/verify-references.mjs 12` from the course repository.
|
||||
+2018
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "systemic-design-workspace",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.20.5",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^5.6.0",
|
||||
"vitest": "^2.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// SpellGrid on the command line: `npx tsx src/cli.ts levels/l1-double-tap.json`.
|
||||
//
|
||||
// A thin loop over the harness: it draws the level, reads a command, and calls
|
||||
// `step`, `cast` or `play`. No rules live here. After a command that ran Part I
|
||||
// Sequences, it prints their events under `Log:` as an indented tree.
|
||||
//
|
||||
// w a s d one turn: up, left, down, right
|
||||
// c <card> [x y] cast a spell from your hand (at the minion on (x, y), if given),
|
||||
// or play a minion from your hand onto the empty tile (x, y)
|
||||
// q quit
|
||||
//
|
||||
// Assemble's choices (Graft) are asked for one at a time: answer with a number or a name.
|
||||
|
||||
import { readFileSync, readSync } from "node:fs";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { newSpellGrid, type LevelDef, type SpellGrid } from "./harness";
|
||||
|
||||
const DIRS = { w: "up", a: "left", s: "down", d: "right" } as const;
|
||||
|
||||
/** One cell of the drawing: the newest object on the tile, as 3 letters; TEXT in capitals. */
|
||||
function cell(g: SpellGrid, x: number, y: number): string {
|
||||
const kinds = g.kindsAt(x, y);
|
||||
if (kinds.length === 0) return " . ";
|
||||
// kindsAt is sorted; prefer text, which is what the player reads.
|
||||
const kind = kinds.find((k) => k.startsWith("text:")) ?? kinds[0];
|
||||
const name = kind.startsWith("text:") ? kind.slice(5).toUpperCase() : kind.toLowerCase();
|
||||
return name.slice(0, 3).padEnd(3);
|
||||
}
|
||||
|
||||
/** The level as text: the grid, the rules, the minions and the hand. */
|
||||
export function render(g: SpellGrid, level: LevelDef): string {
|
||||
const lines: string[] = [];
|
||||
for (let y = 0; y < level.height; y++) {
|
||||
const row: string[] = [];
|
||||
for (let x = 0; x < level.width; x++) row.push(cell(g, x, y));
|
||||
lines.push(row.join(" "));
|
||||
}
|
||||
lines.push(`Rules: ${g.activeRules().join(", ")}`);
|
||||
const minions: string[] = [];
|
||||
for (let y = 0; y < level.height; y++) {
|
||||
for (let x = 0; x < level.width; x++) {
|
||||
const id = g.minionAt(x, y);
|
||||
if (id !== null) minions.push(`${g.nameOf(id)} (${x},${y}) ${g.health(id)} Health`);
|
||||
}
|
||||
}
|
||||
lines.push(`Minions: ${minions.join("; ") || "none"}`);
|
||||
lines.push(`Hand: ${g.hand().join(", ") || "empty"}`);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/** A coordinate, or a chooser's number: one to nine digits, nothing else (no sign, no point). */
|
||||
const NUMBER = /^\d{1,9}$/;
|
||||
|
||||
/** A `c` command: `c <card words...> [x y]`. */
|
||||
function parseCast(args: string[]): { card: string; at?: [number, number] } {
|
||||
const n = args.length;
|
||||
if (n >= 3 && NUMBER.test(args[n - 2]) && NUMBER.test(args[n - 1])) {
|
||||
return { card: args.slice(0, n - 2).join(" "), at: [Number(args[n - 2]), Number(args[n - 1])] };
|
||||
}
|
||||
return { card: args.join(" ") };
|
||||
}
|
||||
|
||||
/**
|
||||
* Play `levelText` (a level in the course's format), reading commands from
|
||||
* `readLine` (undefined at the end of input) and writing to `write`. Returns
|
||||
* `"won"`, `"lost"` or `"quit"`.
|
||||
*/
|
||||
export function run(levelText: string, readLine: () => string | undefined, write: (s: string) => void): string {
|
||||
const level = JSON.parse(levelText) as LevelDef;
|
||||
const g = newSpellGrid(level, []);
|
||||
g.setChooser((kind, options) => {
|
||||
write(`Choose the ${kind} (a number or a name):\n${options.map((o, i) => ` ${i + 1}) ${o}`).join("\n")}\n? `);
|
||||
const answer = readLine()?.trim() ?? "";
|
||||
if (options.includes(answer)) return answer;
|
||||
return (NUMBER.test(answer) ? options[Number(answer) - 1] : undefined) ?? options[0];
|
||||
});
|
||||
for (;;) {
|
||||
write(`${render(g, level)}\n`);
|
||||
if (g.won()) {
|
||||
write("You win!\n");
|
||||
return "won";
|
||||
}
|
||||
if (g.lost()) {
|
||||
write("Nothing is YOU. You lose.\n");
|
||||
return "lost";
|
||||
}
|
||||
write("> ");
|
||||
const line = readLine();
|
||||
if (line === undefined) return "quit";
|
||||
const [command, ...args] = line.trim().split(/\s+/);
|
||||
// The log holds only what this command does.
|
||||
g.clearLog();
|
||||
try {
|
||||
if (command === "q") return "quit";
|
||||
if (command in DIRS) g.step(DIRS[command as keyof typeof DIRS]);
|
||||
else if (command === "c" && args.length > 0) {
|
||||
const { card, at } = parseCast(args);
|
||||
const target = at === undefined ? null : g.minionAt(...at);
|
||||
if (at === undefined) g.cast(card);
|
||||
else if (target !== null) g.cast(card, target);
|
||||
else g.play(card, ...at);
|
||||
} else write("Commands: w a s d (move), c <card> [x y] (cast or play), q (quit)\n");
|
||||
} catch (e) {
|
||||
write(`${e instanceof Error ? e.message : String(e)}\n`);
|
||||
}
|
||||
const tree = g.logTree();
|
||||
if (tree !== "") write(`Log:\n${tree}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Lines from standard input, read synchronously, so the chooser can ask mid-Sequence. */
|
||||
function stdinLines(): () => string | undefined {
|
||||
const buffer = Buffer.alloc(4096);
|
||||
let pending = "";
|
||||
let ended = false;
|
||||
return () => {
|
||||
while (!pending.includes("\n") && !ended) {
|
||||
const n = readSync(0, buffer, 0, buffer.length, null);
|
||||
if (n === 0) ended = true;
|
||||
else pending += buffer.toString("utf8", 0, n);
|
||||
}
|
||||
if (pending === "" && ended) return undefined;
|
||||
const end = pending.indexOf("\n");
|
||||
const line = end < 0 ? pending : pending.slice(0, end);
|
||||
pending = end < 0 ? "" : pending.slice(end + 1);
|
||||
return line;
|
||||
};
|
||||
}
|
||||
|
||||
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
const path = process.argv[2];
|
||||
if (path === undefined) {
|
||||
process.stderr.write("usage: npx tsx src/cli.ts <level.json>\n");
|
||||
process.exit(2);
|
||||
}
|
||||
const outcome = run(readFileSync(path, "utf8"), stdinLines(), (s) => process.stdout.write(s));
|
||||
process.exit(outcome === "won" ? 0 : 1);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Part II: what each condition word means (Module 11). The engine asks these checks
|
||||
// every time it is about to use a rule with a condition, for one object, against the
|
||||
// board as it is then. A new condition word is one entry in `words.json`, with role
|
||||
// "condition", and one check here.
|
||||
|
||||
import type { puzzle } from "../engine";
|
||||
|
||||
type Level = puzzle.Level;
|
||||
type ObjectId = puzzle.ObjectId;
|
||||
|
||||
/**
|
||||
* Can each noun be given an object of its own among `others`, one the noun names?
|
||||
* `ON ROCK AND ROCK` needs two rocks (the wiki: "AND in the noun2 part requires at
|
||||
* least as many objects as are mentioned"). Tries every assignment.
|
||||
*/
|
||||
function eachHasOne(level: Level, nouns: readonly string[], others: readonly ObjectId[]): boolean {
|
||||
const taken = new Set<ObjectId>();
|
||||
const assign = (i: number): boolean => {
|
||||
if (i === nouns.length) return true;
|
||||
for (const other of others) {
|
||||
if (taken.has(other) || !level.names(nouns[i], other)) continue;
|
||||
taken.add(other);
|
||||
if (assign(i + 1)) return true;
|
||||
taken.delete(other);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
return assign(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* ON: for each noun, another object on the object's tile that the noun names, a
|
||||
* different one for each noun. Float levels don't matter ("ON ignores FLOAT levels").
|
||||
*/
|
||||
function on(level: Level, id: ObjectId, nouns: readonly string[]): boolean {
|
||||
const o = level.board.get(id);
|
||||
const others = level.board
|
||||
.at(o.x, o.y)
|
||||
.map((other) => other.id)
|
||||
.filter((other) => other !== id);
|
||||
return eachHasOne(level, nouns, others);
|
||||
}
|
||||
|
||||
/** The condition checks, by condition word. */
|
||||
export function conditions(): puzzle.ConditionChecks {
|
||||
return { ON: on };
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Part II: what destroys what at the end of a turn. The engine runs these
|
||||
// hazards in this order (the order of the wiki's `block()`: SINK, then HOT/MELT,
|
||||
// then DEFEAT), and destroys each one's victims together before the next runs.
|
||||
// A hazard only reaches objects on the same float level: it asks the level what
|
||||
// shares a tile (`Level.sharing`). A new hazard property is one more function here.
|
||||
|
||||
import type { puzzle } from "../engine";
|
||||
|
||||
type Level = puzzle.Level;
|
||||
type ObjectId = puzzle.ObjectId;
|
||||
|
||||
/** The objects that have `property`, oldest first. */
|
||||
const withProperty = (level: Level, property: string): ObjectId[] =>
|
||||
level.board
|
||||
.objects()
|
||||
.map((o) => o.id)
|
||||
.filter((id) => level.hasProperty(id, property));
|
||||
|
||||
/** A SINK object that shares its tile with anything destroys all of it, and itself. */
|
||||
function sink(level: Level): ObjectId[] {
|
||||
const doomed: ObjectId[] = [];
|
||||
for (const id of withProperty(level, "SINK")) {
|
||||
const others = level.sharing(id);
|
||||
if (others.length > 0) doomed.push(id, ...others);
|
||||
}
|
||||
return doomed;
|
||||
}
|
||||
|
||||
/** A MELT object is destroyed if it is HOT itself, or shares its tile with a HOT one. */
|
||||
function hotMelt(level: Level): ObjectId[] {
|
||||
return destroyedBy(level, "MELT", "HOT");
|
||||
}
|
||||
|
||||
/** A YOU object is destroyed if it is DEFEAT itself, or shares its tile with a DEFEAT one. */
|
||||
function defeat(level: Level): ObjectId[] {
|
||||
return destroyedBy(level, "YOU", "DEFEAT");
|
||||
}
|
||||
|
||||
/** The objects with `victim` that have `killer` too, or share a tile with one that does. */
|
||||
function destroyedBy(level: Level, victim: string, killer: string): ObjectId[] {
|
||||
const deadly = (id: ObjectId) => level.hasProperty(id, killer);
|
||||
return withProperty(level, victim).filter((id) => deadly(id) || level.sharing(id).some(deadly));
|
||||
}
|
||||
|
||||
/** The hazards, in the order the engine runs them. */
|
||||
export function hazards(): puzzle.Hazard[] {
|
||||
return [sink, hotMelt, defeat];
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Content: the cards and the Baba Is You words. Only this directory (and the card
|
||||
// data in `cards/`) may name specific cards, or specific Baba Is You nouns.
|
||||
//
|
||||
// From Module 5 every card is a JSON file in `cards/` at the package root, in the
|
||||
// course's card format (`course/schema/card.schema.json`). The functions that were
|
||||
// card effects in Modules 2–4 are gone: the engine interprets the data.
|
||||
// `start-module` copies the course's card files into `cards/`; add your own there.
|
||||
//
|
||||
// Module 10: the cards are read with Node's file system, not Vite's `import.meta.glob`,
|
||||
// so the SpellGrid command line (`npx tsx src/cli.ts`), which runs without Vite, reads
|
||||
// the same cards as the tests.
|
||||
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import type { CardDef, puzzle, SeamWords } from "../engine";
|
||||
import seamWords from "./seams.json";
|
||||
import wordList from "./words.json";
|
||||
|
||||
export { conditions } from "./conditions";
|
||||
export { hazards } from "./hazards";
|
||||
export { responses as movement } from "./movement";
|
||||
|
||||
const CARDS = new URL("../../cards/", import.meta.url);
|
||||
let loaded: CardDef[] | undefined;
|
||||
|
||||
/** Every card in `cards/`, in file-name order. Read once. */
|
||||
export function cards(): CardDef[] {
|
||||
loaded ??= readdirSync(CARDS)
|
||||
.filter((file) => file.endsWith(".json"))
|
||||
.sort()
|
||||
.map((file) => JSON.parse(readFileSync(new URL(file, CARDS), "utf8")) as CardDef);
|
||||
return loaded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Part II: the words of Baba Is You the parser can read, besides the engine's own
|
||||
* (`IS`, `AND`, `NOT`, `TEXT`). Nouns and properties are data: a new word is one
|
||||
* more entry in `words.json` in this directory. A condition word (Module 11) also
|
||||
* needs its check in `conditions.ts`.
|
||||
*/
|
||||
export function words(): puzzle.WordDef[] {
|
||||
return wordList as puzzle.WordDef[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Part III: the words that cross between the engines (`seams.json`). A noun that
|
||||
* names a trigger, and a property that multiplies one: `DEATHRATTLE IS DOUBLE`.
|
||||
*/
|
||||
export function seams(): SeamWords {
|
||||
return seamWords as SeamWords;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Part II: what each property does when an object moves. The engine plans a move
|
||||
// one step at a time and runs these responses for every step, in this order (the
|
||||
// order of the wiki's movement checks: OPEN/SHUT, then PUSH, then STOP). A new
|
||||
// movement property is one more response here.
|
||||
|
||||
import type { puzzle } from "../engine";
|
||||
|
||||
type Planner = puzzle.Planner;
|
||||
type Step = puzzle.Step;
|
||||
|
||||
/**
|
||||
* An OPEN object stepping onto a SHUT one (or a SHUT one onto an OPEN one)
|
||||
* destroys both, and that object doesn't block the step. One partner per step:
|
||||
* the oldest.
|
||||
*/
|
||||
function openShut(p: Planner, s: Step): boolean {
|
||||
for (const [mine, theirs] of [
|
||||
["OPEN", "SHUT"],
|
||||
["SHUT", "OPEN"],
|
||||
]) {
|
||||
if (!p.has(s.mover, mine)) continue;
|
||||
const partner = p.stayingAt(s.to).find((o) => p.has(o, theirs));
|
||||
if (partner !== undefined) {
|
||||
p.destroy(partner);
|
||||
p.destroy(s.mover);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Every PUSH object on the tile ahead must step the same way, or the step fails. */
|
||||
function push(p: Planner, s: Step): boolean {
|
||||
return p.stayingAt(s.to).every((o) => !p.has(o, "PUSH") || p.tryMove(o));
|
||||
}
|
||||
|
||||
/** A STOP object still on the tile ahead blocks the step. */
|
||||
function stop(p: Planner, s: Step): boolean {
|
||||
return !p.stayingAt(s.to).some((o) => p.has(o, "STOP"));
|
||||
}
|
||||
|
||||
/** The movement responses, in the order the engine runs them. */
|
||||
export function responses(): puzzle.Response[] {
|
||||
return [openShut, push, stop];
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"triggerWords": { "DEATHRATTLE": "deathrattle" },
|
||||
"multiplierWords": { "DOUBLE": { "times": 2, "stacking": "max" } }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
[
|
||||
{ "name": "BABA", "role": "noun" },
|
||||
{ "name": "ROCK", "role": "noun" },
|
||||
{ "name": "WALL", "role": "noun" },
|
||||
{ "name": "FLAG", "role": "noun" },
|
||||
{ "name": "LAVA", "role": "noun" },
|
||||
{ "name": "KEY", "role": "noun" },
|
||||
{ "name": "DOOR", "role": "noun" },
|
||||
{ "name": "SKULL", "role": "noun" },
|
||||
{ "name": "WATER", "role": "noun" },
|
||||
{ "name": "ALL", "role": "noun", "selects": "things" },
|
||||
{ "name": "KEG", "role": "noun" },
|
||||
{ "name": "BRAMBLE", "role": "noun" },
|
||||
{ "name": "HEDGE", "role": "noun" },
|
||||
{ "name": "WARDEN", "role": "noun" },
|
||||
{ "name": "MOTH", "role": "noun" },
|
||||
{ "name": "SCRIBE", "role": "noun" },
|
||||
{ "name": "KNIGHT", "role": "noun" },
|
||||
{ "name": "CRIER", "role": "noun" },
|
||||
{ "name": "GOLEM", "role": "noun" },
|
||||
{ "name": "SHARD", "role": "noun" },
|
||||
{ "name": "DEATHRATTLE", "role": "noun" },
|
||||
{ "name": "ON", "role": "condition" },
|
||||
{ "name": "YOU", "role": "property" },
|
||||
{ "name": "WIN", "role": "property" },
|
||||
{ "name": "PUSH", "role": "property" },
|
||||
{ "name": "STOP", "role": "property" },
|
||||
{ "name": "OPEN", "role": "property" },
|
||||
{ "name": "SHUT", "role": "property" },
|
||||
{ "name": "HOT", "role": "property" },
|
||||
{ "name": "MELT", "role": "property" },
|
||||
{ "name": "SINK", "role": "property" },
|
||||
{ "name": "DEFEAT", "role": "property" },
|
||||
{ "name": "FLOAT", "role": "property" },
|
||||
{ "name": "DOUBLE", "role": "property" }
|
||||
]
|
||||
@@ -0,0 +1,117 @@
|
||||
// Assemble: "Get a random minion. Change half its text."
|
||||
//
|
||||
// Card text is a list of clauses, so changing half of it is list surgery: the base
|
||||
// card's `text.slice(0, split)` (top) or `text.slice(split)` (bottom) is replaced by
|
||||
// the same half of a donor card. Name, cost and stats stay the base's. This works
|
||||
// only because a card's behaviour is its data: the new card needs no new code.
|
||||
//
|
||||
// Hearthstone's wiki doesn't define "half". The course's `split` field is its
|
||||
// definition: each card's data says where its top half ends.
|
||||
|
||||
import { hasTrigger, wellFormed, type CardDef, type PoolFilter } from "./card";
|
||||
import type { EntityId, PlayerId, World } from "./world";
|
||||
|
||||
export type Half = "top" | "bottom";
|
||||
const HALVES: Half[] = ["top", "bottom"];
|
||||
|
||||
/** Why an Assemble was refused: the text would not change, or would not be well-formed (see `wellFormed`). */
|
||||
export type AssembleFailure = "unchanged" | "illFormed";
|
||||
|
||||
/** Assembling `base` with `donor`'s `half` would leave the base's text unchanged, or ill-formed. */
|
||||
export class AssembleError extends Error {
|
||||
constructor(
|
||||
readonly base: string,
|
||||
readonly donor: string,
|
||||
readonly half: Half,
|
||||
readonly reason: AssembleFailure,
|
||||
) {
|
||||
const result = reason === "unchanged" ? "leaves its text unchanged" : "gives ill-formed text";
|
||||
super(`assembling "${base}" with the ${half} half of "${donor}" ${result}`);
|
||||
this.name = "AssembleError";
|
||||
}
|
||||
}
|
||||
|
||||
/** JSON with object keys sorted, so two clauses written with their keys in a different order compare equal. */
|
||||
const canonical = (value: unknown): string =>
|
||||
JSON.stringify(value, (_key, v) =>
|
||||
v && typeof v === "object" && !Array.isArray(v)
|
||||
? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : 1)))
|
||||
: v,
|
||||
);
|
||||
const sameText = (a: CardDef["text"], b: CardDef["text"]): boolean => canonical(a) === canonical(b);
|
||||
/** Two definitions the engine can't tell apart (it ignores `fictional` and `game`). */
|
||||
const sameCard = (a: CardDef, b: CardDef): boolean => {
|
||||
const read = (d: CardDef) =>
|
||||
canonical([d.name, d.type, d.cost, d.attack ?? 0, d.health ?? 0, d.noun ?? null, d.text, d.split]);
|
||||
return read(a) === read(b);
|
||||
};
|
||||
|
||||
/**
|
||||
* The base card with `half` of its text replaced by the same half of `donor`.
|
||||
* It keeps the base's type, cost and stats, and is named "<base> (Assembled)".
|
||||
*/
|
||||
export function assemble(base: CardDef, donor: CardDef, half: Half): CardDef {
|
||||
const topOf = (c: CardDef) => c.text.slice(0, c.split);
|
||||
const bottomOf = (c: CardDef) => c.text.slice(c.split);
|
||||
const top = half === "top" ? topOf(donor) : topOf(base);
|
||||
const bottom = half === "bottom" ? bottomOf(donor) : bottomOf(base);
|
||||
const text = [...top, ...bottom];
|
||||
if (sameText(text, base.text)) throw new AssembleError(base.name, donor.name, half, "unchanged");
|
||||
if (!wellFormed(text, base.type)) throw new AssembleError(base.name, donor.name, half, "illFormed");
|
||||
return { ...base, name: `${base.name} (Assembled)`, text, split: top.length };
|
||||
}
|
||||
|
||||
/** Does assembling `base` with `donor`'s `half` give a new, well-formed text? */
|
||||
const changes = (base: CardDef, donor: CardDef, half: Half): boolean => {
|
||||
try {
|
||||
assemble(base, donor, half);
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (e instanceof AssembleError) return false;
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Register an assembled card and return its name. If a different card already has
|
||||
* the name (an earlier Assemble of the same base), a number is added: "(Assembled 2)".
|
||||
*/
|
||||
export function registerAssembled(world: World, def: CardDef): string {
|
||||
const stem = def.name.replace(/\)$/, "");
|
||||
let name = def.name;
|
||||
// A different card is any difference the engine reads: the text, the split, or a base re-registered since.
|
||||
for (let n = 2; world.hasCard(name) && !sameCard(world.card(name).def, { ...def, name }); n++) {
|
||||
name = `${stem} ${n})`;
|
||||
}
|
||||
world.registerAssembled({ ...def, name });
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `assemble` effect: the owner's chooser picks a base minion from the pool
|
||||
* (filtered), a donor, and the half to replace. Only combinations that change the
|
||||
* base's text and leave it well-formed are offered: a donor is offered if one of its
|
||||
* halves gives such a text, and a base if it has such a donor. The Assembled minion
|
||||
* goes to the owner's hand. Real Hearthstone picks the base at random and offers two
|
||||
* donors; here every choice is the chooser's.
|
||||
*/
|
||||
export function assembleFromPool(world: World, player: PlayerId, filter: PoolFilter): EntityId | undefined {
|
||||
const pool = world.pool();
|
||||
const donorsFor = (base: CardDef): string[] =>
|
||||
pool
|
||||
.map((c) => c.def)
|
||||
.filter((d) => d.name !== base.name && HALVES.some((h) => changes(base, d, h)))
|
||||
.map((d) => d.name);
|
||||
const bases = pool
|
||||
.filter((c) => (filter.trigger === undefined || hasTrigger(c, filter.trigger)) && donorsFor(c.def).length > 0)
|
||||
.map((c) => c.def.name);
|
||||
if (bases.length === 0) return undefined;
|
||||
const base = world.card(world.choose("base", bases)).def;
|
||||
const donor = world.card(world.choose("donor", donorsFor(base))).def;
|
||||
const half = world.choose(
|
||||
"half",
|
||||
HALVES.filter((h) => changes(base, donor, h)),
|
||||
) as Half;
|
||||
const name = registerAssembled(world, assemble(base, donor, half));
|
||||
return world.create(name, player, "hand");
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// Auras, the one routine that applies trigger multipliers, and the lookup for
|
||||
// damage redirects.
|
||||
//
|
||||
// An aura is data on a card: a continuous effect its minion has while in play.
|
||||
// The engine never asks "is that card on the board?" in the middle of resolving
|
||||
// something. It takes a snapshot of the auras in force at defined points (an Aura
|
||||
// Update) and every rule reads the snapshot.
|
||||
//
|
||||
// Hearthstone runs two kinds of Aura Update when the outermost Phase ends: one for
|
||||
// Health/Attack auras before the Death Creation Step, and one for every other aura
|
||||
// after it. Trigger multipliers are "Other" auras, so a minion that dies in a Death
|
||||
// Creation Step no longer multiplies the Deathrattles of that step's Death Phase.
|
||||
// Summoning a minion also runs an Aura Update.
|
||||
//
|
||||
// Module 10: auras can come from outside the cards. SpellGrid compiles rules on its
|
||||
// grid into auras (`World.setRuleAuras`); they join the snapshot at the next Aura
|
||||
// Update, beside the minions' own, and go through the same routine. A rule's
|
||||
// multiplier stacks with a card's by the same `stacking` field. A cap (`IS NOT`)
|
||||
// limits the total, whatever multiplies it.
|
||||
|
||||
import type { TriggerOn } from "./card";
|
||||
import type { EntityId, PlayerId, World } from "./world";
|
||||
|
||||
/**
|
||||
* Aura Update (Other): replace the snapshot with the auras of every minion now in
|
||||
* play, and the auras from outside the cards, which apply to both players.
|
||||
*/
|
||||
export function auraUpdateOther(world: World): void {
|
||||
const players: PlayerId[] = [0, 1];
|
||||
world.setActiveAuras([
|
||||
...world.minionsInPlay().flatMap((id) =>
|
||||
world.card(world.cardName(id)).auras.map((aura) => ({ owner: world.ownerOf(id), source: id, aura })),
|
||||
),
|
||||
...world.ruleAuras().flatMap((aura) => players.map((owner) => ({ owner, aura }))),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The minion that takes damage meant for `player`'s hero, if a redirect is in force:
|
||||
* the oldest (order of play) of `player`'s minions with a `damageRedirect` aura in the
|
||||
* snapshot. The snapshot lists minions oldest first, so that is the first one found.
|
||||
*/
|
||||
export function redirectFor(world: World, player: PlayerId): EntityId | undefined {
|
||||
return world.activeAuras().find((a) => a.aura.type === "damageRedirect" && a.owner === player)?.source;
|
||||
}
|
||||
|
||||
/**
|
||||
* How many times a trigger listening for `on`, on a minion `owner` controls, activates
|
||||
* when it resolves. Reads the snapshot from the last Aura Update. With no multiplier in
|
||||
* force the answer is 1. Multipliers with `stacking: "max"` contribute their largest
|
||||
* `times`; each `"additive"` one adds `times - 1` extra activations. A cap
|
||||
* (`triggerCap`) then limits the total to its `times`.
|
||||
*/
|
||||
export function activations(world: World, owner: PlayerId, on: TriggerOn): number {
|
||||
let max = 1;
|
||||
let extra = 0;
|
||||
let cap = Infinity;
|
||||
for (const { owner: auraOwner, aura } of world.activeAuras()) {
|
||||
if (aura.type === "damageRedirect" || auraOwner !== owner || aura.trigger !== on) continue;
|
||||
if (aura.type === "triggerCap") cap = Math.min(cap, aura.times);
|
||||
else if (aura.stacking === "max") max = Math.max(max, aura.times);
|
||||
else extra += aura.times - 1;
|
||||
}
|
||||
return Math.min(cap, max + extra);
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
// Cards as data. A `CardDef` is the course's card format (`course/schema/card.schema.json`),
|
||||
// read straight from JSON. The engine compiles each definition once, when it is
|
||||
// registered, into the lists it reads while resolving: triggers, auras and a
|
||||
// spell's effects. The definitions themselves live in `cards/`, loaded by `content`.
|
||||
|
||||
/** What a triggered ability listens for. */
|
||||
export type TriggerOn =
|
||||
| "selfDamaged" // this minion takes damage
|
||||
| "friendlyMinionDamaged" // a minion with the same owner (this one included) takes damage
|
||||
| "anyMinionDamaged" // any minion takes damage
|
||||
| "heroDamaged" // either hero takes damage
|
||||
| "deathrattle" // this minion dies (it resolves after the minion has left play)
|
||||
| "battlecry" // this minion is played from hand
|
||||
| "endOfTurn"; // the end of its owner's turn (Module 12: `endTurn`)
|
||||
|
||||
/** The trigger's family name, as reported in `Triggered` events. */
|
||||
export function triggerLabel(on: TriggerOn): string {
|
||||
switch (on) {
|
||||
case "selfDamaged":
|
||||
case "friendlyMinionDamaged":
|
||||
case "anyMinionDamaged":
|
||||
case "heroDamaged":
|
||||
return "damaged";
|
||||
case "deathrattle":
|
||||
case "battlecry":
|
||||
case "endOfTurn":
|
||||
return on;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An aura: a continuous effect a minion has while it is in play. The engine reads
|
||||
* auras only at the Aura Update points (see `aura.ts`), never mid-Phase.
|
||||
*
|
||||
* `triggerMultiplier`: triggers listening for `trigger`, belonging to minions with
|
||||
* the aura owner's owner, activate `times` times each. `stacking` says how several
|
||||
* multipliers for the same trigger combine: `"max"` takes the largest (two copies of
|
||||
* a doubler still double); `"additive"` adds each copy's extra activations.
|
||||
*/
|
||||
export type Aura =
|
||||
| { type: "triggerMultiplier"; trigger: TriggerOn; times: number; stacking: "max" | "additive" }
|
||||
/**
|
||||
* Damage that would be dealt to the aura owner's hero is dealt to the aura's minion
|
||||
* instead (see `DAMAGE_STEPS` in `queue.ts`).
|
||||
*/
|
||||
| { type: "damageRedirect"; from: "friendlyHero"; to: "self" }
|
||||
/**
|
||||
* Module 10: triggers listening for `trigger` activate at most `times` times, whatever
|
||||
* multiplies them. Not in the card format: SpellGrid compiles it from a negated rule
|
||||
* (`DEATHRATTLE IS NOT DOUBLE`).
|
||||
*/
|
||||
| { type: "triggerCap"; trigger: TriggerOn; times: number };
|
||||
|
||||
/** Who an effect touches. */
|
||||
export type Target = "self" | "allMinions" | "allOtherMinions" | "allOtherCharacters" | "enemyHero" | "chosen";
|
||||
|
||||
/** Which minions an Assemble may pick as its base. An empty filter allows any. */
|
||||
export interface PoolFilter {
|
||||
/** Only minions with a trigger clause listening for this. */
|
||||
trigger?: TriggerOn;
|
||||
}
|
||||
|
||||
/** One effect: a node of a card's ability, interpreted by `effect.ts`. */
|
||||
export type Effect =
|
||||
| { type: "dealDamage"; target: Target; amount: number }
|
||||
| { type: "draw"; count: number }
|
||||
| { type: "summon"; card: string; count: number }
|
||||
| { type: "gainArmor"; amount: number }
|
||||
| { type: "gainAttack"; target: Target; amount: number }
|
||||
| { type: "destroy"; target: Target }
|
||||
/** Part III (SpellGrid) only: puts a word on the grid. */
|
||||
| { type: "spawnText"; word: string; at: "self" }
|
||||
/** Get a minion from the pool, with half its text replaced (see `assemble.ts`). */
|
||||
| { type: "assemble"; filter: PoolFilter }
|
||||
/** Give every minion in the owner's hand +attack/+health. */
|
||||
| { type: "buffHand"; attack: number; health: number };
|
||||
|
||||
/**
|
||||
* One line of card text. A trigger clause applies to the effect clauses after it,
|
||||
* until the next trigger, keyword or aura. Effects before any trigger are what a
|
||||
* spell does when cast.
|
||||
*/
|
||||
export type Clause =
|
||||
| { kind: "keyword"; keyword: string }
|
||||
| { kind: "trigger"; on: TriggerOn }
|
||||
| { kind: "aura"; modifier: Aura }
|
||||
| { kind: "effect"; effect: Effect };
|
||||
|
||||
/** A card as data, in the course's card format. */
|
||||
export interface CardDef {
|
||||
name: string;
|
||||
type: "minion" | "spell";
|
||||
cost: number;
|
||||
attack?: number;
|
||||
health?: number;
|
||||
noun?: string;
|
||||
text: Clause[];
|
||||
/** `text.slice(0, split)` is the top half, `text.slice(split)` the bottom half. */
|
||||
split: number;
|
||||
fictional?: boolean;
|
||||
game?: string;
|
||||
}
|
||||
|
||||
/** A triggered ability: "whenever <on>, <effects>". */
|
||||
export interface Trigger {
|
||||
on: TriggerOn;
|
||||
effects: Effect[];
|
||||
}
|
||||
|
||||
/** A registered card: its definition, and the definition's text compiled into the lists the engine reads. */
|
||||
export interface Card {
|
||||
def: CardDef;
|
||||
/** Triggered abilities, in printed order. */
|
||||
triggers: Trigger[];
|
||||
/** Auras this minion has while in play. */
|
||||
auras: Aura[];
|
||||
/** Keywords, such as `"taunt"` (Module 12: combat reads it). */
|
||||
keywords: string[];
|
||||
/** What the card does when cast (a spell's effects). */
|
||||
onCast: Effect[];
|
||||
/** May an Assemble offer this card? Minions with text that were not themselves assembled. */
|
||||
inPool: boolean;
|
||||
}
|
||||
|
||||
/** Compile a definition's text. Throws if `split` is past the end of the text. */
|
||||
export function compile(def: CardDef, inPool: boolean): Card {
|
||||
if (def.split > def.text.length) throw new Error(`"${def.name}": split ${def.split} is past the end of its text`);
|
||||
const card: Card = { def, triggers: [], auras: [], keywords: [], onCast: [], inPool: false };
|
||||
// The trigger whose effects are still being listed, if any.
|
||||
let open: Trigger | undefined;
|
||||
for (const clause of def.text) {
|
||||
switch (clause.kind) {
|
||||
case "trigger":
|
||||
open = { on: clause.on, effects: [] };
|
||||
card.triggers.push(open);
|
||||
break;
|
||||
case "effect":
|
||||
(open ? open.effects : card.onCast).push(clause.effect);
|
||||
break;
|
||||
case "aura":
|
||||
card.auras.push(clause.modifier);
|
||||
open = undefined;
|
||||
break;
|
||||
case "keyword": // Module 12: combat reads Taunt (`combat.ts`).
|
||||
card.keywords.push(clause.keyword);
|
||||
open = undefined;
|
||||
break;
|
||||
}
|
||||
}
|
||||
card.inPool = inPool && def.type === "minion" && def.text.length > 0;
|
||||
return card;
|
||||
}
|
||||
|
||||
export const hasTrigger = (card: Card, on: TriggerOn): boolean => card.triggers.some((t) => t.on === on);
|
||||
|
||||
/**
|
||||
* Does `text` mean what it says? For a minion, every effect clause belongs to a
|
||||
* trigger (none comes before the first trigger, or after an aura or keyword), and
|
||||
* every trigger has at least one effect before the next trigger, aura, keyword or
|
||||
* the end. The rule is for minions (Assemble makes only minions): a spell passes.
|
||||
*/
|
||||
export function wellFormed(text: readonly Clause[], type: CardDef["type"]): boolean {
|
||||
if (type !== "minion") return true;
|
||||
// The trigger whose effects are being listed: none, one with no effect yet, or one with some.
|
||||
let open: "none" | "empty" | "filled" = "none";
|
||||
for (const clause of text) {
|
||||
if (clause.kind === "effect") {
|
||||
if (open === "none") return false;
|
||||
open = "filled";
|
||||
} else {
|
||||
if (open === "empty") return false;
|
||||
open = clause.kind === "trigger" ? "empty" : "none";
|
||||
}
|
||||
}
|
||||
return open !== "empty";
|
||||
}
|
||||
|
||||
/** Every card the game can create, looked up by name. */
|
||||
export class CardLibrary {
|
||||
private readonly cards = new Map<string, Card>();
|
||||
|
||||
constructor(defs: CardDef[]) {
|
||||
for (const def of defs) this.register(def);
|
||||
}
|
||||
|
||||
/** Add a card, or replace the card with the same name. It joins the Assemble pool if it is a minion with text. */
|
||||
register(def: CardDef): void {
|
||||
this.cards.set(def.name, compile(def, true));
|
||||
}
|
||||
|
||||
/** Add a card made by Assemble. It never joins the pool. */
|
||||
registerAssembled(def: CardDef): void {
|
||||
this.cards.set(def.name, compile(def, false));
|
||||
}
|
||||
|
||||
has(name: string): boolean {
|
||||
return this.cards.has(name);
|
||||
}
|
||||
|
||||
get(name: string): Card {
|
||||
const card = this.cards.get(name);
|
||||
if (!card) throw new Error(`unknown card "${name}": add its file to cards/`);
|
||||
return card;
|
||||
}
|
||||
|
||||
/** The Assemble pool: every card with `inPool`, sorted by name. */
|
||||
pool(): Card[] {
|
||||
return [...this.cards.values()]
|
||||
.filter((c) => c.inPool)
|
||||
.sort((a, b) => (a.def.name < b.def.name ? -1 : a.def.name > b.def.name ? 1 : 0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Combat (Module 12): who may attack whom.
|
||||
//
|
||||
// An attack is one Sequence (`attack` in `queue.ts`): both characters deal their
|
||||
// Attack to each other at once, as one Damage action with two targets, and the
|
||||
// defender's Damage Event queues its triggers first. This file holds only the
|
||||
// legality rules, so the harness can ask them without attacking.
|
||||
|
||||
import type { World, EntityId } from "./world";
|
||||
|
||||
/** The keyword that makes a minion the only thing its enemies may attack. */
|
||||
export const TAUNT = "taunt";
|
||||
|
||||
/** Does `id`, a minion in play, have Taunt? */
|
||||
export function hasTaunt(world: World, id: EntityId): boolean {
|
||||
return world.card(world.cardName(id)).keywords.includes(TAUNT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Why `attacker` may not attack `defender` now, or undefined if it may. The rules, in
|
||||
* the order they are checked: the attacker is a minion in play; the defender is an
|
||||
* enemy minion in play or the enemy hero; the attacker has some Attack; and while the
|
||||
* defender's side has a minion with Taunt, only such a minion may be attacked.
|
||||
*/
|
||||
export function attackError(world: World, attacker: EntityId, defender: EntityId): string | undefined {
|
||||
if (world.isHero(attacker) || world.zoneOf(attacker) !== "board") {
|
||||
return "the attacker is not a minion in play";
|
||||
}
|
||||
const enemy = world.ownerOf(attacker) === 0 ? 1 : 0;
|
||||
const enemyCharacter =
|
||||
world.ownerOf(defender) === enemy && (world.isHero(defender) || world.zoneOf(defender) === "board");
|
||||
if (!enemyCharacter) return "the defender is not an enemy character in play";
|
||||
if (world.attack(attacker) <= 0) return "a minion with 0 Attack cannot attack";
|
||||
const taunts = world.zone(enemy, "board").filter((id) => hasTaunt(world, id));
|
||||
if (taunts.length > 0 && !taunts.includes(defender)) return "a minion with Taunt is in the way";
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// The Death Creation Step: the one place minions leave play.
|
||||
//
|
||||
// Damage and destroy effects only mark a minion (0 or less Health, or pending
|
||||
// destroy). It stays in play, and keeps triggering, until the outermost Phase
|
||||
// ends. Then this step removes every marked minion at once.
|
||||
|
||||
import type { Event } from "./event";
|
||||
import type { EntityId, World } from "./world";
|
||||
|
||||
/**
|
||||
* Remove every mortally wounded or pending-destroy minion from play, simultaneously.
|
||||
* Returns their Death Events in order of play; empty if nothing died.
|
||||
*/
|
||||
export function deathCreationStep(world: World): Event[] {
|
||||
const dying = world.minionsInPlay().filter((id) => world.isDoomed(id));
|
||||
// Every neighbour is read before anything moves: removal is simultaneous. Each Death
|
||||
// Event remembers where its minion stood as a handle, the minion that stays to its
|
||||
// right, not as a board index: an index goes stale as soon as a minion further left
|
||||
// leaves play in the same step (Module 1: hold handles, not indexes).
|
||||
const deaths = dying.map((id) => ({ type: "Destroyed" as const, id, before: survivorToTheRight(world, id) }));
|
||||
for (const { id, before } of deaths) world.kill(id, before);
|
||||
return deaths;
|
||||
}
|
||||
|
||||
/** The nearest minion to the right of `id` on its board that is not leaving play in this step, if any. */
|
||||
function survivorToTheRight(world: World, id: EntityId): EntityId | undefined {
|
||||
const board = world.zone(world.ownerOf(id), "board");
|
||||
return board.slice(board.indexOf(id) + 1).find((other) => !world.isDoomed(other));
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// The interpreter: turns one effect, as data, into engine actions.
|
||||
//
|
||||
// This is the only place that knows what an effect *means*. A card's text is a
|
||||
// small tree (clauses holding effects holding targets); the engine walks it. The
|
||||
// effect vocabulary is closed: a card can only do what this switch can do, which is
|
||||
// what makes a data card safe to load.
|
||||
|
||||
import type { Effect, Target } from "./card";
|
||||
import { hits, type Action, type Ctx } from "./queue";
|
||||
import type { EntityId } from "./world";
|
||||
|
||||
const times = <T>(count: number, make: () => T): T[] => Array.from({ length: count }, make);
|
||||
|
||||
/** The actions one effect performs, in order, given where and for whom it runs. */
|
||||
export function actions(effect: Effect, ctx: Ctx): Action[] {
|
||||
const player = ctx.owner;
|
||||
switch (effect.type) {
|
||||
case "dealDamage":
|
||||
return [{ type: "damage", hits: hits(targets(effect.target, ctx), effect.amount) }];
|
||||
case "draw":
|
||||
return times(effect.count, () => ({ type: "draw", player }));
|
||||
case "summon": {
|
||||
// Several tokens stand left to right in summon order: each goes right of the one before.
|
||||
const at = summonPosition(ctx);
|
||||
return Array.from({ length: effect.count }, (_, i) => ({
|
||||
type: "summon" as const,
|
||||
card: effect.card,
|
||||
player,
|
||||
at: at === undefined ? undefined : at + i,
|
||||
}));
|
||||
}
|
||||
case "gainArmor":
|
||||
return [{ type: "gainArmor", player, amount: effect.amount }];
|
||||
case "gainAttack":
|
||||
return targets(effect.target, ctx).map((id) => ({ type: "gainAttack", id, amount: effect.amount }));
|
||||
case "destroy":
|
||||
return [{ type: "destroy", targets: targets(effect.target, ctx) }];
|
||||
case "assemble":
|
||||
return [{ type: "assemble", player, filter: effect.filter }];
|
||||
case "buffHand":
|
||||
return ctx.world
|
||||
.minionsInHand(player)
|
||||
.map((id) => ({ type: "buff", id, attack: effect.attack, health: effect.health }));
|
||||
case "spawnText":
|
||||
return [{ type: "spawnText", source: ctx.minion(), word: effect.word }];
|
||||
}
|
||||
}
|
||||
|
||||
/** The entities a target names, from where the effect runs. */
|
||||
function targets(target: Target, ctx: Ctx): EntityId[] {
|
||||
const { world } = ctx;
|
||||
const others = (ids: EntityId[]) => ids.filter((id) => id !== ctx.source);
|
||||
switch (target) {
|
||||
case "self":
|
||||
return [ctx.minion()];
|
||||
case "allMinions":
|
||||
return world.minionsInPlay();
|
||||
case "allOtherMinions":
|
||||
return others(world.minionsInPlay());
|
||||
case "allOtherCharacters":
|
||||
return others([world.hero(0), world.hero(1), ...world.minionsInPlay()]);
|
||||
case "enemyHero":
|
||||
return [ctx.enemyHero()];
|
||||
case "chosen":
|
||||
return ctx.target === undefined ? [] : [ctx.target];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a summon goes: to the right of a source still on the board; where a dead
|
||||
* source stood (left of the minion its Death Event remembers); at the right end for a spell.
|
||||
*/
|
||||
function summonPosition(ctx: Ctx): number | undefined {
|
||||
const index = ctx.source === undefined ? undefined : ctx.world.boardIndex(ctx.source);
|
||||
return index === undefined ? ctx.position : index + 1;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// What happened, in order. The engine records an event each time it changes the game.
|
||||
// The world also keeps the nesting depth each event was recorded at (`World.logDepths`).
|
||||
|
||||
import type { TriggerOn } from "./card";
|
||||
import type { EntityId, PlayerId } from "./world";
|
||||
|
||||
export type Event =
|
||||
/**
|
||||
* `id` entered the board. `by` is the minion whose triggered ability put it there (the
|
||||
* trigger resolving when it entered), or undefined for a spell, a play or a summon from
|
||||
* outside a Sequence. Module 10: SpellGrid puts it on `by`'s grid tile. The course's log
|
||||
* doesn't show `by`.
|
||||
*/
|
||||
| { type: "Summoned"; id: EntityId; by: EntityId | undefined }
|
||||
| { type: "Damaged"; target: EntityId; amount: number }
|
||||
| { type: "Triggered"; source: EntityId; on: TriggerOn }
|
||||
| { type: "Drew"; player: PlayerId; id: EntityId }
|
||||
| { type: "Fatigue"; player: PlayerId }
|
||||
| { type: "ArmorGained"; player: PlayerId; amount: number }
|
||||
/** Armor absorbed `amount` of a Damage to `player`'s hero. The `Damaged` that follows shows the full amount. */
|
||||
| { type: "ArmorLost"; player: PlayerId; amount: number }
|
||||
| { type: "StatsChanged"; id: EntityId; attack: number; health: number }
|
||||
| { type: "SpellCast"; card: string }
|
||||
/**
|
||||
* A Death Event: the Death Creation Step moved `id` from play to the graveyard.
|
||||
* `before` is the nearest minion to its right that did not die in the same step, if any:
|
||||
* its Deathrattle summons immediately left of that minion, or at the right end. It is a
|
||||
* handle because a board index goes stale when a minion further left dies in the same step.
|
||||
*/
|
||||
| { type: "Destroyed"; id: EntityId; before: EntityId | undefined }
|
||||
| { type: "DeathPhase"; round: number }
|
||||
/** A minion was played from hand (it has just entered the board). Its Battlecry answers this. */
|
||||
| { type: "Played"; id: EntityId }
|
||||
/** Module 12: `player`'s turn ended. Their minions' end of turn triggers answer this. */
|
||||
| { type: "TurnEnded"; player: PlayerId }
|
||||
/**
|
||||
* Module 10: `source`'s effect asked for `word` to be written on its grid tile. Part I
|
||||
* has no grid: it only records the request. SpellGrid reads it when the Sequence ends.
|
||||
*/
|
||||
| { type: "TextSpawned"; source: EntityId; word: string };
|
||||
@@ -0,0 +1,78 @@
|
||||
// Engine core: generic rules machinery. Never name a specific card here.
|
||||
//
|
||||
// Module 1: every card in the game is an entity addressed by an id handle.
|
||||
// The engine knows which zone each entity is in, who owns it, and when it
|
||||
// entered play.
|
||||
//
|
||||
// Module 2: heroes, Health, Attack and Armor; triggered abilities; and the
|
||||
// action queue that resolves a Sequence depth-first, recording an event log.
|
||||
//
|
||||
// Module 3: deferred death. Damage and destroy effects only mark minions; the
|
||||
// Death Creation Step removes them when the outermost Phase ends, and Death
|
||||
// Phases resolve their Deathrattles until no new deaths occur.
|
||||
//
|
||||
// Module 4: auras as card data, Aura Updates at defined points, and one
|
||||
// routine that decides how many times a queued trigger activates. Playing a
|
||||
// minion from hand, and Battlecries. A second interceptor, replacement: the
|
||||
// steps that rewrite a Damage before it lands (a redirect, then Armor).
|
||||
//
|
||||
// Module 5: behaviour as data. Cards are definitions in the course's card format,
|
||||
// loaded from JSON; one interpreter turns their effects into actions. Assemble
|
||||
// builds a new card by swapping half of one card's text for half of another's, and
|
||||
// offers only results that are well-formed. A Sequence is bounded: a trigger never
|
||||
// nests inside itself, and more than `DEATH_PHASE_LIMIT` Death Phases is an error.
|
||||
//
|
||||
// Module 12: combat (`combat.ts`: who may attack whom; Taunt) and the end of a turn.
|
||||
// A Damage action deals each target its own amount, and a Queue orders its entries by
|
||||
// priority before order of play, so the defender's triggers go first.
|
||||
//
|
||||
// Part II lives in `puzzle/`: a second engine, for the rule-writing puzzle game,
|
||||
// beside the first.
|
||||
// Module 6: the grid, the lexer and the parser.
|
||||
// Module 7: `IS NOT`, and the resolution pass that turns parsed rules into rules in force.
|
||||
// Module 8: movement, planned in full and then committed; push chains.
|
||||
// Module 9: the turn, as a list of phases; hazards; winning.
|
||||
// Module 11: conditions (`X ON Z IS P`), checked for each object when a rule is used.
|
||||
//
|
||||
// Part III lives in `spellgrid.ts`, the only file that knows both engines.
|
||||
// Module 10: SpellGrid. Part I gains auras from outside the cards (`World.setRuleAuras`),
|
||||
// a cap on activations, the `spawnText` effect (recorded as a `TextSpawned` event) and
|
||||
// the end-of-Phase steps as a list (`END_OF_PHASE`); Part II gains a `Destroy` hook.
|
||||
|
||||
export * as puzzle from "./puzzle";
|
||||
export { AssembleError, assemble, registerAssembled, type AssembleFailure, type Half } from "./assemble";
|
||||
export {
|
||||
CardLibrary,
|
||||
triggerLabel,
|
||||
type Aura,
|
||||
type Card,
|
||||
type CardDef,
|
||||
type Clause,
|
||||
type Effect,
|
||||
type PoolFilter,
|
||||
type Target,
|
||||
type Trigger,
|
||||
type TriggerOn,
|
||||
wellFormed,
|
||||
} from "./card";
|
||||
export type { Event } from "./event";
|
||||
export { auraUpdateOther } from "./aura";
|
||||
export { attackError, TAUNT } from "./combat";
|
||||
export {
|
||||
Ctx,
|
||||
DAMAGE_STEPS,
|
||||
DEATH_PHASE_LIMIT,
|
||||
DEFENDER,
|
||||
END_OF_PHASE,
|
||||
hits,
|
||||
NORMAL,
|
||||
runSequence,
|
||||
summon,
|
||||
type Action,
|
||||
type DamageStep,
|
||||
type EndOfPhaseStep,
|
||||
type Hit,
|
||||
type Priority,
|
||||
} from "./queue";
|
||||
export { ruleAuras, SpellGrid, type SeamWords } from "./spellgrid";
|
||||
export { HERO_HEALTH, World, type Chooser, type EntityId, type PlayerId, type Zone } from "./world";
|
||||
@@ -0,0 +1,21 @@
|
||||
// Conditions (Module 11): `X ON Z IS P` gives an X the property P only while it is on a Z.
|
||||
//
|
||||
// The parser reads a condition into the rule (`Rule.conditions`); the engine never
|
||||
// decides it there. A condition is evaluated for one object, against the board as
|
||||
// it is, every time a rule is about to be used: by `Level.hasProperty` (and so by
|
||||
// movement, the hazards and the win check), and by conversion. What a condition
|
||||
// word means is a `ConditionCheck` that content provides, registered by word, as
|
||||
// movement responses and hazards are. The engine knows only that a word with role
|
||||
// `"condition"` may stand between the subjects and `IS`.
|
||||
|
||||
import type { ObjectId } from "./grid";
|
||||
import type { Level } from "./level";
|
||||
|
||||
/**
|
||||
* Content's meaning for one condition word: does the condition, with these nouns
|
||||
* (in the order they are written), hold for object `id` on the board as it is now?
|
||||
*/
|
||||
export type ConditionCheck = (level: Level, id: ObjectId, nouns: readonly string[]) => boolean;
|
||||
|
||||
/** Content's condition checks, by condition word: `{ ON: on }`. */
|
||||
export type ConditionChecks = Readonly<Record<string, ConditionCheck>>;
|
||||
@@ -0,0 +1,145 @@
|
||||
// The grid: objects on tiles. `x` grows right, `y` grows down, and any number of
|
||||
// objects may share a tile.
|
||||
|
||||
export type ObjectId = number;
|
||||
|
||||
/** A level in the course's level format (`course/schema/level.schema.json`). */
|
||||
export interface LevelDef {
|
||||
width: number;
|
||||
height: number;
|
||||
objects: LevelObject[];
|
||||
/** Module 10, read only by SpellGrid: minions in play, each on its tile. */
|
||||
cards?: LevelCard[];
|
||||
/** Module 10, read only by SpellGrid: the cards in player 0's hand. */
|
||||
hand?: string[];
|
||||
}
|
||||
|
||||
/** A minion card on the grid (Module 10). */
|
||||
export interface LevelCard {
|
||||
card: string;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface LevelObject {
|
||||
kind: string;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* What an object is: a thing named by a noun (kind `"<noun>"`, the noun in lower case),
|
||||
* or a piece of text carrying one word (kind `"text:<WORD>"`).
|
||||
*/
|
||||
export type Kind = { type: "thing"; noun: string } | { type: "text"; word: string };
|
||||
|
||||
const TEXT_PREFIX = "text:";
|
||||
|
||||
export const Kind = {
|
||||
parse(kind: string): Kind {
|
||||
return kind.startsWith(TEXT_PREFIX)
|
||||
? { type: "text", word: kind.slice(TEXT_PREFIX.length).toUpperCase() }
|
||||
: { type: "thing", noun: kind.toUpperCase() };
|
||||
},
|
||||
/** The kind as it is placed: `"<noun>"` in lower case, or `"text:<WORD>"`. */
|
||||
format(kind: Kind): string {
|
||||
return kind.type === "text" ? TEXT_PREFIX + kind.word : kind.noun.toLowerCase();
|
||||
},
|
||||
};
|
||||
|
||||
export interface Obj {
|
||||
id: ObjectId;
|
||||
kind: Kind;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
/** What `Board.restore` puts back (Module 9, undo): every object, oldest first, and the id counter. */
|
||||
export interface BoardState {
|
||||
objects: Obj[];
|
||||
nextId: ObjectId;
|
||||
}
|
||||
|
||||
export class Board {
|
||||
private readonly objectsById = new Map<ObjectId, Obj>();
|
||||
private nextId = 0;
|
||||
|
||||
constructor(
|
||||
readonly width: number,
|
||||
readonly height: number,
|
||||
) {}
|
||||
|
||||
inBounds(x: number, y: number): boolean {
|
||||
return x >= 0 && x < this.width && y >= 0 && y < this.height;
|
||||
}
|
||||
|
||||
/** Add an object; ids start at 1 and are never reused. Throws off the board. */
|
||||
place(kind: Kind, x: number, y: number): ObjectId {
|
||||
if (!this.inBounds(x, y)) throw new Error(`(${x}, ${y}) is outside the ${this.width}x${this.height} level`);
|
||||
const id = ++this.nextId;
|
||||
this.objectsById.set(id, { id, kind, x, y });
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* An id that no object will ever have (Module 10): SpellGrid gives one to each
|
||||
* card that isn't on the grid, so cards and objects share one id space.
|
||||
*/
|
||||
reserveId(): ObjectId {
|
||||
return ++this.nextId;
|
||||
}
|
||||
|
||||
/** The object `id`. Throws if there is none. */
|
||||
get(id: ObjectId): Obj {
|
||||
const o = this.objectsById.get(id);
|
||||
if (o === undefined) throw new Error(`no object ${id}`);
|
||||
return o;
|
||||
}
|
||||
|
||||
/** The object `id`, or `undefined` once it has been removed. Throws on an id this board never issued. */
|
||||
find(id: ObjectId): Obj | undefined {
|
||||
if (!(id >= 1 && id <= this.nextId)) throw new Error(`no object ${id}`);
|
||||
return this.objectsById.get(id);
|
||||
}
|
||||
|
||||
/** Take object `id` off the board for good. */
|
||||
remove(id: ObjectId): void {
|
||||
this.objectsById.delete(id);
|
||||
}
|
||||
|
||||
/** Move object `id` by `[dx, dy]`. Throws if it would leave the board. */
|
||||
shift(id: ObjectId, [dx, dy]: readonly [number, number]): void {
|
||||
const o = this.get(id);
|
||||
const [x, y] = [o.x + dx, o.y + dy];
|
||||
if (!this.inBounds(x, y)) throw new Error(`(${x}, ${y}) is outside the ${this.width}x${this.height} level`);
|
||||
o.x = x;
|
||||
o.y = y;
|
||||
}
|
||||
|
||||
/** Make object `id` a `kind`, where it stands. Throws if there is no such object. */
|
||||
setKind(id: ObjectId, kind: Kind): void {
|
||||
this.get(id).kind = kind;
|
||||
}
|
||||
|
||||
/** The objects on tile (x, y), oldest first. */
|
||||
at(x: number, y: number): Obj[] {
|
||||
return this.objects().filter((o) => o.x === x && o.y === y);
|
||||
}
|
||||
|
||||
/** Every object, oldest first. */
|
||||
objects(): Obj[] {
|
||||
return [...this.objectsById.values()];
|
||||
}
|
||||
|
||||
/** A copy of everything the board holds (Module 9, undo). */
|
||||
snapshot(): BoardState {
|
||||
return { objects: this.objects().map((o) => ({ ...o })), nextId: this.nextId };
|
||||
}
|
||||
|
||||
/** Put the board back as `state` recorded it: the same objects, ids, ages and id counter. */
|
||||
restore(state: BoardState): void {
|
||||
this.objectsById.clear();
|
||||
for (const o of state.objects) this.objectsById.set(o.id, { ...o });
|
||||
this.nextId = state.nextId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Part II: the rule-writing puzzle game. Objects have no behaviour of their own; every rule is
|
||||
// compiled from the text on the board, and recompiled whenever the board changes.
|
||||
//
|
||||
// Module 6: the grid, the lexer (text objects to words with grammatical roles)
|
||||
// and the parser (words to rules). The engine knows the operators `IS`, `AND`,
|
||||
// `NOT`, the meta-noun `TEXT` and the base rule `TEXT IS PUSH`. Every other word,
|
||||
// nouns included, is data handed in by content.
|
||||
//
|
||||
// Module 7: `IS NOT` in the parser, and the resolution pass (negation, then the
|
||||
// identity lock) that turns the parsed rules into the rules in force. Objects are
|
||||
// asked about through `Level.hasProperty`, which knows which nouns name them.
|
||||
//
|
||||
// Module 8: movement. `Level.moveYou` plans each `YOU` object's move in full
|
||||
// (`Planner`), then commits it, then reparses. What a property does when something
|
||||
// moves is a `Response` that content provides; the engine runs them in order.
|
||||
//
|
||||
// Module 9: the turn. `Level.step` runs the phases of `TURN` in order: movement,
|
||||
// parse, conversion, parse, hazards, win, parse. What a hazard property destroys
|
||||
// is a `Hazard` that content provides; the engine knows `YOU`, `WIN` and `FLOAT`.
|
||||
//
|
||||
// Module 10: `Level.step` and `Level.moveYou` take a `Destroy`, which decides what
|
||||
// happens to the objects they destroy; `Board.reserveId` hands out an id no object has.
|
||||
// The puzzle engine still knows nothing of cards: SpellGrid (`../spellgrid.ts`) uses these.
|
||||
//
|
||||
// Module 11: conditions. A word with role `"condition"` may stand between a rule's
|
||||
// subjects and `IS` (`X ON Z IS P`); the rule carries it (`Rule.conditions`).
|
||||
// What it means is a `ConditionCheck` content registers by word. `Level` asks the
|
||||
// checks every time it uses a rule, against the board as it is then.
|
||||
|
||||
export type { ConditionCheck, ConditionChecks } from "./condition";
|
||||
export { Board, Kind, type LevelCard, type LevelDef, type LevelObject, type Obj, type ObjectId } from "./grid";
|
||||
export { FLOAT, Level, removeAll, WIN, YOU, type Destroy } from "./level";
|
||||
export { delta, Planner, type Dir, type MoveContext, type Plan, type Pos, type Response, type Step } from "./movement";
|
||||
export {
|
||||
BASE_RULES,
|
||||
isConversion,
|
||||
isIdentity,
|
||||
negates,
|
||||
parse,
|
||||
ruleText,
|
||||
sameConditions,
|
||||
type Condition,
|
||||
type Rule,
|
||||
} from "./parse";
|
||||
export { resolve } from "./resolve";
|
||||
export { TURN, type Hazard, type Phase } from "./turn";
|
||||
export { lex, Lexicon, type Role, type Selects, type Token, type WordDef } from "./word";
|
||||
@@ -0,0 +1,316 @@
|
||||
// A level in play: the board, the words content provides, and the rules compiled
|
||||
// from them. Every change to the board recompiles the rules from scratch: parse,
|
||||
// then resolve. Every question about what an object is goes through `hasProperty`.
|
||||
//
|
||||
// A move (Module 8) is planned for each `YOU` object, then committed; the rules are
|
||||
// reparsed once, after all of them.
|
||||
//
|
||||
// A turn (Module 9) runs the phases of `TURN` in order: movement, parse,
|
||||
// conversion, parse, content's hazards, the win check, parse.
|
||||
//
|
||||
// Undo (Module 9): before each move or turn the level saves the board (every
|
||||
// object's id, kind and position, oldest first, and the id counter) and `won`.
|
||||
// The rules are not saved: undo restores the board and reparses.
|
||||
//
|
||||
// Module 10: what happens to the objects a turn destroys is a `Destroy` the caller
|
||||
// may pass in. The default removes them. SpellGrid passes one that sends minions to
|
||||
// Part I's Death Creation Step instead. SpellGrid doesn't offer undo: Part I has
|
||||
// state the level's snapshot doesn't cover.
|
||||
//
|
||||
// Module 11: a rule may carry conditions (`X ON Z IS P`). They are not
|
||||
// decided when the rules are compiled. Every question about an object (`hasProperty`,
|
||||
// conversion) asks content's `ConditionCheck`s against the board as it is at that
|
||||
// moment, and uses only the rules whose conditions hold for that object.
|
||||
|
||||
import type { ConditionChecks } from "./condition";
|
||||
import { Board, Kind, type BoardState, type LevelDef, type ObjectId } from "./grid";
|
||||
import { delta, Planner, type Dir, type Plan, type Response } from "./movement";
|
||||
import { isConversion, isIdentity, parse, type Rule } from "./parse";
|
||||
import { resolve } from "./resolve";
|
||||
import { TURN, type Hazard } from "./turn";
|
||||
import { Lexicon, type WordDef } from "./word";
|
||||
|
||||
/** The property that makes an object move when the player moves. */
|
||||
export const YOU = "YOU";
|
||||
/** The property that wins the level when a `YOU` object is on it, or is it. */
|
||||
export const WIN = "WIN";
|
||||
/**
|
||||
* The property that puts an object on the other float level: only objects on
|
||||
* the same level share a tile for hazards and for winning.
|
||||
*/
|
||||
export const FLOAT = "FLOAT";
|
||||
|
||||
/**
|
||||
* What to do with objects a move or a turn destroys (Module 10). It may change the
|
||||
* board, and reparse, before it returns. An id may appear more than once.
|
||||
*/
|
||||
export type Destroy = (level: Level, ids: ObjectId[]) => void;
|
||||
|
||||
/** The default `Destroy`: take every object off the board. */
|
||||
export const removeAll: Destroy = (level, ids) => {
|
||||
for (const id of ids) level.board.remove(id);
|
||||
};
|
||||
|
||||
export class Level {
|
||||
readonly board: Board;
|
||||
private readonly lexicon: Lexicon;
|
||||
private compiled: Rule[] = [];
|
||||
private active: Rule[] = [];
|
||||
private hasWon = false;
|
||||
/** What `undo` puts back: one entry per move or turn, the latest last (Module 9). */
|
||||
private history: { board: BoardState; won: boolean }[] = [];
|
||||
|
||||
/**
|
||||
* A level from its definition, the words content provides, content's movement
|
||||
* responses and hazards, each in the order they are to run, and content's
|
||||
* condition checks, by word. Throws if a word with role `"condition"` has no check.
|
||||
*/
|
||||
constructor(
|
||||
def: LevelDef,
|
||||
words: readonly WordDef[],
|
||||
private readonly moveResponses: readonly Response[],
|
||||
private readonly hazards: readonly Hazard[],
|
||||
private readonly conditions: ConditionChecks,
|
||||
) {
|
||||
for (const w of words) {
|
||||
if (w.role === "condition" && !Object.hasOwn(conditions, w.name.toUpperCase())) {
|
||||
throw new Error(`the condition word ${w.name} has no condition check`);
|
||||
}
|
||||
}
|
||||
this.board = new Board(def.width, def.height);
|
||||
this.lexicon = new Lexicon(words);
|
||||
for (const o of def.objects) this.board.place(Kind.parse(o.kind), o.x, o.y);
|
||||
this.reparse();
|
||||
}
|
||||
|
||||
place(kind: string, x: number, y: number): ObjectId {
|
||||
const id = this.board.place(Kind.parse(kind), x, y);
|
||||
this.history = [];
|
||||
this.reparse();
|
||||
return id;
|
||||
}
|
||||
|
||||
/** The movement responses, in the order they run. */
|
||||
responses(): readonly Response[] {
|
||||
return this.moveResponses;
|
||||
}
|
||||
|
||||
/** Every rule the text spells, as parsed: negated rules and duplicates included. */
|
||||
rules(): readonly Rule[] {
|
||||
return this.compiled;
|
||||
}
|
||||
|
||||
/** The rules in force after the resolution pass. */
|
||||
activeRules(): readonly Rule[] {
|
||||
return this.active;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does object `id` have `property`? Yes if an active rule that applies to it
|
||||
* (`appliesTo`) gives it the property and no active negated rule that applies to
|
||||
* it takes it away. A destroyed object has no properties.
|
||||
*/
|
||||
hasProperty(id: ObjectId, property: string): boolean {
|
||||
if (this.board.find(id) === undefined) return false;
|
||||
const aboutIt = this.active.filter((r) => r.complement === property && this.appliesTo(r, id));
|
||||
return aboutIt.some((r) => !r.negated) && !aboutIt.some((r) => r.negated);
|
||||
}
|
||||
|
||||
/** Does the noun `word`, as the subject of a rule, name object `id`? */
|
||||
names(word: string, id: ObjectId): boolean {
|
||||
return this.lexicon.names(word, this.board.get(id).kind);
|
||||
}
|
||||
|
||||
/**
|
||||
* Does `rule` apply to object `id` now? Its subject names the object, and each of
|
||||
* its conditions holds for the object on the board as it is (Module 11).
|
||||
*/
|
||||
private appliesTo(rule: Rule, id: ObjectId): boolean {
|
||||
return (
|
||||
this.names(rule.subject, id) && rule.conditions.every((c) => this.conditions[c.word](this, id, c.nouns))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The other objects on object `id`'s tile that are on its float level (both
|
||||
* `FLOAT` or both not), oldest first. Hazards and the win check ask this.
|
||||
*/
|
||||
sharing(id: ObjectId): ObjectId[] {
|
||||
const o = this.board.get(id);
|
||||
const floats = this.hasProperty(id, FLOAT);
|
||||
return this.board
|
||||
.at(o.x, o.y)
|
||||
.filter((other) => other.id !== id && this.hasProperty(other.id, FLOAT) === floats)
|
||||
.map((other) => other.id);
|
||||
}
|
||||
|
||||
/** Has a turn's win check found a `YOU` object on a `WIN` one? Stays true. */
|
||||
won(): boolean {
|
||||
return this.hasWon;
|
||||
}
|
||||
|
||||
/** Is there no `YOU` object left? */
|
||||
lost(): boolean {
|
||||
return !this.board.objects().some((o) => this.hasProperty(o.id, YOU));
|
||||
}
|
||||
|
||||
/**
|
||||
* Move every `YOU` object one tile in `dir`, then reparse (Module 8). Movement
|
||||
* only: no conversion, hazard or win.
|
||||
*/
|
||||
moveYou(dir: Dir, destroy: Destroy = removeAll): void {
|
||||
this.save();
|
||||
this.movement(dir, destroy);
|
||||
this.reparse();
|
||||
}
|
||||
|
||||
/** Play one turn: the phases of `TURN`, in order. Destroyed objects go to `destroy`. */
|
||||
step(dir: Dir, destroy: Destroy = removeAll): void {
|
||||
this.save();
|
||||
for (const phase of TURN) {
|
||||
switch (phase) {
|
||||
case "movement":
|
||||
this.movement(dir, destroy);
|
||||
break;
|
||||
case "parse":
|
||||
this.reparse();
|
||||
break;
|
||||
case "conversion":
|
||||
this.convert(destroy);
|
||||
break;
|
||||
case "hazards":
|
||||
this.runHazards(destroy);
|
||||
break;
|
||||
case "win":
|
||||
this.checkWin();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the level back as it was before the last `moveYou` or `step` (Module 9),
|
||||
* and reparse. False, and no change, if there is none; `place` forgets them all.
|
||||
*/
|
||||
undo(): boolean {
|
||||
const last = this.history.pop();
|
||||
if (last === undefined) return false;
|
||||
this.board.restore(last.board);
|
||||
this.hasWon = last.won;
|
||||
this.reparse();
|
||||
return true;
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
this.history.push({ board: this.board.snapshot(), won: this.hasWon });
|
||||
}
|
||||
|
||||
/**
|
||||
* The `YOU` objects move one at a time, the one furthest ahead in `dir` first
|
||||
* (oldest first on a tie); each one's move is planned in full, then committed,
|
||||
* before the next is planned. Every move uses the rules in force before the first.
|
||||
*
|
||||
* An object steps at most once in a movement phase. A `YOU` object that an
|
||||
* earlier move already carried along (pushed, or moved by any other response)
|
||||
* doesn't start a move of its own, and no later move can make it step again.
|
||||
*/
|
||||
private movement(dir: Dir, destroy: Destroy): void {
|
||||
const [dx, dy] = delta(dir);
|
||||
const ahead = (o: { x: number; y: number }) => o.x * dx + o.y * dy;
|
||||
const you = this.board
|
||||
.objects()
|
||||
.filter((o) => this.hasProperty(o.id, YOU))
|
||||
.sort((a, b) => ahead(b) - ahead(a) || a.id - b.id)
|
||||
.map((o) => o.id);
|
||||
const stepped = new Set<ObjectId>();
|
||||
for (const id of you) {
|
||||
if (this.board.find(id) === undefined) continue; // destroyed by an earlier move
|
||||
if (stepped.has(id)) continue; // already moved, by an earlier move
|
||||
const planner = new Planner(this, dir, stepped);
|
||||
if (!planner.tryMove(id)) continue;
|
||||
const plan = planner.result();
|
||||
this.commit(plan, dir, destroy);
|
||||
for (const moved of plan.moving) if (!plan.destroyed.has(moved)) stepped.add(moved);
|
||||
}
|
||||
}
|
||||
|
||||
/** Destroy, then move what is still on the board (a `Destroy` may remove more than it was given). */
|
||||
private commit(plan: Plan, dir: Dir, destroy: Destroy): void {
|
||||
if (plan.destroyed.size > 0) destroy(this, [...plan.destroyed]);
|
||||
for (const id of plan.moving) {
|
||||
if (!plan.destroyed.has(id) && this.board.find(id) !== undefined) this.board.shift(id, delta(dir));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every object named by a conversion `X IS Y` (`Y` a noun) becomes a `Y` where
|
||||
* it stands, keeping its id; with several `Y`s it becomes the first, and each
|
||||
* other `Y` is a new object on its tile. An `X IS X` naming the object blocks
|
||||
* this. An object named by `X IS NOT X` is deleted, and still makes its `Y`s,
|
||||
* as new objects: the negation cancelled `X IS X`.
|
||||
*
|
||||
* Negation is settled per object, as in `hasProperty`: an object doesn't become
|
||||
* a `Y` if any active `... IS NOT Y` names it, whatever noun gave it the
|
||||
* conversion (`ALL IS Y` with `X IS NOT Y` leaves every X an X).
|
||||
*
|
||||
* Every object is decided from the board as movement left it, before any
|
||||
* changes, so `X IS Y` and `Y IS X` swap the Xs and the Ys. Only the rules that
|
||||
* apply to the object are used: their conditions are checked on that board too.
|
||||
*/
|
||||
private convert(destroy: Destroy): void {
|
||||
const changes: { id: ObjectId; x: number; y: number; deleted: boolean; into: Kind[] }[] = [];
|
||||
for (const o of this.board.objects()) {
|
||||
const aboutIt = this.active.filter((r) => this.appliesTo(r, o.id));
|
||||
const deleted = aboutIt.some((r) => r.negated && isIdentity(r));
|
||||
const locked = aboutIt.some((r) => !r.negated && isIdentity(r));
|
||||
const into: Kind[] = [];
|
||||
if (!locked) {
|
||||
for (const r of aboutIt) {
|
||||
if (r.negated || !isConversion(r)) continue;
|
||||
if (aboutIt.some((n) => n.negated && n.complement === r.complement)) continue;
|
||||
const kind = this.lexicon.thingNamed(r.complement);
|
||||
if (kind === undefined) continue;
|
||||
const same = (k: Kind) => Kind.format(k) === Kind.format(kind);
|
||||
if (!same(o.kind) && !into.some(same)) into.push(kind);
|
||||
}
|
||||
}
|
||||
if (deleted || into.length > 0) changes.push({ id: o.id, x: o.x, y: o.y, deleted, into });
|
||||
}
|
||||
for (const { id, x, y, deleted, into } of changes) {
|
||||
if (!deleted) this.board.setKind(id, into[0]);
|
||||
for (const kind of deleted ? into : into.slice(1)) this.board.place(kind, x, y);
|
||||
}
|
||||
const deleted = changes.filter((c) => c.deleted).map((c) => c.id);
|
||||
if (deleted.length > 0) destroy(this, deleted);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run content's hazards in order. Each one's victims are destroyed together
|
||||
* before the next runs; no reparse until the turn's last phase.
|
||||
*/
|
||||
private runHazards(destroy: Destroy): void {
|
||||
for (const hazard of this.hazards) {
|
||||
const victims = hazard(this);
|
||||
if (victims.length > 0) destroy(this, victims);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The level is won if any `YOU` object is `WIN`, or shares its tile with a
|
||||
* `WIN` object on its float level.
|
||||
*/
|
||||
private checkWin(): void {
|
||||
const wins = (id: ObjectId) => this.hasProperty(id, WIN);
|
||||
const won = this.board
|
||||
.objects()
|
||||
.filter((o) => this.hasProperty(o.id, YOU))
|
||||
.some((o) => wins(o.id) || this.sharing(o.id).some(wins));
|
||||
this.hasWon ||= won;
|
||||
}
|
||||
|
||||
/** Recompile the rules from the board: parse, then resolve. */
|
||||
reparse(): void {
|
||||
this.compiled = parse(this.board, this.lexicon);
|
||||
this.active = resolve(this.compiled);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// Movement: validate, then commit.
|
||||
//
|
||||
// A move is planned before anything on the board changes. The `Planner` asks
|
||||
// whether one object can step one tile; to answer, it runs every movement
|
||||
// response content provides for that step, and a response may ask the planner
|
||||
// to move other objects too (a push), or to destroy objects. If any response
|
||||
// says no, the planner forgets everything that step added to the plan, so a
|
||||
// failed push leaves no trace. Only a plan that succeeded is committed.
|
||||
//
|
||||
// The engine knows the board, its edge, and the order of the steps. What each
|
||||
// property does when something moves (`PUSH`, `STOP`, `OPEN`/`SHUT`, ...) is a
|
||||
// response in content, run in the order content lists them.
|
||||
|
||||
import type { Board, ObjectId } from "./grid";
|
||||
|
||||
/** One of the four directions a move can take. */
|
||||
export type Dir = "up" | "down" | "left" | "right";
|
||||
|
||||
export type Pos = readonly [number, number];
|
||||
|
||||
/** One tile in direction `dir`, as `[dx, dy]`; `y` grows down. */
|
||||
export function delta(dir: Dir): Pos {
|
||||
switch (dir) {
|
||||
case "up":
|
||||
return [0, -1];
|
||||
case "down":
|
||||
return [0, 1];
|
||||
case "left":
|
||||
return [-1, 0];
|
||||
case "right":
|
||||
return [1, 0];
|
||||
}
|
||||
}
|
||||
|
||||
/** One object stepping one tile, from `from` to `to`, in direction `dir`. */
|
||||
export interface Step {
|
||||
mover: ObjectId;
|
||||
from: Pos;
|
||||
to: Pos;
|
||||
dir: Dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* A movement response: content's rule for what happens when an object steps.
|
||||
* It returns `false` to block the step. It may plan other moves or destroy
|
||||
* objects through the planner.
|
||||
*/
|
||||
export type Response = (p: Planner, s: Step) => boolean;
|
||||
|
||||
/**
|
||||
* What a move will do: the objects that step one tile, and the objects destroyed.
|
||||
* A destroyed object doesn't step, even if it was pushed.
|
||||
*/
|
||||
export interface Plan {
|
||||
moving: Set<ObjectId>;
|
||||
destroyed: Set<ObjectId>;
|
||||
}
|
||||
|
||||
/** What the planner reads: the board, the properties in force, the responses. */
|
||||
export interface MoveContext {
|
||||
readonly board: Board;
|
||||
hasProperty(id: ObjectId, property: string): boolean;
|
||||
responses(): readonly Response[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans one move on a board it only reads. `stepped` holds the objects that have
|
||||
* already stepped in this movement phase, in an earlier committed plan: an object
|
||||
* steps at most once per phase, so none of them steps again.
|
||||
*/
|
||||
export class Planner {
|
||||
private plan: Plan = { moving: new Set(), destroyed: new Set() };
|
||||
|
||||
constructor(
|
||||
private readonly level: MoveContext,
|
||||
private readonly dir: Dir,
|
||||
private readonly stepped: ReadonlySet<ObjectId>,
|
||||
) {}
|
||||
|
||||
/** Does object `id` have `property`, under the rules in force before the move? */
|
||||
has(id: ObjectId, property: string): boolean {
|
||||
return this.level.hasProperty(id, property);
|
||||
}
|
||||
|
||||
/**
|
||||
* The objects that will still be on tile `at` when the plan so far is
|
||||
* committed: those there now, less those planned to move away or be destroyed.
|
||||
* Oldest first.
|
||||
*/
|
||||
stayingAt([x, y]: Pos): ObjectId[] {
|
||||
return this.level.board
|
||||
.at(x, y)
|
||||
.map((o) => o.id)
|
||||
.filter((id) => !this.plan.moving.has(id) && !this.plan.destroyed.has(id));
|
||||
}
|
||||
|
||||
/** Plan object `id`'s destruction. */
|
||||
destroy(id: ObjectId): void {
|
||||
this.plan.destroyed.add(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan object `id` stepping one tile in the move's direction, with whatever
|
||||
* the responses add. Returns whether it can. If it can't, the plan is left as
|
||||
* it was before the call. An object already planned to move, or to be
|
||||
* destroyed, is out of the way: the answer is yes, and nothing is added. An
|
||||
* object that has already stepped in this movement phase doesn't step again, and
|
||||
* doesn't hold the mover back either: the answer is yes, and nothing is added, so
|
||||
* objects that began the phase stacked on one tile end it stacked.
|
||||
*/
|
||||
tryMove(id: ObjectId): boolean {
|
||||
if (this.plan.moving.has(id) || this.plan.destroyed.has(id)) return true;
|
||||
if (this.stepped.has(id)) return true;
|
||||
const o = this.level.board.get(id);
|
||||
const [dx, dy] = delta(this.dir);
|
||||
const to: Pos = [o.x + dx, o.y + dy];
|
||||
// The edge of the level blocks every step (the course's choice; see the lesson).
|
||||
if (!this.level.board.inBounds(...to)) return false;
|
||||
const before: Plan = { moving: new Set(this.plan.moving), destroyed: new Set(this.plan.destroyed) };
|
||||
this.plan.moving.add(id);
|
||||
const step: Step = { mover: id, from: [o.x, o.y], to, dir: this.dir };
|
||||
const allowed = this.level.responses().every((respond) => respond(this, step));
|
||||
if (!allowed) this.plan = before;
|
||||
return allowed;
|
||||
}
|
||||
|
||||
result(): Plan {
|
||||
return this.plan;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// The parser: words on the grid become rules.
|
||||
//
|
||||
// Grammar (Module 7): `NOUN [AND NOUN]* IS [NOT] (NOUN|PROPERTY) [AND [NOT] (NOUN|PROPERTY)]*`,
|
||||
// read left to right in a row and top to bottom in a column. The parser starts at
|
||||
// every `IS`, collects the subjects before it and the complements after it, and
|
||||
// emits one rule per pair: AND distributes over both sides. A tile holding several
|
||||
// words contributes each of them, so stacked text yields every possible rule.
|
||||
//
|
||||
// `NOT` before a complement negates that one complement. `NOT` before a subject is
|
||||
// not in the grammar: the run of subjects stops there and that subject is dropped.
|
||||
//
|
||||
// Module 11: conditions. `NOUN [AND NOUN]* [CONDITION NOUN [AND NOUN]*] IS ...`: a word
|
||||
// whose role is `"condition"` may stand between the subjects and `IS`, followed by
|
||||
// the nouns it is about. The condition belongs to every subject of the sentence,
|
||||
// and AND among its nouns means all of them. A run of nouns before `IS` is the
|
||||
// condition's when a condition word stands before it, and then it is not a run of
|
||||
// subjects. Stacked text still yields every possible rule: a stack of nouns after
|
||||
// the condition word gives one rule per noun, as a stack after `IS` does.
|
||||
//
|
||||
// The parser only reads; which rules win is the resolution pass (`resolve`), and
|
||||
// whether a condition holds is decided for each object when someone asks (`Level`).
|
||||
|
||||
import type { Board, ObjectId } from "./grid";
|
||||
import { AND, IS, lex, NOT, TEXT, tileKey, type Lexicon, type Role, type Token } from "./word";
|
||||
|
||||
/**
|
||||
* A condition on a rule (Module 11): the condition word and the nouns after it, in
|
||||
* the order they are written. `X ON Y AND Z IS P` has `{ word: "ON",
|
||||
* nouns: ["Y", "Z"] }`.
|
||||
*/
|
||||
export interface Condition {
|
||||
word: string;
|
||||
nouns: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* One rule: `subject IS complement`, or `subject IS NOT complement` when `negated`,
|
||||
* applying to an object only while each of its `conditions` holds for that object
|
||||
* (none for an unconditional rule). `text` is the text objects that spell it
|
||||
* (subject, condition word and nouns if any, `IS`, `NOT` if any, complement), or
|
||||
* empty for a base rule.
|
||||
*/
|
||||
export interface Rule {
|
||||
subject: string;
|
||||
complement: string;
|
||||
complementRole: Role;
|
||||
negated: boolean;
|
||||
conditions: Condition[];
|
||||
text: ObjectId[];
|
||||
}
|
||||
|
||||
/** The normalised form: `"TEXT IS PUSH"`, `"TEXT IS NOT PUSH"`, `"X ON Y AND Z IS P"`. */
|
||||
export const ruleText = (r: Rule): string => {
|
||||
const conditions = r.conditions.map((c) => ` ${c.word} ${c.nouns.join(` ${AND} `)}`).join("");
|
||||
return `${r.subject}${conditions} ${IS}${r.negated ? ` ${NOT}` : ""} ${r.complement}`;
|
||||
};
|
||||
|
||||
/** The same conditions: the same words, each with the same nouns in any order. */
|
||||
export const sameConditions = (a: Rule, b: Rule): boolean => {
|
||||
const key = (r: Rule) => JSON.stringify(r.conditions.map((c) => [c.word, [...c.nouns].sort()]));
|
||||
return key(a) === key(b);
|
||||
};
|
||||
|
||||
/** `X IS Y` where `Y` is a noun: every X is to become a Y. */
|
||||
export const isConversion = (r: Rule): boolean => r.complementRole === "noun";
|
||||
|
||||
/** `X IS X` (or `X IS NOT X`). */
|
||||
export const isIdentity = (r: Rule): boolean => r.subject === r.complement;
|
||||
|
||||
/**
|
||||
* Same subject, complement and conditions, opposite sign: `X IS NOT Y` negates
|
||||
* `X IS Y`, and `X ON Z IS NOT Y` negates `X ON Z IS Y` (Module 11), but not `X IS Y`.
|
||||
*/
|
||||
export const negates = (n: Rule, r: Rule): boolean =>
|
||||
n.negated && !r.negated && n.subject === r.subject && n.complement === r.complement && sameConditions(n, r);
|
||||
|
||||
/** Rules in force with no text: the game's base rules (`[subject, property]`). */
|
||||
export const BASE_RULES: readonly (readonly [string, string])[] = [[TEXT, "PUSH"]];
|
||||
|
||||
type Tiles = Map<string, Token[]>;
|
||||
type Pos = readonly [number, number];
|
||||
|
||||
/** A word in a run, with the `NOT` in front of it if there is one. */
|
||||
interface Word {
|
||||
not?: Token;
|
||||
token: Token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every rule the board spells, base rules first, negated rules included. A rule
|
||||
* spelled by two different sets of text objects appears twice.
|
||||
*/
|
||||
export function parse(board: Board, lexicon: Lexicon): Rule[] {
|
||||
const tiles = lex(board, lexicon);
|
||||
const rules: Rule[] = BASE_RULES.map(([subject, property]) => ({
|
||||
subject,
|
||||
complement: property,
|
||||
complementRole: "property",
|
||||
negated: false,
|
||||
conditions: [],
|
||||
text: [],
|
||||
}));
|
||||
for (const o of board.objects()) {
|
||||
if (o.kind.type !== "text" || o.kind.word !== IS) continue;
|
||||
for (const [dx, dy] of [
|
||||
[1, 0],
|
||||
[0, 1],
|
||||
] as const) {
|
||||
const cs = complements(tiles, [o.x + dx, o.y + dy], [dx, dy]);
|
||||
for (const { subjects, conditions, text } of beforeIs(tiles, [o.x - dx, o.y - dy], [-dx, -dy])) {
|
||||
for (const s of subjects) {
|
||||
for (const c of cs) {
|
||||
rules.push({
|
||||
subject: s.word,
|
||||
complement: c.token.word,
|
||||
complementRole: c.token.role,
|
||||
negated: c.not !== undefined,
|
||||
conditions,
|
||||
text: [s.id, ...text, o.id, ...(c.not ? [c.not.id] : []), c.token.id],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rules;
|
||||
}
|
||||
|
||||
const wordsAt = (tiles: Tiles, [x, y]: Pos): Token[] => tiles.get(tileKey(x, y)) ?? [];
|
||||
const holds = (tiles: Tiles, p: Pos, word: string): boolean => wordsAt(tiles, p).some((t) => t.word === word);
|
||||
const ahead = ([x, y]: Pos, [dx, dy]: Pos): Pos => [x + dx, y + dy];
|
||||
|
||||
/** What stands before an `IS` (Module 11): the subjects, with the condition on them if there is one. */
|
||||
interface Reading {
|
||||
subjects: Token[];
|
||||
conditions: Condition[];
|
||||
/** The condition word and its nouns, in reading order (empty without a condition). */
|
||||
text: ObjectId[];
|
||||
}
|
||||
|
||||
const isCondition = (t: Token) => t.role === "condition";
|
||||
|
||||
/**
|
||||
* Every way to read the words before an `IS`, walking backwards from `at`.
|
||||
*
|
||||
* - The run of subjects, without a condition, unless a condition word stands
|
||||
* before the run: then those nouns are the condition's, not subjects.
|
||||
* - For every run of nouns that has a condition word before it, the run of
|
||||
* subjects before that word, with the condition. A stack among the condition's
|
||||
* nouns gives one reading per noun (`nounRuns`).
|
||||
*/
|
||||
function beforeIs(tiles: Tiles, at: Pos, step: Pos): Reading[] {
|
||||
const readings: Reading[] = [];
|
||||
const run = subjects(tiles, at, step);
|
||||
if (!wordsAt(tiles, run.stop).some(isCondition)) readings.push({ subjects: run.tokens, conditions: [], text: [] });
|
||||
for (const nouns of nounRuns(tiles, at, step)) {
|
||||
const inOrder = [...nouns.tokens].reverse();
|
||||
for (const word of wordsAt(tiles, nouns.stop).filter(isCondition)) {
|
||||
readings.push({
|
||||
subjects: subjects(tiles, ahead(nouns.stop, step), step).tokens,
|
||||
conditions: [{ word: word.word, nouns: inOrder.map((t) => t.word) }],
|
||||
text: [word.id, ...inOrder.map((t) => t.id)],
|
||||
});
|
||||
}
|
||||
}
|
||||
return readings;
|
||||
}
|
||||
|
||||
/**
|
||||
* The run of subjects before an `IS`, walking backwards from `at`: the nouns at
|
||||
* `at`, then, if the tile before them holds an AND, the run beyond it. A `NOT`
|
||||
* before a noun ends the run without it (a negated subject is not in the grammar).
|
||||
* `stop` is the tile the walk stopped on, before the run's first word.
|
||||
*/
|
||||
function subjects(tiles: Tiles, at: Pos, step: Pos): { tokens: Token[]; stop: Pos } {
|
||||
const before = ahead(at, step);
|
||||
if (holds(tiles, before, NOT)) return { tokens: [], stop: before };
|
||||
const found = wordsAt(tiles, at).filter((t) => t.role === "noun");
|
||||
if (found.length > 0 && holds(tiles, before, AND)) {
|
||||
const rest = subjects(tiles, ahead(before, step), step);
|
||||
if (rest.tokens.length > 0) return { tokens: [...found, ...rest.tokens], stop: rest.stop };
|
||||
}
|
||||
return { tokens: found, stop: before };
|
||||
}
|
||||
|
||||
/**
|
||||
* Every run of nouns walking backwards from `at`, one noun from each tile, joined
|
||||
* by AND; each with the tile before its first noun (`stop`). Runs that end early,
|
||||
* at an AND, are included: a condition word stacked on that AND starts a reading.
|
||||
* A `NOT` before a noun ends every run through it.
|
||||
*/
|
||||
function nounRuns(tiles: Tiles, at: Pos, step: Pos): { tokens: Token[]; stop: Pos }[] {
|
||||
const before = ahead(at, step);
|
||||
if (holds(tiles, before, NOT)) return [];
|
||||
const runs: { tokens: Token[]; stop: Pos }[] = [];
|
||||
for (const noun of wordsAt(tiles, at).filter((t) => t.role === "noun")) {
|
||||
runs.push({ tokens: [noun], stop: before });
|
||||
if (!holds(tiles, before, AND)) continue;
|
||||
for (const rest of nounRuns(tiles, ahead(before, step), step)) {
|
||||
runs.push({ tokens: [noun, ...rest.tokens], stop: rest.stop });
|
||||
}
|
||||
}
|
||||
return runs;
|
||||
}
|
||||
|
||||
/**
|
||||
* The run of complements after an `IS`, walking forwards from `at`: the nouns
|
||||
* and properties at `at`, or, if `at` holds a `NOT`, those on the tile after it,
|
||||
* negated; then, if the next tile holds an AND, the run beyond it.
|
||||
*/
|
||||
function complements(tiles: Tiles, at: Pos, step: Pos): Word[] {
|
||||
const fits = (t: Token) => t.role === "noun" || t.role === "property";
|
||||
const found: Word[] = [];
|
||||
// Plain words here, and negated words one tile on: a stack may hold both.
|
||||
const branches: [Token | undefined, Pos][] = [[undefined, at]];
|
||||
for (const not of wordsAt(tiles, at).filter((t) => t.word === NOT)) branches.push([not, ahead(at, step)]);
|
||||
for (const [not, p] of branches) {
|
||||
const words = wordsAt(tiles, p)
|
||||
.filter(fits)
|
||||
.map((token) => ({ not, token }));
|
||||
if (words.length === 0) continue;
|
||||
found.push(...words);
|
||||
const andAt = ahead(p, step);
|
||||
if (holds(tiles, andAt, AND)) found.push(...complements(tiles, ahead(andAt, step), step));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// The resolution pass: from every rule the text spells to the rules in force.
|
||||
//
|
||||
// The parser reports what is written; this pass decides what wins, over the whole
|
||||
// rule list at once, so it doesn't matter where on the board each rule is written:
|
||||
//
|
||||
// 1. Negation. `X IS NOT Y` cancels every `X IS Y`. The negated rule stays in
|
||||
// force: it keeps overriding, and `X IS NOT X` is also the record that every X is
|
||||
// to vanish (the turn removes them, Module 9).
|
||||
// 2. Identity. A surviving `X IS X` cancels every conversion `X IS Y` (`Y` a noun):
|
||||
// X can't become anything else. It doesn't stop other nouns becoming X. Because
|
||||
// negation runs first, `X IS NOT X` cancels `X IS X` and conversions work again.
|
||||
//
|
||||
// Base rules are rules like any other, so `TEXT IS NOT PUSH` cancels `TEXT IS PUSH`.
|
||||
//
|
||||
// Module 11: both steps pair rules only when their conditions are the same.
|
||||
// `X ON Z IS NOT P` cancels `X ON Z IS P` here, but not `X IS P`:
|
||||
// which of those wins depends on where each X stands, so it is settled per
|
||||
// object when someone asks (`Level.hasProperty`, and conversion), among the rules
|
||||
// whose conditions hold for that object.
|
||||
|
||||
import { isConversion, isIdentity, negates, sameConditions, type Rule } from "./parse";
|
||||
|
||||
/** The rules in force, in the order they were parsed. */
|
||||
export function resolve(rules: readonly Rule[]): Rule[] {
|
||||
const survivesNegation = rules.filter((r) => !rules.some((n) => negates(n, r)));
|
||||
const locked = (r: Rule) =>
|
||||
survivesNegation.some((l) => !l.negated && isIdentity(l) && l.subject === r.subject && sameConditions(l, r));
|
||||
return survivesNegation.filter((r) => r.negated || !isConversion(r) || isIdentity(r) || !locked(r));
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// The turn (Module 9): one move of the player, as a fixed list of phases.
|
||||
//
|
||||
// The course's turn is a labelled simplification of the game's (see the lesson):
|
||||
// movement, parse, conversion, parse, hazards, win, and a last parse so that
|
||||
// the rules match the board when the turn ends. Each phase reads the rules from
|
||||
// the parse before it, so a rule that movement breaks is gone before hazards run.
|
||||
//
|
||||
// What a hazard property does (`SINK`, `HOT`/`MELT`, `DEFEAT`, ...) is a `Hazard`
|
||||
// that content provides, as with movement's responses. The engine runs them in
|
||||
// content's order and owns only the phases, `YOU`, `WIN` and float levels.
|
||||
|
||||
import type { ObjectId } from "./grid";
|
||||
import type { Level } from "./level";
|
||||
|
||||
/**
|
||||
* One phase of the turn:
|
||||
* - `"movement"`: every `YOU` object moves (Module 8), without the reparse;
|
||||
* - `"parse"`: the rules are recompiled from the board;
|
||||
* - `"conversion"`: `X IS Y` conversions, and `X IS NOT X` deletions;
|
||||
* - `"hazards"`: content's hazards, in content's order;
|
||||
* - `"win"`: a `YOU` object on a `WIN` one (or `WIN` itself) wins the level.
|
||||
*/
|
||||
export type Phase = "movement" | "parse" | "conversion" | "hazards" | "win";
|
||||
|
||||
/** The turn, in order. */
|
||||
export const TURN: readonly Phase[] = ["movement", "parse", "conversion", "parse", "hazards", "win", "parse"];
|
||||
|
||||
/**
|
||||
* A hazard: content's rule for what destroys what at the end of a turn. It reads
|
||||
* the level and returns the objects to destroy; the engine destroys them all at
|
||||
* once, before the next hazard runs. An id may appear more than once.
|
||||
*/
|
||||
export type Hazard = (level: Level) => ObjectId[];
|
||||
@@ -0,0 +1,110 @@
|
||||
// The lexer: text objects become words with a grammatical role.
|
||||
//
|
||||
// The engine owns the grammar words (`IS`, `AND`, `NOT`) and the meta-noun `TEXT`.
|
||||
// Every other word comes from content as data: the engine never names a noun.
|
||||
// A noun also says which objects it names (`Selects`), so a meta-noun that names
|
||||
// a whole group of objects can be data too.
|
||||
//
|
||||
// Module 11: a fourth role, `"condition"`. The engine knows only where a condition
|
||||
// word may stand in a sentence (between the subjects and `IS`); what it means is a
|
||||
// check content provides (`ConditionCheck`).
|
||||
|
||||
import type { Board, Kind, ObjectId } from "./grid";
|
||||
|
||||
export type Role = "noun" | "property" | "operator" | "condition";
|
||||
|
||||
/**
|
||||
* Which objects a noun names when it is the subject of a rule:
|
||||
* - `"named"` (the default): the things of its own name, `<NOUN>` names every object of kind `"<noun>"`;
|
||||
* - `"text"`: every text object (the meta-noun `TEXT`);
|
||||
* - `"things"`: every object that is not text, whatever its noun.
|
||||
*/
|
||||
export type Selects = "named" | "text" | "things";
|
||||
|
||||
/**
|
||||
* One entry of the word list content provides: `{ "name": "<NOUN>", "role": "noun" }`,
|
||||
* optionally with `"selects"` (default `"named"`).
|
||||
*/
|
||||
export interface WordDef {
|
||||
name: string;
|
||||
role: Role;
|
||||
selects?: Selects;
|
||||
}
|
||||
|
||||
export const IS = "IS";
|
||||
export const AND = "AND";
|
||||
export const NOT = "NOT";
|
||||
/** The meta-noun for every text object. */
|
||||
export const TEXT = "TEXT";
|
||||
|
||||
/** Every word the parser can read, with its role. */
|
||||
export class Lexicon {
|
||||
private readonly roles = new Map<string, Role>();
|
||||
private readonly selects = new Map<string, Selects>();
|
||||
|
||||
/** The engine's own words plus `words`. Content can't redefine an engine word. */
|
||||
constructor(words: readonly WordDef[]) {
|
||||
for (const w of words) {
|
||||
this.roles.set(w.name.toUpperCase(), w.role);
|
||||
this.selects.set(w.name.toUpperCase(), w.selects ?? "named");
|
||||
}
|
||||
for (const op of [IS, AND, NOT]) this.roles.set(op, "operator");
|
||||
this.roles.set(TEXT, "noun");
|
||||
this.selects.set(TEXT, "text");
|
||||
}
|
||||
|
||||
/** `undefined` for a word the lexicon doesn't know: such text spells nothing. */
|
||||
role(word: string): Role | undefined {
|
||||
return this.roles.get(word);
|
||||
}
|
||||
|
||||
/** Does the noun `word`, as the subject of a rule, name an object of this kind? */
|
||||
names(word: string, kind: Kind): boolean {
|
||||
switch (this.selects.get(word) ?? "named") {
|
||||
case "named":
|
||||
return kind.type === "thing" && kind.noun === word;
|
||||
case "text":
|
||||
return kind.type === "text";
|
||||
case "things":
|
||||
return kind.type === "thing";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a conversion into the noun `word` makes (Module 9): a thing of that
|
||||
* name, if `word` names the things of its own name. `undefined` for a noun that
|
||||
* names a group (`TEXT`, or `ALL` if content adds it): the course doesn't
|
||||
* convert into those.
|
||||
*/
|
||||
thingNamed(word: string): Kind | undefined {
|
||||
return (this.selects.get(word) ?? "named") === "named" ? { type: "thing", noun: word } : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** A piece of text the parser can read: which object, which word, which role. */
|
||||
export interface Token {
|
||||
id: ObjectId;
|
||||
word: string;
|
||||
role: Role;
|
||||
}
|
||||
|
||||
/** Tile id for maps: `"x,y"`. */
|
||||
export const tileKey = (x: number, y: number): string => `${x},${y}`;
|
||||
|
||||
/**
|
||||
* The words on the board, by tile; a tile's words in object order (oldest first).
|
||||
* Text whose word the lexicon doesn't know is left out.
|
||||
*/
|
||||
export function lex(board: Board, lexicon: Lexicon): Map<string, Token[]> {
|
||||
const tiles = new Map<string, Token[]>();
|
||||
for (const o of board.objects()) {
|
||||
if (o.kind.type !== "text") continue;
|
||||
const role = lexicon.role(o.kind.word);
|
||||
if (role === undefined) continue;
|
||||
const tile = tileKey(o.x, o.y);
|
||||
const tokens = tiles.get(tile) ?? [];
|
||||
tokens.push({ id: o.id, word: o.kind.word, role });
|
||||
tiles.set(tile, tokens);
|
||||
}
|
||||
return tiles;
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
// The action queue: how one player action (a Sequence) resolves.
|
||||
//
|
||||
// Performing an action changes the world and produces events. Every trigger that
|
||||
// responds to those events goes into one Queue, oldest listener first, and the Queue
|
||||
// is locked. Each queued trigger then resolves completely, including everything
|
||||
// its own actions cause, before the next one starts: depth-first.
|
||||
//
|
||||
// Module 3: nothing leaves play mid-Sequence. When the outermost Phase ends, the
|
||||
// Death Creation Step removes the dead, and a Death Phase resolves their
|
||||
// Deathrattles. That repeats until a step finds no new deaths.
|
||||
//
|
||||
// Module 4: a queued trigger may activate more than once. How many times is
|
||||
// decided by one routine, `activations` in `aura.ts`, from aura data on cards.
|
||||
// Nothing here knows which cards multiply which triggers.
|
||||
//
|
||||
// Module 4, second interceptor: replacement. Before a Damage changes the world,
|
||||
// the steps in `DAMAGE_STEPS` may rewrite it, in that order: a redirect changes
|
||||
// who takes it, then Armor takes what it can of damage to a hero.
|
||||
//
|
||||
// Module 5: a card's effects are data. Each one is interpreted (`effect.ts`) and
|
||||
// its actions performed before the next effect of the same ability is read, so
|
||||
// "Assemble a minion. Give all minions in your hand +2/+2." buffs the new minion.
|
||||
//
|
||||
// Module 5, robustness: once a test can write any card as data, one card can make a
|
||||
// Sequence endless. A trigger is never queued while that same trigger of that same
|
||||
// minion is resolving (the nesting guard in `react`), and a Sequence that needs more
|
||||
// than `DEATH_PHASE_LIMIT` Death Phases is an error.
|
||||
//
|
||||
// Module 10: the steps at the end of the outermost Phase are a list, `END_OF_PHASE`,
|
||||
// read from the world, as Part II's turn is a list of phases. SpellGrid's tests run
|
||||
// the same Sequence with the list reversed, to show what the order decides.
|
||||
//
|
||||
// Module 12: combat and the end of a turn. An attack is one Damage action whose two
|
||||
// targets take different amounts (`Hit`), and the triggers answering the defender's
|
||||
// Damage Event queue before the attacker's, whatever their order of play. That
|
||||
// exception is data on the queue entry, a priority: `react` orders its Queue by
|
||||
// priority first and keeps the order it was filled in (order of play) within one
|
||||
// priority. Ending a turn raises an event that the turn's player's end of turn
|
||||
// triggers answer.
|
||||
|
||||
import { assembleFromPool } from "./assemble";
|
||||
import { attackError } from "./combat";
|
||||
import { activations, auraUpdateOther, redirectFor } from "./aura";
|
||||
import type { Effect, PoolFilter, Trigger, TriggerOn } from "./card";
|
||||
import { deathCreationStep } from "./death";
|
||||
import { actions } from "./effect";
|
||||
import type { Event } from "./event";
|
||||
import type { EntityId, PlayerId, World } from "./world";
|
||||
|
||||
/**
|
||||
* How early the triggers answering an event queue (Module 12). A Queue resolves its
|
||||
* entries highest priority first and, within one priority, in the order it was filled:
|
||||
* for each event in order of play, each listener in order of play.
|
||||
*/
|
||||
export type Priority = number;
|
||||
|
||||
/** The priority of every entry, except where a rule says otherwise. */
|
||||
export const NORMAL: Priority = 0;
|
||||
|
||||
/** Combat: the triggers answering the defender's Damage Event go first. */
|
||||
export const DEFENDER: Priority = 1;
|
||||
|
||||
/** One target of a Damage action, the amount it takes, and the priority of the triggers its Damage Event queues. */
|
||||
export interface Hit {
|
||||
target: EntityId;
|
||||
amount: number;
|
||||
priority: Priority;
|
||||
}
|
||||
|
||||
/** Something the engine can do. Card effects return these instead of changing the world. */
|
||||
export type Action =
|
||||
/** Deal each hit's amount to its target at once: all damage first, then the reactions. */
|
||||
| { type: "damage"; hits: Hit[] }
|
||||
| { type: "draw"; player: PlayerId }
|
||||
| { type: "gainArmor"; player: PlayerId; amount: number }
|
||||
| { type: "gainAttack"; id: EntityId; amount: number }
|
||||
| { type: "cast"; card: string; player: PlayerId; target?: EntityId }
|
||||
/** Mark each target pending destroy. They leave play in the next Death Creation Step. */
|
||||
| { type: "destroy"; targets: EntityId[] }
|
||||
/** Summon `card` for `player` at board index `at`, or at the right end if `at` is undefined. */
|
||||
| { type: "summon"; card: string; player: PlayerId; at?: number }
|
||||
/** Play a minion from its owner's hand: it enters the right end of the board, then its Battlecry resolves. */
|
||||
| { type: "play"; id: EntityId }
|
||||
/** Put an Assembled minion into `player`'s hand (see `assemble.ts`). */
|
||||
| { type: "assemble"; player: PlayerId; filter: PoolFilter }
|
||||
/** Give one entity +attack/+health. */
|
||||
| { type: "buff"; id: EntityId; attack: number; health: number }
|
||||
/** Ask for `word` to be written on `source`'s grid tile (Module 10). Part I only records it. */
|
||||
| { type: "spawnText"; source: EntityId; word: string }
|
||||
/** Combat (Module 12): `attacker` and `defender` deal their Attack to each other at once. */
|
||||
| { type: "attack"; attacker: EntityId; defender: EntityId }
|
||||
/** The end of `player`'s turn (Module 12): their minions' end of turn triggers answer it. */
|
||||
| { type: "endTurn"; player: PlayerId };
|
||||
|
||||
/** The same amount to each target, at normal priority: what area damage and a spell deal. */
|
||||
export function hits(targets: readonly EntityId[], amount: number): Hit[] {
|
||||
return targets.map((target) => ({ target, amount, priority: NORMAL }));
|
||||
}
|
||||
|
||||
/**
|
||||
* A step that runs when the outermost Phase ends:
|
||||
* - `"deathCreation"`: the Death Creation Step (Module 3);
|
||||
* - `"auraUpdate"`: an Aura Update (Other) (Module 4).
|
||||
*/
|
||||
export type EndOfPhaseStep = "deathCreation" | "auraUpdate";
|
||||
|
||||
/**
|
||||
* The end of the outermost Phase, in Hearthstone's order: the dead leave play first,
|
||||
* then the auras are read again, so a minion that just died multiplies nothing in
|
||||
* the Death Phase that follows.
|
||||
*/
|
||||
export const END_OF_PHASE: readonly EndOfPhaseStep[] = ["deathCreation", "auraUpdate"];
|
||||
|
||||
/**
|
||||
* A step that may rewrite one Damage to one target before the world changes:
|
||||
* - `"redirect"`: damage to a hero whose owner has a `damageRedirect` aura in force
|
||||
* goes to that aura's minion instead (the oldest one's, if several);
|
||||
* - `"armor"`: damage to a hero lowers its owner's Armor first, then Health.
|
||||
*/
|
||||
export type DamageStep = "redirect" | "armor";
|
||||
|
||||
/**
|
||||
* The order the steps run in. Each runs once per Damage, so a rewritten Damage is
|
||||
* never offered to a redirect again. A redirect comes first: Armor protects only
|
||||
* the hero that actually takes the damage.
|
||||
*/
|
||||
export const DAMAGE_STEPS: readonly DamageStep[] = ["redirect", "armor"];
|
||||
|
||||
/** What an effect may look at when it runs. */
|
||||
export class Ctx {
|
||||
constructor(
|
||||
readonly world: World,
|
||||
/** The player the effect works for. */
|
||||
readonly owner: PlayerId,
|
||||
/** The minion whose trigger is resolving; undefined for a spell. */
|
||||
readonly source?: EntityId,
|
||||
/** The chosen target, if any. */
|
||||
readonly target?: EntityId,
|
||||
/**
|
||||
* The source's board position. For a Deathrattle, the source has left play, and
|
||||
* this is where it stood: immediately left of the minion its Death Event remembers.
|
||||
*/
|
||||
readonly position?: number,
|
||||
) {}
|
||||
|
||||
/** The minion whose trigger is resolving. */
|
||||
minion(): EntityId {
|
||||
if (this.source === undefined) throw new Error("only a triggered ability has a source");
|
||||
return this.source;
|
||||
}
|
||||
|
||||
enemyHero(): EntityId {
|
||||
return this.world.hero(this.owner === 0 ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The most Death Phases one Sequence may have. One more is an error, not a cut-off:
|
||||
* a Sequence that stopped early would resolve differently without saying so.
|
||||
*/
|
||||
export const DEATH_PHASE_LIMIT = 64;
|
||||
|
||||
/** Run one Sequence: a player action and everything it causes. */
|
||||
export function runSequence(world: World, action: Action): void {
|
||||
perform(world, action);
|
||||
// The outermost Phase has ended. Each Death Phase is itself an outermost
|
||||
// Phase, so the end-of-Phase steps run again after it, until nothing dies.
|
||||
let deaths = endOfOutermostPhase(world);
|
||||
for (let round = 1; deaths.length > 0; round++) {
|
||||
// Between Death Phases no trigger is resolving, so the error leaves no block open.
|
||||
if (round > DEATH_PHASE_LIMIT) {
|
||||
throw new Error(`Death Phase limit: more than ${DEATH_PHASE_LIMIT} Death Phases in one Sequence`);
|
||||
}
|
||||
world.record({ type: "DeathPhase", round });
|
||||
react(world, deaths);
|
||||
deaths = endOfOutermostPhase(world);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The steps that run only when the outermost Phase ends, in the world's order
|
||||
* (`END_OF_PHASE` unless changed); returns the Death Events. Hearthstone runs an
|
||||
* Aura Update (Health/Attack) first. The course has no Health/Attack auras, so that
|
||||
* step has nothing to do and is left out.
|
||||
*/
|
||||
function endOfOutermostPhase(world: World): Event[] {
|
||||
let deaths: Event[] = [];
|
||||
for (const step of world.endOfPhase()) {
|
||||
switch (step) {
|
||||
case "deathCreation":
|
||||
deaths = deathCreationStep(world);
|
||||
break;
|
||||
case "auraUpdate":
|
||||
auraUpdateOther(world);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return deaths;
|
||||
}
|
||||
|
||||
/** Summon `card` for `player` at board index `at` (or the right end). Summoning runs an Aura Update. */
|
||||
export function summon(world: World, card: string, player: PlayerId, at?: number): EntityId {
|
||||
const id = world.create(card, player, "board", at);
|
||||
auraUpdateOther(world);
|
||||
return id;
|
||||
}
|
||||
|
||||
function perform(world: World, action: Action): void {
|
||||
switch (action.type) {
|
||||
case "damage": {
|
||||
// Area damage: every Damage Event is created, in order of play, before any reaction.
|
||||
const sorted = [...action.hits].sort((a, b) => world.orderOfPlay(a.target)! - world.orderOfPlay(b.target)!);
|
||||
const events = sorted.map((hit) => applyDamage(world, hit.target, hit.amount));
|
||||
react(world, events, sorted.map((hit) => hit.priority));
|
||||
break;
|
||||
}
|
||||
case "attack": {
|
||||
const { attacker, defender } = action;
|
||||
const error = attackError(world, attacker, defender);
|
||||
if (error !== undefined) throw new Error(error);
|
||||
// Both amounts are read before either is dealt: the damage is simultaneous. A
|
||||
// hero has no Attack, so it deals nothing back; nor does a 0 Attack minion.
|
||||
const attack: Hit[] = [{ target: defender, amount: world.attack(attacker), priority: DEFENDER }];
|
||||
const counter = world.attack(defender);
|
||||
if (counter > 0) attack.push({ target: attacker, amount: counter, priority: NORMAL });
|
||||
perform(world, { type: "damage", hits: attack });
|
||||
break;
|
||||
}
|
||||
case "endTurn": {
|
||||
const ended: Event = { type: "TurnEnded", player: action.player };
|
||||
world.record(ended);
|
||||
react(world, [ended]);
|
||||
break;
|
||||
}
|
||||
case "draw":
|
||||
world.draw(action.player);
|
||||
break;
|
||||
case "gainArmor":
|
||||
world.gainArmor(action.player, action.amount);
|
||||
break;
|
||||
case "gainAttack":
|
||||
world.gainAttack(action.id, action.amount);
|
||||
break;
|
||||
case "destroy":
|
||||
for (const target of action.targets) world.markDestroyed(target);
|
||||
break;
|
||||
case "summon":
|
||||
summon(world, action.card, action.player, action.at);
|
||||
break;
|
||||
case "play": {
|
||||
if (world.zoneOf(action.id) !== "hand") throw new Error(`play: entity ${action.id} is not in a hand`);
|
||||
// Playing is not summoning: no Aura Update here. The played minion's own
|
||||
// auras join at the end of the outermost Phase.
|
||||
world.moveTo(action.id, "board");
|
||||
const played: Event = { type: "Played", id: action.id };
|
||||
world.record(played);
|
||||
react(world, [played]);
|
||||
break;
|
||||
}
|
||||
case "cast": {
|
||||
const spell = world.card(action.card);
|
||||
if (spell.def.type !== "spell") throw new Error(`"${action.card}" is not a spell`);
|
||||
world.record({ type: "SpellCast", card: action.card });
|
||||
runEffects(world, spell.onCast, new Ctx(world, action.player, undefined, action.target));
|
||||
break;
|
||||
}
|
||||
case "assemble":
|
||||
assembleFromPool(world, action.player, action.filter);
|
||||
break;
|
||||
case "buff":
|
||||
world.buff(action.id, action.attack, action.health);
|
||||
break;
|
||||
case "spawnText":
|
||||
world.record({ type: "TextSpawned", source: action.source, word: action.word });
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Interpret and perform an ability's effects in printed order. Each effect sees the
|
||||
* world as the effects before it left it. Depth-first: each action, and every
|
||||
* reaction it causes, finishes before the next.
|
||||
*/
|
||||
function runEffects(world: World, effects: Effect[], ctx: Ctx): void {
|
||||
for (const effect of effects) {
|
||||
for (const action of actions(effect, ctx)) perform(world, action);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deal one Damage to one target, after the steps of `DAMAGE_STEPS` have rewritten it.
|
||||
* Returns its Damage Event, which names whoever took it.
|
||||
*/
|
||||
function applyDamage(world: World, target: EntityId, amount: number): Event {
|
||||
let taker = target;
|
||||
let absorbed = 0;
|
||||
for (const step of DAMAGE_STEPS) {
|
||||
switch (step) {
|
||||
case "redirect":
|
||||
if (world.isHero(taker)) taker = redirectFor(world, world.ownerOf(taker)) ?? taker;
|
||||
break;
|
||||
case "armor":
|
||||
if (world.isHero(taker)) {
|
||||
const player = world.ownerOf(taker);
|
||||
absorbed = Math.min(world.armor(player), amount);
|
||||
if (absorbed > 0) world.loseArmor(player, absorbed);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
world.damage(taker, amount, absorbed);
|
||||
return { type: "Damaged", target: taker, amount };
|
||||
}
|
||||
|
||||
/**
|
||||
* A Phase: queue every trigger that responds to `events`, then resolve them one by one.
|
||||
* `priorities[i]` is the priority of the entries answering `events[i]` (`NORMAL` if absent).
|
||||
*/
|
||||
function react(world: World, events: Event[], priorities: readonly Priority[] = []): void {
|
||||
// Fill the Queue: for each event (already in order of play), each listener in order of play.
|
||||
// The nesting guard: a trigger that is resolving right now is not queued again, so
|
||||
// a trigger is never nested inside itself.
|
||||
const queue: [EntityId, number, Trigger, Event, Priority][] = [];
|
||||
events.forEach((event, e) => {
|
||||
for (const listener of listeners(world, event)) {
|
||||
world.card(world.cardName(listener)).triggers.forEach((trigger, index) => {
|
||||
if (responds(world, trigger.on, listener, event) && !world.isResolving(listener, index)) {
|
||||
queue.push([listener, index, trigger, event, priorities[e] ?? NORMAL]);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
// Priority first; the sort is stable, so entries of one priority keep the order above.
|
||||
queue.sort((a, b) => b[4] - a[4]);
|
||||
// The Queue is now locked: nothing that happens below adds to it.
|
||||
for (const [source, index, trigger, event] of queue) {
|
||||
// The interceptor: the entry was queued once; the auras in force when it
|
||||
// starts decide how many times it activates, back to back.
|
||||
const times = activations(world, world.ownerOf(source), trigger.on);
|
||||
for (let i = 0; i < times; i++) {
|
||||
world.record({ type: "Triggered", source, on: trigger.on });
|
||||
const position =
|
||||
event.type === "Destroyed" && event.id === source
|
||||
? positionLeftOf(world, world.ownerOf(source), event.before)
|
||||
: world.boardIndex(source);
|
||||
// The trigger's consequences are one level deeper in the log tree.
|
||||
world.openBlock(source, index);
|
||||
runEffects(world, trigger.effects, new Ctx(world, world.ownerOf(source), source, undefined, position));
|
||||
world.closeBlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The board index, right now, immediately left of `before` on `owner`'s board; the
|
||||
* right end if `before` is undefined or no longer there. A Death Event remembers the
|
||||
* minion, not an index, so this still holds after other minions have left or arrived.
|
||||
*/
|
||||
function positionLeftOf(world: World, owner: PlayerId, before: EntityId | undefined): number {
|
||||
const board = world.zone(owner, "board");
|
||||
const index = before === undefined ? -1 : board.indexOf(before);
|
||||
return index < 0 ? board.length : index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who may respond to `event`, in order of play: every minion in play and, for a
|
||||
* Death Event, the minion that died. It has left play, but its Deathrattle still answers.
|
||||
*/
|
||||
function listeners(world: World, event: Event): EntityId[] {
|
||||
const inPlay = world.minionsInPlay();
|
||||
if (event.type !== "Destroyed") return inPlay;
|
||||
return [...inPlay, event.id].sort((a, b) => world.orderOfPlay(a)! - world.orderOfPlay(b)!);
|
||||
}
|
||||
|
||||
/** Does a trigger listening for `on`, belonging to `listener`, respond to `event`? */
|
||||
function responds(world: World, on: TriggerOn, listener: EntityId, event: Event): boolean {
|
||||
if (event.type === "Destroyed") return on === "deathrattle" && event.id === listener;
|
||||
if (event.type === "Played") return on === "battlecry" && event.id === listener;
|
||||
if (event.type === "TurnEnded") return on === "endOfTurn" && world.ownerOf(listener) === event.player;
|
||||
if (event.type !== "Damaged") return false;
|
||||
const isMinion = !world.isHero(event.target);
|
||||
switch (on) {
|
||||
case "selfDamaged":
|
||||
return event.target === listener;
|
||||
case "friendlyMinionDamaged":
|
||||
return isMinion && world.ownerOf(event.target) === world.ownerOf(listener);
|
||||
case "anyMinionDamaged":
|
||||
return isMinion;
|
||||
case "heroDamaged":
|
||||
return !isMinion;
|
||||
case "deathrattle":
|
||||
case "battlecry":
|
||||
case "endOfTurn":
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
// Part III: SpellGrid, the two engines in one level.
|
||||
//
|
||||
// Part I (the card engine) and Part II (the grid engine, `puzzle/`) don't import each
|
||||
// other. This file is the only place that knows both, and they meet at four seams:
|
||||
//
|
||||
// 1. Rules become modifiers. After every reparse, the rules in force that join a
|
||||
// trigger word to a multiplier word (`DEATHRATTLE IS DOUBLE`) are compiled into
|
||||
// auras, and handed to Part I with `World.setRuleAuras`. A negated one
|
||||
// (`DEATHRATTLE IS NOT DOUBLE`) becomes a cap. Which words are which is content's
|
||||
// data (`SeamWords`), not code here.
|
||||
// 2. Hazards mark, the death step removes. The grid engine hands the objects a turn
|
||||
// destroys to `destroy` below. A minion among them is marked pending destroy, in
|
||||
// one Sequence, and Part I's Death Creation Step removes it.
|
||||
// 3. Grid changes reparse. While a Sequence runs, the grid doesn't change. When it
|
||||
// ends, the text its effects asked for (`TextSpawned` events) is written, the
|
||||
// minions that died (`Destroyed` events) leave the grid, and the rules are parsed
|
||||
// again, before anything else happens.
|
||||
// 4. Summoned minions enter the grid. In the same place, before the dead leave: a
|
||||
// minion that a minion's ability summoned (`Summoned` events with a `by`), whose card
|
||||
// has a noun, becomes an object of that noun on its summoner's tile. One summoned by
|
||||
// a spell, or with no noun, is in play but not on the grid.
|
||||
//
|
||||
// One id space: a minion's id is its grid object's id. Every other card (a hero, a
|
||||
// card in hand) gets an id from the same counter that no object will have.
|
||||
|
||||
import { auraUpdateOther } from "./aura";
|
||||
import type { Aura, CardLibrary, TriggerOn } from "./card";
|
||||
import type { Event } from "./event";
|
||||
import * as puzzle from "./puzzle";
|
||||
import { runSequence, type Action } from "./queue";
|
||||
import { World, type EntityId } from "./world";
|
||||
|
||||
/**
|
||||
* The words that cross the seam, from content: nouns that name a trigger
|
||||
* (`"DEATHRATTLE": "deathrattle"`) and properties that multiply one
|
||||
* (`"DOUBLE": { "times": 2, "stacking": "max" }`).
|
||||
*/
|
||||
export interface SeamWords {
|
||||
triggerWords: Record<string, TriggerOn>;
|
||||
multiplierWords: Record<string, { times: number; stacking: "max" | "additive" }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Seam 1: the auras the rules in force give. `T IS M` (T a trigger word, M a multiplier
|
||||
* word) multiplies T's triggers; `T IS NOT M` caps them at one activation, so it
|
||||
* cancels a card's multiplier too, as `X IS NOT Y` cancels every `X IS Y`.
|
||||
*
|
||||
* Module 11: a rule with a condition gives no aura. A condition holds or not for one
|
||||
* object on the grid, and a trigger word names no object (the course's choice).
|
||||
*/
|
||||
export function ruleAuras(rules: readonly puzzle.Rule[], words: SeamWords): Aura[] {
|
||||
const auras: Aura[] = [];
|
||||
for (const rule of rules) {
|
||||
if (rule.conditions.length > 0) continue;
|
||||
const trigger = words.triggerWords[rule.subject];
|
||||
const multiplier = words.multiplierWords[rule.complement];
|
||||
if (trigger === undefined || multiplier === undefined) continue;
|
||||
auras.push(
|
||||
rule.negated
|
||||
? { type: "triggerCap", trigger, times: 1 }
|
||||
: { type: "triggerMultiplier", trigger, ...multiplier },
|
||||
);
|
||||
}
|
||||
return auras;
|
||||
}
|
||||
|
||||
/** A SpellGrid level in play: a grid and a game, kept in step. Ids are grid ids (see above). */
|
||||
export class SpellGrid {
|
||||
readonly world: World;
|
||||
readonly level: puzzle.Level;
|
||||
/** Every entity's id. */
|
||||
private readonly ids = new Map<EntityId, puzzle.ObjectId>();
|
||||
/** The entity behind each id (a card's old id still finds it after it is played). */
|
||||
private readonly entities = new Map<puzzle.ObjectId, EntityId>();
|
||||
|
||||
/**
|
||||
* The level's objects; its `cards` as minions in play for player 0, each a grid
|
||||
* object named by the card's noun; its `hand` in player 0's hand.
|
||||
*/
|
||||
constructor(
|
||||
def: puzzle.LevelDef,
|
||||
library: CardLibrary,
|
||||
words: readonly puzzle.WordDef[],
|
||||
responses: readonly puzzle.Response[],
|
||||
hazards: readonly puzzle.Hazard[],
|
||||
conditions: puzzle.ConditionChecks,
|
||||
private readonly seamWords: SeamWords,
|
||||
) {
|
||||
this.world = new World(library);
|
||||
this.level = new puzzle.Level(def, words, responses, hazards, conditions);
|
||||
for (const { card, x, y } of def.cards ?? []) {
|
||||
const id = this.level.board.place(this.nounOf(card), x, y);
|
||||
this.link(this.world.create(card, 0, "board"), id);
|
||||
}
|
||||
// Every minion is in play: one Aura Update, as for a summon.
|
||||
auraUpdateOther(this.world);
|
||||
for (const card of def.hand ?? []) this.world.create(card, 0, "hand");
|
||||
this.linkTheRest();
|
||||
this.gridChanged();
|
||||
}
|
||||
|
||||
// ---- Ids ----
|
||||
|
||||
/** The id of entity `entity`. */
|
||||
idOf(entity: EntityId): puzzle.ObjectId {
|
||||
const id = this.ids.get(entity);
|
||||
if (id === undefined) throw new Error(`entity ${entity} has no id`);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** The entity behind `id`. Throws if `id` is not a card's. */
|
||||
entity(id: puzzle.ObjectId): EntityId {
|
||||
const entity = this.entities.get(id);
|
||||
if (entity === undefined) throw new Error(`${id} is not a card`);
|
||||
return entity;
|
||||
}
|
||||
|
||||
/** The id of the minion on tile (x, y), if there is one. */
|
||||
minionAt(x: number, y: number): puzzle.ObjectId | undefined {
|
||||
return this.level.board.at(x, y).find((o) => this.entities.has(o.id))?.id;
|
||||
}
|
||||
|
||||
private link(entity: EntityId, id: puzzle.ObjectId): void {
|
||||
this.ids.set(entity, id);
|
||||
this.entities.set(id, entity);
|
||||
}
|
||||
|
||||
/** Give every entity that has no id one that no object will have. */
|
||||
private linkTheRest(): void {
|
||||
for (let entity = 0; entity < this.world.entityCount(); entity++) {
|
||||
if (!this.ids.has(entity)) this.link(entity, this.level.board.reserveId());
|
||||
}
|
||||
}
|
||||
|
||||
private nounOf(card: string): puzzle.Kind {
|
||||
const { def } = this.world.card(card);
|
||||
if (def.type !== "minion" || def.noun === undefined) throw new Error(`"${card}" is not a minion with a noun`);
|
||||
return puzzle.Kind.parse(def.noun.toLowerCase());
|
||||
}
|
||||
|
||||
// ---- What the player does ----
|
||||
|
||||
/** Add an object or a piece of text, then reparse. */
|
||||
place(kind: string, x: number, y: number): puzzle.ObjectId {
|
||||
const id = this.level.place(kind, x, y);
|
||||
this.gridChanged();
|
||||
return id;
|
||||
}
|
||||
|
||||
/** One whole turn (Module 9); what it destroys goes through seam 2. */
|
||||
step(dir: puzzle.Dir): void {
|
||||
this.level.step(dir, this.destroy);
|
||||
this.gridChanged();
|
||||
}
|
||||
|
||||
/** Movement only (Module 8), then a reparse. */
|
||||
move(dir: puzzle.Dir): void {
|
||||
this.level.moveYou(dir, this.destroy);
|
||||
this.gridChanged();
|
||||
}
|
||||
|
||||
/**
|
||||
* Why `cast(card, target)` can't be done now, or `undefined` if it can: the card must
|
||||
* be a spell in player 0's hand, and a spell that hits a chosen minion needs a target
|
||||
* minion on the grid. Nothing changes when the answer is no.
|
||||
*/
|
||||
checkCast(card: string, target?: puzzle.ObjectId): string | undefined {
|
||||
const problem = this.checkHand(card, "spell");
|
||||
if (problem !== undefined) return problem;
|
||||
const chooses = this.world.card(card).onCast.some((e) => "target" in e && e.target === "chosen");
|
||||
if (target === undefined) return chooses ? `"${card}" needs a target minion` : undefined;
|
||||
const object = this.level.board.find(target);
|
||||
if (object === undefined || !this.entities.has(target)) return `${target} is not a minion on the grid`;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Why `play(card, x, y)` can't be done now, or `undefined` if it can. */
|
||||
checkPlay(card: string, x: number, y: number): string | undefined {
|
||||
const problem = this.checkHand(card, "minion");
|
||||
if (problem !== undefined) return problem;
|
||||
if (this.world.card(card).def.noun === undefined) return `"${card}" has no noun: it can't stand on the grid`;
|
||||
if (!this.level.board.inBounds(x, y)) return `(${x}, ${y}) is off the grid`;
|
||||
if (this.level.board.at(x, y).length > 0) return `(${x}, ${y}) is not empty`;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Cast a spell from player 0's hand, as one Sequence. `target` is a minion's id. Throws if `checkCast` says no. */
|
||||
cast(card: string, target?: puzzle.ObjectId): void {
|
||||
const problem = this.checkCast(card, target);
|
||||
if (problem !== undefined) throw new Error(problem);
|
||||
this.world.moveTo(this.inHand(card)!, "graveyard");
|
||||
const chosen = target === undefined ? undefined : this.entity(target);
|
||||
this.sequence({ type: "cast", card, player: 0, target: chosen });
|
||||
}
|
||||
|
||||
/**
|
||||
* Play a minion from player 0's hand onto the empty tile (x, y), as one Sequence.
|
||||
* Returns its new id. Throws if `checkPlay` says no.
|
||||
*/
|
||||
play(card: string, x: number, y: number): puzzle.ObjectId {
|
||||
const problem = this.checkPlay(card, x, y);
|
||||
if (problem !== undefined) throw new Error(problem);
|
||||
const inHand = this.inHand(card)!;
|
||||
const id = this.level.board.place(this.nounOf(card), x, y);
|
||||
this.link(inHand, id);
|
||||
this.sequence({ type: "play", id: inHand });
|
||||
return id;
|
||||
}
|
||||
|
||||
private inHand(card: string): EntityId | undefined {
|
||||
return this.world.zone(0, "hand").find((id) => this.world.cardName(id) === card);
|
||||
}
|
||||
|
||||
private checkHand(card: string, type: "minion" | "spell"): string | undefined {
|
||||
if (this.inHand(card) === undefined) return `"${card}" is not in the hand`;
|
||||
if (this.world.card(card).def.type !== type) return `"${card}" is not a ${type}`;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// ---- The seams ----
|
||||
|
||||
/**
|
||||
* Seam 2. Objects that aren't cards leave the board. Minions are marked pending
|
||||
* destroy, in one Sequence, under the rules as they stand now.
|
||||
*/
|
||||
private readonly destroy: puzzle.Destroy = (level, ids) => {
|
||||
const present = [...new Set(ids)].filter((id) => level.board.find(id) !== undefined);
|
||||
const minions = present.filter((id) => this.entities.has(id));
|
||||
for (const id of present) if (!this.entities.has(id)) level.board.remove(id);
|
||||
if (minions.length === 0) return;
|
||||
this.syncRules();
|
||||
this.sequence({ type: "destroy", targets: minions.map((id) => this.entity(id)) });
|
||||
};
|
||||
|
||||
/** Run one Sequence in Part I, then seams 3 and 4: apply its grid changes and reparse. */
|
||||
private sequence(action: Action): void {
|
||||
const from = this.world.log().length;
|
||||
runSequence(this.world, action);
|
||||
const events = this.world.log().slice(from);
|
||||
const board = this.level.board;
|
||||
// Text first, while every minion that wrote it is still on its tile.
|
||||
for (const event of events) {
|
||||
if (event.type !== "TextSpawned") continue;
|
||||
// A minion with no id (summoned by this Sequence) is not on the grid yet: nowhere to write.
|
||||
const id = this.ids.get(event.source);
|
||||
const source = id === undefined ? undefined : board.find(id);
|
||||
if (source !== undefined) board.place({ type: "text", word: event.word }, source.x, source.y);
|
||||
}
|
||||
// Seam 4: summoned minions, in summon order, on their summoner's tile. The dead are still
|
||||
// on the grid here, so a Deathrattle's summoner is found where it died; a minion summoned
|
||||
// earlier in the list is already placed, so it can be a summoner too.
|
||||
for (const event of events) {
|
||||
if (event.type !== "Summoned" || event.by === undefined) continue;
|
||||
const card = this.world.cardName(event.id);
|
||||
if (this.ids.has(event.id) || this.world.card(card).def.noun === undefined) continue;
|
||||
const by = this.ids.get(event.by);
|
||||
const summoner = by === undefined ? undefined : board.find(by);
|
||||
if (summoner !== undefined) this.link(event.id, board.place(this.nounOf(card), summoner.x, summoner.y));
|
||||
}
|
||||
for (const event of deaths(events)) {
|
||||
const id = this.ids.get(event.id);
|
||||
if (id !== undefined) board.remove(id);
|
||||
}
|
||||
this.linkTheRest();
|
||||
this.gridChanged();
|
||||
}
|
||||
|
||||
/** The grid changed: reparse it, then seam 1. */
|
||||
private gridChanged(): void {
|
||||
this.level.reparse();
|
||||
this.syncRules();
|
||||
}
|
||||
|
||||
/** Seam 1: compile the rules in force into auras for Part I, then run an Aura Update. */
|
||||
private syncRules(): void {
|
||||
this.world.setRuleAuras(ruleAuras(this.level.activeRules(), this.seamWords));
|
||||
auraUpdateOther(this.world);
|
||||
}
|
||||
}
|
||||
|
||||
const deaths = (events: readonly Event[]) =>
|
||||
events.filter((e): e is Extract<Event, { type: "Destroyed" }> => e.type === "Destroyed");
|
||||
@@ -0,0 +1,382 @@
|
||||
// Entities, zones, order of play, stats and the event log: the game's state.
|
||||
// The rules for resolving actions live in `queue.ts`.
|
||||
|
||||
import type { Aura, Card, CardDef, CardLibrary } from "./card";
|
||||
import type { Event } from "./event";
|
||||
import { END_OF_PHASE, type EndOfPhaseStep } from "./queue";
|
||||
|
||||
/** A handle to an entity. Ids are never reused and stay valid when the entity changes zone. */
|
||||
export type EntityId = number;
|
||||
export type PlayerId = 0 | 1;
|
||||
export type Zone = "deck" | "hand" | "board" | "graveyard";
|
||||
|
||||
/** Starting Health of each hero. */
|
||||
export const HERO_HEALTH = 30;
|
||||
|
||||
interface Entity {
|
||||
card: string;
|
||||
owner: PlayerId;
|
||||
zone: Zone;
|
||||
/** Stamped each time the entity enters the board; undefined until it first does. */
|
||||
orderOfPlay?: number;
|
||||
attack: number;
|
||||
/** Current Health. At 0 or below the entity is mortally wounded: still in play until the Death Creation Step. */
|
||||
health: number;
|
||||
/** Hit by a destroy effect: still in play until the Death Creation Step. */
|
||||
pendingDestroy: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* An aura in force: which minion has it, and that minion's owner. An aura from outside
|
||||
* the cards (Module 10) has no minion, and is in force once for each player.
|
||||
*/
|
||||
export interface ActiveAura {
|
||||
owner: PlayerId;
|
||||
source?: EntityId;
|
||||
aura: Aura;
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a player's choices: called with what is being chosen and the options, it
|
||||
* returns one of the options. Hearthstone would ask the player or pick at random.
|
||||
*/
|
||||
export type Chooser = (kind: string, options: readonly string[]) => string;
|
||||
|
||||
/** One player's zones (each an ordered list of ids; the board is left to right), hero and Armor. */
|
||||
type Side = Record<Zone, EntityId[]> & { hero: EntityId; armor: number };
|
||||
|
||||
export class World {
|
||||
/** Indexed by EntityId. */
|
||||
private readonly entities: Entity[] = [];
|
||||
private readonly sides: [Side, Side];
|
||||
private nextOrderOfPlay = 0;
|
||||
private events: Event[] = [];
|
||||
/** The nesting depth at which each event in `events` was recorded, index for index. */
|
||||
private depths: number[] = [];
|
||||
/**
|
||||
* The triggers resolving right now, one inside another, outermost first: each is a
|
||||
* minion and the index of the trigger in its card's `triggers`. How many there are
|
||||
* is the nesting depth of the log tree.
|
||||
*/
|
||||
private resolving: [EntityId, number][] = [];
|
||||
/** The auras in force as of the last Aura Update. Changes only there (see `aura.ts`). */
|
||||
private auras: ActiveAura[] = [];
|
||||
/** Until a chooser is set, take the first option. */
|
||||
private chooser: Chooser = (_kind, options) => options[0];
|
||||
/**
|
||||
* Module 10: auras that no minion carries, for every player's minions. SpellGrid
|
||||
* compiles them from the rules on its grid. The next Aura Update brings them in.
|
||||
*/
|
||||
private rules: Aura[] = [];
|
||||
/** Module 10: the steps at the end of the outermost Phase, in order. */
|
||||
private endSteps: readonly EndOfPhaseStep[] = END_OF_PHASE;
|
||||
|
||||
/** A new game: both heroes are in play from the start, so they are the oldest entities. */
|
||||
constructor(private readonly library: CardLibrary) {
|
||||
const side = (owner: PlayerId): Side => {
|
||||
const hero = this.entities.length;
|
||||
this.entities.push({
|
||||
card: "Hero",
|
||||
owner,
|
||||
zone: "board",
|
||||
orderOfPlay: ++this.nextOrderOfPlay,
|
||||
attack: 0,
|
||||
health: HERO_HEALTH,
|
||||
pendingDestroy: false,
|
||||
});
|
||||
// In play, but not on the board list: the board holds minions only.
|
||||
return { deck: [], hand: [], board: [], graveyard: [], hero, armor: 0 };
|
||||
};
|
||||
this.sides = [side(0), side(1)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an entity of `card` for `owner` in `zone`: at the end (the right end for the board),
|
||||
* or at index `at` when given (clamped to the zone's length).
|
||||
*/
|
||||
create(card: string, owner: PlayerId, zone: Zone, at?: number): EntityId {
|
||||
if (owner !== 0 && owner !== 1) throw new Error(`no player ${owner}`);
|
||||
const { def } = this.library.get(card);
|
||||
const id = this.entities.length;
|
||||
this.entities.push({
|
||||
card: def.name,
|
||||
owner,
|
||||
zone,
|
||||
attack: def.attack ?? 0,
|
||||
health: def.health ?? 0,
|
||||
pendingDestroy: false,
|
||||
});
|
||||
this.enter(id, zone, at);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Move an entity to the end of `zone` on its owner's side, keeping its id. */
|
||||
moveTo(id: EntityId, zone: Zone): void {
|
||||
const { owner, zone: from } = this.entity(id);
|
||||
const list = this.sides[owner][from];
|
||||
list.splice(list.indexOf(id), 1);
|
||||
this.enter(id, zone);
|
||||
}
|
||||
|
||||
/** The single place an entity arrives in a zone. Entering the board starts a new order of play. */
|
||||
private enter(id: EntityId, zone: Zone, at?: number): void {
|
||||
const entity = this.entity(id);
|
||||
const list = this.sides[entity.owner][zone];
|
||||
list.splice(at === undefined ? list.length : Math.min(at, list.length), 0, id);
|
||||
entity.zone = zone;
|
||||
if (zone === "board") {
|
||||
entity.orderOfPlay = ++this.nextOrderOfPlay;
|
||||
// The summoner is the minion whose trigger is resolving (the innermost one), if any.
|
||||
this.record({ type: "Summoned", id, by: this.resolving.at(-1)?.[0] });
|
||||
}
|
||||
}
|
||||
|
||||
private entity(id: EntityId): Entity {
|
||||
const entity = this.entities[id];
|
||||
if (!entity) throw new Error(`unknown entity id ${id}`);
|
||||
return entity;
|
||||
}
|
||||
|
||||
// ---- Queries ----
|
||||
|
||||
card(name: string): Card {
|
||||
return this.library.get(name);
|
||||
}
|
||||
|
||||
hasCard(name: string): boolean {
|
||||
return this.library.has(name);
|
||||
}
|
||||
|
||||
/** The cards an Assemble may offer, sorted by name. */
|
||||
pool(): Card[] {
|
||||
return this.library.pool();
|
||||
}
|
||||
|
||||
zoneOf(id: EntityId): Zone {
|
||||
return this.entity(id).zone;
|
||||
}
|
||||
|
||||
cardName(id: EntityId): string {
|
||||
return this.entity(id).card;
|
||||
}
|
||||
|
||||
ownerOf(id: EntityId): PlayerId {
|
||||
return this.entity(id).owner;
|
||||
}
|
||||
|
||||
/** When the entity last entered the board (larger is later); undefined if it never has. */
|
||||
orderOfPlay(id: EntityId): number | undefined {
|
||||
return this.entity(id).orderOfPlay;
|
||||
}
|
||||
|
||||
/** The ids in one player's zone, in zone order (left to right for the board). */
|
||||
zone(owner: PlayerId, zone: Zone): readonly EntityId[] {
|
||||
if (owner !== 0 && owner !== 1) throw new Error(`no player ${owner}`);
|
||||
return this.sides[owner][zone];
|
||||
}
|
||||
|
||||
hero(owner: PlayerId): EntityId {
|
||||
if (owner !== 0 && owner !== 1) throw new Error(`no player ${owner}`);
|
||||
return this.sides[owner].hero;
|
||||
}
|
||||
|
||||
isHero(id: EntityId): boolean {
|
||||
return this.sides.some((s) => s.hero === id);
|
||||
}
|
||||
|
||||
/** Every minion on either board, oldest first (order of play). */
|
||||
minionsInPlay(): EntityId[] {
|
||||
return [...this.sides[0].board, ...this.sides[1].board].sort(
|
||||
(a, b) => this.orderOfPlay(a)! - this.orderOfPlay(b)!,
|
||||
);
|
||||
}
|
||||
|
||||
attack(id: EntityId): number {
|
||||
return this.entity(id).attack;
|
||||
}
|
||||
|
||||
health(id: EntityId): number {
|
||||
return this.entity(id).health;
|
||||
}
|
||||
|
||||
/** The cost printed on the entity's card. */
|
||||
cost(id: EntityId): number {
|
||||
return this.card(this.cardName(id)).def.cost;
|
||||
}
|
||||
|
||||
/** The minions in a player's hand, in hand order. */
|
||||
minionsInHand(owner: PlayerId): EntityId[] {
|
||||
return this.zone(owner, "hand").filter((id) => this.card(this.cardName(id)).def.type === "minion");
|
||||
}
|
||||
|
||||
/** Mortally wounded (0 or less Health) or pending destroy: it leaves play at the next Death Creation Step. */
|
||||
isDoomed(id: EntityId): boolean {
|
||||
const entity = this.entity(id);
|
||||
return entity.health <= 0 || entity.pendingDestroy;
|
||||
}
|
||||
|
||||
/** Index of a minion on its owner's board, left to right; undefined if it is not on the board. */
|
||||
boardIndex(id: EntityId): number | undefined {
|
||||
const index = this.sides[this.ownerOf(id)].board.indexOf(id);
|
||||
return index < 0 ? undefined : index;
|
||||
}
|
||||
|
||||
armor(owner: PlayerId): number {
|
||||
return this.sides[owner].armor;
|
||||
}
|
||||
|
||||
activeAuras(): readonly ActiveAura[] {
|
||||
return this.auras;
|
||||
}
|
||||
|
||||
/** Auras from outside the cards (Module 10), as last set. */
|
||||
ruleAuras(): readonly Aura[] {
|
||||
return this.rules;
|
||||
}
|
||||
|
||||
/** The steps at the end of the outermost Phase, in order. */
|
||||
endOfPhase(): readonly EndOfPhaseStep[] {
|
||||
return this.endSteps;
|
||||
}
|
||||
|
||||
/** How many entities exist: ids run from 0 to this, exclusive. */
|
||||
entityCount(): number {
|
||||
return this.entities.length;
|
||||
}
|
||||
|
||||
log(): readonly Event[] {
|
||||
return this.events;
|
||||
}
|
||||
|
||||
/** The nesting depth of each event in `log()`, index for index: 0 for the outermost action's own events. */
|
||||
logDepths(): readonly number[] {
|
||||
return this.depths;
|
||||
}
|
||||
|
||||
// ---- Changes: each one records its event ----
|
||||
|
||||
record(event: Event): void {
|
||||
this.events.push(event);
|
||||
this.depths.push(this.resolving.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger number `trigger` of `source` starts resolving: the events it causes are
|
||||
* recorded one level deeper.
|
||||
*/
|
||||
openBlock(source: EntityId, trigger: number): void {
|
||||
this.resolving.push([source, trigger]);
|
||||
}
|
||||
|
||||
/** The trigger that last opened a block has finished resolving. */
|
||||
closeBlock(): void {
|
||||
this.resolving.pop();
|
||||
}
|
||||
|
||||
/** Is trigger number `trigger` of `source` resolving right now (at any depth)? */
|
||||
isResolving(source: EntityId, trigger: number): boolean {
|
||||
return this.resolving.some(([s, t]) => s === source && t === trigger);
|
||||
}
|
||||
|
||||
/** Add a card to the library, or replace the card with the same name. */
|
||||
register(def: CardDef): void {
|
||||
this.library.register(def);
|
||||
}
|
||||
|
||||
/** Add a card made by Assemble (see `assemble.ts`). */
|
||||
registerAssembled(def: CardDef): void {
|
||||
this.library.registerAssembled(def);
|
||||
}
|
||||
|
||||
setChooser(chooser: Chooser): void {
|
||||
this.chooser = chooser;
|
||||
}
|
||||
|
||||
/** Ask the chooser to pick one of `options` (not empty). Throws if it answers something that isn't an option. */
|
||||
choose(kind: string, options: readonly string[]): string {
|
||||
const answer = this.chooser(kind, options);
|
||||
if (!options.includes(answer)) {
|
||||
throw new Error(`chooser answered "${answer}" for "${kind}"; the options were ${JSON.stringify(options)}`);
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
|
||||
/** Replace the auras from outside the cards. They take effect at the next Aura Update. */
|
||||
setRuleAuras(auras: Aura[]): void {
|
||||
this.rules = auras;
|
||||
}
|
||||
|
||||
/** Change the order of the steps at the end of the outermost Phase. */
|
||||
setEndOfPhase(steps: readonly EndOfPhaseStep[]): void {
|
||||
this.endSteps = steps;
|
||||
}
|
||||
|
||||
/** Only an Aura Update calls this. */
|
||||
setActiveAuras(auras: ActiveAura[]): void {
|
||||
this.auras = auras;
|
||||
}
|
||||
|
||||
clearLog(): void {
|
||||
this.events = [];
|
||||
this.depths = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* `target` takes `amount` damage, of which `absorbed` was already taken by Armor
|
||||
* (see `loseArmor`): Health drops by the rest. The event shows the full amount.
|
||||
*/
|
||||
damage(target: EntityId, amount: number, absorbed = 0): void {
|
||||
this.entity(target).health -= amount - absorbed;
|
||||
this.record({ type: "Damaged", target, amount });
|
||||
}
|
||||
|
||||
/** `player`'s hero's Armor absorbs `amount` damage. */
|
||||
loseArmor(player: PlayerId, amount: number): void {
|
||||
this.sides[player].armor -= amount;
|
||||
this.record({ type: "ArmorLost", player, amount });
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the top card of `player`'s deck (the first in the list). An empty deck
|
||||
* records `Fatigue` and changes nothing else.
|
||||
*/
|
||||
draw(player: PlayerId): void {
|
||||
const id = this.zone(player, "deck")[0];
|
||||
if (id === undefined) {
|
||||
this.record({ type: "Fatigue", player });
|
||||
return;
|
||||
}
|
||||
this.moveTo(id, "hand");
|
||||
this.record({ type: "Drew", player, id });
|
||||
}
|
||||
|
||||
/** Mark for destruction. Nothing leaves play until the Death Creation Step. */
|
||||
markDestroyed(id: EntityId): void {
|
||||
this.entity(id).pendingDestroy = true;
|
||||
}
|
||||
|
||||
/** Move a minion from play to its owner's graveyard, recording its Death Event. */
|
||||
kill(id: EntityId, before: EntityId | undefined): void {
|
||||
this.entity(id).pendingDestroy = false;
|
||||
this.moveTo(id, "graveyard");
|
||||
this.record({ type: "Destroyed", id, before });
|
||||
}
|
||||
|
||||
gainArmor(player: PlayerId, amount: number): void {
|
||||
this.sides[player].armor += amount;
|
||||
this.record({ type: "ArmorGained", player, amount });
|
||||
}
|
||||
|
||||
buff(id: EntityId, attack: number, health: number): void {
|
||||
const entity = this.entity(id);
|
||||
entity.attack += attack;
|
||||
entity.health += health;
|
||||
this.record({ type: "StatsChanged", id, attack: entity.attack, health: entity.health });
|
||||
}
|
||||
|
||||
gainAttack(id: EntityId, amount: number): void {
|
||||
const entity = this.entity(id);
|
||||
entity.attack += amount;
|
||||
this.record({ type: "StatsChanged", id, attack: entity.attack, health: entity.health });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
// Test harness: the thin adapter the course tests call. It translates each
|
||||
// call into engine operations and holds no rules of its own.
|
||||
|
||||
import { cards, conditions, hazards, movement, seams, words } from "./content";
|
||||
import {
|
||||
assemble,
|
||||
attackError,
|
||||
CardLibrary,
|
||||
END_OF_PHASE,
|
||||
hits,
|
||||
SpellGrid as Grid,
|
||||
puzzle,
|
||||
registerAssembled,
|
||||
runSequence,
|
||||
summon,
|
||||
triggerLabel,
|
||||
World,
|
||||
type CardDef,
|
||||
type Chooser,
|
||||
type Event,
|
||||
type Half,
|
||||
type Zone,
|
||||
} from "./engine";
|
||||
|
||||
export { AssembleError } from "./engine";
|
||||
export type { CardDef, Chooser, Half, Zone };
|
||||
|
||||
export type Id = number;
|
||||
export type Player = 0 | 1;
|
||||
|
||||
/** The events the tests read from `log()` (see course/harness.md). */
|
||||
export type GameEvent =
|
||||
| { type: "Summoned"; id: Id }
|
||||
| { type: "Damaged"; target: Id; amount: number }
|
||||
| { type: "Triggered"; source: Id; trigger: string }
|
||||
| { type: "Destroyed"; id: Id }
|
||||
| { type: "DeathPhase"; round: number }
|
||||
| { type: "Drew"; player: Player; id: Id }
|
||||
| { type: "Fatigue"; player: Player }
|
||||
| { type: "ArmorGained"; player: Player; amount: number }
|
||||
| { type: "ArmorLost"; player: Player; amount: number }
|
||||
| { type: "StatsChanged"; id: Id; attack: number; health: number }
|
||||
| { type: "SpellCast"; card: string };
|
||||
|
||||
/** The course's view of an engine event; `undefined` for engine events the course log doesn't show. */
|
||||
function toGameEvent(event: Event): GameEvent | undefined {
|
||||
if (event.type === "Triggered") return { type: "Triggered", source: event.source, trigger: triggerLabel(event.on) };
|
||||
if (event.type === "Destroyed") return { type: "Destroyed", id: event.id };
|
||||
if (event.type === "Summoned") return { type: "Summoned", id: event.id };
|
||||
// A played minion's `Summoned` already shows it entering the board.
|
||||
if (event.type === "Played") return undefined;
|
||||
// The end of a turn shows in the triggers that answer it.
|
||||
if (event.type === "TurnEnded") return undefined;
|
||||
// SpellGrid writes the text on the grid; the course's log doesn't show the request.
|
||||
if (event.type === "TextSpawned") return undefined;
|
||||
return { ...event };
|
||||
}
|
||||
|
||||
/** One event as `scenarios.md` writes it, such as `Triggered{source: 3, trigger: "deathrattle"}`. */
|
||||
function eventText(event: GameEvent): string {
|
||||
const { type, ...fields } = event;
|
||||
const shown = Object.entries(fields).map(
|
||||
([key, value]) => `${key}: ${typeof value === "string" ? JSON.stringify(value) : value}`,
|
||||
);
|
||||
return `${type}{${shown.join(", ")}}`;
|
||||
}
|
||||
|
||||
/** The log as a tree: one event per line, two spaces of indent per level of nesting. */
|
||||
function logTree(world: World, view: (event: Event) => GameEvent | undefined): string {
|
||||
const depths = world.logDepths();
|
||||
return world
|
||||
.log()
|
||||
.map((event, i) => {
|
||||
const shown = view(event);
|
||||
return shown === undefined ? "" : `${" ".repeat(depths[i])}${eventText(shown)}\n`;
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
|
||||
export interface Game {
|
||||
summon(card: string, player?: Player): Id; // to right end of board
|
||||
addToHand(card: string, player?: Player): Id;
|
||||
addToDeck(card: string, player?: Player): Id;
|
||||
play(handId: Id): void; // Module 1 Expansion Drop; required from Module 4 (Battlecry)
|
||||
zoneOf(id: Id): Zone;
|
||||
board(player: Player): Id[]; // left to right
|
||||
hand(player: Player): Id[];
|
||||
orderOfPlay(id: Id): number;
|
||||
nameOf(id: Id): string;
|
||||
// Module 2
|
||||
hero(player: Player): Id;
|
||||
dealDamage(target: Id, amount: number): void; // one Sequence
|
||||
cast(card: string, player?: Player, target?: Id): void;
|
||||
health(id: Id): number;
|
||||
attack(id: Id): number;
|
||||
armor(player: Player): number;
|
||||
log(): GameEvent[];
|
||||
clearLog(): void;
|
||||
logTree(): string; // the log as an indented tree
|
||||
// Module 3
|
||||
destroy(target: Id): void; // marks pending destroy, one Sequence
|
||||
// Module 5
|
||||
registerCards(defs: CardDef[]): void; // add card definitions, replacing any with the same name
|
||||
assemble(base: string, donor: string, half: Half): string; // registers "<base> (Assembled)"; throws AssembleError
|
||||
cost(id: Id): number;
|
||||
setChooser(choose: Chooser): void; // makes Assemble's choices: kind "base" | "donor" | "half"
|
||||
// Module 12
|
||||
orderAttack(attacker: Id, defender: Id): void; // one Sequence; throws Error(canAttack's reason) if illegal
|
||||
canAttack(attacker: Id, defender: Id): string | null; // why not, or null if the attack is legal
|
||||
endTurn(player: Player): void; // one Sequence: the player's end of turn triggers
|
||||
}
|
||||
|
||||
export function newGame(opts?: { decks?: [string[], string[]] }): Game {
|
||||
const world = new World(new CardLibrary(cards()));
|
||||
opts?.decks?.forEach((deck, player) => {
|
||||
for (const card of deck) world.create(card, player as Player, "deck");
|
||||
});
|
||||
|
||||
return {
|
||||
summon: (card, player = 0) => summon(world, card, player),
|
||||
addToHand: (card, player = 0) => world.create(card, player, "hand"),
|
||||
addToDeck: (card, player = 0) => world.create(card, player, "deck"),
|
||||
// Play a card from hand, as one Sequence: it enters the right end of the board, then its Battlecry resolves.
|
||||
play: (handId) => runSequence(world, { type: "play", id: handId }),
|
||||
zoneOf: (id) => world.zoneOf(id),
|
||||
board: (player) => [...world.zone(player, "board")],
|
||||
hand: (player) => [...world.zone(player, "hand")],
|
||||
orderOfPlay: (id) => {
|
||||
const order = world.orderOfPlay(id);
|
||||
if (order === undefined) throw new Error(`entity ${id} has not entered play`);
|
||||
return order;
|
||||
},
|
||||
nameOf: (id) => world.cardName(id),
|
||||
|
||||
hero: (player) => world.hero(player),
|
||||
dealDamage: (target, amount) => runSequence(world, { type: "damage", hits: hits([target], amount) }),
|
||||
cast: (card, player = 0, target) => runSequence(world, { type: "cast", card, player, target }),
|
||||
health: (id) => world.health(id),
|
||||
attack: (id) => world.attack(id),
|
||||
armor: (player) => world.armor(player),
|
||||
log: () => world.log().flatMap((event) => toGameEvent(event) ?? []),
|
||||
clearLog: () => world.clearLog(),
|
||||
logTree: () => logTree(world, toGameEvent),
|
||||
|
||||
destroy: (target) => runSequence(world, { type: "destroy", targets: [target] }),
|
||||
|
||||
registerCards: (defs) => defs.forEach((def) => world.register(def)),
|
||||
assemble: (base, donor, half) =>
|
||||
registerAssembled(world, assemble(world.card(base).def, world.card(donor).def, half)),
|
||||
cost: (id) => world.cost(id),
|
||||
setChooser: (choose) => world.setChooser(choose),
|
||||
|
||||
orderAttack: (attacker, defender) => runSequence(world, { type: "attack", attacker, defender }),
|
||||
canAttack: (attacker, defender) => attackError(world, attacker, defender) ?? null,
|
||||
endTurn: (player) => runSequence(world, { type: "endTurn", player }),
|
||||
};
|
||||
}
|
||||
|
||||
// ======== Part II: Baba Is You ========
|
||||
|
||||
export type { Dir, LevelCard, LevelDef, LevelObject } from "./engine/puzzle";
|
||||
|
||||
/** A Baba Is You level in play (Part II). */
|
||||
export interface Baba {
|
||||
// Module 6
|
||||
place(kind: string, x: number, y: number): Id; // "baba" or "text:BABA"
|
||||
rules(): string[]; // distinct, normalised ("BABA IS YOU", "BABA IS NOT YOU", "BABA ON KEY IS WIN"), sorted; before resolution
|
||||
// Module 7
|
||||
activeRules(): string[]; // the same, after resolution (NOT, identity)
|
||||
hasProperty(id: Id, prop: string): boolean;
|
||||
// Module 8
|
||||
move(dir: puzzle.Dir): void; // every YOU object one tile, with what it pushes; then reparse. Movement only.
|
||||
posOf(id: Id): [number, number] | null; // null once destroyed
|
||||
kindsAt(x: number, y: number): string[]; // kinds as placed ("baba", "text:ROCK"), sorted
|
||||
stackAt(x: number, y: number): string[]; // the same tile, oldest object first
|
||||
// Module 9
|
||||
step(dir: puzzle.Dir): void; // one whole turn: movement, parse, conversion, parse, hazards, win (then parse)
|
||||
won(): boolean; // a turn found a YOU object on a WIN one (or WIN itself); stays true
|
||||
lost(): boolean; // no object is YOU
|
||||
undo(): boolean; // back to before the last step or move; false if there is none
|
||||
}
|
||||
|
||||
/** Distinct rules as normalised strings, sorted. */
|
||||
const normalised = (rules: readonly puzzle.Rule[]): string[] => [...new Set(rules.map(puzzle.ruleText))].sort();
|
||||
|
||||
/** A level from a level definition; its text is parsed straight away. */
|
||||
export function newBaba(level: puzzle.LevelDef): Baba {
|
||||
const lvl = new puzzle.Level(level, words(), movement(), hazards(), conditions());
|
||||
return {
|
||||
place: (kind, x, y) => lvl.place(kind, x, y),
|
||||
rules: () => normalised(lvl.rules()),
|
||||
activeRules: () => normalised(lvl.activeRules()),
|
||||
hasProperty: (id, prop) => lvl.hasProperty(id, prop),
|
||||
move: (dir) => lvl.moveYou(dir),
|
||||
posOf: (id) => {
|
||||
const o = lvl.board.find(id);
|
||||
return o === undefined ? null : [o.x, o.y];
|
||||
},
|
||||
kindsAt: (x, y) =>
|
||||
lvl.board
|
||||
.at(x, y)
|
||||
.map((o) => puzzle.Kind.format(o.kind))
|
||||
.sort(),
|
||||
stackAt: (x, y) =>
|
||||
lvl.board
|
||||
.at(x, y)
|
||||
.map((o) => puzzle.Kind.format(o.kind)),
|
||||
step: (dir) => lvl.step(dir),
|
||||
won: () => lvl.won(),
|
||||
lost: () => lvl.lost(),
|
||||
undo: () => lvl.undo(),
|
||||
};
|
||||
}
|
||||
|
||||
// ======== Part III: SpellGrid ========
|
||||
|
||||
/**
|
||||
* A SpellGrid level in play (Part III): a Baba Is You level whose minions are cards.
|
||||
* Every id is a grid id: a minion's is its grid object's (see `engine/spellgrid.ts`).
|
||||
*/
|
||||
export interface SpellGrid extends Baba {
|
||||
// Module 10
|
||||
cast(card: string, target?: Id): void; // a spell from player 0's hand, as one Sequence; target: a minion
|
||||
play(card: string, x: number, y: number): Id; // a minion from player 0's hand onto an empty tile
|
||||
health(id: Id): number;
|
||||
hero(player: Player): Id;
|
||||
nameOf(id: Id): string;
|
||||
minionAt(x: number, y: number): Id | null;
|
||||
hand(): string[]; // card names in player 0's hand, in order
|
||||
log(): GameEvent[]; // Part I's log, with grid ids
|
||||
clearLog(): void;
|
||||
logTree(): string; // Part I's log as an indented tree, with grid ids
|
||||
setChooser(choose: Chooser): void; // makes Assemble's choices
|
||||
withNaiveAuraTiming(): void; // test hook: Aura Update before the Death Creation Step
|
||||
// For the command line: why `cast`/`play` would fail, or null if they wouldn't
|
||||
checkCast(card: string, target?: Id): string | null;
|
||||
checkPlay(card: string, x: number, y: number): string | null;
|
||||
}
|
||||
|
||||
/** A SpellGrid level; `extra` cards are added to the course's cards, replacing any with the same name. */
|
||||
export function newSpellGrid(level: puzzle.LevelDef, extra: CardDef[]): SpellGrid {
|
||||
const library = new CardLibrary(cards());
|
||||
for (const def of extra) library.register(def);
|
||||
const g = new Grid(level, library, words(), movement(), hazards(), conditions(), seams());
|
||||
const lvl = g.level;
|
||||
/** An engine event with every entity id as a grid id. */
|
||||
const withIds = (event: GameEvent): GameEvent => {
|
||||
switch (event.type) {
|
||||
case "Summoned":
|
||||
case "Destroyed":
|
||||
case "Drew":
|
||||
case "StatsChanged":
|
||||
return { ...event, id: g.idOf(event.id) };
|
||||
case "Damaged":
|
||||
return { ...event, target: g.idOf(event.target) };
|
||||
case "Triggered":
|
||||
return { ...event, source: g.idOf(event.source) };
|
||||
default:
|
||||
return event;
|
||||
}
|
||||
};
|
||||
return {
|
||||
place: (kind, x, y) => g.place(kind, x, y),
|
||||
rules: () => normalised(lvl.rules()),
|
||||
activeRules: () => normalised(lvl.activeRules()),
|
||||
hasProperty: (id, prop) => lvl.hasProperty(id, prop),
|
||||
move: (dir) => g.move(dir),
|
||||
posOf: (id) => {
|
||||
const o = lvl.board.find(id);
|
||||
return o === undefined ? null : [o.x, o.y];
|
||||
},
|
||||
kindsAt: (x, y) =>
|
||||
lvl.board
|
||||
.at(x, y)
|
||||
.map((o) => puzzle.Kind.format(o.kind))
|
||||
.sort(),
|
||||
stackAt: (x, y) =>
|
||||
lvl.board
|
||||
.at(x, y)
|
||||
.map((o) => puzzle.Kind.format(o.kind)),
|
||||
step: (dir) => g.step(dir),
|
||||
won: () => lvl.won(),
|
||||
lost: () => lvl.lost(),
|
||||
// Part I has state (health, hands, the log) that the level's snapshot doesn't cover.
|
||||
undo: () => {
|
||||
throw new Error("undo is not supported in SpellGrid");
|
||||
},
|
||||
|
||||
cast: (card, target) => g.cast(card, target),
|
||||
play: (card, x, y) => g.play(card, x, y),
|
||||
health: (id) => g.world.health(g.entity(id)),
|
||||
hero: (player) => g.idOf(g.world.hero(player)),
|
||||
nameOf: (id) => g.world.cardName(g.entity(id)),
|
||||
minionAt: (x, y) => g.minionAt(x, y) ?? null,
|
||||
hand: () => g.world.zone(0, "hand").map((id) => g.world.cardName(id)),
|
||||
log: () =>
|
||||
g.world
|
||||
.log()
|
||||
.flatMap((event) => toGameEvent(event) ?? [])
|
||||
.map(withIds),
|
||||
clearLog: () => g.world.clearLog(),
|
||||
logTree: () =>
|
||||
logTree(g.world, (event) => {
|
||||
const shown = toGameEvent(event);
|
||||
return shown === undefined ? undefined : withIds(shown);
|
||||
}),
|
||||
setChooser: (choose) => g.world.setChooser(choose),
|
||||
// The naive engine reads the auras before the dead leave play: the same steps, reversed.
|
||||
withNaiveAuraTiming: () => g.world.setEndOfPhase([...END_OF_PHASE].reverse()),
|
||||
checkCast: (card, target) => g.checkCast(card, target) ?? null,
|
||||
checkPlay: (card, x, y) => g.checkPlay(card, x, y) ?? null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// The SpellGrid command line, played from a script (the reference's own check; not a course test).
|
||||
import { readFileSync } from "node:fs";
|
||||
import { expect, test } from "vitest";
|
||||
import { run } from "../src/cli";
|
||||
|
||||
function play(level: string, input: string[]): { outcome: string; out: string } {
|
||||
let out = "";
|
||||
const outcome = run(readFileSync(`levels/${level}.json`, "utf8"), () => input.shift(), (s) => (out += s));
|
||||
return { outcome, out };
|
||||
}
|
||||
|
||||
test("cli_wins_level_1", () => {
|
||||
const { outcome, out } = play("l1-double-tap", ["w", "w", "c Whirlwind", "s", "s", "a", "s", "s", "d", "d"]);
|
||||
expect(outcome).toBe("won");
|
||||
expect(out).toContain("DEA IS DOU");
|
||||
expect(out).toContain("You win!");
|
||||
});
|
||||
|
||||
test("cli_wins_level_2_with_choices_and_play", () => {
|
||||
const input = ["c Graft", "Ember Moth", "Rune Scribe", "bottom", "c Ember Moth (Assembled) 4 3", "a", "a"];
|
||||
const { outcome, out } = play("l2-spliced-corpse", input);
|
||||
expect(outcome).toBe("won");
|
||||
expect(out).toContain("Choose the base");
|
||||
expect(out).toContain("Hand: Ember Moth (Assembled)");
|
||||
});
|
||||
|
||||
test("cli_prints_the_log_tree_of_each_command", () => {
|
||||
const { out } = play("l1-double-tap", ["w", "w", "c Whirlwind", "q"]);
|
||||
// The moves run no Sequence, so only the cast prints a log: its tree, Deathrattles nested.
|
||||
expect(out.split("Log:\n")).toHaveLength(2);
|
||||
expect(out).toContain(
|
||||
[
|
||||
"Log:",
|
||||
'SpellCast{card: "Whirlwind"}',
|
||||
"Damaged{target: 32, amount: 1}",
|
||||
"Damaged{target: 33, amount: 1}",
|
||||
"Destroyed{id: 32}",
|
||||
"DeathPhase{round: 1}",
|
||||
'Triggered{source: 32, trigger: "deathrattle"}',
|
||||
" Damaged{target: 33, amount: 1}",
|
||||
'Triggered{source: 32, trigger: "deathrattle"}',
|
||||
" Damaged{target: 33, amount: 1}",
|
||||
"Destroyed{id: 33}",
|
||||
"DeathPhase{round: 2}",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
|
||||
test("cli_reports_errors_and_quits", () => {
|
||||
const { outcome, out } = play("l3-simultaneous-paradox", ["c Spark", "x", "q"]);
|
||||
expect(outcome).toBe("quit");
|
||||
expect(out).toContain('"Spark" is not in the hand');
|
||||
expect(out).toContain("Commands:");
|
||||
});
|
||||
|
||||
// The two reference CLIs print the same text for the same input (tools/diff-tracks.mjs checks it).
|
||||
test("cli_prints_card_names_as_typed", () => {
|
||||
const { out } = play("l3-simultaneous-paradox", ['c a"b', "q"]);
|
||||
expect(out).toContain('"a"b" is not in the hand');
|
||||
});
|
||||
|
||||
test("cli_numbers_are_plain_digits", () => {
|
||||
// "-1" is not a coordinate, so it is part of the card's name.
|
||||
const cast = play("l1-double-tap", ["c Whirlwind -1 0", "q"]);
|
||||
expect(cast.out).toContain('"Whirlwind -1 0" is not in the hand');
|
||||
// "+2" is not a number, so the chooser takes the first option.
|
||||
const graft = play("l2-spliced-corpse", ["c Graft", "+2", "1", "1", "q"]);
|
||||
expect(graft.out).toContain("Hand: Clay Golem (Assembled)");
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["src", "tests"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: { include: ["tests/**/*.test.ts"], passWithNoTests: true },
|
||||
});
|
||||
Reference in new issue
Block a user