placement.test.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import {
  6. buildingSchema,
  7. createEngine,
  8. type BuildingDef,
  9. type BuildingPlacement,
  10. type PlacementChangeEvent,
  11. type PlacementSystem,
  12. type SaveSystem,
  13. type System,
  14. } from "../src/index.js";
  15. const TIME_YAML = [
  16. "id: default",
  17. "dayLengthTicks: 480",
  18. "seasons:",
  19. " - { name: spring, dayCount: 28 }",
  20. "start: { day: 1, season: spring }",
  21. "",
  22. ].join("\n");
  23. const FARM_YAML = [
  24. "id: farm",
  25. "width: 5",
  26. "height: 5",
  27. 'tilesetRef: "tiles"',
  28. "spawn: { x: 0, y: 0 }",
  29. "layers:",
  30. " - name: ground",
  31. " data:",
  32. " - [grass, grass, water, water, water]",
  33. " - [grass, grass, water, water, water]",
  34. " - [grass, grass, grass, grass, grass]",
  35. " - [tilled, tilled, grass, grass, grass]",
  36. " - [tilled, tilled, grass, grass, grass]",
  37. "",
  38. ].join("\n");
  39. const SHED: BuildingDef = {
  40. id: "shed",
  41. name: "Shed",
  42. footprint: { w: 2, h: 2 },
  43. buildable: "map",
  44. blocksMovement: true,
  45. };
  46. const FENCE: BuildingDef = {
  47. id: "fence",
  48. footprint: { w: 1, h: 1 },
  49. buildable: { tiles: ["grass"] },
  50. blocksMovement: true,
  51. };
  52. const PATH: BuildingDef = {
  53. id: "path",
  54. footprint: { w: 1, h: 1 },
  55. buildable: "any",
  56. blocksMovement: false,
  57. };
  58. interface Setup {
  59. engine: ReturnType<typeof createEngine>;
  60. close: () => Promise<void>;
  61. }
  62. async function setup(spy?: System): Promise<Setup> {
  63. const tmp = await mkdtemp(join(tmpdir(), "farm-placement-"));
  64. await mkdir(join(tmp, "maps"), { recursive: true });
  65. await writeFile(join(tmp, "time.yaml"), TIME_YAML);
  66. await writeFile(join(tmp, "maps", "farm.yaml"), FARM_YAML);
  67. const systems: System[] = [];
  68. if (spy) systems.push(spy);
  69. const engine = createEngine({ contentDir: tmp, systems });
  70. await engine.start();
  71. engine.registry.register("building", SHED);
  72. engine.registry.register("building", FENCE);
  73. engine.registry.register("building", PATH);
  74. return {
  75. engine,
  76. close: async () => {
  77. await engine.stop();
  78. await rm(tmp, { recursive: true, force: true });
  79. },
  80. };
  81. }
  82. function placementOf(engine: ReturnType<typeof createEngine>): PlacementSystem {
  83. const placement = engine.systems.get<PlacementSystem>("placement");
  84. if (!placement) throw new Error("placement system not booted");
  85. return placement;
  86. }
  87. function saveOf(engine: ReturnType<typeof createEngine>): SaveSystem {
  88. const save = engine.systems.get<SaveSystem>("save");
  89. if (!save) throw new Error("save system not booted");
  90. return save;
  91. }
  92. function eventSpy(): { system: System; seen: { event: string; payload: unknown }[] } {
  93. const seen: { event: string; payload: unknown }[] = [];
  94. const system: System = {
  95. id: "spy",
  96. init() {},
  97. on(event, payload) {
  98. seen.push({ event, payload });
  99. },
  100. };
  101. return { system, seen };
  102. }
  103. function changeEvents(seen: { event: string; payload: unknown }[]): PlacementChangeEvent[] {
  104. return seen
  105. .filter((entry) => entry.event === "placement-change")
  106. .map((entry) => entry.payload as PlacementChangeEvent);
  107. }
  108. describe("buildingSchema", () => {
  109. it("accepts a valid def and rejects bad footprints, buildable forms, and missing blocksMovement", () => {
  110. expect(buildingSchema.safeParse(SHED).success).toBe(true);
  111. expect(buildingSchema.safeParse({ ...SHED, buildable: { tiles: ["grass"] } }).success).toBe(true);
  112. expect(buildingSchema.safeParse({ ...SHED, buildable: "any" }).success).toBe(true);
  113. const zeroFootprint = buildingSchema.safeParse({ ...SHED, footprint: { w: 0, h: 2 } });
  114. expect(zeroFootprint.success).toBe(false);
  115. const emptyTiles = buildingSchema.safeParse({ ...SHED, buildable: { tiles: [] } });
  116. expect(emptyTiles.success).toBe(false);
  117. const badBuildable = buildingSchema.safeParse({ ...SHED, buildable: "grass" });
  118. expect(badBuildable.success).toBe(false);
  119. const missingBlocks = buildingSchema.safeParse({ id: "x", footprint: { w: 1, h: 1 }, buildable: "map" });
  120. expect(missingBlocks.success).toBe(false);
  121. });
  122. });
  123. describe("PlacementSystem.place", () => {
  124. it("places a building as a world entity and emits placement-change", async () => {
  125. const { system: spy, seen } = eventSpy();
  126. const { engine, close } = await setup(spy);
  127. try {
  128. const placed = placementOf(engine).place("shed", 0, 0);
  129. expect(placed).toEqual({
  130. id: "building:shed:0:0",
  131. type: "building",
  132. buildingId: "shed",
  133. x: 0,
  134. y: 0,
  135. w: 2,
  136. h: 2,
  137. blocksMovement: true,
  138. });
  139. expect(engine.world.get("building:shed:0:0")).toMatchObject({ type: "building", buildingId: "shed" });
  140. expect(changeEvents(seen)).toEqual([{ type: "place", buildingId: "shed", x: 0, y: 0, w: 2, h: 2 }]);
  141. } finally {
  142. await close();
  143. }
  144. });
  145. it("enforces buildable tile lists against the map terrain", async () => {
  146. const { engine, close } = await setup();
  147. try {
  148. const placement = placementOf(engine);
  149. placement.place("fence", 0, 0);
  150. expect(() => placement.place("fence", 2, 0)).toThrow(/tile \(2,0\) is not buildable for fence/);
  151. expect(() => placement.place("fence", 0, 3)).toThrow(/tile \(0,3\) is not buildable for fence/);
  152. } finally {
  153. await close();
  154. }
  155. });
  156. it("allows map and any buildable on any tile type", async () => {
  157. const { engine, close } = await setup();
  158. try {
  159. const placement = placementOf(engine);
  160. expect(placement.place("shed", 2, 2).buildingId).toBe("shed");
  161. expect(placement.place("path", 2, 0).buildingId).toBe("path");
  162. } finally {
  163. await close();
  164. }
  165. });
  166. it("rejects footprints outside map bounds", async () => {
  167. const { engine, close } = await setup();
  168. try {
  169. const placement = placementOf(engine);
  170. expect(() => placement.place("shed", 4, 4)).toThrow(/footprint out of bounds at \(4,4\)/);
  171. expect(() => placement.place("shed", 0, 4)).toThrow(/footprint out of bounds/);
  172. expect(placement.place("shed", 3, 3).buildingId).toBe("shed");
  173. } finally {
  174. await close();
  175. }
  176. });
  177. it("rejects overlapping buildings and accepts adjacent ones", async () => {
  178. const { engine, close } = await setup();
  179. try {
  180. const placement = placementOf(engine);
  181. placement.place("shed", 0, 0);
  182. expect(() => placement.place("fence", 1, 1)).toThrow(/overlaps existing building building:shed:0:0/);
  183. expect(placement.place("fence", 0, 2).buildingId).toBe("fence");
  184. } finally {
  185. await close();
  186. }
  187. });
  188. it("throws on an unknown building def and on bad coords", async () => {
  189. const { engine, close } = await setup();
  190. try {
  191. const placement = placementOf(engine);
  192. expect(() => placement.place("barn", 0, 0)).toThrow(/unknown building: barn/);
  193. expect(() => placement.place("shed", -1, 0)).toThrow(/non-negative integers/);
  194. expect(() => placement.place("shed", 1.5, 0)).toThrow(/non-negative integers/);
  195. } finally {
  196. await close();
  197. }
  198. });
  199. });
  200. describe("PlacementSystem remove/list/occupies", () => {
  201. it("remove removes the building occupying a cell and emits placement-change", async () => {
  202. const { system: spy, seen } = eventSpy();
  203. const { engine, close } = await setup(spy);
  204. try {
  205. const placement = placementOf(engine);
  206. placement.place("shed", 0, 0);
  207. const removed = placement.remove(1, 1);
  208. expect(removed.id).toBe("building:shed:0:0");
  209. expect(engine.world.get("building:shed:0:0")).toBeUndefined();
  210. expect(changeEvents(seen)).toEqual([
  211. { type: "place", buildingId: "shed", x: 0, y: 0, w: 2, h: 2 },
  212. { type: "remove", buildingId: "shed", x: 0, y: 0, w: 2, h: 2 },
  213. ]);
  214. expect(() => placement.remove(0, 0)).toThrow(/no building at \(0,0\)/);
  215. } finally {
  216. await close();
  217. }
  218. });
  219. it("list returns all placed buildings and occupies resolves containment", async () => {
  220. const { engine, close } = await setup();
  221. try {
  222. const placement = placementOf(engine);
  223. expect(placement.list()).toEqual([]);
  224. placement.place("shed", 0, 0);
  225. placement.place("fence", 3, 2);
  226. const ids = placement.list().map((building) => building.id);
  227. expect(ids).toEqual(["building:shed:0:0", "building:fence:3:2"]);
  228. const inside = placement.occupies(1, 1) as BuildingPlacement;
  229. expect(inside.id).toBe("building:shed:0:0");
  230. const edge = placement.occupies(0, 0) as BuildingPlacement;
  231. expect(edge.id).toBe("building:shed:0:0");
  232. expect(placement.occupies(2, 0)).toBeUndefined();
  233. } finally {
  234. await close();
  235. }
  236. });
  237. });
  238. describe("PlacementSystem hooks and persistence", () => {
  239. it("placement-change maps to the onPlacementChange hook", async () => {
  240. const { engine, close } = await setup();
  241. try {
  242. const seen: unknown[] = [];
  243. engine.hooks.on("onPlacementChange", (ctx) => {
  244. seen.push(ctx.world.query({ type: "building" }).map((building) => building.id));
  245. });
  246. placementOf(engine).place("shed", 0, 0);
  247. expect(seen).toEqual([["building:shed:0:0"]]);
  248. placementOf(engine).remove(0, 0);
  249. expect(seen).toEqual([["building:shed:0:0"], []]);
  250. } finally {
  251. await close();
  252. }
  253. });
  254. it("placed buildings survive save snapshot/restore", async () => {
  255. const { engine, close } = await setup();
  256. try {
  257. placementOf(engine).place("shed", 0, 0);
  258. placementOf(engine).place("fence", 3, 2);
  259. const snapshot = saveOf(engine).snapshot();
  260. expect(snapshot.world.filter((entity) => entity.type === "building")).toHaveLength(2);
  261. saveOf(engine).restore(snapshot);
  262. const restored = placementOf(engine).list();
  263. expect(restored.map((building) => building.id)).toEqual(["building:shed:0:0", "building:fence:3:2"]);
  264. expect(placementOf(engine).occupies(1, 1)?.buildingId).toBe("shed");
  265. } finally {
  266. await close();
  267. }
  268. });
  269. });