Spielerando

Erstes Spiel mit Technologiebaum? Treshams Civilization (1980)

Die meisten Quellen schreiben Francis Treshams Brettspiel Civilization, 1980 in Großbritannien erschienen, die Einführung des Technologiebaums zu. Der leitende Designer von Civilization IV nennt dieses Brettspiel linear, und der verzweigte Plan aus Voraussetzungen, den die meisten mit einem Technologiebaum meinen, ist in Sid Meier's Civilization von 1991 belegt. Die Antwort hängt also davon ab, was man als Baum zählt.

Wer behauptet was?

Quelle Aussage
Wikipedia, Technology tree „Typically the board game Civilization by Francis Tresham (1980) is given the credit of introducing a technology tree“
Wikipedia, Civilization (1980 board game) Das Spiel sei „also first in incorporating a technology tree“, gestützt auf einen Game-Studies-Artikel von 2012, den wir nicht öffnen konnten
Will Slocombe (2019) Das Brettspiel „is often credited as being the first game to incorporate a 'technology tree'“, ohne Quelle für diese Zuschreibung
Benj Edwards, Game Developer (2007) Sid Meier habe für das Computerspiel von 1991 „also created the famous 'technology tree'“
Soren Johnson, leitender Designer von Civilization IV, zitiert bei Edwards „The board game [is] quite linear. The difference in Civilization is that it branches“
Wikipedia-Diskussionsseite (2014 und 2016) Autoren bestreiten die Aussage: Einer sagt, die einzige harte Voraussetzung sei Law gewesen, ein anderer verweist auf die Rabatte, die Karten geben, ein dritter hält die Zuschreibung möglicherweise für „just an urban legend“

Die Zuschreibung an das Brettspiel wird oft wiederholt, aber keine der Quellen, die wir öffnen konnten, zeigt, wo sie begann. Wikipedia und Slocombe nennen sie ohne eigene Quelle, und Wikipedias anderer Satz, der erste Baum „refers to Civilization“, sagt nicht, welches Civilization gemeint ist.

Was machte das Brettspiel von 1980 tatsächlich?

Eine Besprechung in Games International vom Januar 1990 beschreibt die Regeln. Die Spieler kaufen Zivilisationskarten, und „the purchase price is equal to the card value but, in practice, it may be decreased by cards already held“. Literacy und Architecture zusammen „knock forty points off the price of Law“. Der Schritt von einer Epoche in die nächste auf der Archaeological Succession Table braucht zum Beispiel zwei Städte, dann Karten aus drei Farbgruppen, dann sieben Karten.

Das ist ein Netz aus Rabatten und Schwellen, kein Plan aus Sperren. Ob man das einen Baum nennt, ist der ganze Streit.

Hat das Brettspiel das Computerspiel von 1991 geprägt?

Die Designer sind sich nicht einig. Meier sagte zu Edwards: „I had not played that before I did Civilization.“ Sein Mitdesigner Bruce Shelley: „I had played it many times ... I believe Sid had a copy of the game and looked at the components.“ Maher berichtet 2018, Meier habe behauptet, das Brettspiel nur einmal gespielt zu haben, und sieht trotzdem im Kartenstapel des Brettspiels einen Fortschrittsplan, der dem des Computerspiels „not at all far removed“ ist.

Wie hat sich der Technologiebaum über die Jahre verändert?

Wann Spiel Was sich änderte Quelle
Angekündigt Dez. 1966, gespielt ab Sep. 1967 Xeno, ein Spiel per Post Wer acht Runden überlebte, bekam bessere Triebwerke, Waffen und Schilde. Maher nennt es „a tech tree of sorts“. Ein Vorläufer: Die Verbesserungen kommen mit der Zeit, nicht durch Forschung The Digital Antiquarian
1980 (UK), 1981 (USA) Civilization, Brettspiel Karten werden mit Handelswaren gekauft, billiger für jede verwandte Karte im Besitz, und Epochen verlangen eine bestimmte Zahl von Städten und Karten Games International, Game Developer
1984 Incunabula Avalon Hills Computerspiel nach dem Brettspiel, für MS-DOS Game Developer
Dezember 1991 Sid Meier's Civilization Der Fortschrittsplan: Forschung sammelt sich mit der Zeit an, und jeder Fortschritt braucht andere zuerst, so wie Mysticism Ceremonial Burial verlangt. Meier: Es „began as a way of gradually opening up possibilities“ Game Developer, The Digital Antiquarian
Herbst 1992 Dune II In der Echtzeitstrategie wird der Baum zu Gebäuden: Ohne Außenposten lassen sich keine neuen Einheiten bauen. Maher zählt den Technologiebaum von Civilization zu den Einflüssen The Digital Antiquarian
1993 Master of Orion Jedes Volk bekommt eine zufällige Auswahl von etwa der Hälfte der Technologien, und wer für Forschung zahlt, bekommt nur eine langsam steigende Chance, sie in einer Runde zu erhalten The Digital Antiquarian
Oktober 2016 Civilization VI „Eureka-Momente“ beschleunigen die Forschung, wenn der Spieler eine passende Aufgabe erfüllt, und die Kultur wandert in einen eigenen Baum der Gesellschaftspolitik Wikipedia

Edwards' Zeitleiste nennt 1991 für das Computerspiel; Maher schreibt, es sei im Dezember 1991 erschienen.

Seit wann sagt man „Tech Tree“?

Maher stellt fest, dass Master of Orion 1993 „talks about a 'tech tree', while Civilization prefers the word 'advances'“. Das Handbuch zu Civilization II hat einen Abschnitt „Climbing the technology tree“ und ein Poster mit „a graphic technology tree, or flowchart, that lists every civilization advance“. Der Scan, den wir gelesen haben, ist ein späterer Druck mit Seitenköpfen von 2000. Eine Quelle, die nennt, wer einen der beiden Ausdrücke zuerst benutzte, haben wir nicht gefunden.

Was zählt als Technologiebaum?

  • Verbesserungen, die mit der Zeit kommen. Xeno, 1966 bis 1967, passt, aber nichts wird gewählt oder erforscht.
  • Fortschritte, die durch frühere billiger werden. Das Brettspiel von 1980 passt, und diese Fassung schreiben die meisten Quellen zu.
  • Ein verzweigter Plan, in dem jeder Fortschritt andere voraussetzt und mit der Zeit erforscht wird. Sid Meier's Civilization, 1991, ist der früheste belegte Fall in den gelesenen Quellen.
  • Gebäude als Voraussetzung. Dune II, 1992, passt.
  • Ein Baum, der teils verborgen oder dem Zufall überlassen ist. Master of Orion, 1993, passt.

Was lässt sich sicher sagen?

Francis Treshams Civilization, 1980, ist das Spiel, dem die Quellen den Technologiebaum zuschreiben, aber keine, die wir öffnen konnten, zeigt, woher diese Zuschreibung stammt, und sein Mechanismus waren eher Rabatte als Sperren. Sid Meier's Civilization, 1991, ist das früheste Spiel, das wir mit dem verzweigten Plan aus Voraussetzungen belegen können, den der Begriff heute meist meint. Ob das Brettspiel dazu führte, ist zwischen den beiden Machern des Computerspiels umstritten.

Heute selbst bauen

Unser Blueprint für den Technologiebaum ist Forschung im Sinn von 1991: Projekte mit einem Preis, einer Menge Arbeit und anderen Projekten, die zuerst fertig sein müssen, eines läuft, die anderen warten in einer Schlange. Die Regeln, an denen es scheitert, sind darin gelöst: Der Preis wird bezahlt, wenn ein Projekt startet, nicht wenn es eingereiht wird; ein Projekt kann hinter dem warten, das es braucht, aber nie davor; übrige Zeit am Ende eines Projekts geht an das nächste; und ein Abbruch gibt nur einen Teil des Preises zurück, sodass Abbrechen und Neustarten nie Geld bringt. Ein Baum mit einer Schleife oder einem fehlenden Projekt wird abgelehnt. Die Rabatte des Brettspiels, die Zufallsauswahl aus Master of Orion und die Eureka-Boni aus Civilization VI sind nicht dabei; jedes davon wäre eine Regel, um die du deine KI obendrauf bittest.

Baue „Technologiebaum“ in mein Spiel ein.

Das soll es bewirken: Ein Technologiebaum gibt dem Spieler ein langes Ziel, auf das er hinplanen kann. Zu wählen, was als Nächstes erforscht wird, und darauf zu warten, lässt jede Freischaltung verdient wirken und prägt, wie der Spieler zwischendurch spielt.

Baue es genau nach diesem Automaten. Prüfe zuerst, ob er zu meinem Spiel passt, und bau ihn dann so:

```mermaid
stateDiagram-v2
  [*] --> idle
  idle: Nichts eingereiht
  researching: Forscht
  stalled: Wartet aufs Geld
  idle --> researching: reiht ein, kann zahlen
  idle --> stalled: reiht ein, kann nicht
  stalled --> researching: Einnahmen decken Preis
  stalled --> idle: Schlange abgebrochen
  researching --> idle: letztes endet oder geht
  researching --> stalled: endet, nächstes zu teuer
```

Nimm diese Startwerte:
- researchRate: 1 work/s
- cancelRefund: 0.5 x
- queueLimit: 4 projects
- startingBank: 25 money

Achte auf diese typischen Fehler:
- Bezahlen im falschen Moment: Sag deiner KI: Den Preis nehmen, wenn das Projekt startet, und es in der Schlange ohne Preis warten lassen.
- Ein abgebrochenes Projekt, auf das andere warten: Sag deiner KI: Geht ein Projekt, jedes eingereihte Projekt herausnehmen, das es braucht, und jedes, das diese braucht.
- Zeit geht zwischen zwei Projekten verloren: Sag deiner KI: Die Restzeit im selben Tick an das nächste Projekt weitergeben.
- Abbrechen und Neustarten als Geldquelle: Sag deiner KI: Nur einen Anteil des Preises zurückgeben, weniger bei schon geleisteter Arbeit, und die Arbeit verlieren, damit ein Neustart immer etwas kostet.
- Warten aufs Geld ohne Hinweis: Sag deiner KI: Diesen Zustand vom Leerlauf trennen, zeigen, dass die Forschung auf Geld wartet, und das Projekt in dem Moment starten, in dem Einnahmen den Preis decken.
- Baum mit einer Schleife oder einem fehlenden Projekt: Sag deiner KI: Den ganzen Baum einmal beim Laden des Spiels prüfen und jede Schleife und jedes fehlende Projekt auflisten.

Ändere nichts anderes im Spiel. Behaupte nichts, ohne es zu belegen: Modelliere, was dafür nötig ist, und zeig mir, worauf deine Lösung beruht und woran ich sehe, dass sie klappt. Wenn du etwas nicht zeigen kannst, sag, dass du es nicht weißt. Sag mir danach in einfachen Worten, wie ich es ausprobiere.

Der Knopf kopiert diesen Text zusammen mit dem getesteten Code unten, damit deine KI alles hat.

Der getestete Code (TypeScript)
/* A tech tree: projects the player researches over time. Each one has a price, an amount of work and
   other projects that must be finished first. One project runs at a time, the rest wait in a queue.
   Unlike a skill tree, which is bought at once with points, research takes time, and the time is
   what has to be handled with care.

   Rules that go wrong. The price is paid when a project starts, not when it is queued, so a queue
   costs nothing until its turn. A project can be queued behind the one it needs, but it can never be
   queued ahead of it, and taking a project out of the queue takes out everything waiting on it.
   Time is carried over: when one project ends in the middle of a tick, the rest of that tick goes to
   the next one. Cancelling gives back only part of the price, less for work already done, and the work
   is lost, so cancelling and restarting is never a way to make money.

   `phase` names where the research is, for the model in mechanic.json. Time and money come in as
   values: dt is seconds, income is an amount. */

export interface Params {
  /** Work done per second. */
  researchRate: number;
  /** Share of the price handed back for the unfinished part of a cancelled project. */
  cancelRefund: number;
  /** Projects that may wait behind the running one. */
  queueLimit: number;
  /** Money in the bank at the start. */
  startingBank: number;
}

export const DEFAULT_PARAMS: Params = { researchRate: 1, cancelRefund: 0.5, queueLimit: 4, startingBank: 25 };

export interface Tech {
  id: string;
  /** Paid when the project starts. */
  cost: number;
  /** Work needed; takes work / researchRate seconds. */
  work: number;
  requires: string[];
}

export const EXAMPLE_TREE: Tech[] = [
  { id: "pottery", cost: 10, work: 5, requires: [] },
  { id: "weaving", cost: 10, work: 5, requires: [] },
  { id: "irrigation", cost: 20, work: 10, requires: ["pottery"] },
  { id: "looms", cost: 20, work: 10, requires: ["weaving"] },
  { id: "dyes", cost: 30, work: 12, requires: ["pottery", "weaving"] },
  { id: "trade", cost: 50, work: 20, requires: ["irrigation", "looms"] },
];

export interface State {
  tree: Tech[];
  bank: number;
  /** Finished projects, in the order they finished. */
  researched: string[];
  /** The running project and the work done on it. */
  active: { id: string; progress: number } | null;
  /** Waiting projects, in order. */
  queue: string[];
}

export type Action = { type: "enqueue"; tech: string } | { type: "cancel"; tech: string } | { type: "income"; amount: number } | { type: "tick"; dt: number };

export type Phase = "idle" | "researching" | "stalled";

/** Summing time leaves rounding error: a project is done when the time it still needs is this small. */
export const TIME_EPSILON = 1e-9;

export function initialState(params: Params = DEFAULT_PARAMS, tree: Tech[] = EXAMPLE_TREE): State {
  return { tree, bank: params.startingBank, researched: [], active: null, queue: [] };
}

export function phase(state: State): Phase {
  if (state.active) return "researching";
  return state.queue.length > 0 ? "stalled" : "idle";
}

const find = (state: Pick<State, "tree">, id: string) => state.tree.find((t) => t.id === id);

/** Problems that make a tree unusable: unknown projects, projects needing themselves, bad numbers. */
export function validateTree(tree: Tech[]): string[] {
  const problems: string[] = [];
  const ids = new Set<string>();
  for (const t of tree) {
    if (ids.has(t.id)) problems.push(`"${t.id}" appears twice`);
    ids.add(t.id);
    if (!(t.cost >= 0) || !(t.work > 0)) problems.push(`"${t.id}" needs a cost of 0 or more and work above 0`);
  }
  for (const t of tree) for (const r of t.requires) if (!ids.has(r)) problems.push(`"${t.id}" needs "${r}", which does not exist`);
  const byId = new Map(tree.map((t) => [t.id, t]));
  const mark = new Map<string, "open" | "done">();
  const visit = (id: string, trail: string[]): void => {
    if (mark.get(id) === "done") return;
    if (mark.get(id) === "open") {
      problems.push(`a loop: ${[...trail, id].join(" -> ")}`);
      return;
    }
    mark.set(id, "open");
    for (const r of byId.get(id)?.requires ?? []) if (byId.has(r)) visit(r, [...trail, id]);
    mark.set(id, "done");
  };
  for (const t of tree) visit(t.id, []);
  return problems;
}

/** The tech and everything in the queue that waits on it, however far down. */
function withDependants(state: State, tech: string): Set<string> {
  const gone = new Set([tech]);
  let grew = true;
  while (grew) {
    grew = false;
    for (const id of state.queue) {
      if (!gone.has(id) && find(state, id)?.requires.some((r) => gone.has(r))) {
        gone.add(id);
        grew = true;
      }
    }
  }
  return gone;
}

/** Starts the first waiting project if nothing runs and its price can be paid. */
function start(state: State): State {
  if (state.active || state.queue.length === 0) return state;
  const head = find(state, state.queue[0]);
  if (!head || state.bank < head.cost) return state;
  return { ...state, bank: state.bank - head.cost, active: { id: head.id, progress: 0 }, queue: state.queue.slice(1) };
}

function advance(state: State, dt: number, params: Params): State {
  let s = start(state);
  let remaining = dt;
  while (remaining > 0 && s.active) {
    const tech = find(s, s.active.id) as Tech;
    const needed = (tech.work - s.active.progress) / params.researchRate;
    if (needed <= remaining + TIME_EPSILON) {
      // Finished part-way through the tick: the rest of the tick goes on to the next project.
      remaining -= needed;
      s = start({ ...s, researched: [...s.researched, tech.id], active: null });
    } else {
      s = { ...s, active: { id: tech.id, progress: s.active.progress + params.researchRate * remaining } };
      remaining = 0;
    }
  }
  return s;
}

export function reduce(state: State, action: Action, params: Params = DEFAULT_PARAMS): State {
  switch (action.type) {
    case "enqueue": {
      const tech = find(state, action.tech);
      if (!tech || state.researched.includes(tech.id) || state.active?.id === tech.id || state.queue.includes(tech.id)) return state;
      if (state.queue.length >= params.queueLimit) return state;
      // Each need must be finished, running, or ahead of this one in the queue.
      const ahead = (id: string) => state.researched.includes(id) || state.active?.id === id || state.queue.includes(id);
      if (!tech.requires.every(ahead)) return state;
      return start({ ...state, queue: [...state.queue, tech.id] });
    }
    case "cancel": {
      const gone = withDependants(state, action.tech);
      if (state.active?.id === action.tech) {
        const tech = find(state, action.tech) as Tech;
        const refund = Math.floor(tech.cost * params.cancelRefund * (1 - state.active.progress / tech.work));
        return start({ ...state, bank: state.bank + refund, active: null, queue: state.queue.filter((id) => !gone.has(id)) });
      }
      if (!state.queue.includes(action.tech)) return state;
      return start({ ...state, queue: state.queue.filter((id) => !gone.has(id)) });
    }
    case "income":
      if (!Number.isFinite(action.amount) || action.amount <= 0) return state;
      return start({ ...state, bank: state.bank + action.amount });
    case "tick":
      if (!Number.isFinite(action.dt) || action.dt <= 0) return state;
      return advance(state, action.dt, params);
  }
}
Die Tests, die der Referenzcode besteht
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { chance, forAll, int, pick, real, seeded } from "../../../proofs/property.ts";
import { type Action, DEFAULT_PARAMS, EXAMPLE_TREE, type Params, type State, type Tech, initialState, phase, reduce, validateTree } from "./reference.ts";

const P = DEFAULT_PARAMS;

function close(actual: number, expected: number, tolerance = 1e-9): void {
  assert.ok(Math.abs(actual - expected) < tolerance, `${actual} is not ${expected}`);
}

function run(s: State, actions: Action[], params: Params = P): State {
  for (const a of actions) s = reduce(s, a, params);
  return s;
}
const queue = (...techs: string[]): Action[] => techs.map((tech) => ({ type: "enqueue", tech }));
const tick = (dt: number): Action => ({ type: "tick", dt });
const withBank = (bank: number, params: Params = P): State => ({ ...initialState(params), bank });

test("an-unfinished-prerequisite-blocks-queueing", () => {
  const s = initialState(P);
  assert.equal(reduce(s, { type: "enqueue", tech: "irrigation" }, P), s);
  assert.equal(phase(s), "idle");
});

test("a-chain-can-be-queued-in-order", () => {
  const s = run(initialState(P), queue("pottery", "irrigation", "trade"));
  // trade also needs looms, which is not there yet, so it was refused.
  assert.equal(s.active?.id, "pottery");
  assert.deepEqual(s.queue, ["irrigation"]);
});

test("cost-is-paid-when-research-starts", () => {
  let s = run(initialState(P), queue("pottery"));
  assert.equal(s.bank, 15);
  // A second project only waits, and costs nothing yet.
  s = run(s, queue("weaving"));
  assert.equal(s.bank, 15);
  assert.deepEqual(s.queue, ["weaving"]);
});

test("progress-grows-with-time", () => {
  const s = run(initialState(P), [...queue("pottery"), tick(2)]);
  close(s.active?.progress ?? -1, 2);
});

test("finishing-unlocks-the-tech", () => {
  const s = run(initialState(P), [...queue("pottery"), tick(5)]);
  assert.deepEqual(s.researched, ["pottery"]);
  assert.equal(s.active, null);
  assert.equal(phase(s), "idle");
  // What needed it can be queued now. It costs 20 and only 15 is left, so it waits for money.
  const next = run(s, queue("irrigation"));
  assert.deepEqual(next.queue, ["irrigation"]);
  assert.equal(phase(next), "stalled");
});

test("leftover-time-goes-to-the-next-project", () => {
  const s = run(withBank(100), [...queue("pottery", "irrigation"), tick(7)]);
  assert.deepEqual(s.researched, ["pottery"]);
  assert.equal(s.active?.id, "irrigation");
  close(s.active?.progress ?? -1, 2);
  assert.equal(s.bank, 100 - 10 - 20);
});

test("a-project-that-cannot-be-paid-waits", () => {
  const s = run(withBank(5), [...queue("pottery"), tick(100)]);
  assert.equal(phase(s), "stalled");
  assert.equal(s.bank, 5);
  assert.deepEqual(s.researched, []);
});

test("income-starts-a-waiting-project", () => {
  const s = run(withBank(5), [...queue("pottery"), { type: "income", amount: 5 }]);
  assert.equal(phase(s), "researching");
  assert.equal(s.bank, 0);
});

test("cancelling-refunds-the-unfinished-share", () => {
  // Price 10, half back for the whole price, and 2 of 5 work done: 10 * 0.5 * 0.6 = 3.
  let s = run(initialState(P), [...queue("pottery"), tick(2)]);
  s = reduce(s, { type: "cancel", tech: "pottery" }, P);
  assert.equal(s.bank, 15 + 3);
  assert.equal(s.active, null);
  assert.deepEqual(s.researched, []);
});

test("cancel-and-restart-never-makes-money", () => {
  let s = run(withBank(40), [...queue("pottery"), tick(1)]);
  const before = s.bank;
  s = run(s, [{ type: "cancel", tech: "pottery" }, ...queue("pottery")]);
  assert.ok(s.bank < before, `${s.bank} is not below ${before}`);
  close(s.active?.progress ?? -1, 0);
});

test("cancelling-also-removes-what-waits-on-it", () => {
  let s = run(withBank(200), queue("pottery", "irrigation", "weaving", "dyes"));
  assert.deepEqual(s.queue, ["irrigation", "weaving", "dyes"]);
  s = reduce(s, { type: "cancel", tech: "pottery" }, P);
  // irrigation and dyes both needed pottery; weaving did not, and starts.
  assert.equal(s.active?.id, "weaving");
  assert.deepEqual(s.queue, []);
});

test("a-finished-tech-cannot-be-queued-again", () => {
  const s = run(initialState(P), [...queue("pottery"), tick(5)]);
  assert.equal(reduce(s, { type: "enqueue", tech: "pottery" }, P), s);
});

test("a-full-queue-refuses-more", () => {
  const p = { ...P, queueLimit: 1 };
  const s = run(withBank(500, p), queue("pottery", "weaving", "irrigation"), p);
  assert.equal(s.active?.id, "pottery");
  assert.deepEqual(s.queue, ["weaving"]);
});

test("edge: one long tick finishes several projects in order", () => {
  const s = run(withBank(500), [...queue("pottery", "weaving", "irrigation", "looms"), tick(1000)]);
  assert.deepEqual(s.researched, ["pottery", "weaving", "irrigation", "looms"]);
  assert.equal(s.bank, 500 - 10 - 10 - 20 - 20);
});

test("edge: a queue cancelled in the middle removes only what waits on it", () => {
  let s = run(withBank(500), queue("pottery", "weaving", "irrigation", "looms"));
  s = reduce(s, { type: "cancel", tech: "weaving" }, P);
  assert.deepEqual(s.queue, ["irrigation"]);
});

test("edge: a bad time or amount changes nothing", () => {
  const s = run(initialState(P), queue("pottery"));
  for (const dt of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) assert.equal(reduce(s, tick(dt), P), s);
  assert.equal(reduce(s, { type: "income", amount: -3 }, P), s);
  assert.equal(reduce(s, { type: "enqueue", tech: "nothing" }, P), s);
  assert.equal(reduce(s, { type: "cancel", tech: "trade" }, P), s);
});

test("edge: a tree with a loop or a missing need is found", () => {
  assert.deepEqual(validateTree(EXAMPLE_TREE), []);
  const loop: Tech[] = [
    { id: "a", cost: 1, work: 1, requires: ["b"] },
    { id: "b", cost: 1, work: 1, requires: ["a"] },
  ];
  assert.ok(validateTree(loop).some((p) => p.startsWith("a loop")));
  assert.ok(validateTree([{ id: "a", cost: 1, work: 1, requires: ["z"] }]).some((p) => p.includes('"z"')));
});

function randomAction(r: () => number): Action {
  const t = pick(r, ["enqueue", "enqueue", "enqueue", "cancel", "income", "tick", "tick"] as const);
  const tech = pick(r, EXAMPLE_TREE).id;
  if (t === "income") return { type: t, amount: int(r, 1, 40) };
  if (t === "tick") return { type: t, dt: chance(r, 0.1) ? real(r, 10, 60) : real(r, 0, 4) };
  return { type: t, tech };
}

test("property: the queue never holds a project ahead of what it needs", (t) => {
  forAll(t, 91, 400, (r) => {
    const params: Params = { researchRate: real(r, 0.2, 5), cancelRefund: real(r, 0, 1), queueLimit: int(r, 1, 6), startingBank: int(r, 0, 80) };
    let s = initialState(params);
    for (let i = 0; i < 200; i++) {
      s = reduce(s, randomAction(r), params);
      assert.ok(s.bank >= 0);
      const seen = new Set(s.researched);
      const all = [...(s.active ? [s.active.id] : []), ...s.queue];
      assert.equal(new Set([...all, ...s.researched]).size, all.length + s.researched.length, "a project is in two places");
      for (const id of s.researched) assert.ok(s.tree.find((x) => x.id === id)?.requires.every((q) => s.researched.indexOf(q) !== -1 && s.researched.indexOf(q) < s.researched.indexOf(id)), `${id} finished before its needs`);
      const earlier = new Set(seen);
      if (s.active) {
        assert.ok(s.tree.find((x) => x.id === s.active?.id)?.requires.every((q) => seen.has(q)));
        earlier.add(s.active.id);
      }
      for (const id of s.queue) {
        assert.ok(s.tree.find((x) => x.id === id)?.requires.every((q) => earlier.has(q)), `${id} waits ahead of a need`);
        earlier.add(id);
      }
      assert.ok(s.queue.length <= params.queueLimit);
    }
  });
});

test("property: cancelling never pays back more than was paid", (t) => {
  forAll(t, 92, 400, (r) => {
    const params: Params = { ...P, cancelRefund: real(r, 0, 1), startingBank: 500 };
    let s = run(initialState(params), queue("pottery", "irrigation"), params);
    s = reduce(s, tick(real(r, 0, 4)), params);
    if (!s.active) return;
    const cost = s.tree.find((x) => x.id === s.active?.id)?.cost ?? 0;
    const before = s.bank;
    s = reduce(s, { type: "cancel", tech: s.active.id }, params);
    assert.ok(s.bank - before <= cost * params.cancelRefund + 1e-9);
  });
});

/* The model in mechanic.json against the code, both ways. */
const mechanic = JSON.parse(readFileSync(new URL("./mechanic.json", import.meta.url), "utf8"));
const model = mechanic.model as { states: { id: string }[]; moves: { from: string; to: string }[] };
const listed = new Set(model.moves.map((m) => `${m.from}>${m.to}`));

function drive(params: Params, seed: number, steps: number, moves: Set<string>, visited: Set<string>): void {
  const r = seeded(seed);
  let s = initialState(params);
  visited.add(phase(s));
  for (let i = 0; i < steps; i++) {
    const before = phase(s);
    s = reduce(s, randomAction(r), params);
    const after = phase(s);
    visited.add(after);
    if (after !== before) moves.add(`${before}>${after}`);
    // Everything researched leaves nothing to do: start again.
    if (s.researched.length === s.tree.length) s = initialState(params);
  }
}

test("model-matches-code", () => {
  const specs = mechanic.spec.parameters as { name: keyof Params; min: number; max: number }[];
  const variants: Params[] = [P];
  for (const p of specs) for (const v of [p.min, p.max]) variants.push({ ...P, [p.name]: v });
  const moves = new Set<string>();
  const visited = new Set<string>();
  variants.forEach((params, n) => {
    const here = new Set<string>();
    for (let seed = 1; seed <= 20; seed++) drive(params, n * 100 + seed, 1500, here, visited);
    for (const move of here) assert.ok(listed.has(move), `the code does ${move}, which the model does not list (variant ${n})`);
    for (const move of here) moves.add(move);
    if (n === 0) for (const move of listed) assert.ok(here.has(move), `at the default values the model's ${move} never happens`);
  });
  for (const move of listed) assert.ok(moves.has(move), `the model's ${move} never happens`);
  for (const state of model.states) assert.ok(visited.has(state.id), `state ${state.id} is never reached`);
  for (const id of visited) assert.ok(model.states.some((s) => s.id === id), `the code reaches ${id}, which the model does not list`);
});

Zum Blueprint: Technologiebaum

War diese Seite hilfreich?

Ein Klick, ohne Konto. So sehen wir, welche Seiten helfen.

Nächster Schritt

Herkunft

Welches Spiel hatte den ersten Doppelsprung? Dragon Buster

Frühester dokumentierter Doppelsprung: Dragon Buster (Namco), Dezember 1984 laut Guinness, Anfang 1985 laut anderen. Mit Zeitleiste und getestetem Code.

Quellen

Stand: 2026-11-26