election-game/backend/packages/engine/test/engine.test.ts

279 lines
12 KiB
TypeScript
Raw Permalink Normal View History

import { PlayerView, type Order } from "@election2026/protocol";
import { describe, expect, it } from "vitest";
import {
aiOrders,
autoplay,
createMatch,
playWeek,
resolveTurn,
validateOrders,
viewFor,
weeklyLeakChance,
mergeSimilar,
type MatchState,
type SecretRecord,
type World,
} from "../src/index.ts";
import { TEST_SCENARIO, tinyWorld } from "./fixtures.ts";
const order = (o: Partial<Order> & Pick<Order, "actionId" | "slot">): Order => ({
actor: "candidate",
staffId: o.actor === "team" ? "staff-1" : null,
target: null,
amount: null,
opponentId: null,
issueIds: null,
...o,
});
function snapshot(state: MatchState): string {
return JSON.stringify(state, (_, v) => (v instanceof Float32Array ? Array.from(v) : v));
}
function playToEnd(world: World, seed: number, given: (state: MatchState) => Record<string, Order[]> = () => ({})) {
let state = createMatch(world, "m", seed, "alice");
const errors: string[] = [];
while (state.phase !== "finished") {
const out = playWeek(state, world, given(state));
Object.values(out.errors).forEach((e) => errors.push(...e));
state = out.state;
}
return { state, errors };
}
describe("決定性與不可變", () => {
it("同樣的種子打出完全一樣的結果", () => {
const world = tinyWorld();
expect(snapshot(autoplay(world, "m", 42))).toBe(snapshot(autoplay(world, "m", 42)));
});
it("不同種子會有不同的開票結果", () => {
const world = tinyWorld();
expect(autoplay(world, "m", 1).result?.votes).not.toEqual(autoplay(world, "m", 2).result?.votes);
});
it("resolveTurn 不修改輸入的狀態", () => {
const world = tinyWorld();
const state = createMatch(world, "m", 7, "alice");
const before = snapshot(state);
const orders = { alice: aiOrders(state, world, "alice"), bob: aiOrders(state, world, "bob") };
resolveTurn(state, world, orders);
expect(snapshot(state)).toBe(before);
});
});
describe("指令驗證", () => {
const world = tinyWorld();
const state = createMatch(world, "m", 1, "alice");
const check = (orders: Order[]) =>
validateOrders(state, world.scenario, world.pack, world.content, "alice", orders);
it("接受合法的指令", () => {
const v = check([
order({ actionId: "street_canvass", slot: "weekdayMorning", target: "68000010" }),
order({ actionId: "rally", slot: "weekendEvening", target: "68000020", amount: 3_000_000 }),
order({ actor: "team", actionId: "street_canvass", slot: "weekendAfternoon", target: "68000010" }),
]);
expect(v.errors).toEqual([]);
expect(v.orders).toHaveLength(3);
});
it("剔除不合法的指令並說明原因", () => {
const v = check([
order({ actionId: "no_such_action", slot: "weekdayMorning" }),
order({ actionId: "street_canvass", slot: "weekdayEvening", target: "68000010" }),
order({ actionId: "street_canvass", slot: "weekdayMorning", target: null }),
order({ actionId: "eve_rally", slot: "weekendEvening", target: "68000010", amount: 5_000_000 }),
order({ actionId: "rally", slot: "weekendEvening", target: "68000010", amount: 3_100_000 }),
order({ actor: "team", actionId: "rally", slot: "weekendEvening", target: "68000010", amount: 3_000_000 }),
]);
expect(v.orders).toEqual([]);
expect(v.errors).toHaveLength(6);
});
it("兩個時段的行動會佔用前一個時段", () => {
const v = check([
order({ actionId: "street_canvass", slot: "weekendAfternoon", target: "68000010" }),
order({ actionId: "rally", slot: "weekendEvening", target: "68000020", amount: 3_000_000 }),
]);
expect(v.orders).toHaveLength(1);
expect(v.errors[0]).toContain("已經有行程");
});
it("錢不夠時剔除", () => {
const poor = { ...state, candidates: state.candidates.map((c) => ({ ...c, money: 1_500_000 })) };
const v = validateOrders(poor, world.scenario, world.pack, world.content, "alice", [
order({ actionId: "rally", slot: "weekendEvening", target: "68000010", amount: 1_000_000 }),
order({ actionId: "rally", slot: "weekdayEvening", target: "68000010", amount: 1_000_000 }),
]);
expect(v.orders).toHaveLength(1);
expect(v.errors[0]).toContain("錢不夠");
});
});
describe("幕僚", () => {
const world = tinyWorld();
const state = createMatch(world, "m", 1, "alice");
const check = (orders: Order[]) => validateOrders(state, world.scenario, world.pack, world.content, "alice", orders);
it("開局有劇本設定的幕僚人數,每位各有一排行程", () => {
expect(state.candidates[0].staff.map((m) => m.id)).toEqual(["staff-1", "staff-2"]);
const v = check([
order({ actor: "team", staffId: "staff-1", actionId: "street_canvass", slot: "weekdayMorning", target: "68000010" }),
order({ actor: "team", staffId: "staff-2", actionId: "street_canvass", slot: "weekdayMorning", target: "68000020" }),
order({ actionId: "street_canvass", slot: "weekdayMorning", target: "68000020" }),
]);
expect(v.errors).toEqual([]);
});
it("同一位幕僚不能同時段兩個行程;團隊行動要指定存在的幕僚,候選人本人不能指定", () => {
const v = check([
order({ actor: "team", staffId: "staff-1", actionId: "street_canvass", slot: "weekdayMorning", target: "68000010" }),
order({ actor: "team", staffId: "staff-1", actionId: "street_canvass", slot: "weekdayMorning", target: "68000020" }),
order({ actor: "team", staffId: "staff-9", actionId: "street_canvass", slot: "weekdayAfternoon", target: "68000020" }),
order({ actor: "team", staffId: null, actionId: "street_canvass", slot: "weekdayAfternoon", target: "68000020" }),
order({ staffId: "staff-1", actionId: "street_canvass", slot: "weekendMorning", target: "68000020" }),
]);
expect(v.orders).toHaveLength(1);
expect(v.errors).toHaveLength(4);
});
it("找幕僚之後下週多一排行程,薪水算進每週固定支出", () => {
const next = resolveTurn(state, world, { alice: [order({ actionId: "hire_staff", slot: "weekdayMorning" })], bob: [] }).state;
expect(next.candidates[0].staff).toHaveLength(3);
const view = viewFor(next, world, "alice");
expect(view.self.staff).toHaveLength(3);
expect(view.self.upkeep).toBe(3 * 15_000);
});
it("每週先付固定支出,再用剩下的錢驗證指令", () => {
const poor = { ...state, candidates: state.candidates.map((c) => ({ ...c, money: 1_020_000 })) };
const rally = order({ actionId: "rally", slot: "weekendEvening", target: "68000010", amount: 1_000_000 });
const out = resolveTurn(poor, world, { alice: [rally], bob: [] });
expect(out.errors.alice?.[0]).toContain("錢不夠");
expect(out.state.candidates[0].money).toBeGreaterThanOrEqual(0);
});
});
describe("整場比賽", () => {
it("AI 對打可以跑完,AI 的指令全部合法", () => {
const { state, errors } = playToEnd(tinyWorld(), 3);
expect(state.phase).toBe("finished");
expect(state.result).not.toBeNull();
expect(errors).toEqual([]);
});
it("錢不會變負數,花費不超過法定上限", () => {
for (const seed of [1, 2, 3, 4, 5]) {
const end = autoplay(tinyWorld(), "m", seed);
for (const c of end.candidates) {
expect(c.money).toBeGreaterThanOrEqual(0);
expect(c.spent).toBeLessThanOrEqual(TEST_SCENARIO.spendingCap);
}
}
});
it("開票數字前後一致", () => {
const world = tinyWorld();
const r = autoplay(world, "m", 9).result!;
const total = Object.values(r.votes).reduce((a, b) => a + b, 0);
expect(total).toBe(r.valid);
expect(r.ballots).toBeGreaterThanOrEqual(r.valid);
for (const id of Object.keys(r.votes)) {
const fromVillages = Object.values(r.byVillage).reduce((s, row) => s + row[id], 0);
const fromTowns = Object.values(r.byTown).reduce((s, row) => s + row[id], 0);
expect(fromVillages).toBe(r.votes[id]);
expect(fromTowns).toBe(r.votes[id]);
}
expect(r.votes[r.winnerId]).toBe(Math.max(...Object.values(r.votes)));
expect(r.countingOrder).toHaveLength(world.pack.villages.length);
});
it("階段依序推進:選戰 → 選前之夜 → 開票,結束後不再變動", () => {
const world = tinyWorld();
let state = createMatch(world, "m", 5, "alice");
for (let w = 1; w <= TEST_SCENARIO.weeks; w++) {
expect(state.phase).toBe("campaign");
state = playWeek(state, world).state;
}
expect(state.phase).toBe("eve");
state = playWeek(state, world).state;
expect(state.phase).toBe("finished");
expect(resolveTurn(state, world, {}).state).toBe(state);
});
it("沒人檢舉時,買票確實會多拿票", () => {
const world = { ...tinyWorld(), scenario: { ...TEST_SCENARIO, bountyMultiplier: 0 } };
const buy = (s: MatchState): Record<string, Order[]> =>
s.phase === "campaign" && s.week === TEST_SCENARIO.weeks
? { alice: [order({ actor: "team", actionId: "vote_buying", slot: "midnight", target: "68000010", amount: 2_000 })] }
: {};
const clean = playToEnd(world, 11).state.result!;
const dirty = playToEnd(world, 11, buy).state.result!;
expect(dirty.votes.alice).toBeGreaterThan(clean.votes.alice + 1_000);
});
});
describe("玩家視角", () => {
it("符合協定,且看不到別人的祕密與內參", () => {
const world = tinyWorld();
let state = createMatch(world, "m", 13, "alice");
const bobOrders: Order[] = [
order({ actor: "team", actionId: "internal_poll", slot: "weekdayMorning" }),
order({ actor: "team", actionId: "vote_buying", slot: "midnight", target: "68000020", amount: 500 }),
];
state = resolveTurn(state, world, { alice: [], bob: bobOrders }).state;
const alice = viewFor(state, world, "alice");
const bob = viewFor(state, world, "bob");
expect(PlayerView.safeParse(alice).success).toBe(true);
expect(alice.polls.filter((p) => p.kind === "internal")).toEqual([]);
expect(bob.polls.filter((p) => p.kind === "internal")).toHaveLength(1);
expect(bob.polls[0].byTown).not.toBeNull();
expect(bob.self.secretActions).toBe(1);
expect(alice.self.secretActions).toBe(0);
const text = JSON.stringify(alice);
for (const hidden of ["favor", "awareness", "boughtVotes", "secrets", "machine"]) expect(text).not.toContain(`"${hidden}"`);
expect(alice.report.some((r) => r.text.includes("買"))).toBe(false);
});
});
describe("新聞", () => {
it("同一週、同一種行動的新聞合併成一則", () => {
const draft = (name: string, value: number) => ({
title: `${name}發表主打政見`,
value,
candidateId: name,
townCode: null,
tone: "positive" as const,
topic: "announce_policy",
merge: { key: "announce_policy|", template: "{name}發表主打政見", vars: { name, town: "", opponent: "" } },
});
const merged = mergeSimilar([draft("甲", 4), { title: "颱風", value: 7, candidateId: null, townCode: null, tone: "neutral", topic: "typhoon" }, draft("乙", 4), draft("丙", 3)]);
expect(merged.map((d) => d.title)).toEqual(["甲、乙、丙發表主打政見", "颱風"]);
expect(merged[0].value).toBe(5);
expect(merged[0].candidateId).toBeNull();
});
});
describe("通風報信機率", () => {
const record = (recipients: number, machines: number): SecretRecord => ({
id: "x",
week: 1,
kind: "voteBuying",
townIndex: 0,
recipients,
machines,
candidateKnows: false,
exposed: false,
});
it("買越多票越容易被檢舉", () => {
expect(weeklyLeakChance(record(5_000, 13), 3, 10, 1)).toBeGreaterThan(weeklyLeakChance(record(500, 2), 3, 10, 1));
});
it("越接近投票日越危險,且有上限", () => {
expect(weeklyLeakChance(record(1_000, 3), 10, 10, 1)).toBeGreaterThan(weeklyLeakChance(record(1_000, 3), 3, 10, 1));
expect(weeklyLeakChance(record(1_000_000, 3_000), 10, 10, 5)).toBeLessThanOrEqual(0.95);
});
});