Skip to content

A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D

Declare each system's commands (bevy-ts command permissions)

SandroMaglioneaf4b74268f19
diff --git a/src/archetypes.ts b/src/archetypes.ts
index a46abef..a772463 100644
--- a/src/archetypes.ts
+++ b/src/archetypes.ts
@@ -16,6 +16,8 @@ const site = (cost: Kind["cost"]) => {
return total(owed) > 0 ? Game.Command.entry(Site, { owed, total: total(owed) }) : Game.Command.entry(Rising, { ticks: 0 })
}
+/** The components of `buildingDraft`. */
+export const BuildingParts = [Tile, Building, Status, Staff] as const
/** A building of `kind` on `cell`: a site waiting for materials, or (`standing`) already up. */
export const buildingDraft = (kind: Kind, cell: Point) =>
Game.Command.spawn(
@@ -25,15 +27,21 @@ export const buildingDraft = (kind: Kind, cell: Point) =>
[Staff, { needed: kind.workers, assigned: 0, apprentices: 0, nearby: 0 }]
)
+/** The components `wearOf` inserts. */
+export const WearParts = [Risk, Condition] as const
/** What every home and every working building carries: its risks, and how well kept it is. */
export const wearOf = (rules: Rules = shippedRules) => [
Game.Command.entry(Risk, { fire: 0, health: 0, order: 0, thefts: 0 }),
Game.Command.entry(Condition, { value: rules.conditionMax })
]
+/** The components `startOf` (and `houseStart`) may insert: owed materials, or rising. */
+export const StartParts = [Site, Rising] as const
/** How a new building starts: owed its materials, or rising straight away. */
export const startOf = (kind: Kind) => site(kind.cost)
+/** Every component `rolesOf` may insert. */
+export const RoleParts = [Recipe, Gatherer, Planter, Inventory, Storage, Carriers, Service, ...WearParts] as const
/** The role components a kind's buildings carry, inserted after the building is spawned. */
export const rolesOf = (kind: Kind, rules: Rules = shippedRules) => {
const roles = []
@@ -68,20 +76,29 @@ export const rolesOf = (kind: Kind, rules: Rules = shippedRules) => {
return roles
}
+/** The components of `houseDraft`. */
+export const HouseParts = [Tile, House] as const
export const houseDraft = (cell: Point) =>
Game.Command.spawn(
[Tile, { x: cell.x, y: cell.y, size: 1 }],
[House, { tier: 1, residents: 0, food: 0, bread: 0, cloth: 0, faith: 0, furniture: 0, clock: 0 }]
)
export const houseStart = (rules: Rules = shippedRules) => [site(rules.home.cost), ...wearOf(rules)]
+export const RuinParts = [Tile, Ruin] as const
export const ruinDraft = (tile: { readonly x: number; readonly y: number; readonly size: number }, cause: "burnt" | "collapsed" | "derelict") =>
Game.Command.spawn([Tile, { x: tile.x, y: tile.y, size: tile.size }], [Ruin, { cause }])
+export const ParkParts = [Tile, Park] as const
export const parkDraft = (cell: Point, ground: GroundId) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Park, { ground, prop: "none" }])
+export const RoadParts = [Tile, Road] as const
export const roadDraft = (cell: Point) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Road, {}])
+export const TreeParts = [Tile, Tree] as const
export const treeDraft = (cell: Point, growth: number) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Tree, { growth }])
+export const RockParts = [Tile, Rock] as const
export const rockDraft = (cell: Point, ore: boolean, amount: number) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Rock, { ore, amount }])
/** A cell of water never fished: long rested. */
export const UNFISHED = -1_000_000
+export const WaterParts = [Tile, Water] as const
export const waterDraft = (cell: Point) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Water, { fished: UNFISHED }])
+export const FieldParts = [Tile, Field] as const
export const fieldDraft = (cell: Point) => Game.Command.spawn([Tile, { x: cell.x, y: cell.y, size: 1 }], [Field, { growth: 0 }])
diff --git a/src/sim/decay.ts b/src/sim/decay.ts
index 0fa90f5..c42ea49 100644
--- a/src/sim/decay.ts
+++ b/src/sim/decay.ts
@@ -7,7 +7,7 @@ import { spoilExpectation } from "../rules/decay.ts"
*/
import * as Random from "@typeonce/bevy-ts-math/Random"
-import { ruinDraft } from "../archetypes.ts"
+import { RuinParts, ruinDraft } from "../archetypes.ts"
import { foods, goodIds, ticks } from "../content.ts"
import { counted, placeName } from "../places.ts"
import { Building, Burning, Charter, Chronicle, Condition, Game, Rules, House, Inventory, Pantry, Recipe, Rising, Rng, Site, Staff, Tile, Time, maybe } from "../schema.ts"
@@ -36,7 +36,8 @@ export const Decay = Game.System(
pantry: Game.System.writeResource(Pantry),
chronicle: Game.System.writeResource(Chronicle)
},
- services: { rules: Game.System.service(Rules) }
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.spawns(...RuinParts), Game.System.despawns(Condition))
},
({ queries, resources, commands, services }) => {
const rules = services.rules
@@ -56,7 +57,7 @@ export const Decay = Game.System(
}
const tile = data.tile.get()
const b = maybe(data.building)
- commands.despawn(entity.id)
+ commands.despawn(entity)
commands.spawn(ruinDraft(tile, "collapsed"))
write(
resources.chronicle,
diff --git a/src/sim/edits.ts b/src/sim/edits.ts
index 8e528d8..ee819a3 100644
--- a/src/sim/edits.ts
+++ b/src/sim/edits.ts
@@ -6,13 +6,13 @@
* carried to the site afterwards. Upgrading a building is paid at once.
* Once the term has ended, only a new town, or another term, is taken.
*/
-import { buildingDraft, houseDraft, houseStart, parkDraft, roadDraft, rockDraft, rolesOf, startOf, treeDraft, waterDraft } from "../archetypes.ts"
+import { BuildingParts, buildingDraft, houseDraft, HouseParts, houseStart, ParkParts, parkDraft, RoadParts, roadDraft, RockParts, rockDraft, RoleParts, rolesOf, StartParts, startOf, TreeParts, treeDraft, WaterParts, waterDraft } from "../archetypes.ts"
import * as Random from "@typeonce/bevy-ts-math/Random"
import { amounts, anA, builtCost, costText, goodIds, nextUpgrade, RESERVE_MAX, TAX_STEPS, ticks, total, upgradeAt, type Amounts, type Kind, type ParkPiece, type Upgrade } from "../content.ts"
import { canPlace, cellsOf, GridBuilder, ownerAt, useAt } from "../grid.ts"
import { inside } from "../iso.ts"
import { generate } from "../mapgen.ts"
-import { Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, Guide, Rules, History, House, Inventory, Land, Ledger, Market, maybe, Mood, Pantry, Park, Paved, Paused, Policy, Rising, Rng, Rock, Service, Site, Status, Stock, Storage, Time, TownHall, Toast, Treasury, Upgraded, Works, Edits, Selection } from "../schema.ts"
+import { Appeal, Building, Tile, Census, Charter, Chronicle, Crown, Fate, Fires, Game, Guide, Rules, History, House, Inventory, Land, Ledger, Market, maybe, Mood, Pantry, Park, Paved, Paused, Policy, Rising, Rng, Rock, Service, Site, Status, Stock, Storage, Time, TownHall, Toast, Treasury, Upgraded, Works, Edits, Selection } from "../schema.ts"
import { salvageOf, salvageText, withWorks } from "../rules/salvage.ts"
import { elapsed, rollWinters, termTicks, TileRead, useOf, write } from "./shared.ts"
import type { Rules as RuleInputs } from "../rules/config.ts"
@@ -82,7 +82,13 @@ export const ApplyEdits = Game.System(
fires: Game.System.writeResource(Fires)
},
events: { toast: Game.System.writeEvent(Toast), selection: Game.System.writeEvent(Selection) },
- services: { edits: Game.System.service(Edits), rules: Game.System.service(Rules) }
+ services: { edits: Game.System.service(Edits), rules: Game.System.service(Rules) },
+ commands: Game.System.commands(
+ Game.System.spawns(...BuildingParts, ...HouseParts, ...RoadParts, ...ParkParts, ...WaterParts, ...TreeParts, ...RockParts),
+ Game.System.inserts(...StartParts, ...RoleParts, Paved, Paused, Works, TownHall, Status, Inventory),
+ Game.System.removes(Paused),
+ Game.System.despawns(Tile)
+ )
},
({ queries, resources, events, services, commands }) => {
const rules = services.rules
@@ -149,12 +155,20 @@ export const ApplyEdits = Game.System(
for (const c of cellsOf(tile)) {
if (useAt(grid.value(), c.x, c.y) !== "tree") continue
const tree = entities.get(ownerAt(grid.value(), c.x, c.y))
- if (tree !== undefined) commands.despawn(tree)
+ const row = tree === undefined ? undefined : queries.tiles.get(tree)
+ if (row?.ok) commands.despawn(row.value.entity)
}
}
- const spawn = (draft: Parameters<typeof commands.spawn>[0], tile: { x: number; y: number; size: number }, use: "building" | "house" | "road" | "park") => {
+ /**
+ * What this run queued, by id, with how to take it back: no query matches it
+ * before the next `applyDeferred()`, so pulling it down (or a new town) in
+ * the same step despawns it through the id `spawn` returned.
+ */
+ const queuedHere = new Map<number, () => void>()
+ /** Fells what stands on `tile`, spawns what `make` queues there, and claims the tile for it. */
+ const place = <Spawned extends Id>(tile: { x: number; y: number; size: number }, use: "building" | "house" | "road" | "park", make: () => Spawned): Spawned => {
fell(tile)
- const id = commands.spawn(draft)
+ const id = make()
grid.claim(tile, id, use)
entities.set(id, id)
return id
@@ -184,7 +198,8 @@ export const ApplyEdits = Game.System(
break
}
pay(kind.cost)
- const id = spawn(buildingDraft(kind, edit.cell), tile, "building")
+ const id = place(tile, "building", () => commands.spawn(buildingDraft(kind, edit.cell)))
+ queuedHere.set(id, () => commands.despawn(id))
commands.insert(id, startOf(kind), ...rolesOf(kind, rules))
if (edit.open) events.selection.emit({ select: id })
break
@@ -197,7 +212,8 @@ export const ApplyEdits = Game.System(
short = afford(home.cost)
if (short) break
pay(home.cost)
- const id = spawn(houseDraft(cell), tile, "house")
+ const id = place(tile, "house", () => commands.spawn(houseDraft(cell)))
+ queuedHere.set(id, () => commands.despawn(id))
commands.insert(id, ...houseStart(rules))
}
if (short) events.toast.emit(short)
@@ -213,7 +229,8 @@ export const ApplyEdits = Game.System(
break
}
coins -= ROAD_COST
- spawn(roadDraft(cell), tile, "road")
+ const id = place(tile, "road", () => commands.spawn(roadDraft(cell)))
+ queuedHere.set(id, () => commands.despawn(id))
}
if (short) events.toast.emit("Not enough coins")
break
@@ -254,7 +271,10 @@ export const ApplyEdits = Game.System(
pay(piece.cost)
for (const [g, n] of Object.entries(piece.cost.materials)) spent[g] = (spent[g] ?? 0) + (n ?? 0)
if (relay) relay.data.park.set({ ...relay.data.park.get(), ground: edit.ground })
- else spawn(parkDraft(cell, edit.ground), tile, "park")
+ else {
+ const id = place(tile, "park", () => commands.spawn(parkDraft(cell, edit.ground)))
+ queuedHere.set(id, () => commands.despawn(id))
+ }
}
take(spent)
if (short) events.toast.emit(short)
@@ -323,7 +343,10 @@ export const ApplyEdits = Game.System(
if (said !== "") events.toast.emit(`${built.value.data.site.present ? "Cancelled" : "Pulled down"} · ${said}${lost > 0 ? ` (${lost} found no room in storage)` : ""}`)
}
// A building's walkers and a farm's fields are its children, and go with it.
- commands.despawn(owner)
+ const gone = queries.tiles.get(owner)
+ if (gone.ok) commands.despawn(gone.value.entity)
+ else queuedHere.get(owner)?.()
+ queuedHere.delete(owner)
entities.delete(owner)
for (let k = 0; k < grid.owner.length; k++) {
if (grid.owner[k] === owner) {
@@ -434,7 +457,9 @@ export const ApplyEdits = Game.System(
resources.policy.update((p) => ({ ...p, reserve: Math.max(0, Math.min(RESERVE_MAX, Math.round(edit.amount))) }))
break
case "newTown": {
- for (const id of entities.values()) commands.despawn(id)
+ for (const { entity } of rows) commands.despawn(entity)
+ for (const drop of queuedHere.values()) drop()
+ queuedHere.clear()
entities.clear()
const charter = edit.charter
const richness = lands[charter.land]
diff --git a/src/sim/hazards.ts b/src/sim/hazards.ts
index 7803b7f..e0b0567 100644
--- a/src/sim/hazards.ts
+++ b/src/sim/hazards.ts
@@ -12,7 +12,7 @@ import { near, riskIncrements } from "../rules/risks.ts"
import * as Random from "@typeonce/bevy-ts-math/Random"
import { appealGrid, appealAt, buildingSource, homeSource, landSource, parkSources, type AppealSource } from "../appeal.ts"
-import { ruinDraft } from "../archetypes.ts"
+import { RuinParts, ruinDraft } from "../archetypes.ts"
import { goodIds, risk, upgradeAt, type GoodId } from "../content.ts"
import { doors, nearest, pathTo, reach, useAt } from "../grid.ts"
import { counted, placeName, type Landmark } from "../places.ts"
@@ -109,7 +109,13 @@ export const Hazards = Game.System(
fires: Game.System.writeResource(Fires),
chronicle: Game.System.writeResource(Chronicle)
},
- services: { rules: Game.System.service(Rules) }
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(
+ Game.System.spawns(...RuinParts, Figure, Route, Rescue),
+ Game.System.inserts(Burning, Sick),
+ Game.System.removes(Sick),
+ Game.System.despawns(Tile)
+ )
},
({ queries, resources, commands, services }) => {
const rules = services.rules
@@ -144,7 +150,7 @@ export const Hazards = Game.System(
/** Turns a home or building into a ruin. */
const ruin = (row: (typeof rows)[number], cause: "burnt" | "collapsed" | "derelict") => {
- commands.despawn(row.entity.id)
+ commands.despawn(row.entity)
commands.spawn(ruinDraft(row.data.tile.get(), cause))
}
const lost = new Set<number>()
@@ -329,7 +335,8 @@ export const Douse = Game.System(
"Town/Douse",
{
queries: { crews: Game.Query({ selection: { route: Game.Query.write(Route), rescue: Game.Query.write(Rescue) } }), burning: BurningRead },
- resources: { fires: Game.System.writeResource(Fires) }
+ resources: { fires: Game.System.writeResource(Fires) },
+ commands: Game.System.commands(Game.System.spawns(...RuinParts), Game.System.despawns(Rescue, Burning))
},
({ queries, resources, commands }) => {
for (const { entity, data } of queries.crews.each()) {
@@ -338,13 +345,13 @@ export const Douse = Game.System(
const arrived = route.index >= route.cells.length - 1
if (!arrived) continue
if (rescue.back) {
- commands.despawn(entity.id)
+ commands.despawn(entity)
continue
}
const target = queries.burning.getHandle(rescue.target)
if (target.ok) {
const b = target.value.data.burning.get()
- commands.despawn(target.value.entity.id)
+ commands.despawn(target.value.entity)
commands.spawn(ruinDraft(target.value.data.tile.get(), "burnt"))
const house = target.value.data.house.present
resources.fires.update((f) => ({
diff --git a/src/sim/logistics.ts b/src/sim/logistics.ts
index 0c14aac..c81feed 100644
--- a/src/sim/logistics.ts
+++ b/src/sim/logistics.ts
@@ -53,7 +53,8 @@ export const Dispatch = Game.System(
errands: Game.Query({ selection: { errand: Game.Query.read(Errand), home: Game.Query.readRelation(WalkerOf) } })
},
resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) }
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.spawns(Figure, Route, Errand))
},
({ queries, resources, commands, services }) => {
const rules = services.rules
@@ -229,7 +230,8 @@ export const Deliver = Game.System(
sites: Game.Query({ selection: { site: Game.Query.write(Site) } }),
works: Game.Query({ selection: { works: Game.Query.write(Works) } })
},
- services: { rules: Game.System.service(Rules) }
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.despawns(Errand))
},
({ queries, commands, services }) => {
const rules = services.rules
@@ -246,7 +248,7 @@ export const Deliver = Game.System(
const room = inv.cap - inv.stock[errand.good]
home.value.data.inventory.set({ ...inv, stock: { ...inv.stock, [errand.good]: inv.stock[errand.good] + Math.min(room, errand.count) } })
}
- commands.despawn(entity.id)
+ commands.despawn(entity)
continue
}
const target = queries.targets.getHandle(errand.target)
diff --git a/src/sim/town.ts b/src/sim/town.ts
index 642f19f..33a3549 100644
--- a/src/sim/town.ts
+++ b/src/sim/town.ts
@@ -49,7 +49,8 @@ export const Households = Game.System(
policy: Game.System.readResource(Policy),
treasury: Game.System.writeResource(Treasury)
},
- services: { rules: Game.System.service(Rules) }
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.inserts(Rebuilt))
},
({ queries, resources, commands, services }) => {
const rules = services.rules
diff --git a/src/sim/walkers.ts b/src/sim/walkers.ts
index ca289e2..54b574a 100644
--- a/src/sim/walkers.ts
+++ b/src/sim/walkers.ts
@@ -37,7 +37,8 @@ export const Walk = Game.System(
{
queries: { walkers: Game.Query({ selection: { route: Game.Query.write(Route), rescue: Game.Query.optional(Rescue) } }) },
resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) }
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.despawns(Route))
},
({ queries, resources, commands, services }) => {
const grid = resources.grid.get()
@@ -49,7 +50,7 @@ export const Walk = Game.System(
if (route.index >= last) continue
const next = route.cells[route.index + 1]!
if (!isRoad(grid, next.x, next.y)) {
- commands.despawn(entity.id)
+ commands.despawn(entity)
continue
}
const running = data.rescue.present && !data.rescue.get().back
@@ -92,7 +93,8 @@ export const SendWalkers = Game.System(
walkers: Game.Query({ selection: { roam: Game.Query.read(Roam), home: Game.Query.readRelation(WalkerOf) } })
},
resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) }
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.spawns(Figure, Route, Roam), Game.System.inserts(Patrol))
},
({ queries, resources, commands, services }) => {
const rules = services.rules
@@ -190,7 +192,8 @@ export const Wander = Game.System(
inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] })
},
resources: { grid: Game.System.readResource(Grid), appeal: Game.System.readResource(Appeal), pantry: Game.System.writeResource(Pantry), handed: Game.System.writeResource(Handed), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) }
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.despawns(Roam), Game.System.removes(Sick))
},
({ queries, resources, commands, services }) => {
const rules = services.rules
@@ -222,7 +225,7 @@ export const Wander = Game.System(
// the building asks for no more until it is down again, and nothing is lost.
inv.value.data.inventory.set({ ...i, stock: each((g) => i.stock[g] + roam.basket[g]) })
}
- commands.despawn(entity.id)
+ commands.despawn(entity)
continue
}
@@ -285,7 +288,7 @@ export const Wander = Game.System(
const way = reach(grid, [cell])
const door = building.ok ? nearest(way, doors(grid, building.value.data.tile.get())) : null
if (!door) {
- commands.despawn(entity.id)
+ commands.despawn(entity)
continue
}
data.route.set({ cells: pathTo(way, door.cell), index: 0, step: 0 })
diff --git a/src/sim/work.ts b/src/sim/work.ts
index da36d01..9efdb4f 100644
--- a/src/sim/work.ts
+++ b/src/sim/work.ts
@@ -7,7 +7,7 @@ import { wildTreeSpots, canSeedTree } from "../rules/land.ts"
*/
import * as Random from "@typeonce/bevy-ts-math/Random"
-import { fieldDraft, treeDraft } from "../archetypes.ts"
+import { FieldParts, fieldDraft, TreeParts, treeDraft } from "../archetypes.ts"
import { amounts, anA, asUpgraded, crewOf, goodIds, ticks, total, upgradeAt, worksNeeded, type Amounts, type Crew } from "../content.ts"
/** The flow of goods is counted in slices this many seconds long, and the last `FLOW_SLICES` of them (a minute) are kept. */
@@ -174,7 +174,8 @@ export const Raise = Game.System(
charter: Game.System.readResource(Charter),
chronicle: Game.System.writeResource(Chronicle)
},
- services: { rules: Game.System.service(Rules) }
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.removes(Works, Site, Rising), Game.System.inserts(Upgraded, Recipe, Carriers, Service, Rising, Status))
},
({ queries, resources, commands, services }) => {
const rules = services.rules
@@ -366,7 +367,8 @@ export const Work = Game.System(
flow: Game.System.writeResource(Flow),
chronicle: Game.System.writeResource(Chronicle)
},
- services: { rules: Game.System.service(Rules) }
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.despawns(Tree))
},
({ queries, resources, commands, services }) => {
const rules = services.rules
@@ -412,7 +414,7 @@ export const Work = Game.System(
if (source === "tree" && use === "tree") {
const tree = trees().get(id)
if (!tree || tree.data.tree.get().growth < GROWN.tree) continue
- commands.despawn(tree.entity.id)
+ commands.despawn(tree.entity)
used.add(id)
return true
}
@@ -527,7 +529,8 @@ export const Plant = Game.System(
})
},
resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) }
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.spawns(...TreeParts, ...FieldParts))
},
({ queries, resources, commands, services }) => {
const rules = services.rules
@@ -581,7 +584,8 @@ export const Spread = Game.System(
{
queries: { trees: Game.Query({ selection: { tile: Game.Query.read(Tile), tree: Game.Query.read(Tree) } }) },
resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), time: Game.System.readResource(Time) },
- services: { rules: Game.System.service(Rules) }
+ services: { rules: Game.System.service(Rules) },
+ commands: Game.System.commands(Game.System.spawns(...TreeParts))
},
({ queries, resources, commands, services }) => {
const rules = services.rules
diff --git a/test/same-step-edits.test.ts b/test/same-step-edits.test.ts
new file mode 100644
index 0000000..214ebfb
--- /dev/null
+++ b/test/same-step-edits.test.ts
@@ -0,0 +1,45 @@
+/**
+ * What is placed and taken back in the same step: ApplyEdits queues the
+ * spawn, so no query sees it yet, and pulling it down (or founding a new
+ * town) must despawn it through the id `spawn` returned, not leave it
+ * standing off the grid.
+ */
+import assert from "node:assert/strict"
+import { test } from "node:test"
+
+import { STEP_SECONDS, type CharterValue } from "../src/content.ts"
+import { headless } from "../src/sim/headless.ts"
+
+const charter: CharterValue = { size: "small", term: 45, land: "fair", seed: 7 }
+const roads = Array.from({ length: 9 }, (_, i) => ({ x: 34 + i, y: 31 }))
+const home = { x: 36, y: 30 }
+
+const at = (town: ReturnType<typeof headless>, cell: { readonly x: number; readonly y: number }) =>
+ town.snapshot().entities.filter((entity) => {
+ const tile = entity.components["Town/Tile"]
+ return tile !== undefined && tile.x === cell.x && tile.y === cell.y
+ })
+
+test("a home placed and pulled down in the same step is gone", () => {
+ const town = headless(charter)
+ town.edit({ type: "roads", cells: roads }, { type: "homes", cells: [home] }, { type: "remove", cell: home })
+ town.run(STEP_SECONDS)
+ assert.deepEqual(at(town, home), [])
+ // The cell is free again: a home can go there next step.
+ town.edit({ type: "homes", cells: [home] })
+ town.run(STEP_SECONDS)
+ assert.equal(at(town, home).length, 1)
+})
+
+test("a new town founded in the same step as a placement keeps nothing of it", () => {
+ const fresh = headless(charter)
+ fresh.edit({ type: "newTown", charter })
+ fresh.run(STEP_SECONDS)
+
+ const town = headless(charter)
+ town.edit({ type: "roads", cells: roads }, { type: "homes", cells: [home] }, { type: "newTown", charter })
+ town.run(STEP_SECONDS)
+
+ assert.equal(town.snapshot().entities.length, fresh.snapshot().entities.length)
+ assert.deepEqual(at(town, home), at(fresh, home))
+})