| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298 |
- import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
- import { tmpdir } from "node:os";
- import { join } from "node:path";
- import { describe, expect, it } from "vitest";
- import {
- buildingSchema,
- createEngine,
- type BuildingDef,
- type BuildingPlacement,
- type PlacementChangeEvent,
- type PlacementSystem,
- type SaveSystem,
- type System,
- } from "../src/index.js";
- const TIME_YAML = [
- "id: default",
- "dayLengthTicks: 480",
- "seasons:",
- " - { name: spring, dayCount: 28 }",
- "start: { day: 1, season: spring }",
- "",
- ].join("\n");
- const FARM_YAML = [
- "id: farm",
- "width: 5",
- "height: 5",
- 'tilesetRef: "tiles"',
- "spawn: { x: 0, y: 0 }",
- "layers:",
- " - name: ground",
- " data:",
- " - [grass, grass, water, water, water]",
- " - [grass, grass, water, water, water]",
- " - [grass, grass, grass, grass, grass]",
- " - [tilled, tilled, grass, grass, grass]",
- " - [tilled, tilled, grass, grass, grass]",
- "",
- ].join("\n");
- const SHED: BuildingDef = {
- id: "shed",
- name: "Shed",
- footprint: { w: 2, h: 2 },
- buildable: "map",
- blocksMovement: true,
- };
- const FENCE: BuildingDef = {
- id: "fence",
- footprint: { w: 1, h: 1 },
- buildable: { tiles: ["grass"] },
- blocksMovement: true,
- };
- const PATH: BuildingDef = {
- id: "path",
- footprint: { w: 1, h: 1 },
- buildable: "any",
- blocksMovement: false,
- };
- interface Setup {
- engine: ReturnType<typeof createEngine>;
- close: () => Promise<void>;
- }
- async function setup(spy?: System): Promise<Setup> {
- const tmp = await mkdtemp(join(tmpdir(), "farm-placement-"));
- await mkdir(join(tmp, "maps"), { recursive: true });
- await writeFile(join(tmp, "time.yaml"), TIME_YAML);
- await writeFile(join(tmp, "maps", "farm.yaml"), FARM_YAML);
- const systems: System[] = [];
- if (spy) systems.push(spy);
- const engine = createEngine({ contentDir: tmp, systems });
- await engine.start();
- engine.registry.register("building", SHED);
- engine.registry.register("building", FENCE);
- engine.registry.register("building", PATH);
- return {
- engine,
- close: async () => {
- await engine.stop();
- await rm(tmp, { recursive: true, force: true });
- },
- };
- }
- function placementOf(engine: ReturnType<typeof createEngine>): PlacementSystem {
- const placement = engine.systems.get<PlacementSystem>("placement");
- if (!placement) throw new Error("placement system not booted");
- return placement;
- }
- function saveOf(engine: ReturnType<typeof createEngine>): SaveSystem {
- const save = engine.systems.get<SaveSystem>("save");
- if (!save) throw new Error("save system not booted");
- return save;
- }
- function eventSpy(): { system: System; seen: { event: string; payload: unknown }[] } {
- const seen: { event: string; payload: unknown }[] = [];
- const system: System = {
- id: "spy",
- init() {},
- on(event, payload) {
- seen.push({ event, payload });
- },
- };
- return { system, seen };
- }
- function changeEvents(seen: { event: string; payload: unknown }[]): PlacementChangeEvent[] {
- return seen
- .filter((entry) => entry.event === "placement-change")
- .map((entry) => entry.payload as PlacementChangeEvent);
- }
- describe("buildingSchema", () => {
- it("accepts a valid def and rejects bad footprints, buildable forms, and missing blocksMovement", () => {
- expect(buildingSchema.safeParse(SHED).success).toBe(true);
- expect(buildingSchema.safeParse({ ...SHED, buildable: { tiles: ["grass"] } }).success).toBe(true);
- expect(buildingSchema.safeParse({ ...SHED, buildable: "any" }).success).toBe(true);
- const zeroFootprint = buildingSchema.safeParse({ ...SHED, footprint: { w: 0, h: 2 } });
- expect(zeroFootprint.success).toBe(false);
- const emptyTiles = buildingSchema.safeParse({ ...SHED, buildable: { tiles: [] } });
- expect(emptyTiles.success).toBe(false);
- const badBuildable = buildingSchema.safeParse({ ...SHED, buildable: "grass" });
- expect(badBuildable.success).toBe(false);
- const missingBlocks = buildingSchema.safeParse({ id: "x", footprint: { w: 1, h: 1 }, buildable: "map" });
- expect(missingBlocks.success).toBe(false);
- });
- });
- describe("PlacementSystem.place", () => {
- it("places a building as a world entity and emits placement-change", async () => {
- const { system: spy, seen } = eventSpy();
- const { engine, close } = await setup(spy);
- try {
- const placed = placementOf(engine).place("shed", 0, 0);
- expect(placed).toEqual({
- id: "building:shed:0:0",
- type: "building",
- buildingId: "shed",
- x: 0,
- y: 0,
- w: 2,
- h: 2,
- blocksMovement: true,
- });
- expect(engine.world.get("building:shed:0:0")).toMatchObject({ type: "building", buildingId: "shed" });
- expect(changeEvents(seen)).toEqual([{ type: "place", buildingId: "shed", x: 0, y: 0, w: 2, h: 2 }]);
- } finally {
- await close();
- }
- });
- it("enforces buildable tile lists against the map terrain", async () => {
- const { engine, close } = await setup();
- try {
- const placement = placementOf(engine);
- placement.place("fence", 0, 0);
- expect(() => placement.place("fence", 2, 0)).toThrow(/tile \(2,0\) is not buildable for fence/);
- expect(() => placement.place("fence", 0, 3)).toThrow(/tile \(0,3\) is not buildable for fence/);
- } finally {
- await close();
- }
- });
- it("allows map and any buildable on any tile type", async () => {
- const { engine, close } = await setup();
- try {
- const placement = placementOf(engine);
- expect(placement.place("shed", 2, 2).buildingId).toBe("shed");
- expect(placement.place("path", 2, 0).buildingId).toBe("path");
- } finally {
- await close();
- }
- });
- it("rejects footprints outside map bounds", async () => {
- const { engine, close } = await setup();
- try {
- const placement = placementOf(engine);
- expect(() => placement.place("shed", 4, 4)).toThrow(/footprint out of bounds at \(4,4\)/);
- expect(() => placement.place("shed", 0, 4)).toThrow(/footprint out of bounds/);
- expect(placement.place("shed", 3, 3).buildingId).toBe("shed");
- } finally {
- await close();
- }
- });
- it("rejects overlapping buildings and accepts adjacent ones", async () => {
- const { engine, close } = await setup();
- try {
- const placement = placementOf(engine);
- placement.place("shed", 0, 0);
- expect(() => placement.place("fence", 1, 1)).toThrow(/overlaps existing building building:shed:0:0/);
- expect(placement.place("fence", 0, 2).buildingId).toBe("fence");
- } finally {
- await close();
- }
- });
- it("throws on an unknown building def and on bad coords", async () => {
- const { engine, close } = await setup();
- try {
- const placement = placementOf(engine);
- expect(() => placement.place("barn", 0, 0)).toThrow(/unknown building: barn/);
- expect(() => placement.place("shed", -1, 0)).toThrow(/non-negative integers/);
- expect(() => placement.place("shed", 1.5, 0)).toThrow(/non-negative integers/);
- } finally {
- await close();
- }
- });
- });
- describe("PlacementSystem remove/list/occupies", () => {
- it("remove removes the building occupying a cell and emits placement-change", async () => {
- const { system: spy, seen } = eventSpy();
- const { engine, close } = await setup(spy);
- try {
- const placement = placementOf(engine);
- placement.place("shed", 0, 0);
- const removed = placement.remove(1, 1);
- expect(removed.id).toBe("building:shed:0:0");
- expect(engine.world.get("building:shed:0:0")).toBeUndefined();
- expect(changeEvents(seen)).toEqual([
- { type: "place", buildingId: "shed", x: 0, y: 0, w: 2, h: 2 },
- { type: "remove", buildingId: "shed", x: 0, y: 0, w: 2, h: 2 },
- ]);
- expect(() => placement.remove(0, 0)).toThrow(/no building at \(0,0\)/);
- } finally {
- await close();
- }
- });
- it("list returns all placed buildings and occupies resolves containment", async () => {
- const { engine, close } = await setup();
- try {
- const placement = placementOf(engine);
- expect(placement.list()).toEqual([]);
- placement.place("shed", 0, 0);
- placement.place("fence", 3, 2);
- const ids = placement.list().map((building) => building.id);
- expect(ids).toEqual(["building:shed:0:0", "building:fence:3:2"]);
- const inside = placement.occupies(1, 1) as BuildingPlacement;
- expect(inside.id).toBe("building:shed:0:0");
- const edge = placement.occupies(0, 0) as BuildingPlacement;
- expect(edge.id).toBe("building:shed:0:0");
- expect(placement.occupies(2, 0)).toBeUndefined();
- } finally {
- await close();
- }
- });
- });
- describe("PlacementSystem hooks and persistence", () => {
- it("placement-change maps to the onPlacementChange hook", async () => {
- const { engine, close } = await setup();
- try {
- const seen: unknown[] = [];
- engine.hooks.on("onPlacementChange", (ctx) => {
- seen.push(ctx.world.query({ type: "building" }).map((building) => building.id));
- });
- placementOf(engine).place("shed", 0, 0);
- expect(seen).toEqual([["building:shed:0:0"]]);
- placementOf(engine).remove(0, 0);
- expect(seen).toEqual([["building:shed:0:0"], []]);
- } finally {
- await close();
- }
- });
- it("placed buildings survive save snapshot/restore", async () => {
- const { engine, close } = await setup();
- try {
- placementOf(engine).place("shed", 0, 0);
- placementOf(engine).place("fence", 3, 2);
- const snapshot = saveOf(engine).snapshot();
- expect(snapshot.world.filter((entity) => entity.type === "building")).toHaveLength(2);
- saveOf(engine).restore(snapshot);
- const restored = placementOf(engine).list();
- expect(restored.map((building) => building.id)).toEqual(["building:shed:0:0", "building:fence:3:2"]);
- expect(placementOf(engine).occupies(1, 1)?.buildingId).toBe("shed");
- } finally {
- await close();
- }
- });
- });
|