feat: expand genes and refine colony controls
This commit is contained in:
parent
5394313a1f
commit
9f5f12333d
39 changed files with 5363 additions and 368 deletions
26
README.md
26
README.md
|
|
@ -1,6 +1,6 @@
|
|||
# Primordial Soup
|
||||
|
||||
An original vector-art web adaptation of Doris Matthäus and Frank Nestel's base game, for 3–4 colonies. It includes a server-authoritative engine, practice bots, and ten interactive English lessons using the ordinary board controls.
|
||||
An original vector-art web adaptation of Doris Matthäus and Frank Nestel's game, for 3–6 colonies. It includes a server-authoritative engine, practice bots, and ten interactive English lessons using the ordinary board controls.
|
||||
|
||||
```sh
|
||||
pnpm install
|
||||
|
|
@ -13,20 +13,36 @@ Local practice: http://127.0.0.1:5221/ . Lessons start at `/?chapter=drift`.
|
|||
|
||||
Chat and journal preview: `/?chat=1`. This uses the BGS viewer protocol with local messages, unread notifications, mentions and send-failure controls; nothing is sent to other players.
|
||||
|
||||
The **Color-blind mode** button in the top toolbar adds matching colony symbols to amoebas, food and scoring markers: circle, triangle, square, diamond, cross and star. BGS saves the `colorBlind` preference to the signed-in account through the viewer protocol; both the BGS preference panel and the toolbar update the display immediately. Local practice and chat previews save it in the browser. It applies to any player count.
|
||||
|
||||
## Rules and implementation status
|
||||
|
||||
Rules: [Z-Man English rulebook](https://cs.uwaterloo.ca/~dtompkin/archive/dtlib/base/Primordial%20Soup.pdf), [publisher's reference sheets](http://doris-frank.de/download/Ursuppe_Rules.pdf), and [publisher FAQ](http://doris-frank.de/UrsuppeFAQ.html).
|
||||
|
||||
The engine implements all six phases, finite food and genes, the twenty base-game gene effects, interruptions for Holding and combat, and scoring/end conditions. Gene quantities follow the publisher's revised reference table; its total differs from the rulebook's component count and should be checked against a physical set.
|
||||
The engine implements all six phases, finite food and genes, the twenty base-game gene effects, interruptions for Holding and combat, and scoring/end conditions. Gene quantities follow the owner's confirmed lists: 20 cards across 18 gene types for three players; four players add one each of Ray Protection, Intelligence, Speed, Escape, Tentacle, Frugality, Parasitism, Division Rate, Longevity (Life Expectancy), and Movement II, for 30 cards across 20 types. Persistence remains one copy in both pools.
|
||||
|
||||
**The environment-card manifest in `engine/catalog.js` is provisional.** The rulebook does not list all eleven ozone/direction pairs. The photographed 8/east and 12/west cards are matched, but the remaining distribution is not verified. This affects full-game probabilities; tutorials use explicit prepared environments. Confirm against all eleven printed cards before a public release.
|
||||
The environment-card manifest in `engine/catalog.js` uses the owner's confirmed eleven-card list: 6/west, 8/east, 9/west, 9/north, 10/east (two copies), 10/south, 11/north, 12/west, 13/south, and 14/no drift. Tutorials use explicit prepared environments.
|
||||
|
||||
No expansion genes are included. The bots are practice opponents, not a competitive AI.
|
||||
Five and six players use the complete 39-card standard gene pool from the [publisher's Freshly Spiced rules and reference sheets](http://doris-frank.de/download/Ursuppe_Frisch_Abgeschmeckt.pdf). Streamline and Struggle for Survival have mutation sensitivity 5; Frugality costs 5 BP. Amoebas eat four different foreign colours, receive 11 BP in phase 4, and are limited to numbers 1–6. Starting scores are chosen from 1–6, even with five players. Population scores for 0–6 amoebas are 0, 0, 1, 2, 3, 4, 5; gene scoring is unchanged. These rules apply automatically by player count. The other base rules continue to apply, including the first starting amoeba's injury and Tentacle's four-player capacity of three cubes (the translated reference does not state a separate 5–6-player capacity).
|
||||
|
||||
The optional extra genes are from **Primordial Soup: Freshly Spiced** (*Ursuppe: Frisch abgeschmeckt*). All 26 effects are implemented. Enable the boolean `newGenes` option (default false), or check **New genes** before starting a practice game. Direct preview: `/?players=6&newGenes=1`. The catalogue lives in `engine/new-genes.js`, with a seeded shuffle, hidden deck and public market. The recommended initial pair is Social Gene and Population Explosion. Two more cards become available each round in phase 3 immediately after the score leader finishes buying, before the next player's purchases. Previously revealed cards remain available. The option is independent of player count; it does not use the platform's expansions array. The viewer supports gene exchanges, healing, remote food selection, excretion destinations, toxins and private forecasts. Forecasts are stripped separately for each recipient and never written to the public journal. Source errata: [publisher's corrections](http://doris-frank.de/Ursuppe.html#ERRATA).
|
||||
|
||||
Implementation conventions for interactions not detailed by the translated reference: Social Gene collects at the start of phase 6, using the scores before movement; Flexible also discounts transfers and the positive price difference of an exchange; Highly Adaptable still requires and consumes an earlier-round prerequisite for an advanced gene. Healing II follows the reference’s explicit immediate death of the injury recipient, even if otherwise healthy. Ordinary injuries (including toxins and More than a Mouthful) wait for phase 5; lethal Bang chain reactions resolve immediately in descending score and amoeba-number order. Suction II takes at most two cubes from a single adjacent space, including diagonals. Rebound can cross one obstacle to a valid space, without wrapping around the board.
|
||||
|
||||
The bots are practice opponents, not a competitive AI.
|
||||
|
||||
Actions can be undone while the same player remains active in the same phase, until a dice roll, hidden-card reveal or turn handoff. Reversible moves remain pending and undo removes them, including their journal lines. Only the surviving sequence enters the append-only BGS history at the next boundary. `isLiveUpdate` suppresses turn notifications for pending changes; cumulative `timeIncrements` retain a high-water mark through undo/retry, so repeating a move never earns additional time. Tentacle cargo adjustments earn no time. Replay commits the requested history prefix before starting an analysis branch.
|
||||
|
||||
Gene buying and cell division skip automatically on entry when no legal action is available except Done. This checks free exchanges, discounts, healing, injury transfers and free recovery after extinction as well as ordinary purchases and placements. After a player takes an action, Done remains available so they can Undo before handing over. Population Explosion's income choice also keeps this confirmation. Automatic passes still reveal the leader's next two new genes at the usual time and add no synthetic moves or clock increments.
|
||||
|
||||
## Publication
|
||||
|
||||
BGS entry: `primordial-soup`, version 1. Keep `public: false`, metadata `unlisted: true`, and restrict beta access. The private engine is uploaded as an npm-pack tarball to BGS storage; it is not published to npm. The original rules PDF is hosted as a separate BGS asset and linked from the rules panel.
|
||||
|
||||
Artwork is newly drawn SVG, not scans. Bundled fonts retain their OFL notices in `viewer/assets/`.
|
||||
Artwork is newly drawn SVG, not scans. All 26 new genes have individual illustrations in the gene pool and detail view, following the selected colony's colour. Thirteen also add board traits, including sensing antennae, camouflage, healing patches, suction tubes, a hard crust and a PhD cap. Struggle for Survival adds fangs; Aggression adds fangs, angled brows and spines. Traits combine while retaining the colony's colour and colour-blind symbol. Compare them locally at `/?appearance=genes&newGenes=1` or `/?appearance=genes`.
|
||||
|
||||
Movement II has larger, split fins with visible fin rays, distinguishing it from Movement I on the board and in the gene illustrations.
|
||||
|
||||
Bundled fonts retain their OFL notices in `viewer/assets/`.
|
||||
|
||||
The display font is a renamed OFL derivative of Lilita One with corrected glyph bounds. Rebuild it with `uv run --with fonttools --with brotli scripts/build-display-font.py`.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,13 @@
|
|||
export const COLORS = ["green", "red", "blue", "yellow"];
|
||||
export const COLOR_NAMES = ["Green", "Coral", "Blue", "Gold"];
|
||||
import { NEW_GENES } from "./new-genes.js";
|
||||
export const COLORS = ["green", "red", "blue", "yellow", "black", "burgundy"];
|
||||
export const COLOR_NAMES = [
|
||||
"Green",
|
||||
"Coral",
|
||||
"Blue",
|
||||
"Gold",
|
||||
"Black",
|
||||
"Burgundy",
|
||||
];
|
||||
export const CELLS = Array.from({ length: 25 }, (_, i) => i).filter(
|
||||
(i) => ![0, 4, 5, 10, 12, 20].includes(i),
|
||||
);
|
||||
|
|
@ -154,7 +162,7 @@ export const GENES = [
|
|||
6,
|
||||
4,
|
||||
[2, 2],
|
||||
"If you cannot feed, spend 1 BP to attack an amoeba in your space. A successful attack feeds you and leaves one cube of each colour.",
|
||||
"Phase 1 only: if an amoeba cannot feed, spend 1 BP to attack another amoeba in its space. A successful attack feeds the attacker and leaves one cube of each colour. No attack if it can eat normally.",
|
||||
),
|
||||
gene(
|
||||
"parasitism",
|
||||
|
|
@ -177,7 +185,7 @@ export const GENES = [
|
|||
"Persistence",
|
||||
4,
|
||||
4,
|
||||
[1, 2],
|
||||
[1, 1],
|
||||
"After a failed attack or defense, you may make a second attempt for free. Replaces Speed; it does not keep Speed's extra swim.",
|
||||
["speed"],
|
||||
),
|
||||
|
|
@ -196,7 +204,7 @@ export const GENES = [
|
|||
5,
|
||||
5,
|
||||
[1, 1],
|
||||
"After natural deaths, attack one opponent in the same space for 1 BP, once per round. Still allows attacking instead of starving. Armor converts the survival-phase attack to one injury.",
|
||||
"Keeps Struggle for Survival: attack to feed in phase 1 when starving. Adds one attack for your whole colony in phase 5, after natural deaths, even if everyone has eaten. Choose one of your amoebas and an opponent in its space; pay 1 BP. A successful phase-5 attack kills the target; Armor reduces this to one injury.",
|
||||
["struggle"],
|
||||
),
|
||||
gene(
|
||||
|
|
@ -209,22 +217,69 @@ export const GENES = [
|
|||
["defense", "escape"],
|
||||
),
|
||||
];
|
||||
export const GENE = Object.fromEntries(GENES.map((g) => [g.id, g]));
|
||||
export const populationPoints = (n) => [0, 0, 0, 1, 2, 4, 5, 6][n];
|
||||
const sixPlayerCopies = {
|
||||
intelligence: 3,
|
||||
movement1: 3,
|
||||
spores: 2,
|
||||
speed: 2,
|
||||
defense: 2,
|
||||
escape: 2,
|
||||
substitution: 2,
|
||||
ray: 2,
|
||||
streamline: 2,
|
||||
tentacle: 2,
|
||||
holding: 1,
|
||||
longevity: 2,
|
||||
frugality: 2,
|
||||
struggle: 3,
|
||||
parasitism: 2,
|
||||
division: 2,
|
||||
persistence: 1,
|
||||
movement2: 2,
|
||||
aggression: 1,
|
||||
armor: 1,
|
||||
};
|
||||
for (const g of GENES)
|
||||
g.copies.push(sixPlayerCopies[g.id], sixPlayerCopies[g.id]);
|
||||
export const ALL_GENES = [...GENES, ...NEW_GENES];
|
||||
export const GENE = Object.fromEntries(ALL_GENES.map((g) => [g.id, g]));
|
||||
export const copiesOf = (g, players) =>
|
||||
Array.isArray(g.copies) ? g.copies[players - 3] : g.copies;
|
||||
export const populationPoints = (n, players = 4) =>
|
||||
(players >= 5 ? [0, 0, 1, 2, 3, 4, 5] : [0, 0, 0, 1, 2, 4, 5, 6])[n];
|
||||
export const amoebaLimit = (players) => (players >= 5 ? 6 : 7);
|
||||
export const roundIncome = (players) => (players >= 5 ? 11 : 10);
|
||||
export const tentacleLimit = (players) => (players === 3 ? 2 : 3);
|
||||
export function geneFor(id, players) {
|
||||
const g = GENE[id];
|
||||
if (players < 5) return g;
|
||||
const overrides = {
|
||||
streamline: { mutation: 5 },
|
||||
struggle: { mutation: 5 },
|
||||
frugality: { cost: 5 },
|
||||
substitution: {
|
||||
text: "Eat five food cubes from three other colours instead of four cubes from four colours. You may combine this with Frugality and Parasitism.",
|
||||
},
|
||||
tentacle: {
|
||||
text: "Carry up to three food cubes when moving. You may take any colour, including your own.",
|
||||
},
|
||||
};
|
||||
return overrides[id] ? { ...g, ...overrides[id] } : g;
|
||||
}
|
||||
export const genePoints = (n) => Math.min(4, Math.max(0, n - 2));
|
||||
|
||||
// Private playtest deck: exact printed card distribution is still awaiting verification.
|
||||
// Keep this separate from movement rules; see README.md.
|
||||
// Eleven environment cards transcribed and confirmed by the owner.
|
||||
// Direction indexes follow DIRECTIONS; the two 10/East cards are intentional.
|
||||
export const ENVIRONMENTS = [
|
||||
{ ozone: 6, direction: 2 },
|
||||
{ ozone: 7, direction: 0 },
|
||||
{ ozone: 6, direction: 0 },
|
||||
{ ozone: 8, direction: 2 },
|
||||
{ ozone: 8, direction: 3 },
|
||||
{ ozone: 9, direction: 2 },
|
||||
{ ozone: 10, direction: 4 },
|
||||
{ ozone: 11, direction: 0 },
|
||||
{ ozone: 9, direction: 0 },
|
||||
{ ozone: 9, direction: 1 },
|
||||
{ ozone: 10, direction: 2 },
|
||||
{ ozone: 10, direction: 3 },
|
||||
{ ozone: 10, direction: 2 },
|
||||
{ ozone: 11, direction: 1 },
|
||||
{ ozone: 12, direction: 0 },
|
||||
{ ozone: 12, direction: 3 },
|
||||
{ ozone: 13, direction: 2 },
|
||||
{ ozone: 14, direction: 0 },
|
||||
{ ozone: 13, direction: 3 },
|
||||
{ ozone: 14, direction: 4 },
|
||||
];
|
||||
|
|
|
|||
699
engine/index.js
699
engine/index.js
File diff suppressed because it is too large
Load diff
145
engine/new-genes.js
Normal file
145
engine/new-genes.js
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
// Rules and errata: http://doris-frank.de/download/Ursuppe_Frisch_Abgeschmeckt.pdf
|
||||
// http://doris-frank.de/Ursuppe.html#ERRATA
|
||||
export const NEW_GENES_OPTION = {
|
||||
name: "newGenes",
|
||||
label: "New genes",
|
||||
type: "checkbox",
|
||||
default: false,
|
||||
};
|
||||
export const NEW_GENES_TITLE = "Primordial Soup: Freshly Spiced";
|
||||
const extra = (id, name, cost, mutation, base = [], details = {}) => ({
|
||||
id,
|
||||
name,
|
||||
cost,
|
||||
mutation,
|
||||
base,
|
||||
copies: 1,
|
||||
points: base.length ? 2 : 1,
|
||||
implemented: true,
|
||||
...details,
|
||||
});
|
||||
export const NEW_GENES = [
|
||||
extra("doris-frank", "Doris & Frank Gene", 2, 3),
|
||||
extra("glutton", "Glutton", 3, -2),
|
||||
extra("alarm", "Alarm", 3, 3),
|
||||
extra("cleanliness", "Cleanliness", 3, 3),
|
||||
extra("hard-crust", "Hard Crust", 3, 3),
|
||||
extra("migration", "Migration Sensing", 3, 3),
|
||||
extra("social", "Social Gene", 4, 3, [], { transferCost: 2 }),
|
||||
extra("fast-food", "Fast Food", 4, 3),
|
||||
extra("adaptable", "Highly Adaptable", 4, 3),
|
||||
extra("mouthful", "More than a Mouthful", 4, 3),
|
||||
extra("camouflage1", "Camouflage I", 4, 4),
|
||||
extra("suction1", "Suction I", 4, 4),
|
||||
extra("threat", "Threat Display", 4, 4),
|
||||
extra("flexible", "Flexible", 5, 4),
|
||||
extra("healing1", "Healing I", 5, 4),
|
||||
extra("rebound", "Rebound", 5, 4),
|
||||
extra("bang", "Go Out With a Bang", 5, 5),
|
||||
extra("short-life", "Short Life Span", 5, 5, [], { defectRelief: 4 }),
|
||||
extra("toxic", "Toxic Excretions", 5, 5),
|
||||
extra("population", "Population Explosion", 6, 5),
|
||||
extra("energy", "Energy Conservation", 6, 6),
|
||||
extra("phd", "PhD", 3, 4, ["intelligence"]),
|
||||
extra("environmental", "Environmental Sensing", 4, 3, ["migration"]),
|
||||
extra("camouflage2", "Camouflage II", 5, 5, ["camouflage1"]),
|
||||
extra("healing2", "Healing II", 5, 5, ["healing1"]),
|
||||
extra("suction2", "Suction II", 6, 6, ["suction1"]),
|
||||
];
|
||||
const descriptions = {
|
||||
"doris-frank":
|
||||
"At the end of the game, you choose which game everyone plays next.",
|
||||
glutton:
|
||||
"Every amoeba must eat one extra nutrient of another colour at each meal. Its negative sensitivity protects your other genes.",
|
||||
alarm:
|
||||
"After one of your amoebas is eaten in phase 1, your remaining amoebas can use Escape for the rest of that phase.",
|
||||
cleanliness:
|
||||
"After feeding, you may excrete in an adjacent space instead. Both nutrients go to the same space.",
|
||||
"hard-crust":
|
||||
"After overcoming your defenses, an attacker must pay one extra BP to complete its attack. Otherwise the attack fails.",
|
||||
migration:
|
||||
"At the start of phase 1, privately see the environment card that will be revealed in phase 2.",
|
||||
social:
|
||||
"Only the last colony may buy this gene: 4 BP from the bank, or 2 BP paid to its current owner. In phase 6, receive 1 BP from each colony at least six score spaces ahead.",
|
||||
"fast-food":
|
||||
"Your amoebas may feed before moving, instead of after moving, in phase 1.",
|
||||
adaptable:
|
||||
"During phase 3, exchange an owned gene, including this one, for an available gene. Pay only the positive difference in printed prices. Advanced prerequisites still apply.",
|
||||
mouthful:
|
||||
"When an enemy successfully feeds on your amoeba, it takes one injury instead of being eaten. The attacker feeds, but no nutrients appear.",
|
||||
camouflage1:
|
||||
"When attacking, roll a die. On 4–6, ignore Defense, Escape and Alarm for this attack. Armor still works.",
|
||||
suction1:
|
||||
"You may take one nutrient for a meal from one horizontally or vertically adjacent space.",
|
||||
threat:
|
||||
"Your amoebas can only be attacked by amoebas with an equal or lower number.",
|
||||
flexible: "Pay one BP less when acquiring a gene.",
|
||||
healing1:
|
||||
"During phase 4, pay 3 BP to remove one injury from one of your amoebas. You may repeat this.",
|
||||
rebound:
|
||||
"When a move hits an obstacle, you may bounce to the space immediately beyond it, if that space exists.",
|
||||
bang: "When one of your amoebas dies, every other amoeba in its space takes one injury. Lethal injuries cause immediate chain reactions.",
|
||||
"short-life":
|
||||
"Your amoebas die at one injury, or two with Longevity, and cost 4 BP to divide. Mandatory while owned. Discarding this gene relieves only 4 sensitivity.",
|
||||
toxic:
|
||||
"Each excretion leaves one toxin. The next amoeba to enter the space takes all its toxins as injuries.",
|
||||
population:
|
||||
"In phase 4, you may surrender all your BP and receive no income. Instead, divide for free until you have as many amoebas as the score leader. Normal placement rules apply.",
|
||||
energy:
|
||||
"Each amoeba that drifts in phase 1 earns you one BP, even if its drift is blocked.",
|
||||
phd: "An advanced Intelligence gene: counts as two genes when calculating evolution points.",
|
||||
environmental:
|
||||
"Immediately after the environment changes in phase 2, privately see the next environment card.",
|
||||
camouflage2:
|
||||
"Your attacks ignore Defense, Escape and Alarm. Armor still works.",
|
||||
healing2:
|
||||
"During phase 4, pay 3 BP to remove one injury, or transfer an injury to another amoeba in the same space for free. The recipient dies immediately.",
|
||||
suction2:
|
||||
"You may take up to two nutrients for a meal from one adjacent space, including diagonally.",
|
||||
};
|
||||
for (const g of NEW_GENES) g.text = descriptions[g.id];
|
||||
export const INITIAL_NEW_GENES = ["social", "population"];
|
||||
|
||||
// randomIndex must use the engine's seeded RNG; never Math.random in a game.
|
||||
export function createNewGeneMarket(options, randomIndex) {
|
||||
if (options.newGenes !== undefined && typeof options.newGenes !== "boolean")
|
||||
throw new Error("New genes must be enabled or disabled.");
|
||||
if (!options.newGenes) return undefined;
|
||||
const remaining = NEW_GENES.map((g) => g.id).filter(
|
||||
(id) => !INITIAL_NEW_GENES.includes(id),
|
||||
);
|
||||
for (let i = remaining.length - 1; i > 0; i--) {
|
||||
const j = randomIndex(i + 1);
|
||||
if (!Number.isInteger(j) || j < 0 || j > i)
|
||||
throw new Error("Invalid shuffle index.");
|
||||
[remaining[i], remaining[j]] = [remaining[j], remaining[i]];
|
||||
}
|
||||
return {
|
||||
available: [...INITIAL_NEW_GENES],
|
||||
_deck: remaining,
|
||||
revealedRound: 0,
|
||||
};
|
||||
}
|
||||
export function revealNewGenesAfterPurchases(
|
||||
market,
|
||||
{ phase, round, player, leader, finishedBuying },
|
||||
) {
|
||||
if (
|
||||
!market ||
|
||||
phase !== 2 ||
|
||||
!finishedBuying ||
|
||||
player !== leader ||
|
||||
round <= market.revealedRound
|
||||
)
|
||||
return market;
|
||||
return {
|
||||
available: [...market.available, ...market._deck.slice(0, 2)],
|
||||
_deck: market._deck.slice(2),
|
||||
revealedRound: round,
|
||||
};
|
||||
}
|
||||
export function publicNewGeneMarket(market) {
|
||||
return market
|
||||
? { available: [...market.available], remaining: market._deck.length }
|
||||
: undefined;
|
||||
}
|
||||
100
engine/undo.js
Normal file
100
engine/undo.js
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
const clone = (value) => structuredClone(value);
|
||||
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
||||
const progress = (state) => state._moveDepth ?? state.history.length;
|
||||
|
||||
export const timeIncrements = (state) =>
|
||||
state._timeIncrements ?? state.players.map(() => 0);
|
||||
export const isLiveUpdate = (state) => state._liveUpdate === true;
|
||||
export const canUndo = (state, player) =>
|
||||
Boolean(
|
||||
!state.finished &&
|
||||
!state.players[player]?.dropped &&
|
||||
state._undo?.at(-1)?.player === player &&
|
||||
player !== undefined,
|
||||
);
|
||||
export function commitPending(state) {
|
||||
state.history.push(...(state._pendingMoves ?? []));
|
||||
delete state._pendingMoves;
|
||||
delete state._undo;
|
||||
// A shorter replacement turn must not consume the next player's increments.
|
||||
if (state._maxMoveDepth !== undefined) state._moveDepth = state._maxMoveDepth;
|
||||
state._liveUpdate = false;
|
||||
return state;
|
||||
}
|
||||
|
||||
export function recordMove(before, after, action, player, samePlayer) {
|
||||
const rearrangingCargo = ["carry", "return-food"].includes(action.type);
|
||||
after._moveDepth = progress(before) + Number(!rearrangingCargo);
|
||||
after._maxMoveDepth = Math.max(
|
||||
before._maxMoveDepth ?? progress(before),
|
||||
after._moveDepth,
|
||||
);
|
||||
after._timeIncrements = [...timeIncrements(before)];
|
||||
// Undo restores logical progress, but never the high-water mark or earned time.
|
||||
if (after._moveDepth > (before._maxMoveDepth ?? progress(before)))
|
||||
after._timeIncrements[player]++;
|
||||
after.history = [...before.history];
|
||||
after._pendingMoves = [
|
||||
...(before._pendingMoves ?? []),
|
||||
{ player, move: clone(action) },
|
||||
];
|
||||
|
||||
const reversible =
|
||||
samePlayer &&
|
||||
!after.finished &&
|
||||
before.round === after.round &&
|
||||
before.phase === after.phase &&
|
||||
before._counter === after._counter &&
|
||||
same(before._deck, after._deck) &&
|
||||
same(before._knowledge, after._knowledge) &&
|
||||
same(before.newGeneMarket, after.newGeneMarket);
|
||||
if (!reversible) {
|
||||
return commitPending(after);
|
||||
}
|
||||
const omitted = new Set([
|
||||
"_undo",
|
||||
"history",
|
||||
"log",
|
||||
"_pendingMoves",
|
||||
"_timeIncrements",
|
||||
"_maxMoveDepth",
|
||||
"_liveUpdate",
|
||||
]);
|
||||
const snapshot = clone(
|
||||
Object.fromEntries(
|
||||
Object.entries(before).filter(([key]) => !omitted.has(key)),
|
||||
),
|
||||
);
|
||||
snapshot._moveDepth = progress(before);
|
||||
const previous = before._undo?.at(-1)?.player === player ? before._undo : [];
|
||||
after._undo = [
|
||||
...previous.slice(-63),
|
||||
{
|
||||
player,
|
||||
action: clone(action),
|
||||
logLength: before.log.length,
|
||||
state: snapshot,
|
||||
},
|
||||
];
|
||||
after._liveUpdate = true;
|
||||
return after;
|
||||
}
|
||||
|
||||
export function undoMove(data, action, player) {
|
||||
if (!same(action, { type: "undo" }) || !canUndo(data, player))
|
||||
throw new Error("That action can no longer be undone.");
|
||||
const entry = data._undo.at(-1);
|
||||
const state = clone(entry.state);
|
||||
state.players.forEach((p, i) => {
|
||||
p.name = data.players[i].name;
|
||||
p.dropped = data.players[i].dropped;
|
||||
});
|
||||
state.history = clone(data.history);
|
||||
state.log = clone(data.log.slice(0, entry.logLength));
|
||||
state._pendingMoves = clone(data._pendingMoves.slice(0, -1));
|
||||
state._undo = clone(data._undo.slice(0, -1));
|
||||
state._timeIncrements = [...timeIncrements(data)];
|
||||
state._maxMoveDepth = data._maxMoveDepth;
|
||||
state._liveUpdate = true;
|
||||
return state;
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@boardgamers/primordial-soup",
|
||||
"version": "0.1.4",
|
||||
"version": "0.2.16",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist/engine.js",
|
||||
|
|
@ -11,7 +11,7 @@
|
|||
"build": "node scripts/build.mjs",
|
||||
"test": "node --test test/*.test.js",
|
||||
"dev": "node scripts/dev.mjs",
|
||||
"test:browser": "pnpm build && node test/analysis-chat-browser.mjs"
|
||||
"test:browser": "pnpm build && node test/analysis-chat-browser.mjs && node test/preferences-browser.mjs && node test/new-genes-browser.mjs && node test/turn-controls-browser.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@boardgamers/protocol": "0.5.0",
|
||||
|
|
|
|||
|
|
@ -2,7 +2,10 @@ import { readFile, mkdir, writeFile } from "node:fs/promises";
|
|||
import { homedir } from "node:os";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import assert from "node:assert/strict";
|
||||
import { NEW_GENES_OPTION } from "../engine/new-genes.js";
|
||||
import { chapterMetadata } from "../viewer/tutorials.js";
|
||||
import { COLOR_BLIND_PREFERENCE } from "../viewer/preferences.js";
|
||||
const token = (await readFile(`${homedir()}/.bgs`, "utf8")).trim();
|
||||
const base =
|
||||
"https://admin.boardgamers.space/api/admin/gameinfo/primordial-soup";
|
||||
|
|
@ -35,6 +38,10 @@ if (before.public || !meta.unlisted)
|
|||
);
|
||||
await mkdir(".local/release", { recursive: true });
|
||||
await writeFile(".local/release/before.json", JSON.stringify(before, null, 2));
|
||||
await writeFile(
|
||||
".local/release/meta-before.json",
|
||||
JSON.stringify(meta, null, 2),
|
||||
);
|
||||
execFileSync("pnpm", ["pack", "--pack-destination", ".local/release"], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
|
@ -66,8 +73,19 @@ const current = await api("/1");
|
|||
await api("/1", "PUT", {
|
||||
...current,
|
||||
public: false,
|
||||
preferences: [
|
||||
...(current.preferences ?? []).filter(
|
||||
(preference) => preference.name !== COLOR_BLIND_PREFERENCE.name,
|
||||
),
|
||||
COLOR_BLIND_PREFERENCE,
|
||||
],
|
||||
options: [
|
||||
...(current.options ?? []).filter((o) => o.name !== NEW_GENES_OPTION.name),
|
||||
NEW_GENES_OPTION,
|
||||
],
|
||||
engine: { ...uploaded.engine, entryPoint: "dist/engine.js" },
|
||||
viewer: {
|
||||
...current.viewer,
|
||||
url: viewer.url,
|
||||
topLevelVariable: "primordialSoup",
|
||||
fullScreen: true,
|
||||
|
|
@ -95,12 +113,29 @@ await api("/1", "PUT", {
|
|||
})),
|
||||
},
|
||||
});
|
||||
await api("/beta-users", "POST", { usernameOrEmail: "coyotte508" });
|
||||
await api("/meta", "PUT", { ...meta, players: [3, 4, 5, 6] });
|
||||
const published = await api("/1"),
|
||||
privacy = await api("/meta"),
|
||||
access = await api("/beta-users");
|
||||
if (published.public || !privacy.unlisted)
|
||||
throw new Error("Privacy check failed");
|
||||
assert.deepEqual(privacy.players, [3, 4, 5, 6]);
|
||||
assert.deepEqual(
|
||||
published.options.find((option) => option.name === NEW_GENES_OPTION.name),
|
||||
NEW_GENES_OPTION,
|
||||
);
|
||||
assert.equal(published.engine.package.version, pkg.version);
|
||||
assert.deepEqual(
|
||||
published.preferences.find(
|
||||
(preference) => preference.name === COLOR_BLIND_PREFERENCE.name,
|
||||
),
|
||||
COLOR_BLIND_PREFERENCE,
|
||||
);
|
||||
assert.equal(
|
||||
published.viewer.chat,
|
||||
current.viewer?.chat,
|
||||
"Publication changed the viewer chat setting",
|
||||
);
|
||||
await writeFile(
|
||||
".local/release/published.json",
|
||||
JSON.stringify(published, null, 2),
|
||||
|
|
@ -110,6 +145,9 @@ console.log(
|
|||
{
|
||||
private: !published.public,
|
||||
unlisted: privacy.unlisted,
|
||||
players: privacy.players,
|
||||
options: published.options,
|
||||
preferences: published.preferences,
|
||||
chapters: published.tutorial.chapters.length,
|
||||
access: access.map((x) => x.username),
|
||||
engine: published.engine.package,
|
||||
|
|
|
|||
218
test/automatic-phases.test.js
Normal file
218
test/automatic-phases.test.js
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import * as E from "../engine/index.js";
|
||||
import { prepared } from "../viewer/tutorials.js";
|
||||
|
||||
const act = (s, type, details = {}) => {
|
||||
const move = E.legalMoves(s).find(
|
||||
(m) =>
|
||||
m.type === type &&
|
||||
Object.entries(details).every(([key, value]) => m[key] === value),
|
||||
);
|
||||
assert.ok(move, `Missing ${type}`);
|
||||
return E.move(s, move, E.currentPlayer(s));
|
||||
};
|
||||
function beforeTurn(kind, { players = 4, bp = 0, genes = [] } = {}) {
|
||||
const s = prepared({ players, bp, genes, phase: kind === "genes" ? 2 : 3 });
|
||||
s.players.forEach((p, i) => {
|
||||
p.name = `Colony ${i + 1}`;
|
||||
p.score = players - i;
|
||||
});
|
||||
// Passing the preceding turn enters the turn under test through settle().
|
||||
s.tasks = [
|
||||
{ kind, p: players - 1 },
|
||||
{ kind, p: 0 },
|
||||
{ kind, p: 1 },
|
||||
];
|
||||
return s;
|
||||
}
|
||||
const own = (s, p, ...ids) =>
|
||||
(s.players[p].genes = ids.map((id) => ({ id, round: 1 })));
|
||||
function fillColony(s, p) {
|
||||
s.amoebas = s.amoebas.filter((a) => a.p !== p);
|
||||
for (let n = 1; n <= E.amoebaLimit(s.players.length); n++)
|
||||
s.amoebas.push({ id: `${p}-${n}`, p, n, cell: E.CELLS[n], hp: 0 });
|
||||
}
|
||||
|
||||
test("empty gene and division turns skip on entry without synthetic moves or time credits", () => {
|
||||
for (const players of [3, 4, 5, 6]) {
|
||||
for (const kind of ["genes", "division"]) {
|
||||
const initial = beforeTurn(kind, { players });
|
||||
const s = act(initial, "done");
|
||||
assert.equal(E.currentPlayer(s), 1);
|
||||
assert.equal(s.tasks[0].kind, kind);
|
||||
assert.deepEqual(s.history, [
|
||||
{ player: players - 1, move: { type: "done" } },
|
||||
]);
|
||||
assert.deepEqual(
|
||||
E.timeIncrements(s),
|
||||
s.players.map((_, p) => Number(p === players - 1)),
|
||||
);
|
||||
assert.equal(
|
||||
s.log.filter((line) => line.text.startsWith("Colony 1 finishes"))
|
||||
.length,
|
||||
1,
|
||||
);
|
||||
assert.equal(E.canUndo(s, players - 1), false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("gene skips account for supply, discounts, prerequisites and free exchanges", () => {
|
||||
const exhausted = beforeTurn("genes", { bp: 2 });
|
||||
own(exhausted, 1, "intelligence");
|
||||
own(exhausted, 2, "intelligence");
|
||||
assert.equal(E.currentPlayer(act(exhausted, "done")), 1);
|
||||
|
||||
const discounted = beforeTurn("genes", { bp: 1, genes: ["flexible"] });
|
||||
const entered = act(discounted, "done");
|
||||
assert.equal(E.currentPlayer(entered), 0);
|
||||
assert.ok(
|
||||
E.legalMoves(entered).some(
|
||||
(m) => m.type === "buy" && m.gene === "intelligence",
|
||||
),
|
||||
);
|
||||
|
||||
const exchange = act(beforeTurn("genes", { genes: ["adaptable"] }), "done");
|
||||
assert.equal(E.currentPlayer(exchange), 0);
|
||||
assert.ok(!E.legalMoves(exchange).some((m) => m.type === "buy"));
|
||||
assert.ok(E.legalMoves(exchange).some((m) => m.type === "exchange"));
|
||||
|
||||
const prerequisite = beforeTurn("genes", {
|
||||
bp: 3,
|
||||
genes: ["intelligence", "movement1", "spores"],
|
||||
});
|
||||
prerequisite.players[0].genes[0].round = prerequisite.round;
|
||||
prerequisite.newGeneMarket = {
|
||||
available: ["phd"],
|
||||
_deck: [],
|
||||
revealedRound: prerequisite.round,
|
||||
};
|
||||
assert.equal(E.currentPlayer(act(prerequisite, "done")), 1);
|
||||
prerequisite.players[0].genes[0].round--;
|
||||
const upgrade = act(prerequisite, "done");
|
||||
assert.equal(E.currentPlayer(upgrade), 0);
|
||||
assert.ok(E.legalMoves(upgrade).some((m) => m.gene === "phd"));
|
||||
});
|
||||
|
||||
test("a skipped leader reveals new genes after passing, before the next colony's choices", () => {
|
||||
const initial = beforeTurn("genes");
|
||||
initial.options.newGenes = true;
|
||||
initial.newGeneMarket = {
|
||||
available: ["social", "population"],
|
||||
_deck: ["glutton", "alarm", "energy"],
|
||||
revealedRound: 0,
|
||||
};
|
||||
const s = act(initial, "done");
|
||||
assert.equal(E.currentPlayer(s), 1);
|
||||
assert.deepEqual(s.newGeneMarket.available, [
|
||||
"social",
|
||||
"population",
|
||||
"glutton",
|
||||
"alarm",
|
||||
]);
|
||||
assert.deepEqual(s.newGeneMarket._deck, ["energy"]);
|
||||
assert.match(s.log.at(-2).text, /^Colony 1 finishes buying genes/);
|
||||
assert.match(s.log.at(-1).text, /^New genes available:/);
|
||||
assert.ok(
|
||||
E.legalMoves(s).some((m) => m.type === "buy" && m.gene === "glutton"),
|
||||
);
|
||||
assert.equal(E.canUndo(s, 3), false);
|
||||
assert.deepEqual(act(s, "done").newGeneMarket._deck, ["energy"]);
|
||||
});
|
||||
|
||||
test("division does not skip healing, injury transfers or free extinction recovery", () => {
|
||||
for (const [genes, bp, expected] of [
|
||||
[["healing1"], 3, "heal"],
|
||||
[["healing2"], 0, "transfer-injury"],
|
||||
[[], 0, "divide"],
|
||||
]) {
|
||||
const initial = beforeTurn("division", { genes, bp });
|
||||
if (genes.length) {
|
||||
E.amoeba(initial, "0-1").hp = 1;
|
||||
E.amoeba(initial, "1-1").cell = E.amoeba(initial, "0-1").cell;
|
||||
} else initial.amoebas = initial.amoebas.filter((a) => a.p !== 0);
|
||||
const s = act(initial, "done");
|
||||
assert.equal(E.currentPlayer(s), 0);
|
||||
assert.ok(E.legalMoves(s).some((m) => m.type === expected));
|
||||
}
|
||||
const full = beforeTurn("division", { bp: 99 });
|
||||
fillColony(full, 0);
|
||||
assert.equal(E.currentPlayer(act(full, "done")), 1);
|
||||
});
|
||||
|
||||
test("spending the final BP or taking the final action still keeps Done and Undo", () => {
|
||||
for (const [kind, bp, genes, type, details] of [
|
||||
["genes", 2, [], "buy", { gene: "intelligence" }],
|
||||
[
|
||||
"genes",
|
||||
0,
|
||||
["adaptable"],
|
||||
"exchange",
|
||||
{ gene: "intelligence", exchange: "adaptable" },
|
||||
],
|
||||
["division", 6, [], "divide", {}],
|
||||
["division", 3, ["healing1"], "heal", {}],
|
||||
["division", 0, ["healing2"], "transfer-injury", { target: "1-1" }],
|
||||
]) {
|
||||
const initial = beforeTurn(kind, { bp, genes });
|
||||
if (type === "heal" || type === "transfer-injury") {
|
||||
E.amoeba(initial, "0-1").hp = 1;
|
||||
E.amoeba(initial, "1-1").cell = E.amoeba(initial, "0-1").cell;
|
||||
}
|
||||
const entered = act(initial, "done");
|
||||
let s = act(entered, type, details);
|
||||
assert.equal(E.currentPlayer(s), 0);
|
||||
assert.deepEqual(E.legalMoves(s), [{ type: "done" }]);
|
||||
assert.equal(E.canUndo(s, 0), true);
|
||||
s = E.move(s, { type: "undo" }, 0);
|
||||
assert.deepEqual(s.players, entered.players);
|
||||
assert.deepEqual(s.amoebas, entered.amoebas);
|
||||
assert.deepEqual(s.tasks, entered.tasks);
|
||||
assert.deepEqual(s.history, entered.history);
|
||||
assert.deepEqual(s.log, entered.log);
|
||||
s = act(act(s, type, details), "done");
|
||||
assert.equal(E.currentPlayer(s), 1);
|
||||
assert.equal(E.canUndo(s, 0), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("Population Explosion's income choice remains undoable even when division is empty", () => {
|
||||
for (const type of ["take-income", "population-explosion"]) {
|
||||
const initial = beforeTurn("division", { genes: ["population"] });
|
||||
fillColony(initial, 0);
|
||||
initial.tasks.splice(1, 0, { kind: "income", p: 0 });
|
||||
const entered = act(initial, "done");
|
||||
assert.equal(entered.tasks[0].kind, "population");
|
||||
const chosen = act(entered, type);
|
||||
assert.equal(chosen.tasks[0].kind, "division");
|
||||
assert.deepEqual(E.legalMoves(chosen), [{ type: "done" }]);
|
||||
assert.equal(E.canUndo(chosen, 0), true);
|
||||
const undone = E.move(chosen, { type: "undo" }, 0);
|
||||
assert.deepEqual(undone.players, entered.players);
|
||||
assert.deepEqual(undone.tasks, entered.tasks);
|
||||
}
|
||||
});
|
||||
|
||||
test("automatic income and empty division chain through to the next round", () => {
|
||||
const initial = beforeTurn("genes");
|
||||
initial.players.forEach((p, i) => {
|
||||
p.bp = 0;
|
||||
fillColony(initial, i);
|
||||
});
|
||||
initial.tasks = [
|
||||
{ kind: "genes", p: 0 },
|
||||
...[1, 2, 3].map((p) => ({ kind: "genes", p })),
|
||||
];
|
||||
const s = act(initial, "done");
|
||||
assert.equal(s.round, initial.round + 1);
|
||||
assert.equal(s.phase, 0);
|
||||
assert.equal(s.tasks[0].kind, "movement");
|
||||
assert.ok(s.players.every((p) => p.bp === 10));
|
||||
assert.deepEqual(s.history, [{ player: 0, move: { type: "done" } }]);
|
||||
assert.deepEqual(E.timeIncrements(s), [1, 0, 0, 0]);
|
||||
assert.equal(
|
||||
s.log.filter((l) => l.text.includes("finishes cell division")).length,
|
||||
4,
|
||||
);
|
||||
});
|
||||
|
|
@ -98,10 +98,20 @@ test("swimming pays once; Movement I rolls two, Movement II chooses, Speed has n
|
|||
s = act(s, "swim");
|
||||
assert.equal(s.players[0].bp, 11);
|
||||
assert.equal(s.tasks[0].dice.length, 2);
|
||||
assert.equal(
|
||||
s.log.at(-1).text,
|
||||
`You #1 rolls ${s.tasks[0].dice.join(" and ")}.`,
|
||||
);
|
||||
s = prepared({ genes: ["movement2", "speed"] });
|
||||
s = act(s, "swim");
|
||||
assert.equal(E.legalMoves(s).length, 5);
|
||||
s = act(s, "direction", { direction: 1 });
|
||||
assert.ok(
|
||||
s.log.some(
|
||||
(line) => line.text === "You #1 chooses north with Movement II.",
|
||||
),
|
||||
);
|
||||
assert.ok(!s.log.some((line) => /rolls/.test(line.text)));
|
||||
assert.equal(s.tasks[0].kind, "speed");
|
||||
s = act(s, "swim-again");
|
||||
assert.equal(s.players[0].bp, 11);
|
||||
|
|
@ -396,13 +406,19 @@ test("replay restores a playable analysis boundary without running dropped-playe
|
|||
const original = structuredClone(state);
|
||||
for (const to of [0, 5, 20, state.history.length]) {
|
||||
const copy = E.replay(state, { to });
|
||||
assert.deepEqual(copy, snapshots[to]);
|
||||
const view = E.stripSecret(copy);
|
||||
const expected = E.stripSecret(snapshots[to]);
|
||||
delete expected.undoPlayer;
|
||||
assert.deepEqual(view, expected);
|
||||
assert.deepEqual(copy.history, state.history.slice(0, to));
|
||||
assert.equal(E.logLength(copy), to);
|
||||
if (!copy.finished)
|
||||
assert.ok(
|
||||
E.move(copy, E.legalMoves(copy)[0], E.currentPlayer(copy)).history
|
||||
.length > to,
|
||||
if (!copy.finished) {
|
||||
const next = E.move(copy, E.legalMoves(copy)[0], E.currentPlayer(copy));
|
||||
assert.equal(
|
||||
next.history.length + (next._pendingMoves?.length ?? 0),
|
||||
to + 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(state, original);
|
||||
});
|
||||
|
|
|
|||
185
test/five-six.test.js
Normal file
185
test/five-six.test.js
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import * as E from "../engine/index.js";
|
||||
import { scoringLegend } from "../viewer/scoring-legend.js";
|
||||
import { food } from "../viewer/rich-text.js";
|
||||
const act = (s, type, details = {}) => {
|
||||
const action = E.legalMoves(s).find(
|
||||
(m) =>
|
||||
m.type === type && Object.entries(details).every(([k, v]) => m[k] === v),
|
||||
);
|
||||
assert.ok(action, `Missing ${type}`);
|
||||
return E.move(s, action, E.currentPlayer(s));
|
||||
};
|
||||
function fixture(players, genes = [], kind = "feeding") {
|
||||
const s = E.init(players, [], {}, "six-player-rules");
|
||||
s.round = 2;
|
||||
s.phase = kind === "genes" ? 2 : kind === "division" ? 3 : 0;
|
||||
s.players.forEach((p, i) => {
|
||||
p.score = players - i;
|
||||
p.bp = 20;
|
||||
});
|
||||
s.players[0].genes = genes.map((id) => ({ id, round: 1 }));
|
||||
s.amoebas = s.players.map((_, p) => ({
|
||||
id: `${p}-1`,
|
||||
p,
|
||||
n: 1,
|
||||
cell: E.CELLS[p],
|
||||
hp: 0,
|
||||
}));
|
||||
s.tasks = [{ kind, ...(kind === "feeding" ? { a: "0-1" } : { p: 0 }) }];
|
||||
return s;
|
||||
}
|
||||
function feedAt(s, values) {
|
||||
const cell = E.amoeba(s, "0-1").cell;
|
||||
values.forEach((n, p) => {
|
||||
s.supply[p] += s.food[cell][p] - n;
|
||||
});
|
||||
s.food[cell] = values;
|
||||
}
|
||||
function assertConserved(s) {
|
||||
for (let p = 0; p < s.players.length; p++) {
|
||||
const carried = s.tasks
|
||||
.filter((t) => t.kind === "carry")
|
||||
.reduce((n, t) => n + t.cargo.filter((c) => c === p).length, 0);
|
||||
assert.equal(
|
||||
s.food.reduce((n, row) => n + row[p], s.supply[p]) + carried,
|
||||
55,
|
||||
);
|
||||
assert.ok(s.players[p].bp >= 0);
|
||||
assert.ok(E.colony(s, p).every((a) => a.n <= 6));
|
||||
assert.ok(E.colony(s, p).length <= 6);
|
||||
}
|
||||
}
|
||||
test("five/six-player setup offers six scores, six amoebas, six distinct colours and normal initial wounds", () => {
|
||||
for (const n of [5, 6]) {
|
||||
let s = E.init(n, [], {}, "setup-six");
|
||||
assert.equal(new Set(s.players.map((p) => p.color)).size, n);
|
||||
assert.deepEqual(
|
||||
E.legalMoves(s).map((m) => m.score),
|
||||
[1, 2, 3, 4, 5, 6],
|
||||
);
|
||||
while (s.phase === "setup-score") s = act(s, "score");
|
||||
assert.deepEqual(
|
||||
[...new Set(E.legalMoves(s).map((m) => m.n))],
|
||||
[1, 2, 3, 4, 5, 6],
|
||||
);
|
||||
while (s.round === 0) s = act(s, "place");
|
||||
for (let p = 0; p < n; p++)
|
||||
assert.deepEqual(
|
||||
E.colony(s, p).map((a) => a.hp),
|
||||
[1, 0],
|
||||
);
|
||||
assertConserved(s);
|
||||
}
|
||||
});
|
||||
test("the 39-card pool applies replacement sensitivity and Frugality price in purchases and defects", () => {
|
||||
assert.deepEqual(
|
||||
[3, 4, 5, 6].map((n) =>
|
||||
E.GENES.reduce((sum, g) => sum + g.copies[n - 3], 0),
|
||||
),
|
||||
[20, 30, 39, 39],
|
||||
);
|
||||
for (const n of [5, 6]) {
|
||||
let s = fixture(n, [], "genes");
|
||||
s.players[0].bp = 5;
|
||||
s = act(s, "buy", { gene: "frugality" });
|
||||
assert.equal(s.players[0].bp, 0);
|
||||
s = fixture(n, ["streamline", "struggle"], "genes");
|
||||
assert.equal(E.mutation(s, 0), 10);
|
||||
s.phase = 1;
|
||||
s.tasks = [{ kind: "defect", p: 0, debt: 6 }];
|
||||
s = act(s, "discard", { gene: "streamline" });
|
||||
assert.equal(s.tasks[0].debt, 1);
|
||||
s = act(s, "pay-defect");
|
||||
assert.equal(s.players[0].bp, 19);
|
||||
s = fixture(n, [], "genes");
|
||||
s.players[1].genes = [{ id: "streamline", round: 1 }];
|
||||
s.players[2].genes = [{ id: "streamline", round: 1 }];
|
||||
assert.ok(!E.legalMoves(s).some((m) => m.gene === "streamline"));
|
||||
}
|
||||
assert.equal(E.geneFor("frugality", 4).cost, 6);
|
||||
assert.equal(E.geneFor("struggle", 4).mutation, 4);
|
||||
});
|
||||
test("unmodified amoebas eat four distinct foreign colours, choosing the omitted colour with six players", () => {
|
||||
for (const n of [5, 6]) {
|
||||
let s = fixture(n);
|
||||
const meals = E.menus(s, E.amoeba(s, "0-1"));
|
||||
assert.equal(meals.length, n === 5 ? 1 : 5);
|
||||
for (const { food } of meals) {
|
||||
assert.equal(food[0], 0);
|
||||
assert.equal(food.filter((x) => x === 1).length, 4);
|
||||
}
|
||||
const cell = E.amoeba(s, "0-1").cell;
|
||||
s = act(s, "eat");
|
||||
assert.equal(s.food[cell][0], 4);
|
||||
assertConserved(s);
|
||||
s = fixture(n);
|
||||
feedAt(s, [0, 4, 4, ...Array(n - 3).fill(0)]);
|
||||
assert.equal(E.menus(s, E.amoeba(s, "0-1")).length, 0);
|
||||
s = act(s, "starve");
|
||||
assert.equal(E.amoeba(s, "0-1").hp, 1);
|
||||
}
|
||||
});
|
||||
test("five/six-player feeding adaptations combine without accepting the old three-cube diet", () => {
|
||||
for (const n of [5, 6]) {
|
||||
let s = fixture(n, ["substitution"]);
|
||||
feedAt(s, [0, 3, 1, 1, ...Array(n - 4).fill(0)]);
|
||||
assert.ok(E.menus(s, E.amoeba(s, "0-1")).some((m) => m.food[1] === 3));
|
||||
assertConserved(act(s, "eat"));
|
||||
s = fixture(n, ["frugality"]);
|
||||
feedAt(s, [0, 1, 1, 1, ...Array(n - 4).fill(0)]);
|
||||
assert.ok(E.menus(s, E.amoeba(s, "0-1")).length);
|
||||
s = fixture(n, ["frugality", "substitution", "parasitism"]);
|
||||
E.amoeba(s, "1-1").cell = E.amoeba(s, "0-1").cell;
|
||||
feedAt(s, [0, 0, 3, ...Array(n - 3).fill(0)]);
|
||||
assert.ok(
|
||||
E.menus(s, E.amoeba(s, "0-1")).some(
|
||||
(m) => m.host === 1 && m.food[2] === 3,
|
||||
),
|
||||
);
|
||||
const after = act(s, "eat");
|
||||
assert.equal(after.players[1].bp, 19);
|
||||
assertConserved(after);
|
||||
s.players[1].bp = 0;
|
||||
assert.equal(E.menus(s, E.amoeba(s, "0-1")).length, 0);
|
||||
}
|
||||
});
|
||||
test("five/six-player income, population limit and scoring use the expansion rules", () => {
|
||||
for (const n of [5, 6]) {
|
||||
let s = fixture(n, [], "genes");
|
||||
s = act(s, "done");
|
||||
assert.equal(s.players[0].bp, 31);
|
||||
s = fixture(n, [], "division");
|
||||
s.amoebas = s.amoebas.filter((a) => a.p !== 0);
|
||||
for (let i = 1; i <= 6; i++)
|
||||
s.amoebas.push({ id: `0-${i}`, p: 0, n: i, cell: E.CELLS[i + 6], hp: 0 });
|
||||
assert.ok(!E.legalMoves(s).some((m) => m.type === "divide"));
|
||||
assert.equal(E.evolution(s, 0), 5);
|
||||
assert.deepEqual(
|
||||
Array.from({ length: 7 }, (_, i) => E.populationPoints(i, n)),
|
||||
[0, 0, 1, 2, 3, 4, 5],
|
||||
);
|
||||
assert.ok(!scoringLegend(6, 2, "burgundy", false, n).includes("undefined"));
|
||||
}
|
||||
assert.ok(food(4).includes("black"));
|
||||
assert.ok(food(5).includes("burgundy"));
|
||||
});
|
||||
test("complete five/six-player games conserve resources and replay after save/reload", () => {
|
||||
for (const n of [5, 6])
|
||||
for (let seed = 0; seed < 3; seed++) {
|
||||
let s = E.init(n, [], {}, `complete-six-${seed}`),
|
||||
steps = 0;
|
||||
while (!E.ended(s) && steps++ < 2000) {
|
||||
s = E.moveAI(s, E.currentPlayer(s));
|
||||
if (steps % 17 === 0) s = JSON.parse(JSON.stringify(s));
|
||||
assertConserved(s);
|
||||
}
|
||||
assert.ok(E.ended(s));
|
||||
assert.ok(s.round <= 10);
|
||||
const replay = E.replay(s);
|
||||
assert.deepEqual(E.scores(replay), E.scores(s));
|
||||
assert.deepEqual(replay.amoebas, s.amoebas);
|
||||
assert.equal(replay.winner, s.winner);
|
||||
}
|
||||
});
|
||||
103
test/journal.test.js
Normal file
103
test/journal.test.js
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { journalHtml, journalEntryHtml } from "../viewer/journal.js";
|
||||
|
||||
const players = [
|
||||
{ name: "Maya", color: "red" },
|
||||
{ name: "Maya_2", color: "blue" },
|
||||
];
|
||||
|
||||
test("swimming rolls show each die and its direction without treating combat rolls as movement", () => {
|
||||
const directions = ["West", "North", "East", "South", "Stay", "Choose"];
|
||||
for (let value = 1; value <= 6; value++) {
|
||||
const html = journalEntryHtml(
|
||||
{ phase: 0, text: `Maya #1 rolls ${value}.` },
|
||||
players,
|
||||
);
|
||||
assert.match(
|
||||
html,
|
||||
new RegExp(`aria-label="Rolled ${value}: ${directions[value - 1]}"`),
|
||||
);
|
||||
assert.match(html, /aria-label="Maya, amoeba 1"/);
|
||||
}
|
||||
const html = journalEntryHtml(
|
||||
{ phase: 0, text: "Maya #2 rolls 3 and 6." },
|
||||
players,
|
||||
);
|
||||
assert.equal((html.match(/class="journal-die"/g) ?? []).length, 2);
|
||||
assert.match(html, /Rolled 3: East/);
|
||||
assert.match(html, /Rolled 6: Choose/);
|
||||
for (const text of [
|
||||
"Maya rolls 2; Maya_2 rolls 4.",
|
||||
"Maya #1 rolls 4 for Camouflage I: defenses are bypassed.",
|
||||
]) {
|
||||
assert.doesNotMatch(
|
||||
journalEntryHtml({ phase: 0, text }, players),
|
||||
/journal-die/,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("journal preserves amoeba identities, coordinates and resource amounts", () => {
|
||||
const html = journalHtml(
|
||||
[
|
||||
{ round: 1, phase: 0, text: "Maya #1 moves to D2." },
|
||||
{
|
||||
round: 1,
|
||||
phase: 0,
|
||||
text: "Maya_2 #2 excretes two blue nutrients at D2.",
|
||||
},
|
||||
],
|
||||
players,
|
||||
);
|
||||
assert.match(html, /aria-label="Maya, amoeba 1"/);
|
||||
assert.match(html, /aria-label="Maya_2, amoeba 2"/);
|
||||
assert.match(html, /title="Space D2"/);
|
||||
assert.match(html, /aria-label="2 blue nutrients"/);
|
||||
assert.doesNotMatch(html, /Maya #1|Maya_2 #2/);
|
||||
});
|
||||
|
||||
test("journal uses one round divider across phase changes and retains historical environments", () => {
|
||||
const html = journalHtml(
|
||||
[
|
||||
{ round: 1, phase: 0, text: "Maya #1 feeds." },
|
||||
{ round: 1, phase: 1, text: "The current is west. Ozone layer: 12." },
|
||||
{ round: 1, phase: 2, text: "Maya evolves Movement II for 5 BP." },
|
||||
{ round: 2, phase: 1, text: "The current is still. Ozone layer: 14." },
|
||||
],
|
||||
players,
|
||||
);
|
||||
assert.equal((html.match(/>Round 1</g) ?? []).length, 1);
|
||||
assert.equal((html.match(/>Round 2</g) ?? []).length, 1);
|
||||
assert.match(html, /aria-label="Current west\. Ozone layer 12\."/);
|
||||
assert.match(html, /aria-label="Current still\. Ozone layer 14\."/);
|
||||
assert.match(html, />Movement II<\/span>/);
|
||||
assert.match(html, /aria-label="5 biological points"/);
|
||||
});
|
||||
|
||||
test("player names are treated as literal text and safely escaped in journal markup", () => {
|
||||
const name = 'Ada.+<img src=x onerror="oops">';
|
||||
const html = journalHtml(
|
||||
[
|
||||
{
|
||||
round: 0,
|
||||
phase: "setup-first",
|
||||
text: `${name} places amoeba #2 at C2.`,
|
||||
},
|
||||
{
|
||||
round: 1,
|
||||
phase: 0,
|
||||
text: `${name} #2 feeds. <script>alert(1)</script>`,
|
||||
},
|
||||
{ round: 1, phase: 0, text: "NotMaya #1 feeds." },
|
||||
],
|
||||
[...players, { name, color: "green" }],
|
||||
);
|
||||
assert.match(
|
||||
html,
|
||||
/Ada\.\+<img src=x onerror="oops">, amoeba 2/,
|
||||
);
|
||||
assert.doesNotMatch(html, /<img|<script/);
|
||||
assert.match(html, /<script>/);
|
||||
assert.match(html, /NotMaya #1 feeds/);
|
||||
});
|
||||
602
test/new-gene-effects.test.js
Normal file
602
test/new-gene-effects.test.js
Normal file
|
|
@ -0,0 +1,602 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import * as E from "../engine/index.js";
|
||||
import { NEW_GENES } from "../engine/new-genes.js";
|
||||
import { prepared } from "../viewer/tutorials.js";
|
||||
import { geneSummary } from "../viewer/gene-summary.js";
|
||||
import { moveLabel } from "../viewer/ui.js";
|
||||
const own = (s, p, ...ids) =>
|
||||
(s.players[p].genes = ids.map((id) => ({ id, round: 1 })));
|
||||
const a = (p, n, cell = 6, hp = 0) => ({ id: `${p}-${n}`, p, n, cell, hp });
|
||||
function fixture({
|
||||
genes = [],
|
||||
task = { kind: "movement", a: "0-1" },
|
||||
phase = 0,
|
||||
...rest
|
||||
} = {}) {
|
||||
const s = prepared({ genes, task, phase, ...rest });
|
||||
s.options = { newGenes: true };
|
||||
s.newGeneMarket = {
|
||||
available: NEW_GENES.map((g) => g.id),
|
||||
_deck: [],
|
||||
revealedRound: 0,
|
||||
};
|
||||
s.toxins = Array(25).fill(0);
|
||||
s.alarmPlayers = [];
|
||||
s._knowledge = {};
|
||||
// A sentinel decision keeps assertions inside the phase being tested.
|
||||
s.tasks.push({ kind: "genes", p: 3 });
|
||||
return s;
|
||||
}
|
||||
function act(s, type, props = {}) {
|
||||
const m = E.legalMoves(s).find(
|
||||
(m) =>
|
||||
m.type === type && Object.entries(props).every(([k, v]) => m[k] === v),
|
||||
);
|
||||
assert.ok(
|
||||
m,
|
||||
`${type} ${JSON.stringify(props)} missing at ${JSON.stringify(s.tasks[0])}`,
|
||||
);
|
||||
return E.move(s, m, E.currentPlayer(s));
|
||||
}
|
||||
const opts = (s) => E.legalMoves(s).map((m) => m.type);
|
||||
function clearFood(s, cell) {
|
||||
s.food[cell].forEach((n, p) => (s.supply[p] += n));
|
||||
s.food[cell].fill(0);
|
||||
}
|
||||
function invariant(s) {
|
||||
for (let p = 0; p < s.players.length; p++) {
|
||||
const carried = s.tasks
|
||||
.filter((t) => t.kind === "carry")
|
||||
.reduce((n, t) => n + t.cargo.filter((c) => c === p).length, 0);
|
||||
assert.equal(s.food.reduce((n, v) => n + v[p], s.supply[p]) + carried, 55);
|
||||
assert.ok(s.food.every((v) => v[p] >= 0));
|
||||
assert.ok(s.players[p].bp >= 0);
|
||||
const own = E.colony(s, p);
|
||||
assert.ok(own.length <= E.amoebaLimit(s.players.length));
|
||||
assert.equal(new Set(own.map((a) => a.n)).size, own.length);
|
||||
assert.ok(own.every((a) => E.CELLS.includes(a.cell) && a.hp >= 0));
|
||||
}
|
||||
for (const g of E.ALL_GENES) {
|
||||
const count = s.players.reduce(
|
||||
(n, p) => n + p.genes.filter((x) => x.id === g.id).length,
|
||||
0,
|
||||
);
|
||||
assert.ok(count <= E.copiesOf(g, s.players.length), `${g.id} exhausted`);
|
||||
}
|
||||
assert.ok(s.toxins.every((n) => Number.isInteger(n) && n >= 0));
|
||||
}
|
||||
test("all 26 effects have descriptions; the option works independently with 3–6 players", () => {
|
||||
assert.equal(NEW_GENES.length, 26);
|
||||
for (const g of NEW_GENES) {
|
||||
assert.ok(g.implemented);
|
||||
assert.ok(g.text);
|
||||
assert.ok(geneSummary(g.id, 4));
|
||||
assert.equal(E.geneFor(g.id, 6), g);
|
||||
}
|
||||
for (const n of [3, 4, 5, 6]) {
|
||||
const s = E.init(n, [], { newGenes: true }, "option");
|
||||
assert.equal(
|
||||
E.genesInGame(s).filter((g) => NEW_GENES.includes(g)).length,
|
||||
2,
|
||||
);
|
||||
assert.equal(s.newGeneMarket._deck.length, 24);
|
||||
assert.deepEqual(s, E.init(n, [], { newGenes: true }, "option"));
|
||||
assert.ok(!E.init(n).newGeneMarket);
|
||||
}
|
||||
assert.throws(() => E.init(3, [], { newGenes: "false" }));
|
||||
});
|
||||
test("the market reveals after the actual leader finishes, never before or twice", () => {
|
||||
let s = fixture({ phase: 2, task: { kind: "genes", p: 0 } });
|
||||
s.newGeneMarket = {
|
||||
available: ["social", "population"],
|
||||
_deck: ["energy", "glutton", "alarm"],
|
||||
revealedRound: 0,
|
||||
};
|
||||
s.tasks = [
|
||||
{ kind: "genes", p: 0 },
|
||||
{ kind: "genes", p: 1 },
|
||||
{ kind: "genes", p: 2 },
|
||||
];
|
||||
assert.ok(!E.legalMoves(s).some((m) => m.gene === "energy"));
|
||||
s = act(s, "done");
|
||||
assert.match(s.log.at(-2).text, /finishes buying genes/);
|
||||
assert.match(s.log.at(-1).text, /^New genes available:/);
|
||||
assert.deepEqual(s.newGeneMarket.available, [
|
||||
"social",
|
||||
"population",
|
||||
"energy",
|
||||
"glutton",
|
||||
]);
|
||||
assert.ok(E.legalMoves(s).some((m) => m.gene === "energy"));
|
||||
s = act(s, "done");
|
||||
assert.equal(s.newGeneMarket._deck.length, 1);
|
||||
assert.equal(E.stripSecret(s).newGeneMarket.remaining, 1);
|
||||
assert.ok(!JSON.stringify(E.stripSecret(s)).includes('"_deck"'));
|
||||
});
|
||||
test("Glutton forces an extra foreign nutrient, including combined reduced and substituted meals", () => {
|
||||
for (const players of [3, 4, 5, 6]) {
|
||||
const s = fixture({ players, genes: ["glutton"] });
|
||||
const meals = E.menus(s, s.amoebas[0]);
|
||||
assert.ok(meals.length);
|
||||
assert.ok(
|
||||
meals.every(
|
||||
(m) =>
|
||||
m.food[0] === 0 &&
|
||||
m.food.reduce((a, b) => a + b, 0) === (players >= 5 ? 5 : 4),
|
||||
),
|
||||
);
|
||||
own(s, 0, "glutton", "frugality", "substitution", "parasitism");
|
||||
s.amoebas.push(a(1, 6));
|
||||
assert.ok(
|
||||
E.menus(s, s.amoebas[0]).some(
|
||||
(m) =>
|
||||
m.host === 1 &&
|
||||
m.food.reduce((a, b) => a + b, 0) === (players >= 5 ? 3 : 2),
|
||||
),
|
||||
);
|
||||
assert.equal(E.mutation(s, 0), -2 + 5 + 4 + 5);
|
||||
}
|
||||
});
|
||||
test("Suction borrows from one legal space, conserves food, and enables otherwise impossible meals", () => {
|
||||
let s = fixture({ genes: ["suction1"], task: { kind: "feeding", a: "0-1" } });
|
||||
s.supply[1] += s.food[6][1];
|
||||
s.food[6][1] = 0;
|
||||
let m = E.legalMoves(s).find((m) => m.type === "eat" && m.source === 7);
|
||||
assert.ok(m);
|
||||
assert.equal(
|
||||
m.borrowed.reduce((a, b) => a + b, 0),
|
||||
1,
|
||||
);
|
||||
s = E.move(s, m, 0);
|
||||
invariant(s);
|
||||
assert.equal(s.food[7][1], 1);
|
||||
s = fixture({ genes: ["suction2"], task: { kind: "feeding", a: "0-1" } });
|
||||
for (const p of [1, 2]) {
|
||||
s.supply[p] += s.food[6][p];
|
||||
s.food[6][p] = 0;
|
||||
}
|
||||
m = E.legalMoves(s).find((m) => m.source === 2);
|
||||
assert.ok(m);
|
||||
assert.equal(
|
||||
m.borrowed.reduce((a, b) => a + b, 0),
|
||||
2,
|
||||
);
|
||||
assert.ok(!E.legalMoves(s).some((m) => m.source === 18));
|
||||
s = E.move(s, m, 0);
|
||||
invariant(s);
|
||||
const bad = fixture({ genes: ["suction2"] });
|
||||
clearFood(bad, 6);
|
||||
assert.equal(E.menus(bad, bad.amoebas[0]).length, 0); // Cannot borrow all three.
|
||||
});
|
||||
test("Cleanliness and Toxic Excretions share the chosen space; the next entrant absorbs all toxins", () => {
|
||||
let s = fixture({
|
||||
genes: ["cleanliness", "toxic"],
|
||||
task: { kind: "feeding", a: "0-1" },
|
||||
});
|
||||
s.toxins[7] = 2;
|
||||
s = act(s, "eat");
|
||||
assert.equal(s.tasks[0].kind, "excrete");
|
||||
assert.ok(!E.legalMoves(s).some((m) => m.cell === 18));
|
||||
s = act(s, "excrete", { cell: 7 });
|
||||
assert.equal(s.food[7][0], 4);
|
||||
assert.equal(s.toxins[7], 3);
|
||||
invariant(s);
|
||||
s.tasks = [
|
||||
{ kind: "movement", a: "0-1" },
|
||||
{ kind: "genes", p: 3 },
|
||||
];
|
||||
s = act(s, "drift");
|
||||
assert.equal(s.amoebas[0].hp, 3);
|
||||
assert.equal(s.toxins[7], 0);
|
||||
assert.ok(s.amoebas[0]); // Toxin damage waits for the normal survival phase.
|
||||
});
|
||||
test("Fast Food completes feeding once, then movement and Speed, without a second meal", () => {
|
||||
let s = fixture({
|
||||
genes: ["fast-food", "movement2", "speed", "energy", "cleanliness"],
|
||||
});
|
||||
s = act(s, "eat-first");
|
||||
s = act(s, "eat");
|
||||
s = act(s, "excrete", { cell: 6 });
|
||||
assert.equal(s.tasks[0].kind, "movement");
|
||||
assert.ok(!opts(s).includes("eat-first"));
|
||||
const before = s.players[0].bp;
|
||||
s = act(s, "drift");
|
||||
assert.equal(s.players[0].bp, before + 1);
|
||||
assert.equal(s.tasks[0].kind, "genes");
|
||||
s = fixture({ genes: ["fast-food", "movement2", "speed"] });
|
||||
s = act(s, "eat-first");
|
||||
s = act(s, "eat");
|
||||
s = act(s, "swim");
|
||||
s = act(s, "direction", { direction: 2 });
|
||||
s = act(s, "swim-again");
|
||||
s = act(s, "direction", { direction: 3 });
|
||||
assert.equal(s.tasks[0].kind, "genes");
|
||||
s = fixture({
|
||||
genes: ["fast-food", "struggle"],
|
||||
amoebas: [a(0, 1), a(1, 1)],
|
||||
});
|
||||
clearFood(s, 6);
|
||||
s = act(s, "eat-first");
|
||||
s = act(s, "attack", { victim: "1-1" });
|
||||
assert.equal(s.tasks[0].kind, "movement");
|
||||
assert.ok(s.tasks[0].fed);
|
||||
});
|
||||
test("Rebound crosses only a single obstacle; Energy Conservation also rewards blocked drift", () => {
|
||||
let s = fixture({ genes: ["rebound", "energy"], amoebas: [a(0, 1, 11)] });
|
||||
assert.deepEqual(
|
||||
E.legalMoves(s)
|
||||
.filter((m) => m.type === "drift")
|
||||
.map((m) => m.cell),
|
||||
[11, 13],
|
||||
);
|
||||
s = act(s, "drift", { cell: 13 });
|
||||
assert.equal(s.amoebas[0].cell, 13);
|
||||
assert.equal(s.players[0].bp, 13);
|
||||
s = fixture({ genes: ["rebound", "energy"], amoebas: [a(0, 1, 9)] });
|
||||
assert.deepEqual(
|
||||
E.legalMoves(s)
|
||||
.filter((m) => m.type === "drift")
|
||||
.map((m) => m.cell),
|
||||
[9],
|
||||
);
|
||||
s = act(s, "drift");
|
||||
assert.equal(s.players[0].bp, 13);
|
||||
});
|
||||
test("Hard Crust charges after defenses; refusing or being unable to pay fails the attack", () => {
|
||||
for (const pay of [true, false]) {
|
||||
let s = fixture({
|
||||
genes: ["struggle"],
|
||||
bp: pay ? 2 : 1,
|
||||
amoebas: [a(0, 1), a(1, 1)],
|
||||
task: { kind: "feeding", a: "0-1" },
|
||||
});
|
||||
own(s, 1, "hard-crust");
|
||||
clearFood(s, 6);
|
||||
s = act(s, "attack");
|
||||
assert.equal(s.tasks[0].kind, "crust");
|
||||
assert.equal(E.currentPlayer(s), 0);
|
||||
s = act(s, pay ? "pay-crust" : "abandon-attack");
|
||||
assert.equal(!!E.amoeba(s, "1-1"), !pay);
|
||||
assert.equal(E.amoeba(s, "0-1").hp, pay ? 0 : 1);
|
||||
}
|
||||
});
|
||||
test("Alarm enables Escape only after an actual meal, and Mouthful prevents that meal's death and nutrients", () => {
|
||||
let s = fixture({
|
||||
genes: ["struggle"],
|
||||
amoebas: [a(0, 1), a(0, 2), a(1, 1), a(1, 2)],
|
||||
task: { kind: "feeding", a: "0-1" },
|
||||
});
|
||||
s.tasks = [
|
||||
{ kind: "feeding", a: "0-1" },
|
||||
{ kind: "feeding", a: "0-2" },
|
||||
{ kind: "genes", p: 3 },
|
||||
];
|
||||
own(s, 1, "alarm");
|
||||
clearFood(s, 6);
|
||||
s = act(s, "attack", { victim: "1-1" });
|
||||
assert.deepEqual(s.alarmPlayers, [1]);
|
||||
clearFood(s, 6);
|
||||
s = act(s, "attack", { victim: "1-2" });
|
||||
assert.equal(s.tasks[0].kind, "combat");
|
||||
assert.ok(opts(s).includes("escape"));
|
||||
s = fixture({
|
||||
genes: ["struggle"],
|
||||
amoebas: [a(0, 1), a(1, 1)],
|
||||
task: { kind: "feeding", a: "0-1" },
|
||||
});
|
||||
own(s, 1, "alarm", "mouthful");
|
||||
clearFood(s, 6);
|
||||
s = act(s, "attack");
|
||||
assert.equal(E.amoeba(s, "1-1").hp, 1);
|
||||
assert.equal(E.amoeba(s, "0-1").hp, 0);
|
||||
assert.deepEqual(s.food[6], [0, 0, 0, 0]);
|
||||
assert.deepEqual(s.alarmPlayers, []);
|
||||
});
|
||||
test("Threat Display checks amoeba numbers for both forms of attack", () => {
|
||||
let s = fixture({
|
||||
genes: ["struggle", "aggression"],
|
||||
amoebas: [a(0, 3), a(1, 2), a(1, 4)],
|
||||
task: { kind: "feeding", a: "0-3" },
|
||||
});
|
||||
own(s, 1, "threat");
|
||||
clearFood(s, 6);
|
||||
assert.deepEqual(
|
||||
E.legalMoves(s)
|
||||
.filter((m) => m.type === "attack")
|
||||
.map((m) => m.victim),
|
||||
["1-4"],
|
||||
);
|
||||
s.phase = 4;
|
||||
s.tasks = [{ kind: "aggression", p: 0 }];
|
||||
assert.deepEqual(
|
||||
E.legalMoves(s)
|
||||
.filter((m) => m.type === "attack")
|
||||
.map((m) => m.victim),
|
||||
["1-4"],
|
||||
);
|
||||
});
|
||||
test("Camouflage I rolls once; II bypasses active defense but not Armor or Hard Crust", () => {
|
||||
const observed = new Set();
|
||||
for (let seed = 0; seed < 30; seed++) {
|
||||
let s = fixture({
|
||||
genes: ["struggle", "camouflage1"],
|
||||
amoebas: [a(0, 1), a(1, 1)],
|
||||
task: { kind: "feeding", a: "0-1" },
|
||||
seed: String(seed),
|
||||
});
|
||||
own(s, 1, "defense", "escape");
|
||||
clearFood(s, 6);
|
||||
s = act(s, "attack");
|
||||
observed.add(s.tasks[0].kind === "combat");
|
||||
assert.equal(
|
||||
s.log.filter((l) => l.text.includes("for Camouflage I")).length,
|
||||
1,
|
||||
);
|
||||
}
|
||||
assert.equal(observed.size, 2);
|
||||
let s = fixture({
|
||||
phase: 4,
|
||||
genes: ["aggression", "camouflage2"],
|
||||
amoebas: [a(0, 1), a(1, 1)],
|
||||
task: { kind: "aggression", p: 0 },
|
||||
});
|
||||
own(s, 1, "armor");
|
||||
s = act(s, "attack");
|
||||
assert.equal(E.amoeba(s, "1-1").hp, 1);
|
||||
s = fixture({
|
||||
genes: ["struggle", "camouflage2"],
|
||||
amoebas: [a(0, 1), a(1, 1)],
|
||||
task: { kind: "feeding", a: "0-1" },
|
||||
});
|
||||
own(s, 1, "defense", "escape", "hard-crust");
|
||||
clearFood(s, 6);
|
||||
s = act(s, "attack");
|
||||
assert.equal(s.tasks[0].kind, "crust");
|
||||
});
|
||||
test("Go Out With a Bang handles lethal chains once per amoeba, including the attacker", () => {
|
||||
let s = fixture({
|
||||
genes: ["struggle"],
|
||||
amoebas: [a(0, 1, 6, 1), a(1, 1), a(1, 2, 6, 1), a(2, 1, 6)],
|
||||
task: { kind: "feeding", a: "0-1" },
|
||||
});
|
||||
own(s, 1, "bang");
|
||||
clearFood(s, 6);
|
||||
s = act(s, "attack", { victim: "1-1" });
|
||||
assert.equal(s.amoebas.length, 0);
|
||||
assert.equal(s.tasks[0].kind, "genes");
|
||||
assert.equal(
|
||||
s.log.filter((l) => l.text.includes("returns to the soup")).length,
|
||||
4,
|
||||
);
|
||||
invariant(s);
|
||||
});
|
||||
test("Short Life Span changes death threshold, division cost and defect relief", () => {
|
||||
let s = fixture({
|
||||
genes: ["short-life"],
|
||||
phase: 3,
|
||||
task: { kind: "division", p: 0 },
|
||||
});
|
||||
assert.equal(E.injuriesToDie(s, 0), 1);
|
||||
s = act(s, "divide");
|
||||
assert.equal(s.players[0].bp, 8);
|
||||
own(s, 0, "short-life", "longevity");
|
||||
assert.equal(E.injuriesToDie(s, 0), 2);
|
||||
s.phase = 1;
|
||||
s.tasks = [
|
||||
{ kind: "defect", p: 0, debt: 5 },
|
||||
{ kind: "genes", p: 3 },
|
||||
];
|
||||
s = act(s, "discard", { gene: "short-life" });
|
||||
assert.equal(s.tasks[0].debt, 1);
|
||||
s = fixture({
|
||||
genes: ["short-life"],
|
||||
phase: 3,
|
||||
amoebas: [a(0, 1, 6, 1), a(1, 1)],
|
||||
task: { kind: "division", p: 0 },
|
||||
});
|
||||
s.tasks = [s.tasks[0]];
|
||||
s = act(s, "done");
|
||||
assert.ok(!E.amoeba(s, "0-1"));
|
||||
});
|
||||
test("Healing I can save a dying amoeba; Healing II transfers an injury and immediately kills the recipient", () => {
|
||||
let s = fixture({
|
||||
genes: ["healing1"],
|
||||
phase: 3,
|
||||
amoebas: [a(0, 1, 6, 2)],
|
||||
task: { kind: "division", p: 0 },
|
||||
});
|
||||
s = act(s, "heal");
|
||||
assert.equal(s.amoebas[0].hp, 1);
|
||||
assert.equal(s.players[0].bp, 9);
|
||||
s = act(s, "heal");
|
||||
assert.equal(s.amoebas[0].hp, 0);
|
||||
assert.ok(!opts(s).includes("heal"));
|
||||
s = fixture({
|
||||
genes: ["healing2"],
|
||||
bp: 0,
|
||||
phase: 3,
|
||||
amoebas: [a(0, 1, 6, 1), a(1, 1)],
|
||||
task: { kind: "division", p: 0 },
|
||||
});
|
||||
own(s, 1, "armor", "threat");
|
||||
s = act(s, "transfer-injury", { target: "1-1" });
|
||||
assert.equal(s.amoebas[0].hp, 0);
|
||||
assert.ok(!E.amoeba(s, "1-1"));
|
||||
assert.equal(s.players[0].bp, 0);
|
||||
invariant(s);
|
||||
});
|
||||
test("Population Explosion replaces income and savings with limited free legal placement", () => {
|
||||
let s = fixture({
|
||||
genes: ["population"],
|
||||
phase: 2,
|
||||
task: { kind: "genes", p: 3 },
|
||||
});
|
||||
s.players[0].score = 1;
|
||||
s.players[1].score = 9;
|
||||
s.players[3].score = 4;
|
||||
s.amoebas = [a(0, 1), a(1, 1, 7), a(1, 2, 8), a(1, 3, 9), a(1, 4, 13)];
|
||||
s.tasks = [
|
||||
{ kind: "genes", p: 3 },
|
||||
{ kind: "income", p: 0 },
|
||||
{ kind: "division", p: 0 },
|
||||
{ kind: "genes", p: 3 },
|
||||
];
|
||||
s = act(s, "done");
|
||||
assert.equal(s.tasks[0].kind, "population");
|
||||
s = act(s, "population-explosion");
|
||||
assert.equal(s.players[0].bp, 0);
|
||||
while (E.colony(s, 0).length < 4) {
|
||||
assert.ok(!opts(s).includes("done"));
|
||||
s = act(s, "divide");
|
||||
}
|
||||
assert.ok(!opts(s).includes("divide"));
|
||||
assert.ok(opts(s).includes("done"));
|
||||
invariant(s);
|
||||
});
|
||||
test("Social Gene transfers only to last place and collects BP from colonies six spaces ahead", () => {
|
||||
let s = fixture({ phase: 2, task: { kind: "genes", p: 0 } });
|
||||
own(s, 1, "social");
|
||||
assert.ok(!E.legalMoves(s).some((m) => m.gene === "social"));
|
||||
s.players[0].score = 0;
|
||||
const before = s.players[1].bp;
|
||||
s = act(s, "buy", { gene: "social" });
|
||||
assert.equal(s.players[0].bp, 10);
|
||||
assert.equal(s.players[1].bp, before + 2);
|
||||
assert.ok(!E.has(s, 1, "social"));
|
||||
s.players.forEach((pl, p) => (pl.score = [0, 5, 6, 12][p]));
|
||||
s.players[3].bp = 0;
|
||||
s.phase = 4;
|
||||
s.tasks = [{ kind: "aggression", p: 1 }];
|
||||
const money = s.players.map((p) => p.bp);
|
||||
s = act(s, "done");
|
||||
assert.equal(s.players[0].bp, money[0] + 1);
|
||||
assert.equal(s.players[1].bp, money[1]);
|
||||
assert.equal(s.players[2].bp, money[2] - 1);
|
||||
});
|
||||
test("Flexible and Highly Adaptable price exchanges, return cards, and preserve advanced prerequisites", () => {
|
||||
let s = fixture({
|
||||
genes: ["flexible", "adaptable", "intelligence"],
|
||||
phase: 2,
|
||||
task: { kind: "genes", p: 0 },
|
||||
});
|
||||
s = act(s, "buy", { gene: "movement1" });
|
||||
assert.equal(s.players[0].bp, 10); // cost 3 - 1
|
||||
const before = s.players[0].bp;
|
||||
s = act(s, "exchange", {
|
||||
gene: "phd",
|
||||
exchange: "intelligence",
|
||||
base: "intelligence",
|
||||
});
|
||||
assert.equal(s.players[0].bp, before);
|
||||
assert.ok(!E.has(s, 0, "intelligence"));
|
||||
assert.ok(E.has(s, 0, "phd"));
|
||||
assert.equal(E.GENE.phd.points, 2);
|
||||
assert.ok(!E.legalMoves(s).some((m) => m.gene === "movement2")); // bought this round
|
||||
const cost = E.genePurchaseCost(s, 0, "energy", "adaptable");
|
||||
assert.equal(cost, 1);
|
||||
s = act(s, "exchange", { gene: "energy", exchange: "adaptable" });
|
||||
assert.ok(!opts(s).includes("exchange"));
|
||||
});
|
||||
test("Migration and Environmental Sensing reveal only to their owner at their respective times", () => {
|
||||
let s = fixture({
|
||||
genes: ["migration"],
|
||||
phase: 5,
|
||||
task: { kind: "genes", p: 3 },
|
||||
});
|
||||
s.tasks = [s.tasks[0]];
|
||||
const next = structuredClone(s._deck[0]);
|
||||
s = act(s, "done");
|
||||
assert.deepEqual(E.stripSecret(s, 0).foreseenEnvironment, next);
|
||||
for (const p of [undefined, 1, 2, 3])
|
||||
assert.ok(!E.stripSecret(s, p).foreseenEnvironment);
|
||||
assert.ok(!JSON.stringify(E.stripSecret(s, 0)).includes('"_knowledge"'));
|
||||
own(s, 0, "environmental");
|
||||
s.phase = 0;
|
||||
s.tasks = [{ kind: "movement", a: "0-1" }];
|
||||
s = act(s, "drift");
|
||||
s = act(s, "eat");
|
||||
assert.deepEqual(s.environment, next);
|
||||
assert.deepEqual(E.stripSecret(s, 0).foreseenEnvironment, s._deck[0]);
|
||||
assert.ok(!JSON.stringify(s.log).includes("Private forecast"));
|
||||
});
|
||||
test("Doris & Frank records who chooses the next game", () => {
|
||||
let s = fixture({
|
||||
genes: ["doris-frank"],
|
||||
phase: 4,
|
||||
task: { kind: "aggression", p: 1 },
|
||||
});
|
||||
s.tasks = [s.tasks[0]];
|
||||
s._deck = [];
|
||||
s = act(s, "done");
|
||||
assert.ok(s.finished);
|
||||
assert.equal(s.nextGameChooser, 0);
|
||||
});
|
||||
test("new action labels and player-count prices are readable", () => {
|
||||
const s = fixture({
|
||||
phase: 2,
|
||||
task: { kind: "genes", p: 0 },
|
||||
genes: ["flexible", "adaptable"],
|
||||
});
|
||||
s.actor = 0;
|
||||
for (const m of E.legalMoves(s))
|
||||
assert.ok(!moveLabel(m, s).includes("undefined"));
|
||||
const six = fixture({ players: 6, phase: 2, task: { kind: "genes", p: 0 } });
|
||||
six.actor = 0;
|
||||
assert.ok(moveLabel({ type: "buy", gene: "frugality" }, six).includes("5"));
|
||||
});
|
||||
test("complete New genes games at all player counts conserve resources and replay deterministically", () => {
|
||||
for (const n of [3, 4, 5, 6])
|
||||
for (const seed of ["new-effects", "interactions"]) {
|
||||
let s = E.init(n, [], { newGenes: true }, seed + ":" + n),
|
||||
steps = 0;
|
||||
while (!s.finished && steps++ < 2500) {
|
||||
invariant(s);
|
||||
s = E.move(s, E.chooseAI(s), E.currentPlayer(s));
|
||||
if (steps % 101 === 0) s = JSON.parse(JSON.stringify(s));
|
||||
}
|
||||
invariant(s);
|
||||
assert.ok(s.finished, `${n} players, ${seed} stalled`);
|
||||
assert.deepEqual(E.replay(s), s);
|
||||
}
|
||||
});
|
||||
|
||||
test("Hard Crust also protects Armor against Aggression without bypassing the injury limit", () => {
|
||||
for (const pay of [true, false]) {
|
||||
let s = fixture({
|
||||
genes: ["aggression"],
|
||||
phase: 4,
|
||||
task: { kind: "aggression", p: 0 },
|
||||
amoebas: [a(0, 1), a(1, 1)],
|
||||
});
|
||||
own(s, 1, "armor", "hard-crust");
|
||||
s = act(s, "attack");
|
||||
assert.equal(E.amoeba(s, "1-1").hp, 0);
|
||||
s = act(s, pay ? "pay-crust" : "abandon-attack");
|
||||
assert.equal(E.amoeba(s, "1-1").hp, pay ? 1 : 0);
|
||||
}
|
||||
});
|
||||
test("random choices with all extra genes in the pool preserve invariants across uncommon interactions", () => {
|
||||
for (let run = 0; run < 8; run++) {
|
||||
const n = 3 + (run % 4);
|
||||
let s = E.init(n, [], { newGenes: true }, `new-random-${run}`),
|
||||
rng = run + 1,
|
||||
steps = 0;
|
||||
// Make late advanced combinations reachable without waiting for the reveal deck.
|
||||
s.newGeneMarket.available = NEW_GENES.map((g) => g.id);
|
||||
s.newGeneMarket._deck = [];
|
||||
const random = (n) => {
|
||||
rng = (Math.imul(rng, 1664525) + 1013904223) >>> 0;
|
||||
return rng % n;
|
||||
};
|
||||
while (!s.finished && steps++ < 4000) {
|
||||
const moves = E.legalMoves(s);
|
||||
assert.ok(moves.length);
|
||||
const buys = moves.filter((m) => m.type === "buy");
|
||||
const choices = buys.length && random(3) ? buys : moves;
|
||||
s = E.move(s, choices[random(choices.length)], E.currentPlayer(s));
|
||||
invariant(s);
|
||||
}
|
||||
assert.ok(s.finished, `random New genes run ${run} must finish`);
|
||||
}
|
||||
});
|
||||
119
test/new-genes-browser.mjs
Normal file
119
test/new-genes-browser.mjs
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { chromium } from "playwright";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as E from "../engine/index.js";
|
||||
import { NEW_GENES } from "../engine/new-genes.js";
|
||||
import { prepared } from "../viewer/tutorials.js";
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.CHROMIUM_EXECUTABLE,
|
||||
});
|
||||
try {
|
||||
for (const width of [390, 1400]) {
|
||||
const page = await browser.newPage({ viewport: { width, height: 1000 } }),
|
||||
errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.setContent(
|
||||
'<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"></head><body><div id="app"></div></body></html>',
|
||||
);
|
||||
await page.addStyleTag({ path: root + "dist/viewer.css" });
|
||||
await page.addScriptTag({ path: root + "dist/viewer.js" });
|
||||
let s = prepared({
|
||||
genes: ["flexible", "adaptable"],
|
||||
phase: 2,
|
||||
task: { kind: "genes", p: 0 },
|
||||
});
|
||||
s.options = { newGenes: true };
|
||||
s.newGeneMarket = {
|
||||
available: NEW_GENES.map((g) => g.id),
|
||||
_deck: [],
|
||||
revealedRound: 2,
|
||||
};
|
||||
s.toxins = Array(25).fill(0);
|
||||
s.toxins[7] = 2;
|
||||
s._knowledge = { 0: { ozone: 14, direction: 4 } };
|
||||
await page.evaluate(
|
||||
(state) => {
|
||||
window.e = primordialSoup.launch("#app");
|
||||
window.moves = [];
|
||||
e.on("move", (m) => moves.push(m));
|
||||
e.emit("player", { index: 0 });
|
||||
e.emit("state", state);
|
||||
},
|
||||
E.stripSecret(s, 0),
|
||||
);
|
||||
assert.match(
|
||||
await page.locator(".private-forecast").textContent(),
|
||||
/ozone 14/,
|
||||
);
|
||||
assert.equal(await page.locator(".toxin-marker").count(), 1);
|
||||
await page.getByRole("button", { name: "Genes", exact: true }).click();
|
||||
assert.equal(await page.locator(".shop-card").count(), 46);
|
||||
assert.match(
|
||||
await page.locator(".market-status").textContent(),
|
||||
/unrevealed · \+2 per round/,
|
||||
);
|
||||
assert.ok(
|
||||
!(await page.locator("dialog").textContent()).includes("undefined"),
|
||||
);
|
||||
const exchange = page
|
||||
.locator('[data-tutorial="gene-energy"] button')
|
||||
.filter({ hasText: "Exchange Highly Adaptable" });
|
||||
await exchange.click();
|
||||
assert.equal(await page.evaluate(() => moves[0].type), "exchange");
|
||||
// A real server response clears the pending UI request.
|
||||
const action = await page.evaluate(() => moves[0]);
|
||||
s = E.move(s, action, 0);
|
||||
await page.evaluate((state) => e.emit("state", state), E.stripSecret(s, 0));
|
||||
await page.screenshot({
|
||||
path: `/tmp/soup-new-genes-shop-${width}.png`,
|
||||
fullPage: true,
|
||||
});
|
||||
await page.getByRole("button", { name: "Close", exact: true }).click();
|
||||
// Hide other players' forecasts and exercise the food source picker.
|
||||
s = prepared({ genes: ["suction2"], task: { kind: "feeding", a: "0-1" } });
|
||||
s.tasks.push({ kind: "genes", p: 1 });
|
||||
s.newGeneMarket = { available: ["suction2"], _deck: [], revealedRound: 2 };
|
||||
await page.evaluate((state) => e.emit("state", state), E.stripSecret(s, 0));
|
||||
assert.equal(await page.locator(".private-forecast").isVisible(), false);
|
||||
await page.getByLabel("Food source", { exact: true }).selectOption("7");
|
||||
const eat = page
|
||||
.locator(".action-buttons button")
|
||||
.filter({ hasText: "Eat" })
|
||||
.first();
|
||||
assert.match(await eat.textContent(), /from C2/);
|
||||
await eat.click();
|
||||
assert.equal(await page.evaluate(() => moves.at(-1).source), 7);
|
||||
await page.evaluate(
|
||||
(state) => e.emit("state", state),
|
||||
E.stripSecret(E.move(s, await page.evaluate(() => moves.at(-1)), 0), 0),
|
||||
);
|
||||
assert.deepEqual(errors, []);
|
||||
await page.close();
|
||||
console.log(
|
||||
`New genes ${width}: market, exchange, private forecast, toxins and suction controls passed`,
|
||||
);
|
||||
}
|
||||
const page = await browser.newPage();
|
||||
await page.goto("http://127.0.0.1:5221/?players=6&newGenes=1");
|
||||
assert.equal(
|
||||
await page
|
||||
.getByRole("checkbox", { name: "New genes", exact: true })
|
||||
.isChecked(),
|
||||
true,
|
||||
);
|
||||
await page.getByRole("button", { name: "New 5-colony game" }).click();
|
||||
await page.waitForURL("**/?players=5&newGenes=1");
|
||||
assert.equal(await page.locator(".players .player").count(), 5);
|
||||
const saved = await page.evaluate(() =>
|
||||
JSON.parse(localStorage.getItem("soup:practice:1:5:newGenes")),
|
||||
);
|
||||
assert.equal(saved.options.newGenes, true);
|
||||
assert.deepEqual(saved.newGeneMarket.available, ["social", "population"]);
|
||||
await page.close();
|
||||
console.log(
|
||||
"Practice toggle keeps New genes enabled independently of player count",
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
64
test/new-genes.test.js
Normal file
64
test/new-genes.test.js
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
createNewGeneMarket,
|
||||
revealNewGenesAfterPurchases,
|
||||
publicNewGeneMarket,
|
||||
} from "../engine/new-genes.js";
|
||||
const event = {
|
||||
phase: 2,
|
||||
round: 1,
|
||||
player: 5,
|
||||
leader: 5,
|
||||
finishedBuying: true,
|
||||
};
|
||||
test("New genes is a boolean option independent of player count and disabled by default", () => {
|
||||
const noRandom = () => {
|
||||
throw Error("disabled option consumed randomness");
|
||||
};
|
||||
assert.equal(createNewGeneMarket({}, noRandom), undefined);
|
||||
assert.equal(createNewGeneMarket({ newGenes: false }, noRandom), undefined);
|
||||
assert.throws(() => createNewGeneMarket({ newGenes: "false" }, noRandom));
|
||||
});
|
||||
test("the recommended initial genes are visible, the shuffled future is secret, and exactly two arrive after the leader finishes", () => {
|
||||
const market = createNewGeneMarket({ newGenes: true }, (n) => n - 1);
|
||||
assert.deepEqual(publicNewGeneMarket(market), {
|
||||
available: ["social", "population"],
|
||||
remaining: 24,
|
||||
});
|
||||
for (const patch of [{ finishedBuying: false }, { phase: 1 }, { player: 4 }])
|
||||
assert.equal(
|
||||
revealNewGenesAfterPurchases(market, { ...event, ...patch }),
|
||||
market,
|
||||
);
|
||||
const next = revealNewGenesAfterPurchases(market, event);
|
||||
assert.equal(next.available.length, 4);
|
||||
assert.equal(next._deck.length, 22);
|
||||
assert.deepEqual(next.available.slice(-2), market._deck.slice(0, 2));
|
||||
assert.equal(market.available.length, 2);
|
||||
assert.equal(revealNewGenesAfterPurchases(next, event), next);
|
||||
const restored = JSON.parse(JSON.stringify(next));
|
||||
assert.deepEqual(revealNewGenesAfterPurchases(restored, event), next);
|
||||
const round2 = revealNewGenesAfterPurchases(restored, {
|
||||
...event,
|
||||
round: 2,
|
||||
player: 0,
|
||||
leader: 0,
|
||||
});
|
||||
assert.equal(round2.available.length, 6);
|
||||
});
|
||||
test("the new gene market keeps previously revealed cards and stops cleanly when the deck runs out", () => {
|
||||
let market = createNewGeneMarket({ newGenes: true }, () => 0);
|
||||
const order = [...market.available, ...market._deck];
|
||||
for (let round = 1; round <= 15; round++)
|
||||
market = revealNewGenesAfterPurchases(market, { ...event, round });
|
||||
assert.deepEqual(market.available, order);
|
||||
assert.equal(new Set(market.available).size, 26);
|
||||
assert.equal(publicNewGeneMarket(market).remaining, 0);
|
||||
const odd = revealNewGenesAfterPurchases(
|
||||
{ available: [], _deck: ["glutton"], revealedRound: 0 },
|
||||
event,
|
||||
);
|
||||
assert.deepEqual(odd.available, ["glutton"]);
|
||||
assert.deepEqual(odd._deck, []);
|
||||
});
|
||||
112
test/preferences-browser.mjs
Normal file
112
test/preferences-browser.mjs
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { chromium } from "playwright";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { COLOR_BLIND_PREFERENCE } from "../viewer/preferences.js";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.CHROMIUM_EXECUTABLE,
|
||||
});
|
||||
const key = COLOR_BLIND_PREFERENCE.name;
|
||||
const localKey = "primordial-soup-colony-symbols";
|
||||
|
||||
async function hostedViewer(preferences, localValue) {
|
||||
const page = await browser.newPage(),
|
||||
errors = [];
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
await page.route("**/__preferences-test", (route) =>
|
||||
route.fulfill({
|
||||
contentType: "text/html",
|
||||
body: '<!doctype html><div id="app"></div>',
|
||||
}),
|
||||
);
|
||||
await page.goto("http://127.0.0.1:5221/__preferences-test");
|
||||
if (localValue !== undefined)
|
||||
await page.evaluate(
|
||||
({ localKey, localValue }) =>
|
||||
localStorage.setItem(localKey, String(localValue)),
|
||||
{ localKey, localValue },
|
||||
);
|
||||
await page.addStyleTag({ path: root + "dist/viewer.css" });
|
||||
await page.addScriptTag({ path: root + "dist/viewer.js" });
|
||||
await page.evaluate((preferences) => {
|
||||
window.emitter = primordialSoup.launch("#app");
|
||||
window.savedPreferences = preferences;
|
||||
window.updates = [];
|
||||
emitter.on("update:preference", (update) => {
|
||||
updates.push(update);
|
||||
savedPreferences = { ...savedPreferences, [update.name]: update.value };
|
||||
emitter.emit("preferences", savedPreferences);
|
||||
});
|
||||
emitter.emit("preferences", preferences);
|
||||
}, preferences);
|
||||
return {
|
||||
page,
|
||||
errors,
|
||||
button: page.getByRole("button", { name: "Color-blind mode", exact: true }),
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const first = await hostedViewer({ [key]: false, analysis: false }, true);
|
||||
// Account preferences take precedence over a stale local practice preference.
|
||||
assert.equal(await first.button.getAttribute("aria-pressed"), "false");
|
||||
await first.page.evaluate(
|
||||
(key) => emitter.emit("preferences", { [key]: true }),
|
||||
key,
|
||||
);
|
||||
assert.equal(await first.button.getAttribute("aria-pressed"), "true");
|
||||
assert.deepEqual(await first.page.evaluate(() => updates), []);
|
||||
await first.button.click();
|
||||
assert.equal(await first.button.getAttribute("aria-pressed"), "false");
|
||||
await first.button.click();
|
||||
assert.equal(await first.button.getAttribute("aria-pressed"), "true");
|
||||
assert.deepEqual(await first.page.evaluate(() => updates), [
|
||||
{ name: key, value: false },
|
||||
{ name: key, value: true },
|
||||
]);
|
||||
const saved = await first.page.evaluate(() => savedPreferences);
|
||||
assert.deepEqual(first.errors, []);
|
||||
await first.page.close();
|
||||
|
||||
// A fresh browser context restores the host's saved value without local storage.
|
||||
const restored = await hostedViewer(saved);
|
||||
assert.equal(
|
||||
await restored.page.evaluate(
|
||||
(localKey) => localStorage.getItem(localKey),
|
||||
localKey,
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(await restored.button.getAttribute("aria-pressed"), "true");
|
||||
await restored.page.evaluate(() => emitter.emit("preferences", {}));
|
||||
assert.equal(await restored.button.getAttribute("aria-pressed"), "false");
|
||||
assert.deepEqual(await restored.page.evaluate(() => updates), []);
|
||||
assert.deepEqual(restored.errors, []);
|
||||
await restored.page.close();
|
||||
console.log(
|
||||
"BGS preferences: incoming updates, outgoing saves, host echoes and fresh-session restoration passed",
|
||||
);
|
||||
|
||||
const local = await browser.newPage();
|
||||
for (const query of ["?chat", "?players=3"]) {
|
||||
await local.goto("http://127.0.0.1:5221/" + query);
|
||||
const button = local.getByRole("button", {
|
||||
name: "Color-blind mode",
|
||||
exact: true,
|
||||
});
|
||||
assert.equal(await button.getAttribute("aria-pressed"), "false");
|
||||
await button.click();
|
||||
await local.reload();
|
||||
assert.equal(await button.getAttribute("aria-pressed"), "true");
|
||||
await button.click();
|
||||
await local.reload();
|
||||
assert.equal(await button.getAttribute("aria-pressed"), "false");
|
||||
}
|
||||
await local.close();
|
||||
console.log(
|
||||
"Local chat preview and practice retain browser preference storage",
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
184
test/turn-controls-browser.mjs
Normal file
184
test/turn-controls-browser.mjs
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { chromium } from "playwright";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as E from "../engine/index.js";
|
||||
import { prepared } from "../viewer/tutorials.js";
|
||||
import { colors } from "../viewer/art.js";
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.CHROMIUM_EXECUTABLE,
|
||||
});
|
||||
try {
|
||||
for (const width of [320, 390, 1400]) {
|
||||
const page = await browser.newPage({ viewport: { width, height: 1000 } });
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.setContent(
|
||||
'<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><div id="app"></div>',
|
||||
);
|
||||
await page.addStyleTag({ path: root + "dist/viewer.css" });
|
||||
await page.addScriptTag({ path: root + "dist/viewer.js" });
|
||||
await page.evaluate(() => {
|
||||
window.e = primordialSoup.launch("#app");
|
||||
window.moves = [];
|
||||
e.on("move", (m) => moves.push(m));
|
||||
e.emit("player", { index: 0 });
|
||||
});
|
||||
const show = async (s) => {
|
||||
await page.evaluate((s) => e.emit("state", s), E.stripSecret(s, 0));
|
||||
await page.waitForTimeout(30);
|
||||
};
|
||||
let s = prepared();
|
||||
await show(s);
|
||||
assert.match(
|
||||
await page.locator(".phase-steps li").nth(3).textContent(),
|
||||
/\+10/,
|
||||
);
|
||||
const swim = page.locator(".board-swim");
|
||||
assert.ok(await swim.isVisible());
|
||||
await page.screenshot({
|
||||
path: `/tmp/soup-swim-${width}.png`,
|
||||
fullPage: true,
|
||||
});
|
||||
assert.match(await swim.getAttribute("aria-label"), /1 biological point/);
|
||||
// A deterministic drift offers undo; cancelling uses the real protocol move.
|
||||
const drift = E.legalMoves(s).find((m) => m.type === "drift");
|
||||
await page.locator(`[data-cell="${drift.cell}"]`).click();
|
||||
assert.deepEqual(await page.evaluate(() => moves.at(-1)), drift);
|
||||
s = E.move(s, drift, 0);
|
||||
await show(s);
|
||||
assert.ok(!(await swim.isVisible()));
|
||||
await page.locator("[data-undo]").click();
|
||||
const cancellation = await page.evaluate(() => moves.at(-1));
|
||||
assert.deepEqual(cancellation, { type: "undo" });
|
||||
s = E.move(s, cancellation, 0);
|
||||
await show(s);
|
||||
assert.equal(E.logLength(s), 0);
|
||||
assert.ok(await swim.isVisible());
|
||||
await swim.click();
|
||||
assert.deepEqual(await page.evaluate(() => moves.at(-1)), { type: "swim" });
|
||||
s = E.move(s, { type: "swim" }, 0);
|
||||
await show(s);
|
||||
assert.equal(await page.locator("[data-undo]").count(), 0);
|
||||
assert.ok(!(await swim.isVisible()));
|
||||
|
||||
// Empty phase entries hand over; a final purchase/placement keeps Done and Undo.
|
||||
for (const [phase, kind, bp, type] of [
|
||||
[2, "genes", 2, "buy"],
|
||||
[3, "division", 6, "divide"],
|
||||
]) {
|
||||
s = prepared({ phase, bp: 0, task: { kind, p: 1 } });
|
||||
s.tasks.push({ kind, p: 0 }, { kind, p: 2 });
|
||||
s = E.move(s, { type: "done" }, 1);
|
||||
assert.equal(E.currentPlayer(s), 2);
|
||||
await show(s);
|
||||
assert.match(
|
||||
await page.locator(".phase-instruction").textContent(),
|
||||
/Waiting for Leo/,
|
||||
);
|
||||
assert.equal(
|
||||
await page.locator(".turnbar .action-buttons button").count(),
|
||||
0,
|
||||
);
|
||||
|
||||
s = prepared({ phase, bp, task: { kind, p: 0 } });
|
||||
s.tasks.push({ kind, p: 1 });
|
||||
const action = E.legalMoves(s).find(
|
||||
(m) => m.type === type && (type !== "buy" || m.gene === "intelligence"),
|
||||
);
|
||||
s = E.move(s, action, 0);
|
||||
await show(s);
|
||||
assert.equal(s.players[0].bp, 0);
|
||||
assert.ok(
|
||||
await page
|
||||
.getByRole("button", { name: "Done", exact: true })
|
||||
.isVisible(),
|
||||
);
|
||||
await page.locator("[data-undo]").click();
|
||||
const undo = await page.evaluate(() => moves.at(-1));
|
||||
assert.deepEqual(undo, { type: "undo" });
|
||||
s = E.move(s, undo, 0);
|
||||
assert.equal(s.players[0].bp, bp);
|
||||
await show(s);
|
||||
}
|
||||
|
||||
// Six overlapping colonies, with their number badges above every neighbour.
|
||||
s = prepared({ players: 6, phase: 2, task: { kind: "genes", p: 0 } });
|
||||
s.players.forEach((p, i) => {
|
||||
p.name = `Colony ${i + 1}`;
|
||||
p.score = 6 - i;
|
||||
p.genes = [{ id: "fast-food", round: 1 }];
|
||||
});
|
||||
s.amoebas = s.players.map((_, i) => ({
|
||||
id: `${i}-${i + 1}`,
|
||||
p: i,
|
||||
n: i + 1,
|
||||
cell: 6,
|
||||
hp: 0,
|
||||
}));
|
||||
await show(s);
|
||||
assert.match(
|
||||
await page.locator(".phase-steps li").nth(3).textContent(),
|
||||
/\+11/,
|
||||
);
|
||||
for (const a of s.amoebas) {
|
||||
const badge = page.locator(`[data-amoeba="${a.id}"] .amoeba-number`);
|
||||
await badge.scrollIntoViewIfNeeded();
|
||||
const hit = await badge.evaluate((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return {
|
||||
owner: document
|
||||
.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2)
|
||||
?.closest("[data-amoeba]")?.dataset.amoeba,
|
||||
opacity: getComputedStyle(el).opacity,
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
};
|
||||
});
|
||||
assert.equal(
|
||||
hit.owner,
|
||||
a.id,
|
||||
`badge ${a.id} must remain on top at ${width}`,
|
||||
);
|
||||
assert.equal(hit.opacity, "1");
|
||||
assert.ok(hit.width >= 16 && hit.height >= 16);
|
||||
}
|
||||
await page.screenshot({
|
||||
path: `/tmp/soup-turn-controls-${width}.png`,
|
||||
fullPage: true,
|
||||
});
|
||||
// Clicking another colony keeps that colony's colour in its gene illustration.
|
||||
await page.locator('[data-player="2"]').click();
|
||||
await page.locator('.gene-list [data-gene="fast-food"]').click();
|
||||
assert.ok(
|
||||
!(await page.locator(".modal-content").textContent()).includes(
|
||||
"COLONY GENE",
|
||||
),
|
||||
);
|
||||
assert.equal(
|
||||
await page
|
||||
.locator(".gene-explainer-art stop")
|
||||
.first()
|
||||
.getAttribute("stop-color"),
|
||||
colors.blue.light,
|
||||
);
|
||||
await page.screenshot({
|
||||
path: `/tmp/soup-gene-colour-${width}.png`,
|
||||
fullPage: true,
|
||||
});
|
||||
await page.getByRole("button", { name: "Close", exact: true }).click();
|
||||
assert.ok(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= window.innerWidth,
|
||||
),
|
||||
`no horizontal overflow at ${width}`,
|
||||
);
|
||||
assert.deepEqual(errors, []);
|
||||
await page.close();
|
||||
console.log(
|
||||
`Turn controls ${width}: swim, undo, dice boundary, automatic empty turns, final-action confirmation, income, six visible badges and colony gene colour passed`,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
233
test/undo.test.js
Normal file
233
test/undo.test.js
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import * as E from "../engine/index.js";
|
||||
import { prepared } from "../viewer/tutorials.js";
|
||||
import { recordMove } from "../engine/undo.js";
|
||||
|
||||
const act = (s, type, extra = {}) => {
|
||||
const action = E.legalMoves(s).find(
|
||||
(m) =>
|
||||
m.type === type &&
|
||||
Object.entries(extra).every(([key, value]) => m[key] === value),
|
||||
);
|
||||
assert.ok(action, `Missing ${type} in ${JSON.stringify(s.tasks[0])}`);
|
||||
return E.move(s, action, E.currentPlayer(s));
|
||||
};
|
||||
const undo = (s, p = 0) => E.move(s, { type: "undo" }, p);
|
||||
const publicPosition = (s) => {
|
||||
const view = E.stripSecret(s, 0);
|
||||
delete view.undoPlayer;
|
||||
return view;
|
||||
};
|
||||
|
||||
test("100 drift/undo cycles restore the board without growing history, journal or time", () => {
|
||||
const initial = prepared({ genes: ["energy"] });
|
||||
initial.toxins = Array(25).fill(0);
|
||||
initial.toxins[7] = 1;
|
||||
let s = initial;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
s = act(s, "drift");
|
||||
assert.equal(E.amoeba(s, "0-1").cell, 7);
|
||||
assert.equal(s.players[0].bp, initial.players[0].bp + 1);
|
||||
assert.equal(E.isLiveUpdate(s), true);
|
||||
assert.equal(E.canUndo(s, 0), true);
|
||||
assert.throws(() => undo(s, 1));
|
||||
assert.throws(() => E.move(s, { type: "undo", player: 0 }, 0));
|
||||
const view = E.stripSecret(s, 1);
|
||||
for (const key of [
|
||||
"_undo",
|
||||
"_pendingMoves",
|
||||
"_counter",
|
||||
"_timeIncrements",
|
||||
"_moveDepth",
|
||||
])
|
||||
assert.ok(!(key in view));
|
||||
s = undo(s);
|
||||
assert.deepEqual(publicPosition(s), publicPosition(initial));
|
||||
assert.deepEqual(s.log, initial.log);
|
||||
assert.equal(E.logLength(s), 0);
|
||||
assert.deepEqual(E.logSlice(s), []);
|
||||
assert.deepEqual(E.timeIncrements(s), [1, 0, 0, 0]);
|
||||
assert.equal(E.canUndo(s, 0), false);
|
||||
}
|
||||
assert.equal(initial._undo, undefined);
|
||||
});
|
||||
|
||||
test("multiple deterministic actions undo in reverse, then commit only the final sequence", () => {
|
||||
const initial = prepared();
|
||||
let s = act(initial, "drift");
|
||||
const drifted = s;
|
||||
s = act(s, "eat");
|
||||
assert.equal(E.amoeba(s, "0-1").cell, 7);
|
||||
s = undo(s);
|
||||
assert.deepEqual(publicPosition(s), publicPosition(drifted));
|
||||
s = undo(s);
|
||||
assert.deepEqual(publicPosition(s), publicPosition(initial));
|
||||
s = act(act(act(act(s, "drift"), "eat"), "drift"), "eat");
|
||||
assert.equal(E.canUndo(s, 0), false);
|
||||
assert.equal(E.isLiveUpdate(s), false);
|
||||
assert.deepEqual(
|
||||
E.logSlice(s).map((x) => x.move.type),
|
||||
["drift", "eat", "drift", "eat"],
|
||||
);
|
||||
assert.deepEqual(E.timeIncrements(s), [4, 0, 0, 0]);
|
||||
assert.throws(() => undo(s));
|
||||
});
|
||||
|
||||
test("dice rolls commit preceding actions and cannot be cancelled or rerolled", () => {
|
||||
let s = act(act(prepared(), "drift"), "eat");
|
||||
assert.equal(E.logLength(s), 0);
|
||||
s = act(s, "swim");
|
||||
const rolled = s;
|
||||
assert.equal(E.logLength(s), 3);
|
||||
assert.equal(E.canUndo(s, 0), false);
|
||||
assert.equal(E.isLiveUpdate(s), false);
|
||||
assert.throws(() => undo(s));
|
||||
s = act(s, "direction");
|
||||
s = undo(s);
|
||||
assert.deepEqual(publicPosition(s), publicPosition(rolled));
|
||||
assert.equal(s._counter, rolled._counter);
|
||||
assert.deepEqual(s.tasks[0].dice, rolled.tasks[0].dice);
|
||||
assert.deepEqual(s.history, rolled.history);
|
||||
assert.throws(() => undo(s));
|
||||
});
|
||||
|
||||
test("Movement II swimming and direction choices refund fully because no dice are rolled", () => {
|
||||
const initial = prepared({ genes: ["movement2"] });
|
||||
let s = act(act(initial, "swim"), "direction");
|
||||
assert.equal(s.players[0].bp, initial.players[0].bp - 1);
|
||||
assert.equal(s._counter, initial._counter);
|
||||
s = undo(undo(s));
|
||||
assert.deepEqual(publicPosition(s), publicPosition(initial));
|
||||
assert.deepEqual(E.timeIncrements(s), [2, 0, 0, 0]);
|
||||
});
|
||||
|
||||
test("gene purchases and division can be cancelled with prices refunded", () => {
|
||||
for (const [phase, task, type] of [
|
||||
[2, "genes", "buy"],
|
||||
[3, "division", "divide"],
|
||||
]) {
|
||||
const initial = prepared({ phase, task: { kind: task, p: 0 } });
|
||||
initial.tasks.push({ kind: task, p: 1 });
|
||||
let s = act(initial, type);
|
||||
assert.ok(s.players[0].bp < initial.players[0].bp);
|
||||
s = undo(s);
|
||||
assert.deepEqual(publicPosition(s), publicPosition(initial));
|
||||
s = act(act(s, type), "done");
|
||||
assert.equal(E.currentPlayer(s), 1);
|
||||
assert.equal(E.canUndo(s, 0), false);
|
||||
assert.equal(E.isLiveUpdate(s), false);
|
||||
assert.deepEqual(
|
||||
s.history.map((x) => x.move.type),
|
||||
[type, "done"],
|
||||
);
|
||||
assert.throws(() => undo(s));
|
||||
}
|
||||
});
|
||||
|
||||
test("opponent Holding decisions are a handoff boundary even without randomness", () => {
|
||||
let s = prepared();
|
||||
s.players[1].genes = [{ id: "holding", round: 1 }];
|
||||
E.amoeba(s, "1-1").cell = 6;
|
||||
s = act(s, "drift");
|
||||
assert.equal(E.currentPlayer(s), 1);
|
||||
assert.equal(s.tasks[0].kind, "follow");
|
||||
assert.equal(E.logLength(s), 1);
|
||||
assert.equal(E.canUndo(s, 0), false);
|
||||
assert.throws(() => undo(s));
|
||||
});
|
||||
|
||||
test("a shorter replacement turn does not consume another player's time credit", () => {
|
||||
let s = prepared({ phase: 2, bp: 30, task: { kind: "genes", p: 0 } });
|
||||
s.tasks.push({ kind: "genes", p: 1 });
|
||||
s = act(act(act(s, "buy"), "buy"), "buy");
|
||||
s = undo(undo(undo(s)));
|
||||
s = act(s, "done");
|
||||
const credits = E.timeIncrements(s);
|
||||
s = act(s, "buy");
|
||||
assert.equal(E.timeIncrements(s)[0], credits[0]);
|
||||
assert.equal(E.timeIncrements(s)[1], credits[1] + 1);
|
||||
});
|
||||
|
||||
test("hidden information and phase boundaries commit even when the player stays the same", () => {
|
||||
const initial = prepared();
|
||||
for (const change of [
|
||||
(s) => {
|
||||
s._counter++;
|
||||
},
|
||||
(s) => {
|
||||
s._deck.shift();
|
||||
},
|
||||
(s) => {
|
||||
s._knowledge = { 0: structuredClone(s._deck[0]) };
|
||||
},
|
||||
(s) => {
|
||||
s.newGeneMarket = { available: ["social"], _deck: [], revealedRound: 2 };
|
||||
},
|
||||
(s) => {
|
||||
s.phase++;
|
||||
},
|
||||
(s) => {
|
||||
s.round++;
|
||||
},
|
||||
]) {
|
||||
const after = structuredClone(initial);
|
||||
change(after);
|
||||
const s = recordMove(initial, after, { type: "done" }, 0, true);
|
||||
assert.equal(E.canUndo(s, 0), false);
|
||||
assert.equal(E.isLiveUpdate(s), false);
|
||||
assert.equal(E.logLength(s), 1);
|
||||
}
|
||||
});
|
||||
|
||||
test("Tentacle cargo adjustments give no time; cancelling removes all pending actions", () => {
|
||||
const initial = prepared({ genes: ["tentacle"] });
|
||||
let s = act(initial, "drift");
|
||||
const increments = E.timeIncrements(s);
|
||||
for (let i = 0; i < 100; i++) {
|
||||
s = act(s, "carry");
|
||||
s = undo(s);
|
||||
assert.deepEqual(E.timeIncrements(s), increments);
|
||||
assert.equal(E.logLength(s), 0);
|
||||
}
|
||||
s = act(act(s, "carry"), "return-food");
|
||||
assert.deepEqual(E.timeIncrements(s), increments);
|
||||
s = undo(undo(undo(s)));
|
||||
assert.deepEqual(publicPosition(s), publicPosition(initial));
|
||||
});
|
||||
|
||||
test("dropping a player commits pending moves and invalidates undo", () => {
|
||||
const pending = act(prepared(), "drift");
|
||||
const s = E.dropPlayer(pending, 1);
|
||||
assert.equal(s.players[1].dropped, true);
|
||||
assert.equal(E.canUndo(s, 0), false);
|
||||
assert.equal(E.logLength(s), 1);
|
||||
assert.deepEqual(E.timeIncrements(s), E.timeIncrements(pending));
|
||||
});
|
||||
|
||||
test("a whole game keeps published history append-only and time counts monotonic", () => {
|
||||
let s = E.init(3, [], { newGenes: true }, "undo-replay");
|
||||
let steps = 0;
|
||||
while (!E.ended(s) && steps++ < 3000) {
|
||||
const before = s;
|
||||
s = E.move(s, E.chooseAI(s), E.currentPlayer(s));
|
||||
assert.deepEqual(s.history.slice(0, before.history.length), before.history);
|
||||
E.timeIncrements(s).forEach((value, p) =>
|
||||
assert.ok(value >= E.timeIncrements(before)[p]),
|
||||
);
|
||||
const p = E.currentPlayer(s);
|
||||
if (E.canUndo(s, p)) {
|
||||
const next = s;
|
||||
s = undo(s, p);
|
||||
assert.deepEqual(E.timeIncrements(s), E.timeIncrements(next));
|
||||
assert.deepEqual(s.history, next.history);
|
||||
assert.deepEqual(publicPosition(s), publicPosition(before));
|
||||
s = E.move(s, E.chooseAI(s), p);
|
||||
}
|
||||
}
|
||||
assert.ok(s.finished);
|
||||
assert.equal(s._pendingMoves, undefined);
|
||||
const replay = E.replay(s);
|
||||
assert.deepEqual(publicPosition(replay), publicPosition(s));
|
||||
assert.deepEqual(replay.history, s.history);
|
||||
});
|
||||
|
|
@ -112,14 +112,16 @@
|
|||
}
|
||||
.soup-activity .chat-author {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
vertical-align: middle;
|
||||
align-items: baseline;
|
||||
vertical-align: baseline;
|
||||
gap: 6px;
|
||||
padding: 0;
|
||||
font-weight: 700;
|
||||
}
|
||||
.soup-activity .chat-portrait {
|
||||
display: inline-block;
|
||||
display: block;
|
||||
align-self: center;
|
||||
flex: none;
|
||||
width: 23px;
|
||||
height: 23px;
|
||||
}
|
||||
|
|
@ -206,6 +208,167 @@
|
|||
.soup-activity .journal-empty {
|
||||
color: var(--muted);
|
||||
}
|
||||
.soup .journal-list .journal-round-group,
|
||||
.soup .journal-list .journal-group {
|
||||
display: block;
|
||||
border: 0;
|
||||
padding: 0 0 8px;
|
||||
}
|
||||
.journal-round-divider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin: 4px 0 8px;
|
||||
color: #526e4e;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.journal-round-divider::after {
|
||||
content: "";
|
||||
flex: 1;
|
||||
border-top: 1px solid #c8d6bd;
|
||||
}
|
||||
.journal-group h4 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
margin: 0 0 3px;
|
||||
color: #768772;
|
||||
font-size: 10px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.journal-group h4 svg {
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
}
|
||||
.journal-group > ol,
|
||||
.journal-round-group > ol {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
.soup .journal-list .journal-event {
|
||||
display: block;
|
||||
padding: 7px 0;
|
||||
border: 0;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.journal-amoeba,
|
||||
.journal-player {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
vertical-align: baseline;
|
||||
gap: 6px;
|
||||
color: var(--ink);
|
||||
}
|
||||
.journal-dice {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
vertical-align: middle;
|
||||
margin-left: 3px;
|
||||
}
|
||||
.journal-die {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
color: var(--ink);
|
||||
}
|
||||
.journal-die > svg {
|
||||
width: 25px;
|
||||
height: 25px;
|
||||
flex: none;
|
||||
}
|
||||
.journal-die rect {
|
||||
fill: #fffcf3;
|
||||
stroke: #879d78;
|
||||
}
|
||||
.journal-die circle {
|
||||
fill: currentColor;
|
||||
}
|
||||
.journal-die small {
|
||||
font-size: 10px;
|
||||
color: #617653;
|
||||
}
|
||||
.journal-amoeba {
|
||||
vertical-align: middle;
|
||||
margin: -4px 3px -4px 0;
|
||||
cursor: help;
|
||||
}
|
||||
.journal-portrait {
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
flex: none;
|
||||
align-self: center;
|
||||
}
|
||||
.journal-player .journal-portrait {
|
||||
width: 23px;
|
||||
height: 23px;
|
||||
}
|
||||
.journal-portrait > svg {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
.journal-portrait > b {
|
||||
position: absolute;
|
||||
right: -3px;
|
||||
bottom: -1px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
border-radius: 50%;
|
||||
border: 1px solid #8da681;
|
||||
background: #ffffed;
|
||||
font-size: 9px;
|
||||
line-height: 1;
|
||||
}
|
||||
.journal-cell {
|
||||
display: inline-block;
|
||||
padding: 0 4px;
|
||||
border: 1px solid #cbd8bd;
|
||||
border-radius: 4px;
|
||||
color: #526e4e;
|
||||
font-size: 0.85em;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.journal-environment {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 18px;
|
||||
padding: 9px 12px;
|
||||
border: 1px solid #a8c9b1;
|
||||
border-radius: 11px;
|
||||
background: #e2efe1;
|
||||
}
|
||||
.journal-current {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.journal-current-arrow {
|
||||
display: inline-block;
|
||||
font-size: 27px;
|
||||
line-height: 1;
|
||||
}
|
||||
.journal-ozone {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 3px 7px;
|
||||
border: 1px solid #b29843;
|
||||
border-radius: 7px;
|
||||
background: #fff1bc;
|
||||
color: #685017;
|
||||
line-height: 1;
|
||||
font-size: 24px;
|
||||
}
|
||||
.journal-ozone svg {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
.soup-chat-shortcut {
|
||||
position: fixed;
|
||||
left: max(16px, env(safe-area-inset-left));
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { mountChat } from "@boardgamers/protocol/chat/dom";
|
||||
import { amoeba, colors, icon } from "./art.js";
|
||||
import { richText } from "./rich-text.js";
|
||||
import { journalHtml } from "./journal.js";
|
||||
|
||||
let sequence = 0;
|
||||
|
||||
|
|
@ -164,16 +164,10 @@ export function mountActivity(target, { chat, openPlayer, backToBoard } = {}) {
|
|||
chatView?.refresh();
|
||||
}
|
||||
const lines = state.log.slice(-150);
|
||||
const key = JSON.stringify(lines);
|
||||
const key = nextIdentity + JSON.stringify(lines);
|
||||
if (key === journalKey) return;
|
||||
journalKey = key;
|
||||
journal.innerHTML =
|
||||
lines
|
||||
.map(
|
||||
(line) =>
|
||||
`<li><small>Round ${Number(line.round)}</small><span>${richText(line.text)}</span></li>`,
|
||||
)
|
||||
.join("") || '<li class="journal-empty">No moves yet.</li>';
|
||||
journal.innerHTML = journalHtml(lines, players);
|
||||
followJournal();
|
||||
},
|
||||
destroy() {
|
||||
|
|
|
|||
41
viewer/amoeba-traits.js
Normal file
41
viewer/amoeba-traits.js
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
// Small adaptations share the colony palette and leave the eyes, number badge,
|
||||
// injury badge and lower-left accessibility symbol readable.
|
||||
export function amoebaAdaptations(c, traits, body) {
|
||||
let behind = "",
|
||||
skin = "",
|
||||
front = "",
|
||||
mouth = "";
|
||||
if (traits.has("frill"))
|
||||
behind += `<path d="M24 23 13 17 16 31 3 30 11 43 1 50 15 57 9 70 26 67M75 22 87 15 85 31 98 30 91 44 100 51 87 58 94 71 77 68" fill="${c.light}" stroke="${c.stroke}" stroke-width="2.3" stroke-linejoin="round"/><path d="m14 27 11 7M10 48l12 1m-5 14 11-6m58-31-11 9m15 14-12 1m7 14-10-7" fill="none" stroke="${c.shade}" stroke-width="3" stroke-linecap="round"/>`;
|
||||
if (traits.has("movement2"))
|
||||
behind += `<path d="M27 65Q-2 57-5 30 9 32 14 43 1 25 7 13 28 21 33 48ZM74 61Q103 53 106 26 92 28 87 39 100 21 94 9 73 17 68 44Z" fill="${c.light}" stroke="${c.stroke}" stroke-width="2" stroke-linejoin="round"/><path d="M25 56Q14 33 10 20M22 57Q8 47 1 36M76 52Q87 29 91 16M79 53Q93 43 100 32" fill="none" stroke="${c.stroke}" stroke-width="1.6" stroke-linecap="round" opacity=".65"/>`;
|
||||
if (traits.has("sensing") || traits.has("sensing2")) {
|
||||
const advanced = traits.has("sensing2");
|
||||
behind += `<g fill="none" stroke="${c.stroke}" stroke-width="2.6" stroke-linecap="round"><path d="M30 28Q16 13 24 5M76 28Q91 17 86 7"/>${advanced ? '<path d="M15 4q-5 7 0 13m80-12q5 7 0 13" stroke="#7698a0" stroke-width="2"/>' : ""}</g><circle cx="24" cy="6" r="4.5" fill="${c.light}" stroke="${c.stroke}" stroke-width="2"/><circle cx="86" cy="8" r="4.5" fill="${advanced ? "#f3d279" : c.light}" stroke="${c.stroke}" stroke-width="2"/>`;
|
||||
}
|
||||
if (traits.has("toxic"))
|
||||
behind +=
|
||||
'<g fill="#b99dcb" stroke="#75548b" stroke-width="1.8"><circle cx="20" cy="69" r="6"/><circle cx="80" cy="71" r="6"/><circle cx="57" cy="80" r="5"/></g>';
|
||||
if (traits.has("crust"))
|
||||
skin += `<path d="${body}" fill="none" stroke="#8b7052" stroke-width="5" stroke-linejoin="round"/><path d="${body}" fill="none" stroke="#e5c997" stroke-width="3" stroke-dasharray="9 4" stroke-linejoin="round"/>`;
|
||||
if (traits.has("camouflage") || traits.has("camouflage2"))
|
||||
skin += `<g fill="${c.stroke}" opacity=".24"><path d="M22 30q12-9 14 1t-12 9q-10-2-2-10M65 20q12-2 11 9t-12 1q-7-6 1-10M72 59q11-10 13 1t-9 11q-12-3-4-12M29 62q11-7 15 3t-11 10q-12 0-4-13"/>${traits.has("camouflage2") ? '<path d="M42 20q8-5 13 1t-5 8q-10 0-8-9M52 69q11-6 13 2t-9 7q-9-2-4-9M18 46q8-6 10 2t-5 8q-9-2-5-10"/>' : ""}</g>`;
|
||||
if (traits.has("healing") || traits.has("healing2"))
|
||||
front += `<g transform="rotate(-15 76 64)"><rect x="65" y="57" width="22" height="15" rx="5" fill="#fff9df" stroke="#62886f" stroke-width="1.5"/><path d="M76 60v9m-4.5-4.5h9" stroke="#529981" stroke-width="3" stroke-linecap="round"/></g>${traits.has("healing2") ? '<path d="m91 49 1.5 3.5L96 54l-3.5 1.5L91 59l-1.5-3.5L86 54l3.5-1.5Z" fill="#f3d279" stroke="#a88a40" stroke-width="1"/>' : ""}`;
|
||||
if (traits.has("phd"))
|
||||
front +=
|
||||
'<path d="M34 15v10q17 8 34-1V14Z" fill="#456c70" stroke="#284a50" stroke-width="1.8"/><path d="m25 12 29-9 29 10-30 10Z" fill="#537e82" stroke="#284a50" stroke-width="1.8" stroke-linejoin="round"/><path d="m55 12 24 5v17m-2-3-1 7h6l-1-7" fill="#edcc78" stroke="#c09c4c" stroke-width="1.7" stroke-linecap="round"/>';
|
||||
if (traits.has("suction") || traits.has("suction2"))
|
||||
mouth = `<g fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M54 62q-10 18 9 17h9${traits.has("suction2") ? "m-8 0q-1 11 13 11" : ""}" stroke="${c.stroke}" stroke-width="9"/><path d="M54 62q-10 18 9 17h9${traits.has("suction2") ? "m-8 0q-1 11 13 11" : ""}" stroke="${c.light}" stroke-width="5"/></g><ellipse cx="75" cy="79" rx="4" ry="6" fill="${c.shade}" stroke="${c.stroke}" stroke-width="2"/>${traits.has("suction2") ? `<ellipse cx="80" cy="90" rx="4" ry="5" fill="${c.shade}" stroke="${c.stroke}" stroke-width="2"/>` : ""}`;
|
||||
else if (traits.has("hungry"))
|
||||
mouth = `<path d="M42 59q13 6 28-2-1 18-14 17-12 0-14-15Z" fill="#694c47" stroke="${c.stroke}" stroke-width="1.8"/><path d="M47 62q10 3 18-1l-1 5q-8 3-15 0Z" fill="#fff9df"/><path d="M51 71q7-6 13-1" fill="#dc9685"/>`;
|
||||
if (traits.has("bite")) {
|
||||
if (!mouth)
|
||||
mouth = `<path d="M43 60q13 9 27-2-2 15-13 14-10 0-14-12Z" fill="#694c47" stroke="${c.stroke}" stroke-width="1.8"/>`;
|
||||
const teethY = traits.has("suction") || traits.has("suction2") ? 60 : 63;
|
||||
front += `<path d="m45 ${teethY} 4 9 4-7m7-1 3 8 4-11" fill="#fff9df" stroke="${c.stroke}" stroke-width="1.2" stroke-linejoin="round"/>`;
|
||||
}
|
||||
if (traits.has("fierce"))
|
||||
front += `<path d="m32 25 16 5m13-1 17-7" fill="none" stroke="${c.stroke}" stroke-width="4" stroke-linecap="round"/>`;
|
||||
return { behind, skin, front, mouth };
|
||||
}
|
||||
|
|
@ -1,4 +1,20 @@
|
|||
import { amoebaAdaptations } from "./amoeba-traits.js";
|
||||
|
||||
const colors = {
|
||||
black: {
|
||||
body: "#7f8589",
|
||||
shade: "#505960",
|
||||
light: "#c7cdd0",
|
||||
stroke: "#303b43",
|
||||
cheek: "#70777e",
|
||||
},
|
||||
burgundy: {
|
||||
body: "#b479aa",
|
||||
shade: "#855076",
|
||||
light: "#ebc5e0",
|
||||
stroke: "#683b5b",
|
||||
cheek: "#ac6797",
|
||||
},
|
||||
green: {
|
||||
body: "#b7d967",
|
||||
shade: "#8cb74a",
|
||||
|
|
@ -29,6 +45,8 @@ const colors = {
|
|||
},
|
||||
};
|
||||
const iconPaths = {
|
||||
"colony-symbols":
|
||||
'<circle cx="6" cy="7" r="4"/><path d="m17 3 5 9H12Z"/><rect x="3" y="15" width="8" height="7" rx="1"/><path d="m18 15 4 4-4 4-4-4Z"/>',
|
||||
help: '<circle cx="12" cy="12" r="9"/><path d="M9.5 9a2.5 2.5 0 0 1 5 0c0 2-2.5 2-2.5 4m0 3v.1"/>',
|
||||
heart:
|
||||
'<path d="M12 20S3 15 3 8.5A4.5 4.5 0 0 1 12 7a4.5 4.5 0 0 1 9 1.5C21 15 12 20 12 20Z"/>',
|
||||
|
|
@ -45,6 +63,8 @@ const iconPaths = {
|
|||
wave: '<path d="M2 8q3-5 7 0t7 0 6 0M2 15q3-5 7 0t7 0 6 0"/>',
|
||||
arrow: '<path d="M4 12h16m-6-6 6 6-6 6"/>',
|
||||
sun: '<circle cx="12" cy="12" r="4"/><path d="M12 1v2m0 18v2M1 12h2m18 0h2M4 4l2 2m12 12 2 2M4 20l2-2M18 6l2-2"/>',
|
||||
ozone:
|
||||
'<circle cx="12" cy="7" r="3"/><path d="M12 1v1M5.5 2.5l1 1M2 7h2m16 0h2m-4.5-4.5-1 1M7 11l-1 1m11-1 1 1M2 16q2.5-2 5 0t5 0 5 0 5 0M2 21q2.5-2 5 0t5 0 5 0 5 0"/>',
|
||||
divide:
|
||||
'<path d="M11 5C4-2-3 14 5 19c4 3 5-3 7-3s3 6 7 3c8-5 1-21-6-14Z"/><circle cx="7" cy="11" r="2"/><circle cx="17" cy="11" r="2"/>',
|
||||
shield:
|
||||
|
|
@ -60,8 +80,27 @@ const iconPaths = {
|
|||
};
|
||||
const icon = (name) =>
|
||||
`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${iconPaths[name] || iconPaths.spark}</svg>`;
|
||||
export const PHASE_ICONS = [
|
||||
"wave",
|
||||
"ozone",
|
||||
"gene",
|
||||
"divide",
|
||||
"heart",
|
||||
"spark",
|
||||
];
|
||||
|
||||
let artId = 0;
|
||||
const colonySymbols = {
|
||||
green: '<circle cx="12" cy="12" r="9"/>',
|
||||
red: '<path d="m12 2 10 19H2Z"/>',
|
||||
blue: '<rect x="3" y="3" width="18" height="18" rx="1"/>',
|
||||
yellow: '<path d="m12 1 11 11-11 11L1 12Z"/>',
|
||||
black: '<path d="M8 2h8v6h6v8h-6v6H8v-6H2V8h6Z"/>',
|
||||
burgundy: '<path d="m12 1 3 7 8 1-6 6 2 8-7-4-7 4 2-8-6-6 8-1Z"/>',
|
||||
};
|
||||
export const colonySymbol = (color) =>
|
||||
`<svg class="colony-symbol" data-colony="${color}" viewBox="0 0 24 24" fill="${colors[color].light}" stroke="#24433a" stroke-width="2.5" stroke-linejoin="round" aria-hidden="true">${colonySymbols[color]}</svg>`;
|
||||
|
||||
function amoeba(color, variant = 0, feature = "") {
|
||||
const c = colors[color];
|
||||
const traits = new Set(Array.isArray(feature) ? feature : [feature]);
|
||||
|
|
@ -72,11 +111,14 @@ function amoeba(color, variant = 0, feature = "") {
|
|||
: variant % 3 === 1
|
||||
? "M18 47C5 34 16 22 29 27C24 10 42 6 49 20C56 5 73 14 70 25C88 16 98 30 84 40C103 49 94 63 81 63C90 80 72 87 61 73C58 90 38 89 34 73C19 84 7 74 18 61C5 63 5 48 18 47Z"
|
||||
: "M19 55C5 48 11 30 25 33C12 17 34 8 40 24C44 5 64 8 66 25C81 11 97 30 83 42C104 43 98 63 82 62C89 80 65 89 59 74C47 93 27 86 31 70C11 82 4 61 19 55Z";
|
||||
const adaptations = amoebaAdaptations(c, traits, body);
|
||||
return `<svg viewBox="0 0 100 100" overflow="visible" aria-hidden="true"><defs><radialGradient id="${id}" cx="40%" cy="24%" r="75%"><stop stop-color="${c.light}"/><stop offset=".48" stop-color="${c.body}"/><stop offset="1" stop-color="${c.shade}"/></radialGradient></defs>
|
||||
${adaptations.behind}
|
||||
${traits.has("movement") ? `<path d="M23 65Q-12 45 2 35Q17 40 23 53M77 60Q105 35 99 25Q84 31 77 43" fill="${c.body}" stroke="${c.stroke}" stroke-width="2"/>` : ""}
|
||||
${traits.has("spines") ? `<path d="M25 29 17 8 39 23M64 21 80 6 77 31M82 54 99 71 76 69M37 72 31 94 52 76M19 52 0 64 23 67" fill="${c.shade}" stroke="${c.stroke}" stroke-width="2" stroke-linejoin="round"/>` : ""}
|
||||
${traits.has("tentacle") ? `<g fill="none" stroke-linecap="round"><path d="M28 64C13 79 2 72 5 56s14-8 9-4M77 61c20 2 23 18 13 19s-10-7-5-7" stroke="${c.stroke}" stroke-width="8"/><path d="M28 64C13 79 2 72 5 56s14-8 9-4M77 61c20 2 23 18 13 19s-10-7-5-7" stroke="${c.body}" stroke-width="4.5"/></g>` : ""}
|
||||
<path d="${body}" fill="url(#${id})" stroke="${c.stroke}" stroke-width="2" stroke-linejoin="round"/>
|
||||
${adaptations.skin}
|
||||
<path d="M26 32q1-6 7-7M55 24q5-3 9 0" stroke="#fff" stroke-opacity=".65" stroke-width="4" fill="none" stroke-linecap="round"/>
|
||||
<ellipse cx="36" cy="64" rx="7" ry="5" fill="${c.cheek}" opacity=".6"/><ellipse cx="71" cy="60" rx="6" ry="4" fill="${c.cheek}" opacity=".55"/>
|
||||
<circle cx="29" cy="46" r="3" fill="${c.light}"/><circle cx="74" cy="38" r="2" fill="${c.shade}" opacity=".45"/><circle cx="47" cy="70" r="2" fill="${c.shade}" opacity=".7"/>
|
||||
|
|
@ -84,20 +126,37 @@ function amoeba(color, variant = 0, feature = "") {
|
|||
<g class="eyes"><ellipse cx="43" cy="41" rx="12" ry="14" fill="#fffef1" stroke="${c.stroke}" stroke-width="1.7"/><ellipse cx="65" cy="40" rx="12" ry="14.5" fill="#fffef1" stroke="${c.stroke}" stroke-width="1.7"/>
|
||||
<ellipse cx="${45 + (variant % 2)}" cy="44" rx="4.3" ry="6.2" fill="#24433a"/><ellipse cx="${65 + (variant % 2)}" cy="43" rx="4.3" ry="6.2" fill="#24433a"/><circle cx="44" cy="41" r="1.8" fill="white"/><circle cx="64" cy="40" r="1.8" fill="white"/></g>
|
||||
${traits.has("glasses") ? '<g fill="none" stroke="#425d48" stroke-width="2.7"><rect x="30" y="27" width="26" height="28" rx="9"/><rect x="54" y="26" width="26" height="28" rx="9"/><path d="m30 36-9-3m59 2 6-4"/></g>' : ""}
|
||||
<path d="M47 61q7 8 14-1" stroke="${c.stroke}" stroke-width="2" stroke-linecap="round" fill="none"/>
|
||||
${adaptations.mouth || `<path d="M47 61q7 8 14-1" stroke="${c.stroke}" stroke-width="2" stroke-linecap="round" fill="none"/>`}
|
||||
${traits.has("food") ? '<path d="M65 70q9-13 11-2q-1 12-11 2" fill="#ffd4a2" stroke="#86613c" stroke-width="1.5"/><rect x="68" y="68" width="9" height="8" rx="2" fill="#ed9785" stroke="#a46c54"/>' : ""}
|
||||
${traits.has("shield") || traits.has("armor") ? '<path d="m75 55 18 7v12q-5 10-18 15-12-5-15-15V62Z" fill="#dbe8e0" stroke="#4d7767" stroke-width="2"/><path d="m68 71 5 5 11-11" fill="none" stroke="#6b995b" stroke-width="3"/>' : ""}
|
||||
${adaptations.front}
|
||||
<g class="amoeba-symbol" transform="translate(9 62)"><rect x="-2" y="-2" width="29" height="29" rx="6" fill="#fffef1" stroke="#24433a" stroke-width="1.5"/>${colonySymbol(color).replace('viewBox="0 0 24 24"', 'width="25" height="25" viewBox="0 0 24 24"')}</g>
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
export function colonyTraits(genes) {
|
||||
const ids = new Set(genes.map((gene) => gene.id));
|
||||
const traits = [];
|
||||
if (ids.has("movement1") || ids.has("movement2")) traits.push("movement");
|
||||
if (ids.has("aggression")) traits.push("spines");
|
||||
if (ids.has("movement2")) traits.push("movement2");
|
||||
else if (ids.has("movement1")) traits.push("movement");
|
||||
if (ids.has("struggle") || ids.has("aggression")) traits.push("bite");
|
||||
if (ids.has("aggression")) traits.push("spines", "fierce");
|
||||
if (ids.has("tentacle")) traits.push("tentacle");
|
||||
if (ids.has("armor")) traits.push("armor");
|
||||
if (ids.has("intelligence")) traits.push("glasses");
|
||||
if (ids.has("intelligence") || ids.has("phd")) traits.push("glasses");
|
||||
if (ids.has("phd")) traits.push("phd");
|
||||
if (ids.has("hard-crust")) traits.push("crust");
|
||||
if (ids.has("camouflage2")) traits.push("camouflage2");
|
||||
else if (ids.has("camouflage1")) traits.push("camouflage");
|
||||
if (ids.has("environmental")) traits.push("sensing2");
|
||||
else if (ids.has("migration")) traits.push("sensing");
|
||||
if (ids.has("healing2")) traits.push("healing2");
|
||||
else if (ids.has("healing1")) traits.push("healing");
|
||||
if (ids.has("suction2")) traits.push("suction2");
|
||||
else if (ids.has("suction1")) traits.push("suction");
|
||||
if (ids.has("toxic")) traits.push("toxic");
|
||||
if (ids.has("threat")) traits.push("frill");
|
||||
if (ids.has("glutton")) traits.push("hungry");
|
||||
return traits;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,13 +1,40 @@
|
|||
import * as E from "../engine/index.js";
|
||||
import { chatSegments } from "@boardgamers/protocol/chat";
|
||||
import { prepared } from "./tutorials.js";
|
||||
import {
|
||||
COLOR_BLIND_PREFERENCE,
|
||||
readLocalColorBlindMode,
|
||||
saveLocalColorBlindMode,
|
||||
} from "./preferences.js";
|
||||
|
||||
export function mountChatPreview(nav) {
|
||||
let state = prepared({ round: 3 });
|
||||
state.log = [
|
||||
{ round: 2, phase: 0, text: "You #1 rolls 2 and 3." },
|
||||
{ round: 2, phase: 0, text: "You #1 chooses east." },
|
||||
{ round: 2, phase: 0, text: "You #1 moves to D2." },
|
||||
{ round: 2, phase: 0, text: "You #1 feeds." },
|
||||
{ round: 2, phase: 0, text: "You #1 excretes two green nutrients at D2." },
|
||||
{ round: 2, phase: 0, text: "Maya #2 moves to B4." },
|
||||
{ round: 2, phase: 1, text: "The current is west. Ozone layer: 12." },
|
||||
{ round: 2, phase: 2, text: "Leo evolves Movement II for 5 BP." },
|
||||
{ round: 3, phase: 0, text: "You #2 moves to B5." },
|
||||
{ round: 3, phase: 0, text: "You #2 feeds." },
|
||||
{ round: 3, phase: 0, text: "You #2 excretes two green nutrients at B5." },
|
||||
];
|
||||
let sequence = 0;
|
||||
let failNext = false;
|
||||
let spectator = false;
|
||||
const emitter = window.primordialSoup.launch("#game");
|
||||
emitter.on("update:preference", ({ name, value }) => {
|
||||
if (name === COLOR_BLIND_PREFERENCE.name) {
|
||||
saveLocalColorBlindMode(value === true);
|
||||
emitter.emit("preferences", { [name]: value === true });
|
||||
}
|
||||
});
|
||||
emitter.emit("preferences", {
|
||||
[COLOR_BLIND_PREFERENCE.name]: readLocalColorBlindMode(),
|
||||
});
|
||||
const people = state.players.map((p, i) => ({
|
||||
id: String(i),
|
||||
name: p.name,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { amoeba } from "./art.js";
|
||||
import { newGeneArt } from "./new-gene-art.js";
|
||||
|
||||
const creature = (
|
||||
const drawCreature = (
|
||||
x = 16,
|
||||
y = 8,
|
||||
size = 86,
|
||||
|
|
@ -19,7 +20,9 @@ const die = (x, y, dots) =>
|
|||
const arrows = (path, color = "#668f72") =>
|
||||
`<path d="${path}" fill="none" stroke="${color}" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>`;
|
||||
|
||||
export function geneArt(id) {
|
||||
export function geneArt(id, colonyColor = "green") {
|
||||
const creature = (x, y, size, variant, feature, color = colonyColor) =>
|
||||
drawCreature(x, y, size, variant, feature, color);
|
||||
let art;
|
||||
switch (id) {
|
||||
case "movement1":
|
||||
|
|
@ -38,7 +41,7 @@ export function geneArt(id) {
|
|||
break;
|
||||
case "movement2":
|
||||
art =
|
||||
creature(16, 4, 86, 1, "movement") +
|
||||
creature(16, 4, 86, 1, "movement2") +
|
||||
'<circle cx="89" cy="73" r="19" fill="#fffbed" stroke="#668f72" stroke-width="2"/>' +
|
||||
arrows(
|
||||
"M89 59v28m-14-14h28m-18-10 4-4 4 4m6 6 4 4-4 4m-14 6 4 4 4-4m-14-14-4 4 4 4",
|
||||
|
|
@ -119,7 +122,7 @@ export function geneArt(id) {
|
|||
case "holding":
|
||||
art =
|
||||
creature(0, 10, 79, 0) +
|
||||
creature(60, 24, 54, 1, "", "blue") +
|
||||
creature(60, 24, 54, 1, "", colonyColor === "blue" ? "red" : "blue") +
|
||||
'<g fill="none" stroke="#708d78" stroke-width="4"><rect x="49" y="71" width="19" height="12" rx="6" transform="rotate(-24 49 71)"/><rect x="61" y="69" width="19" height="12" rx="6" transform="rotate(-24 61 69)"/></g>';
|
||||
break;
|
||||
case "longevity":
|
||||
|
|
@ -135,13 +138,13 @@ export function geneArt(id) {
|
|||
break;
|
||||
case "struggle":
|
||||
art =
|
||||
creature(16, 6, 87, 2) +
|
||||
'<g fill="none" stroke="#899d8f" stroke-width="3" stroke-linecap="round"><path d="M15 50v40M8 38v12q7 8 14 0V38m-7 0v13M102 37v53m0-53q-15 12 0 24"/></g><path d="M53 63q8 10 17-1" fill="#835548" stroke="#56713f" stroke-width="1.5"/>';
|
||||
creature(16, 6, 87, 2, "bite") +
|
||||
'<g fill="none" stroke="#899d8f" stroke-width="3" stroke-linecap="round"><path d="M15 50v40M8 38v12q7 8 14 0V38m-7 0v13M102 37v53m0-53q-15 12 0 24"/></g>';
|
||||
break;
|
||||
case "parasitism":
|
||||
art =
|
||||
creature(0, 17, 75, 0) +
|
||||
creature(64, 29, 50, 1, "", "red") +
|
||||
creature(64, 29, 50, 1, "", colonyColor === "red" ? "blue" : "red") +
|
||||
'<path d="m46 64 11 8h20V49" fill="none" stroke="#b89862" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><circle cx="87" cy="25" r="12" fill="#efdb89" stroke="#ac9954" stroke-width="2"/><path d="M85 18h4m-3 0v6l-4 6h10l-4-6v-6" fill="none" stroke="#978847" stroke-width="1.6"/>';
|
||||
break;
|
||||
case "persistence":
|
||||
|
|
@ -153,11 +156,13 @@ export function geneArt(id) {
|
|||
break;
|
||||
case "aggression":
|
||||
art =
|
||||
creature(16, 4, 86, 0, "spines") +
|
||||
creature(16, 4, 86, 0, ["spines", "bite", "fierce"]) +
|
||||
'<path d="M24 48C4 38 0 59 8 68l15 2 8-11Z" fill="#de9380" stroke="#ab6f5c" stroke-width="2"/><path d="M94 47c20-10 24 11 16 20l-15 2-8-11Z" fill="#de9380" stroke="#ab6f5c" stroke-width="2"/><path d="m11 68 12 2m74-1 10-2" stroke="#f2c7a5" stroke-width="6"/>';
|
||||
break;
|
||||
default:
|
||||
art = creature();
|
||||
art =
|
||||
newGeneArt(id, { creature, cube, die, arrows }, colonyColor) ??
|
||||
creature();
|
||||
}
|
||||
return `<svg class="gene-illustration" viewBox="-6 -6 132 112" aria-hidden="true">${art}</svg>`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { GENES, GENE } from "../engine/catalog.js";
|
||||
import { ALL_GENES, GENE } from "../engine/catalog.js";
|
||||
import { NEW_GENES } from "../engine/new-genes.js";
|
||||
import { icon } from "./art.js";
|
||||
|
||||
const escape = (text) =>
|
||||
|
|
@ -30,13 +31,51 @@ const symbols = {
|
|||
parasitism: "bio",
|
||||
struggle: "attack",
|
||||
aggression: "attack",
|
||||
"doris-frank": "spark",
|
||||
glutton: "food",
|
||||
alarm: "shield",
|
||||
cleanliness: "grid",
|
||||
"hard-crust": "shield",
|
||||
migration: "sun",
|
||||
social: "bio",
|
||||
"fast-food": "arrow",
|
||||
adaptable: "swap",
|
||||
mouthful: "heart",
|
||||
camouflage1: "shield",
|
||||
camouflage2: "shield",
|
||||
suction1: "food",
|
||||
suction2: "food",
|
||||
threat: "attack",
|
||||
flexible: "bio",
|
||||
healing1: "heart",
|
||||
healing2: "heart",
|
||||
rebound: "undo",
|
||||
bang: "attack",
|
||||
"short-life": "divide",
|
||||
toxic: "sun",
|
||||
population: "divide",
|
||||
energy: "wave",
|
||||
phd: "spark",
|
||||
environmental: "sun",
|
||||
};
|
||||
const newGeneIds = new Set(NEW_GENES.map((g) => g.id));
|
||||
export const isNewGene = (id) => newGeneIds.has(id);
|
||||
export const newGeneMark = (id, labelled = false) =>
|
||||
isNewGene(id)
|
||||
? `<span class="${labelled ? "new-gene-badge" : "new-gene-star"}" title="New genes · Freshly Spiced" role="img" aria-label="New gene"><span aria-hidden="true">★</span>${labelled ? " New gene" : ""}</span>`
|
||||
: "";
|
||||
export const geneIcon = (id) => icon(symbols[id] ?? "spark");
|
||||
export function geneScoringMark(id) {
|
||||
const value = GENE[id].points;
|
||||
if (value === 1) return "";
|
||||
const label = `Counts as ${value} genes for scoring. Use this total in the gene row to calculate evolution points.`;
|
||||
return `<span class="gene-scoring-badge" role="img" tabindex="0" aria-label="${label}" title="${label}">${icon("gene")}<b>${value}</b></span>`;
|
||||
}
|
||||
export function geneLabel(id, name = GENE[id].name) {
|
||||
return `<span class="gene-label" title="Gene · ${escape(GENE[id].text)}">${geneIcon(id)}<span>${escape(name)}</span></span>`;
|
||||
return `<span class="gene-label" title="Gene · ${escape(GENE[id].text)}">${geneIcon(id)}<span>${escape(name)}</span>${newGeneMark(id)}</span>`;
|
||||
}
|
||||
|
||||
const byName = Object.fromEntries(GENES.map((g) => [g.name, g.id]));
|
||||
const byName = Object.fromEntries(ALL_GENES.map((g) => [escape(g.name), g.id]));
|
||||
byName.Struggle = "struggle";
|
||||
const pattern = new RegExp(
|
||||
`\\b(${Object.keys(byName)
|
||||
|
|
@ -45,5 +84,5 @@ const pattern = new RegExp(
|
|||
"g",
|
||||
);
|
||||
export function geneText(text) {
|
||||
return escape(text).replace(pattern, (name) => geneLabel(byName[name], name));
|
||||
return escape(text).replace(pattern, (name) => geneLabel(byName[name]));
|
||||
}
|
||||
|
|
|
|||
31
viewer/gene-pool.js
Normal file
31
viewer/gene-pool.js
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
// Only group cards already in the visible pool; unrevealed genes stay hidden.
|
||||
export function geneFamilies(genes) {
|
||||
const byId = new Map(genes.map((gene) => [gene.id, gene]));
|
||||
const upgrades = (id) => genes.filter((gene) => gene.base.includes(id));
|
||||
const seen = new Set();
|
||||
const families = [];
|
||||
for (const gene of genes) {
|
||||
if (seen.has(gene.id)) continue;
|
||||
const related = new Set();
|
||||
function collect(card) {
|
||||
if (!card || related.has(card.id)) return;
|
||||
related.add(card.id);
|
||||
card.base.forEach((id) => collect(byId.get(id)));
|
||||
upgrades(card.id).forEach(collect);
|
||||
}
|
||||
collect(gene);
|
||||
const family = [];
|
||||
function append(card) {
|
||||
if (seen.has(card.id)) return;
|
||||
seen.add(card.id);
|
||||
family.push(card);
|
||||
upgrades(card.id).forEach(append);
|
||||
}
|
||||
const members = genes.filter((card) => related.has(card.id));
|
||||
members
|
||||
.filter((card) => !card.base.some((id) => related.has(id)))
|
||||
.forEach(append);
|
||||
families.push(family);
|
||||
}
|
||||
return families;
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import { GENE } from "../engine/catalog.js";
|
||||
const summaries = {
|
||||
intelligence: "1 gene for scoring; no special ability.",
|
||||
movement1: "Swim: roll two dice and choose one.",
|
||||
|
|
@ -12,15 +13,16 @@ const summaries = {
|
|||
holding: "Stay instead of drifting, or follow another amoeba.",
|
||||
longevity: "Survive 2 injuries.",
|
||||
frugality: "Eat one fewer food cube.",
|
||||
struggle: "If starving, attack for 1 BP to feed.",
|
||||
struggle: "Phase 1: attack for 1 BP only when starving, to feed.",
|
||||
parasitism: "An opponent here pays 1 BP; eat one fewer cube.",
|
||||
division: "New amoebas cost 4 BP instead of 6 BP.",
|
||||
persistence: "Retry a failed attack or defense for free.",
|
||||
aggression: "One attack for 1 BP after natural deaths.",
|
||||
aggression:
|
||||
"Keeps starvation attacks. Adds one colony attack in phase 5 for 1 BP, even when fed.",
|
||||
armor: "Cannot be eaten; Aggression causes 1 injury.",
|
||||
};
|
||||
|
||||
export const geneSummary = (id, playerCount) =>
|
||||
id === "tentacle"
|
||||
? `Carry up to ${playerCount === 3 ? 2 : 3} food cubes when moving.`
|
||||
: summaries[id];
|
||||
: (summaries[id] ?? GENE[id]?.text);
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { stripSecret } from "../engine/index.js";
|
|||
import { chapters } from "./tutorials.js";
|
||||
import { richText } from "./rich-text.js";
|
||||
import { mountGame } from "./ui.js";
|
||||
import { COLOR_BLIND_PREFERENCE } from "./preferences.js";
|
||||
export async function mountLesson(target, options) {
|
||||
const chapter = chapters[options.chapter];
|
||||
if (!chapter) throw new Error("Unknown tutorial chapter.");
|
||||
|
|
@ -58,6 +59,8 @@ registerViewer(
|
|||
const ui = mountGame(ctx.target, {
|
||||
chat,
|
||||
onOpenPlayer: ctx.openPlayer,
|
||||
onColorBlindChange: (enabled) =>
|
||||
ctx.updatePreference(COLOR_BLIND_PREFERENCE.name, enabled),
|
||||
onMove: (m) =>
|
||||
new Promise((resolve, reject) => {
|
||||
pending = { resolve, reject };
|
||||
|
|
@ -76,6 +79,7 @@ registerViewer(
|
|||
chat,
|
||||
onPreferences(preferences) {
|
||||
ui.setAnalysisMode(preferences.analysis === true);
|
||||
ui.setColorBlind(preferences[COLOR_BLIND_PREFERENCE.name] === true);
|
||||
},
|
||||
onPlayer(player) {
|
||||
ui.setPlayer(player.index);
|
||||
|
|
|
|||
169
viewer/journal.js
Normal file
169
viewer/journal.js
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
import { DIRECTIONS, PHASES } from "../engine/catalog.js";
|
||||
import { amoeba, colors, icon, PHASE_ICONS } from "./art.js";
|
||||
import { richText } from "./rich-text.js";
|
||||
|
||||
const escape = (text) =>
|
||||
String(text).replace(
|
||||
/[&<>"']/g,
|
||||
(c) =>
|
||||
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[
|
||||
c
|
||||
],
|
||||
);
|
||||
const escapePattern = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
function coordinates(text) {
|
||||
return text
|
||||
.split(/(\b[A-E][1-5]\b)/)
|
||||
.map((part) =>
|
||||
/^[A-E][1-5]$/.test(part)
|
||||
? `<span class="journal-cell" title="Space ${part}">${part}</span>`
|
||||
: richText(part),
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
|
||||
export function playerReference(player, number) {
|
||||
const label = number ? `${player.name}, amoeba ${number}` : player.name;
|
||||
const portrait = `<span class="journal-portrait">${amoeba(player.color, Number(number) || 0)}${number ? `<b>${number}</b>` : ""}</span>`;
|
||||
return `<span class="${number ? "journal-amoeba" : "journal-player"}" title="${escape(label)}" ${number ? `role="img" tabindex="0" aria-label="${escape(label)}"` : ""}>${portrait}${number ? "" : `<strong>${escape(player.name)}</strong>`}</span>`;
|
||||
}
|
||||
|
||||
function textRenderer(players) {
|
||||
const byName = new Map(
|
||||
players.filter((p) => p.name && colors[p.color]).map((p) => [p.name, p]),
|
||||
);
|
||||
if (!byName.size) return coordinates;
|
||||
const names = [...byName.keys()]
|
||||
.sort((a, b) => b.length - a.length)
|
||||
.map(escapePattern)
|
||||
.join("|");
|
||||
const references = new RegExp(
|
||||
`(?<![\\p{L}\\p{N}_])(${names})(?: #([1-7])(?!\\d))?(?![\\p{L}\\p{N}_])`,
|
||||
"gu",
|
||||
);
|
||||
const placement = new RegExp(
|
||||
`^(${names}) places amoeba #([1-7]) at (.+)$`,
|
||||
"u",
|
||||
);
|
||||
return (text) => {
|
||||
const placed = text.match(placement);
|
||||
if (placed)
|
||||
return `${playerReference(byName.get(placed[1]), placed[2])} placed at ${coordinates(placed[3])}`;
|
||||
let result = "",
|
||||
offset = 0;
|
||||
for (const match of text.matchAll(references)) {
|
||||
result += coordinates(text.slice(offset, match.index));
|
||||
result += playerReference(byName.get(match[1]), match[2]);
|
||||
offset = match.index + match[0].length;
|
||||
}
|
||||
return result + coordinates(text.slice(offset));
|
||||
};
|
||||
}
|
||||
|
||||
function environmentEntry(line) {
|
||||
const match =
|
||||
line.phase === 1 &&
|
||||
line.text.match(
|
||||
/^The current is (west|north|east|south|still)\. Ozone layer: (\d+)\.$/,
|
||||
);
|
||||
if (!match) return;
|
||||
const direction = DIRECTIONS.findIndex((d) => d.toLowerCase() === match[1]);
|
||||
return `<div class="journal-environment" role="img" aria-label="Current ${match[1]}. Ozone layer ${match[2]}."><span class="journal-current"><span class="journal-current-arrow" aria-hidden="true" style="transform:rotate(${[180, 270, 0, 90, 0][direction]}deg)">${direction === 4 ? "·" : "➜"}</span><strong>${DIRECTIONS[direction]}</strong></span><span class="journal-ozone" title="Ozone layer ${match[2]} — protection from radiation">${icon("ozone")}<strong>${match[2]}</strong></span></div>`;
|
||||
}
|
||||
|
||||
function swimmingRoll(line, renderText) {
|
||||
const match = line.text.match(
|
||||
/^(.+ #[1-7]) rolls ([1-6])(?: and ([1-6]))?\.$/,
|
||||
);
|
||||
if (!match) return;
|
||||
const pips = [
|
||||
[],
|
||||
[[12, 12]],
|
||||
[
|
||||
[6, 6],
|
||||
[18, 18],
|
||||
],
|
||||
[
|
||||
[6, 6],
|
||||
[12, 12],
|
||||
[18, 18],
|
||||
],
|
||||
[
|
||||
[6, 6],
|
||||
[18, 6],
|
||||
[6, 18],
|
||||
[18, 18],
|
||||
],
|
||||
[
|
||||
[6, 6],
|
||||
[18, 6],
|
||||
[12, 12],
|
||||
[6, 18],
|
||||
[18, 18],
|
||||
],
|
||||
[
|
||||
[6, 6],
|
||||
[18, 6],
|
||||
[6, 12],
|
||||
[18, 12],
|
||||
[6, 18],
|
||||
[18, 18],
|
||||
],
|
||||
];
|
||||
const dice = match
|
||||
.slice(2)
|
||||
.filter(Boolean)
|
||||
.map((value) => {
|
||||
const direction = ["West", "North", "East", "South", "Stay", "Choose"][
|
||||
Number(value) - 1
|
||||
];
|
||||
return `<span class="journal-die" role="img" aria-label="Rolled ${value}: ${direction}" title="${value}: ${direction}"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="1" y="1" width="22" height="22" rx="4"/>${pips[Number(value)].map(([x, y]) => `<circle cx="${x}" cy="${y}" r="1.8"/>`).join("")}</svg><small>${direction}</small></span>`;
|
||||
})
|
||||
.join("");
|
||||
return `<span class="journal-text">${renderText(match[1])} rolls <span class="journal-dice">${dice}</span></span>`;
|
||||
}
|
||||
|
||||
function renderEntry(line, renderText) {
|
||||
return (
|
||||
environmentEntry(line) ??
|
||||
swimmingRoll(line, renderText) ??
|
||||
`<span class="journal-text">${renderText(line.text)}</span>`
|
||||
);
|
||||
}
|
||||
|
||||
export function journalEntryHtml(line, players) {
|
||||
return line ? renderEntry(line, textRenderer(players)) : "";
|
||||
}
|
||||
|
||||
export function journalHtml(lines, players) {
|
||||
if (!lines.length) return '<li class="journal-empty">No moves yet.</li>';
|
||||
const renderText = textRenderer(players);
|
||||
const groups = [];
|
||||
for (const line of lines) {
|
||||
let round = groups.at(-1);
|
||||
if (!round || round.number !== line.round) {
|
||||
round = { number: line.round, phases: [] };
|
||||
groups.push(round);
|
||||
}
|
||||
let group = round.phases.at(-1);
|
||||
if (!group || group.phase !== line.phase) {
|
||||
group = { phase: line.phase, lines: [] };
|
||||
round.phases.push(group);
|
||||
}
|
||||
group.lines.push(line);
|
||||
}
|
||||
return groups
|
||||
.map(({ number, phases }) => {
|
||||
return `<li class="journal-round-group"><h3 class="journal-round-divider">${number ? `Round ${Number(number)}` : "Setup"}</h3><ol>${phases
|
||||
.map(({ phase, lines }) => {
|
||||
const heading =
|
||||
typeof phase === "number" && PHASES[phase]
|
||||
? `<h4>${icon(PHASE_ICONS[phase])}${phase + 1} · ${escape(PHASES[phase])}</h4>`
|
||||
: "";
|
||||
return `<li class="journal-group">${heading}<ol>${lines.map((line) => `<li class="journal-event">${renderEntry(line, renderText)}</li>`).join("")}</ol></li>`;
|
||||
})
|
||||
.join("")}</ol></li>`;
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
250
viewer/new-gene-art.js
Normal file
250
viewer/new-gene-art.js
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
import { colors } from "./art.js";
|
||||
|
||||
const sparkle = (x, y, size = 7) =>
|
||||
`<path d="M${x} ${y - size}q1 ${size - 1} ${size} ${size}q-${size - 1} 1-${size} ${size}q-1-${size - 1}-${size}-${size}q${size - 1}-1 ${size}-${size}Z" fill="#fff8cd" stroke="#a0ad76" stroke-width="1.5"/>`;
|
||||
const flask = (x, y, size = 23, fill = "#a9ca80") =>
|
||||
`<svg x="${x}" y="${y}" width="${size}" height="${size}" viewBox="0 0 28 30" overflow="visible"><path d="M10 2h8m-6 0v10L5 24q-2 4 3 4h12q5 0 3-4l-7-12V2" fill="#fff9de" stroke="#6d8055" stroke-width="1.8" stroke-linejoin="round"/><path d="m9 19-3 6q0 1 3 1h10q3 0 3-1l-3-6Z" fill="${fill}"/><circle cx="12" cy="21" r="1.5" fill="#fffce8"/></svg>`;
|
||||
const patch = (x, y, angle = -20) =>
|
||||
`<g transform="translate(${x} ${y}) rotate(${angle} 13 6)"><rect width="26" height="13" rx="4" fill="#f1d2a0" stroke="#a58160" stroke-width="1.5"/><rect x="9" y="2" width="8" height="9" rx="2" fill="#fff8dd"/><path d="M4 4v1m1 3v1m17-5v1m-1 3v1" stroke="#b18f69" stroke-width="1.5" stroke-linecap="round"/></g>`;
|
||||
const leaf = (x, y, size = 25, angle = 0, color = "#a4c180") =>
|
||||
`<g transform="translate(${x} ${y}) rotate(${angle}) scale(${size / 25})"><path d="M0 22Q-6 1 22 0Q24 23 0 22Z" fill="${color}" stroke="#688360" stroke-width="1.7"/><path d="M-4 26 16 6m-11 11-1-8m1 8 9 0" stroke="#688360" stroke-width="1.4" fill="none" stroke-linecap="round"/></g>`;
|
||||
const tile = (x, y, width = 31, height = 30) =>
|
||||
`<rect x="${x}" y="${y}" width="${width}" height="${height}" rx="6" fill="#cce3d4" stroke="#91b2a0" stroke-width="1.6" stroke-dasharray="4 3"/>`;
|
||||
const forecast = (x, y, angle = 0, advanced = false) =>
|
||||
`<g transform="translate(${x} ${y}) rotate(${angle} 18 23)"><rect width="36" height="47" rx="6" fill="#fff8df" stroke="#9aaa7a" stroke-width="1.8"/><path d="M1 15h34" stroke="#d5dfb8"/><circle cx="12" cy="9" r="4" fill="#f1cf72"/><path d="m19 9h9" stroke="#a1bea4" stroke-width="2"/><path d="M8 33h20m-7-7 7 7-7 7" fill="none" stroke="#669b8c" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>${advanced ? '<path d="m28 3 1.2 3.8L33 8l-3.8 1.2L28 13l-1.2-3.8L23 8l3.8-1.2Z" fill="#d7ae57"/>' : ""}</g>`;
|
||||
const geneCard = (x, y, color, angle = 0) =>
|
||||
`<g transform="translate(${x} ${y}) rotate(${angle} 16 21)"><rect width="32" height="43" rx="5" fill="${color}" stroke="#748769" stroke-width="1.8"/><path d="M11 8c0 10 10 15 10 27M21 8c0 10-10 15-10 27m1-24h8m-6 8h4m-4 8h4m-6 6h8" fill="none" stroke="#617c58" stroke-width="1.8" stroke-linecap="round"/></g>`;
|
||||
|
||||
export function newGeneArt(id, { creature, cube, die, arrows }, colonyColor) {
|
||||
const c = colors[colonyColor];
|
||||
const other = colonyColor === "blue" ? "red" : "blue";
|
||||
const food = ["red", "blue", "yellow", "green"]
|
||||
.filter((color) => color !== colonyColor)
|
||||
.map((color) => colors[color].body);
|
||||
switch (id) {
|
||||
case "doris-frank":
|
||||
return (
|
||||
creature(0, 5, 65, 0, "glasses") +
|
||||
creature(56, 8, 63, 1, "", other) +
|
||||
'<path d="m19 65 68-2 18 28H6Z" fill="#d9bd8d" stroke="#967e59" stroke-width="2"/><path d="m25 70 56-1 9 17H17Z" fill="#f5e5b5" stroke="#b79d6b" stroke-width="1.5"/><path d="m30 71-3 14m16-15-1 15m14-15 2 15m12-15 5 15M22 77h63" stroke="#c9b07c"/>' +
|
||||
cube(29, 70, c.body, 9) +
|
||||
cube(67, 77, colors[other].body, 9) +
|
||||
die(90, 65, [
|
||||
[6, 6],
|
||||
[17, 17],
|
||||
])
|
||||
);
|
||||
case "glutton":
|
||||
return (
|
||||
creature(13, -2, 92, 2, "hungry") +
|
||||
'<ellipse cx="60" cy="85" rx="42" ry="12" fill="#fff8e0" stroke="#b4b187" stroke-width="2"/><ellipse cx="60" cy="85" rx="31" ry="7" fill="none" stroke="#dcd4b1"/>' +
|
||||
cube(28, 73, food[0], 14) +
|
||||
cube(46, 71, food[1], 14) +
|
||||
cube(65, 74, food[2], 14) +
|
||||
cube(54, 60, food[0], 14) +
|
||||
sparkle(99, 40)
|
||||
);
|
||||
case "alarm":
|
||||
return (
|
||||
creature(28, 22, 75, 1) +
|
||||
creature(1, 54, 36, 2, "movement", other) +
|
||||
'<g transform="rotate(-12 31 26)"><path d="M14 38q8-7 7-21 0-14 13-14t13 14q-1 14 7 21Z" fill="#eed187" stroke="#ac8a43" stroke-width="2"/><path d="M14 38h40M29 42q5 7 10 0M32 0h4" fill="none" stroke="#ac8a43" stroke-width="2.5" stroke-linecap="round"/><path d="M10 13q-6 10 0 17m49-17q6 10 0 17" fill="none" stroke="#c29562" stroke-width="2"/></g>' +
|
||||
arrows("M8 84H0m5-5-5 5 5 5", "#9aad8a")
|
||||
);
|
||||
case "cleanliness":
|
||||
return (
|
||||
tile(80, 59, 35, 34) +
|
||||
creature(9, 4, 81, 1) +
|
||||
'<path d="m55 76 21-40" stroke="#9d8058" stroke-width="5" stroke-linecap="round"/><path d="m43 82 14-15 13 7-4 22Z" fill="#e4c989" stroke="#a58a5c" stroke-width="1.8"/><path d="m52 78-5 10m10-7-3 11m8-8-2 9" stroke="#b39a65" stroke-width="1.4"/>' +
|
||||
cube(85, 76, c.body, 10) +
|
||||
cube(99, 70, c.body, 10) +
|
||||
arrows("M69 60q13-7 24 0m-5-5 5 5-5 4") +
|
||||
sparkle(15, 25) +
|
||||
sparkle(99, 29, 9)
|
||||
);
|
||||
case "hard-crust":
|
||||
return (
|
||||
creature(14, 3, 91, 2, "crust") +
|
||||
'<path d="m12 81 9-12 10 7 12-4 8 13-14 10-15-2Z" fill="#e0c592" stroke="#9d8059" stroke-width="2"/><path d="m21 71 6 12 13-8m-13 8 2 10m-2-10-12-1" fill="none" stroke="#b1976d" stroke-width="1.5"/>' +
|
||||
sparkle(98, 34)
|
||||
);
|
||||
case "migration":
|
||||
return (
|
||||
forecast(75, 6, 11) +
|
||||
creature(2, 14, 91, 1, "sensing") +
|
||||
arrows("M91 64q-3 15-17 20m8-1-8 1 3-7", "#82aab0")
|
||||
);
|
||||
case "social":
|
||||
return (
|
||||
'<path d="M28 34q31-27 64 0M19 55q-1 25 22 29m64-30q-2 22-25 29" fill="none" stroke="#adc49a" stroke-width="2" stroke-dasharray="5 4"/>' +
|
||||
creature(0, 12, 50, 0, "", other) +
|
||||
creature(
|
||||
76,
|
||||
10,
|
||||
47,
|
||||
1,
|
||||
"",
|
||||
colonyColor === "yellow" ? "green" : "yellow",
|
||||
) +
|
||||
creature(32, 40, 67, 2) +
|
||||
flask(32, 27, 21) +
|
||||
flask(71, 28, 21) +
|
||||
arrows("m38 52 9 6-1-8m32 3-9 6 1-8", "#9b9c66")
|
||||
);
|
||||
case "fast-food":
|
||||
return (
|
||||
arrows("M2 28h20M6 40h15", "#9bad8c") +
|
||||
creature(21, 0, 82, 1, ["food", "movement"]) +
|
||||
'<ellipse cx="26" cy="79" rx="23" ry="9" fill="#fff9e5" stroke="#b5b68c" stroke-width="1.8"/>' +
|
||||
cube(18, 66, food[0], 13) +
|
||||
arrows("M53 83h47m-8-8 8 8-8 8") +
|
||||
'<path d="m10 58 3-5m-1 0h5" fill="none" stroke="#c09c4c" stroke-width="2"/>'
|
||||
);
|
||||
case "adaptable":
|
||||
return (
|
||||
geneCard(8, 38, "#e9edca", -11) +
|
||||
geneCard(77, 35, "#d3e6d8", 12) +
|
||||
creature(35, 0, 55, 1) +
|
||||
arrows(
|
||||
"M27 24q26-17 56-2m-6-6 7 6-9 2M89 86q-25 15-52 2m6 6-7-6 9-3",
|
||||
"#829c83",
|
||||
) +
|
||||
sparkle(58, 66, 9)
|
||||
);
|
||||
case "mouthful":
|
||||
return (
|
||||
creature(0, 27, 49, 2, "hungry", other) +
|
||||
creature(34, 3, 91, 0, "hungry") +
|
||||
patch(74, 72, 18) +
|
||||
'<path d="M27 33q-5-9-10-1-2 7 10 14 12-11 8-16-4-5-8 3Z" fill="#e5a18e" stroke="#b47c6b" stroke-width="1.6"/>'
|
||||
);
|
||||
case "camouflage1":
|
||||
return (
|
||||
leaf(2, 32, 31, -20) +
|
||||
creature(14, 4, 86, 1, "camouflage") +
|
||||
leaf(92, 49, 26, 17) +
|
||||
leaf(18, 73, 25, -45) +
|
||||
die(85, 74, [
|
||||
[6, 6],
|
||||
[17, 6],
|
||||
[6, 17],
|
||||
[17, 17],
|
||||
])
|
||||
);
|
||||
case "camouflage2":
|
||||
return (
|
||||
leaf(1, 17, 34, -14) +
|
||||
leaf(81, 3, 32, 13) +
|
||||
creature(16, 5, 88, 1, "camouflage2") +
|
||||
leaf(14, 77, 27, -52) +
|
||||
leaf(85, 71, 31, 10) +
|
||||
'<path d="m72 88 5 5 10-12" fill="none" stroke="#648458" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>'
|
||||
);
|
||||
case "suction1":
|
||||
return (
|
||||
tile(82, 61, 33, 34) +
|
||||
creature(1, 0, 84, 0, "suction") +
|
||||
arrows("M66 71q12-17 29-4", "#91b4a6") +
|
||||
cube(88, 71, food[0], 14) +
|
||||
'<path d="M81 77h-6m6 7-5 2" stroke="#92aea1" stroke-width="1.8" stroke-linecap="round"/>'
|
||||
);
|
||||
case "suction2":
|
||||
return (
|
||||
tile(84, 58, 33, 39) +
|
||||
creature(0, 0, 83, 0, "suction2") +
|
||||
cube(86, 64, food[0], 12) +
|
||||
cube(100, 80, food[1], 12) +
|
||||
arrows("M74 61q10-13 24-7", "#91b4a6") +
|
||||
'<path d="m82 70-8 3m13 17-10-1" stroke="#92aea1" stroke-width="1.8" stroke-linecap="round"/>'
|
||||
);
|
||||
case "threat":
|
||||
return (
|
||||
creature(8, 0, 95, 2, "frill") +
|
||||
creature(84, 60, 36, 1, "", other) +
|
||||
arrows("M9 35 0 31m1 7-1-7 7-2M99 25l12-4m-7-4 8 4-3 7", "#b3946e")
|
||||
);
|
||||
case "flexible":
|
||||
return (
|
||||
'<path d="M13 68Q-7 5 54 17q71 10 40 69" fill="none" stroke="#a5b993" stroke-width="3" stroke-dasharray="5 4"/>' +
|
||||
'<g transform="translate(5 0) skewX(-10)">' +
|
||||
creature(25, 6, 80, 2) +
|
||||
"</g>" +
|
||||
'<g transform="rotate(13 90 77)"><path d="m70 61 35 0 11 17-11 17H70Z" fill="#f4e3ad" stroke="#b8a06b" stroke-width="1.8"/><circle cx="106" cy="78" r="2" fill="#b8a06b"/></g>' +
|
||||
flask(72, 64, 23) +
|
||||
'<path d="M96 78h8" stroke="#8b7854" stroke-width="2.5" stroke-linecap="round"/>'
|
||||
);
|
||||
case "healing1":
|
||||
return (
|
||||
creature(15, 2, 88, 0, "healing") +
|
||||
'<rect x="5" y="69" width="35" height="26" rx="6" fill="#eaf1d9" stroke="#799980" stroke-width="1.8"/><path d="M15 68v-5h13v5" fill="none" stroke="#799980" stroke-width="2"/><path d="M22 75v13m-6.5-6.5h13" stroke="#619b82" stroke-width="4" stroke-linecap="round"/>' +
|
||||
sparkle(100, 36)
|
||||
);
|
||||
case "healing2":
|
||||
return (
|
||||
creature(0, 1, 86, 0, "healing2") +
|
||||
creature(76, 44, 45, 1, "", other) +
|
||||
patch(88, 74, 15) +
|
||||
arrows("M67 24q25-3 34 14m-1-9 2 10-10-2", "#88a996") +
|
||||
sparkle(81, 15) +
|
||||
patch(47, 80, 0)
|
||||
);
|
||||
case "rebound":
|
||||
return (
|
||||
'<path d="M49 91q-9-16-5-27 1-16 12-14 17-8 18 11 12 21 2 30Z" fill="#c2caa5" stroke="#8ea17e" stroke-width="2"/><path d="m51 62 8-3m4 18 6 8" fill="none" stroke="#a5b491" stroke-width="3" stroke-linecap="round"/>' +
|
||||
creature(34, 0, 61, 1, "movement") +
|
||||
arrows("M7 85Q10 13 46 17m33 8q24 18 25 59m-7-6 7 8 7-8", "#75a69b")
|
||||
);
|
||||
case "bang":
|
||||
return (
|
||||
'<path d="m59 1 10 20 23-12-2 24 29 0-16 21 17 18-28 3 2 27-25-13-13 16-8-24-28 9 8-25L0 55l24-12-13-23 29 4Z" fill="#f2d78f" stroke="#c5a068" stroke-width="2" stroke-linejoin="round"/><path d="m55 18 10 20 23-7-5 20 19 16-22 3-10 20-15-14-20 6 3-22-16-7 22-12Z" fill="#edb287"/>' +
|
||||
creature(24, 14, 75, 2) +
|
||||
patch(89, 78, 26) +
|
||||
sparkle(16, 10, 6)
|
||||
);
|
||||
case "short-life":
|
||||
return (
|
||||
creature(0, 25, 73, 2) +
|
||||
'<path d="M77 16h28m-28 64h28M79 19c0 22 12 17 12 29S79 60 79 77m24-58c0 22-12 17-12 29s12 12 12 29" fill="#f6eed3" stroke="#9d956b" stroke-width="2.5" stroke-linecap="round"/><path d="m84 29 7 12 7-12m-16 45 9-17 9 17Z" fill="#e6c771"/><path d="M91 44v8" stroke="#d4b059" stroke-width="2"/>' +
|
||||
leaf(15, 4, 22, 30, "#d7c38c")
|
||||
);
|
||||
case "toxic":
|
||||
return (
|
||||
creature(14, 0, 88, 2, "toxic") +
|
||||
'<path d="M30 79q-19-5-21 5-4 13 27 9 15 14 37 1 32 7 35-4 0-13-23-10-28-13-55-1Z" fill="#b9a0cd" fill-opacity=".8" stroke="#8f72a2" stroke-width="1.8"/><g fill="#e3ccec" stroke="#9272a4" stroke-width="1.5"><circle cx="39" cy="80" r="5"/><circle cx="66" cy="88" r="4"/><circle cx="88" cy="77" r="6"/><circle cx="95" cy="62" r="3"/></g>'
|
||||
);
|
||||
case "population":
|
||||
return (
|
||||
creature(0, 8, 43, 0) +
|
||||
creature(77, 4, 44, 1) +
|
||||
creature(43, -2, 37, 2) +
|
||||
creature(1, 54, 46, 2) +
|
||||
creature(80, 53, 43, 0) +
|
||||
creature(24, 20, 78, 1) +
|
||||
arrows("M12 49v-9m-4 4 4-4 4 4M107 47v-9m-4 4 4-4 4 4", "#98ad7a")
|
||||
);
|
||||
case "energy":
|
||||
return (
|
||||
'<path d="M7 66q19 15 34 0t34 0 34 0M3 83q19 15 34 0t34 0 34 0" fill="none" stroke="#a1c8b9" stroke-width="3" stroke-linecap="round"/>' +
|
||||
'<g transform="rotate(-16 54 49)">' +
|
||||
creature(12, 1, 84, 2) +
|
||||
"</g>" +
|
||||
flask(89, 54, 29) +
|
||||
'<path d="M104 41v10m-5-5h10" stroke="#9ba969" stroke-width="2.2" stroke-linecap="round"/>' +
|
||||
leaf(5, 74, 22, -28)
|
||||
);
|
||||
case "phd":
|
||||
return (
|
||||
creature(14, 6, 91, 0, ["glasses", "phd"]) +
|
||||
'<g transform="rotate(-14 90 80)"><rect x="66" y="70" width="43" height="20" rx="5" fill="#fff3cf" stroke="#b4a078" stroke-width="1.6"/><path d="M73 71v17m29-16v16" stroke="#e0ce9d" stroke-width="2"/><path d="m87 72 0 18 4-3 4 3V72" fill="#dc9e88" stroke="#b87968" stroke-width="1"/></g>'
|
||||
);
|
||||
case "environmental":
|
||||
return (
|
||||
forecast(80, 6, 16, true) +
|
||||
forecast(66, 9, -8, true) +
|
||||
creature(0, 20, 90, 1, "sensing2") +
|
||||
sparkle(111, 64, 6)
|
||||
);
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
|
@ -2,7 +2,14 @@ import { CELLS } from "../engine/catalog.js";
|
|||
export function pondArt() {
|
||||
const shore =
|
||||
"M239 38 Q217 37 211 66 L211 347 Q211 365 193 365 L77 365 Q39 367 38 396 L38 443 Q35 475 76 479 L193 479 Q211 479 211 496 L211 563 Q211 604 250 605 L812 605 Q864 602 864 563 L864 184 Q864 148 821 147 L708 147 Q691 146 691 129 L691 70 Q691 37 649 37 Z";
|
||||
let s = `<defs><linearGradient id="soup-water" x1="0" x2=".8" y1="0" y2="1"><stop stop-color="#bee8cc"/><stop offset=".6" stop-color="#9fd7c0"/><stop offset="1" stop-color="#81baa4"/></linearGradient><pattern id="soup-speckle" width="31" height="29" patternUnits="userSpaceOnUse"><circle cx="4" cy="8" r=".65" fill="#3c8875" opacity=".17"/><circle cx="23" cy="22" r=".7" fill="#fff" opacity=".3"/></pattern><clipPath id="soup-pond-clip"><path d="${shore}"/></clipPath></defs><path d="${shore}" fill="#d8e5b9" stroke="#bed0aa" stroke-width="20" stroke-linejoin="round"/><path d="${shore}" fill="url(#soup-water)" stroke="#739d7c" stroke-width="2"/><g clip-path="url(#soup-pond-clip)"><rect width="900" height="650" fill="url(#soup-speckle)"/><g class="grid-lines" fill="none" stroke="#e5f5da" stroke-width="1.3" stroke-opacity=".6">`;
|
||||
let s = `<defs><linearGradient id="soup-water" x1="0" x2=".8" y1="0" y2="1"><stop stop-color="#bee8cc"/><stop offset=".6" stop-color="#9fd7c0"/><stop offset="1" stop-color="#81baa4"/></linearGradient><radialGradient id="soup-light"><stop stop-color="#f4ffe9" stop-opacity=".65"/><stop offset=".45" stop-color="#f4ffe9" stop-opacity=".3"/><stop offset="1" stop-color="#f4ffe9" stop-opacity="0"/></radialGradient><pattern id="soup-speckle" width="31" height="29" patternUnits="userSpaceOnUse"><circle cx="4" cy="8" r=".65" fill="#3c8875" opacity=".17"/><circle cx="23" cy="22" r=".7" fill="#fff" opacity=".3"/></pattern><clipPath id="soup-pond-clip"><path d="${shore}"/></clipPath></defs><path d="${shore}" fill="#d8e5b9" stroke="#bed0aa" stroke-width="20" stroke-linejoin="round"/><path d="${shore}" fill="url(#soup-water)" stroke="#739d7c" stroke-width="2"/><g clip-path="url(#soup-pond-clip)"><rect width="900" height="650" fill="url(#soup-speckle)"/>`;
|
||||
for (let n = 0; n < 14; n++) {
|
||||
const x = 100 + ((n * 193) % 730),
|
||||
y = 90 + ((n * 127) % 470);
|
||||
s += `<g transform="translate(${x} ${y})"><g class="pond-flow" style="--delay:-${n * 1.7}s;--flow-duration:${18 + (n % 4) * 2}s"><ellipse class="pond-light" rx="${70 + (n % 3) * 12}" ry="32" fill="url(#soup-light)"/></g></g>`;
|
||||
}
|
||||
s +=
|
||||
'<g class="grid-lines" fill="none" stroke="#e5f5da" stroke-width="1.3" stroke-opacity=".6">';
|
||||
for (const cell of CELLS) {
|
||||
const x = 60 + (cell % 5) * 156,
|
||||
y = 55 + Math.floor(cell / 5) * 105;
|
||||
|
|
@ -10,7 +17,7 @@ export function pondArt() {
|
|||
}
|
||||
s += "</g>";
|
||||
for (let n = 0; n < 38; n++)
|
||||
s += `<circle class="pond-bubble" cx="${65 + ((n * 173) % 780)}" cy="${53 + ((n * 83) % 535)}" r="${2 + (n % 4)}" fill="none" stroke="#ecffe5" stroke-width="1.2" style="--delay:-${n % 8}s"/>`;
|
||||
s += `<circle class="pond-bubble" cx="${65 + ((n * 173) % 780)}" cy="${53 + ((n * 83) % 535)}" r="${2 + (n % 4)}" fill="none" stroke="#ecffe5" stroke-width="1.2" style="--delay:-${n * 1.3}s;--flow-duration:${16 + (n % 5) * 2}s"/>`;
|
||||
s +=
|
||||
'</g><path d="M381 273Q396 263 413 271Q441 260 461 271Q500 266 515 284Q530 301 520 328Q525 359 492 363Q463 374 442 365Q412 373 389 356Q368 340 376 319Q366 291 381 273Z" fill="#dce7c4" stroke="#99b69a" stroke-width="2"/>';
|
||||
for (const [x, y, r] of [
|
||||
|
|
|
|||
22
viewer/preferences.js
Normal file
22
viewer/preferences.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
export const COLOR_BLIND_PREFERENCE = {
|
||||
name: "colorBlind",
|
||||
label: "Color-blind mode",
|
||||
type: "checkbox",
|
||||
default: false,
|
||||
};
|
||||
|
||||
const localKey = "primordial-soup-colony-symbols";
|
||||
|
||||
export function readLocalColorBlindMode() {
|
||||
try {
|
||||
return localStorage.getItem(localKey) === "true";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveLocalColorBlindMode(enabled) {
|
||||
try {
|
||||
localStorage.setItem(localKey, String(enabled));
|
||||
} catch {}
|
||||
}
|
||||
|
|
@ -1,23 +1,29 @@
|
|||
import "./style.css";
|
||||
import * as E from "../engine/index.js";
|
||||
import { NEW_GENES } from "../engine/new-genes.js";
|
||||
import { mountGame } from "./ui.js";
|
||||
import { chapterMetadata, prepared } from "./tutorials.js";
|
||||
import { mountLesson } from "./index.js";
|
||||
import { mountChatPreview } from "./chat-preview.js";
|
||||
const params = new URLSearchParams(location.search),
|
||||
chapter = params.get("chapter"),
|
||||
newGenes = params.get("newGenes") === "1",
|
||||
appearance = params.get("appearance") === "genes",
|
||||
waterPreview = params.get("appearance") === "water",
|
||||
chatPreview = params.has("chat"),
|
||||
target = document.querySelector("#game"),
|
||||
nav = document.querySelector("#preview-nav");
|
||||
nav.className = "practice-nav";
|
||||
nav.innerHTML = `<span>Local preview</span><a href="/">Practice game</a><a href="/?appearance=genes">Gene appearances</a><label>Learn <select aria-label="Tutorial chapter"><option value="">Choose a chapter</option>${chapterMetadata.map((c) => `<option value="${c.id}" ${c.id === chapter ? "selected" : ""}>${c.title}</option>`).join("")}</select></label>${chapter || appearance ? "" : '<button id="new-three">New 3-colony game</button><button id="new-four">New 4-colony game</button>'}`;
|
||||
nav.innerHTML = `<span>Local preview</span><a href="/">Practice game</a><a href="/?appearance=genes">Gene appearances</a><a href="/?appearance=water">Water styles</a><label>Learn <select aria-label="Tutorial chapter"><option value="">Choose a chapter</option>${chapterMetadata.map((c) => `<option value="${c.id}" ${c.id === chapter ? "selected" : ""}>${c.title}</option>`).join("")}</select></label>${chapter || appearance || waterPreview ? "" : `<label><input id="new-genes" type="checkbox" ${newGenes ? "checked" : ""}> New genes</label><button id="new-three">New 3-colony game</button><button id="new-four">New 4-colony game</button><button id="new-five">New 5-colony game</button><button id="new-six">New 6-colony game</button>`}`;
|
||||
nav.querySelector("select").addEventListener("change", (e) => {
|
||||
location.href = e.target.value ? `/?chapter=${e.target.value}` : "/";
|
||||
});
|
||||
if (chatPreview) {
|
||||
if (waterPreview) {
|
||||
const { mountWaterPreview } = await import("./water-preview.js");
|
||||
mountWaterPreview(target, params);
|
||||
} else if (chatPreview) {
|
||||
nav
|
||||
.querySelectorAll("#new-three, #new-four")
|
||||
.querySelectorAll("#new-three, #new-four, #new-five, #new-six")
|
||||
.forEach((button) => button.remove());
|
||||
mountChatPreview(nav);
|
||||
} else if (chapter) {
|
||||
|
|
@ -37,12 +43,31 @@ if (chatPreview) {
|
|||
});
|
||||
} else if (appearance) {
|
||||
const state = prepared({ round: 3 });
|
||||
const genes = [
|
||||
["armor", "movement2", "tentacle", "intelligence"],
|
||||
["movement1", "intelligence"],
|
||||
["tentacle", "frugality"],
|
||||
["aggression", "ray"],
|
||||
];
|
||||
nav.insertAdjacentHTML(
|
||||
"beforeend",
|
||||
`<a href="/?appearance=genes${newGenes ? "" : "&newGenes=1"}">${newGenes ? "Standard gene appearances" : "New gene appearances"}</a>`,
|
||||
);
|
||||
if (newGenes) {
|
||||
state.options.newGenes = true;
|
||||
state.newGeneMarket = {
|
||||
available: NEW_GENES.map((gene) => gene.id),
|
||||
_deck: [],
|
||||
revealedRound: state.round,
|
||||
};
|
||||
}
|
||||
const genes = newGenes
|
||||
? [
|
||||
["phd", "healing1", "migration"],
|
||||
["camouflage2", "hard-crust"],
|
||||
["suction2", "toxic"],
|
||||
["threat", "glutton", "movement1"],
|
||||
]
|
||||
: [
|
||||
["armor", "movement2", "tentacle", "intelligence"],
|
||||
["movement1", "intelligence"],
|
||||
["tentacle", "frugality", "struggle"],
|
||||
["aggression", "ray"],
|
||||
];
|
||||
state.players.forEach((p, i) => {
|
||||
p.genes = genes[i].map((id) => ({ id, round: 1 }));
|
||||
});
|
||||
|
|
@ -63,15 +88,25 @@ if (chatPreview) {
|
|||
const ui = mountGame(target);
|
||||
ui.setPlayer(0);
|
||||
ui.setEnabled(false);
|
||||
ui.render(E.stripSecret(state));
|
||||
ui.render(E.stripSecret(state, 0));
|
||||
} else {
|
||||
const requestedPlayers = Number(params.get("players"));
|
||||
const playerCount = [3, 4, 5, 6].includes(requestedPlayers)
|
||||
? requestedPlayers
|
||||
: 3;
|
||||
const baseSaveKey = params.has("players")
|
||||
? `soup:practice:1:${playerCount}`
|
||||
: "soup:practice:1";
|
||||
const saveKey = baseSaveKey + (newGenes ? ":newGenes" : "");
|
||||
let state;
|
||||
try {
|
||||
state = JSON.parse(localStorage.getItem("soup:practice:1"));
|
||||
state = JSON.parse(localStorage.getItem(saveKey));
|
||||
} catch {}
|
||||
if (!state || state.version !== 1)
|
||||
state = E.init(3, [], {}, "practice-" + Date.now());
|
||||
state.players.forEach((p, i) => (p.name = ["You", "Maya", "Leo", "Nina"][i]));
|
||||
state = E.init(playerCount, [], { newGenes }, "practice-" + Date.now());
|
||||
state.players.forEach(
|
||||
(p, i) => (p.name = ["You", "Maya", "Leo", "Nina", "Sam", "Alex"][i]),
|
||||
);
|
||||
const ui = mountGame(target, {
|
||||
onMove: async (m) => {
|
||||
state = E.move(state, m, 0);
|
||||
|
|
@ -81,9 +116,9 @@ if (chatPreview) {
|
|||
});
|
||||
ui.setPlayer(0);
|
||||
const draw = () => {
|
||||
ui.render(E.stripSecret(state));
|
||||
ui.render(E.stripSecret(state, 0));
|
||||
try {
|
||||
localStorage.setItem("soup:practice:1", JSON.stringify(state));
|
||||
localStorage.setItem(saveKey, JSON.stringify(state));
|
||||
} catch {}
|
||||
};
|
||||
async function bots() {
|
||||
|
|
@ -94,15 +129,18 @@ if (chatPreview) {
|
|||
draw();
|
||||
}
|
||||
}
|
||||
for (const count of [3, 4])
|
||||
for (const count of [3, 4, 5, 6])
|
||||
nav
|
||||
.querySelector(count === 3 ? "#new-three" : "#new-four")
|
||||
.querySelector(`#new-${["three", "four", "five", "six"][count - 3]}`)
|
||||
.addEventListener("click", () => {
|
||||
const enabled = nav.querySelector("#new-genes").checked;
|
||||
localStorage.setItem(
|
||||
"soup:practice:1",
|
||||
JSON.stringify(E.init(count, [], {}, "practice-" + Date.now())),
|
||||
`soup:practice:1:${count}${enabled ? ":newGenes" : ""}`,
|
||||
JSON.stringify(
|
||||
E.init(count, [], { newGenes: enabled }, "practice-" + Date.now()),
|
||||
),
|
||||
);
|
||||
location.reload();
|
||||
location.href = `/?players=${count}${enabled ? "&newGenes=1" : ""}`;
|
||||
});
|
||||
draw();
|
||||
await bots();
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { COLORS, COLOR_NAMES } from "../engine/catalog.js";
|
||||
import { icon } from "./art.js";
|
||||
import { icon, colonySymbol } from "./art.js";
|
||||
import { geneText } from "./gene-label.js";
|
||||
|
||||
export const food = (p, n = 1) => {
|
||||
const label =
|
||||
`${n ?? ""} ${COLOR_NAMES[p].toLowerCase()} nutrient${n === 1 ? "" : "s"}`.trim();
|
||||
return `<span class="food-amount" role="img" aria-label="${label}" title="${label}"><span class="food ${COLORS[p]}" aria-hidden="true"></span>${n === null ? "" : `<span>${n}</span>`}</span>`;
|
||||
return `<span class="food-amount" role="img" aria-label="${label}" title="${label}"><span class="food ${COLORS[p]}" aria-hidden="true">${colonySymbol(COLORS[p])}</span>${n === null ? "" : `<span>${n}</span>`}</span>`;
|
||||
};
|
||||
const amount = (kind, n, label, symbol) =>
|
||||
`<span class="resource-amount ${kind}-amount" role="img" aria-label="${label}" title="${label}">${icon(symbol)}<span>${n}</span></span>`;
|
||||
|
|
@ -36,11 +36,21 @@ const numbers = {
|
|||
eight: 8,
|
||||
nine: 9,
|
||||
ten: 10,
|
||||
eleven: 11,
|
||||
};
|
||||
const quantity = `(?:[−-]?\\d+|${Object.keys(numbers).join("|")})`;
|
||||
const colours = { green: 0, coral: 1, red: 1, blue: 2, gold: 3, yellow: 3 };
|
||||
const colours = {
|
||||
green: 0,
|
||||
coral: 1,
|
||||
red: 1,
|
||||
blue: 2,
|
||||
gold: 3,
|
||||
yellow: 3,
|
||||
black: 4,
|
||||
burgundy: 5,
|
||||
};
|
||||
const resource = new RegExp(
|
||||
`(?<!\\w)(?:(?<foodCount>${quantity}) (?<colour>green|coral|red|blue|gold|yellow) (?:nutrients?|(?:food )?cubes?|ones?)|(?<bp>${quantity}) BP|(?<injury>${quantity}) injur(?:y|ies)|(?<evolution>${quantity}) (?:evolution points?|EP)|(?<mutation>${quantity}) mutation(?: sensitivity)?)\\b`,
|
||||
`(?<!\\w)(?:(?<foodCount>${quantity}) (?<colour>green|coral|red|blue|gold|yellow|black|burgundy) (?:nutrients?|(?:food )?cubes?|ones?)|(?<bp>${quantity}) BP|(?<injury>${quantity}) injur(?:y|ies)|(?<evolution>${quantity}) (?:evolution points?|EP)|(?<mutation>${quantity}) mutation(?: sensitivity)?)\\b`,
|
||||
"gi",
|
||||
);
|
||||
const count = (value) =>
|
||||
|
|
|
|||
|
|
@ -1,23 +1,55 @@
|
|||
import { populationPoints, genePoints } from "../engine/catalog.js";
|
||||
import { amoeba, icon } from "./art.js";
|
||||
import { amoeba, colors, colonySymbol, icon } from "./art.js";
|
||||
import { evolutionPoints } from "./rich-text.js";
|
||||
|
||||
const counts = [2, 3, 4, 5, 6, 7];
|
||||
const bucket = (n) => Math.max(2, Math.min(7, n));
|
||||
const escape = (text) =>
|
||||
String(text).replace(
|
||||
/[&<>"']/g,
|
||||
(c) =>
|
||||
({
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
})[c],
|
||||
);
|
||||
|
||||
export function scoringLegend(population, genes, color, expandable = true) {
|
||||
const row = (label, symbol, current, points) =>
|
||||
`<tr><th scope="row" title="${label}" aria-label="${label}">${symbol}</th>${counts
|
||||
export function scoringLegend(
|
||||
population,
|
||||
genes,
|
||||
color,
|
||||
expandable = true,
|
||||
players = 4,
|
||||
colonies = [],
|
||||
) {
|
||||
const counts = players >= 5 ? [1, 2, 3, 4, 5, 6] : [2, 3, 4, 5, 6, 7];
|
||||
const bucket = (n) => Math.max(counts[0], Math.min(counts.at(-1), n));
|
||||
const populationScoreFor = (n) => populationPoints(n, players);
|
||||
const markers = (n, field, points) =>
|
||||
`<span class="scoring-markers">${colonies
|
||||
.filter((player) => bucket(player[field]) === n)
|
||||
.map((player) => {
|
||||
const count = player[field];
|
||||
const label = `${player.name}: ${count} ${field === "population" ? "living amoebas" : "genes for scoring"} → ${points(count)} evolution points`;
|
||||
return `<span class="scoring-marker" role="img" tabindex="0" title="${escape(label)}" aria-label="${escape(label)}" style="--marker-color:${colors[player.color].body};--marker-border:${colors[player.color].stroke}">${colonySymbol(player.color)}</span>`;
|
||||
})
|
||||
.join("")}</span>`;
|
||||
const row = (label, symbol, current, points, field) =>
|
||||
`<tr data-scoring="${field}"><th scope="row" title="${label}" aria-label="${label}">${symbol}</th>${counts
|
||||
.map(
|
||||
(n) =>
|
||||
`<td${bucket(current) === n ? ' class="current"' : ""}>${points(n)}</td>`,
|
||||
`<td data-count="${n}"${bucket(current) === n ? ' class="current"' : ""}><span class="scoring-points">${points(n)}</span>${colonies.length ? markers(n, field, points) : ""}</td>`,
|
||||
)
|
||||
.join("")}</tr>`;
|
||||
const populationScore = populationPoints(population);
|
||||
const populationScore = populationScoreFor(population);
|
||||
const geneScore = genePoints(genes);
|
||||
return `<table class="scoring-table"><caption>${expandable ? `<button class="scoring-help" data-ui="scoring" aria-label="Show scoring reference">${icon("spark")} Each round</button>` : `${icon("spark")} Each round`}</caption><thead><tr><th scope="col" aria-label="Number owned">#</th>${counts
|
||||
.map((n) => `<th scope="col">${n === 2 ? "≤2" : n === 7 ? "7+" : n}</th>`)
|
||||
return `<table class="scoring-table" style="--scoring-current:${colors[color].light}"><caption>${expandable ? `<button class="scoring-help" data-ui="scoring" aria-label="Show scoring reference">${icon("spark")} Each round</button>` : `${icon("spark")} Each round`}</caption><thead><tr><th scope="col" aria-label="Number owned">#</th>${counts
|
||||
.map(
|
||||
(n) =>
|
||||
`<th scope="col">${n === counts[0] ? `≤${n}` : n === counts.at(-1) ? `${n}+` : n}</th>`,
|
||||
)
|
||||
.join(
|
||||
"",
|
||||
)}</tr></thead><tbody>${row("Living amoebas", amoeba(color), population, populationPoints)}${row("Genes used for scoring", icon("gene"), genes, genePoints)}</tbody></table><div class="scoring-total" title="Population points + gene points = total for this colony">${populationScore} + ${geneScore} = ${evolutionPoints(populationScore + geneScore)}</div><small class="scoring-finish">Game ends at ${evolutionPoints(42)}.</small>`;
|
||||
)}</tr></thead><tbody>${row("Living amoebas", amoeba(color), population, populationScoreFor, "population")}${row("Genes used for scoring", icon("gene"), genes, genePoints, "genes")}</tbody></table><div class="scoring-total" title="Population points + gene points = total for this colony">${populationScore} + ${geneScore} = ${evolutionPoints(populationScore + geneScore)}</div>`;
|
||||
}
|
||||
|
|
|
|||
1119
viewer/style.css
1119
viewer/style.css
File diff suppressed because it is too large
Load diff
|
|
@ -1,4 +1,5 @@
|
|||
import * as E from "../engine/index.js";
|
||||
import { commitPending } from "../engine/undo.js";
|
||||
export const chapterMetadata = [
|
||||
{
|
||||
id: "drift",
|
||||
|
|
@ -125,7 +126,8 @@ const only =
|
|||
types.includes(m.type)
|
||||
? undefined
|
||||
: "Try the action described in this step first.";
|
||||
const move = (s, m) => E.move(s, m, 0);
|
||||
// A lesson advances its guide after each action; earlier steps cannot be undone.
|
||||
const move = (s, m) => commitPending(E.move(s, m, 0));
|
||||
const config = (
|
||||
id,
|
||||
initialState,
|
||||
|
|
|
|||
347
viewer/ui.js
347
viewer/ui.js
|
|
@ -1,25 +1,39 @@
|
|||
import {
|
||||
COLORS,
|
||||
ENVIRONMENTS,
|
||||
COLOR_NAMES,
|
||||
CELLS,
|
||||
GENES,
|
||||
copiesOf,
|
||||
GENE,
|
||||
DIRECTIONS,
|
||||
PHASES,
|
||||
coordinate,
|
||||
geneFor,
|
||||
amoebaLimit,
|
||||
roundIncome,
|
||||
} from "../engine/catalog.js";
|
||||
import {
|
||||
colony,
|
||||
genesInGame,
|
||||
genePurchaseCost,
|
||||
mutation,
|
||||
evolution,
|
||||
geneCount,
|
||||
divisionCost,
|
||||
amoeba as findAmoeba,
|
||||
} from "../engine/index.js";
|
||||
import { amoeba, icon, colors, colonyTraits } from "./art.js";
|
||||
import { amoeba, icon, colors, colonyTraits, PHASE_ICONS } from "./art.js";
|
||||
import { geneArt } from "./gene-art.js";
|
||||
import { geneSummary } from "./gene-summary.js";
|
||||
import { geneFamilies } from "./gene-pool.js";
|
||||
import { scoringLegend } from "./scoring-legend.js";
|
||||
import { geneIcon, geneLabel } from "./gene-label.js";
|
||||
import {
|
||||
geneIcon,
|
||||
geneLabel,
|
||||
geneScoringMark,
|
||||
isNewGene,
|
||||
newGeneMark,
|
||||
} from "./gene-label.js";
|
||||
import {
|
||||
richText,
|
||||
food,
|
||||
|
|
@ -29,8 +43,13 @@ import {
|
|||
evolutionPoints,
|
||||
} from "./rich-text.js";
|
||||
import { mountActivity } from "./activity.js";
|
||||
import { journalEntryHtml, playerReference } from "./journal.js";
|
||||
import { pondArt } from "./pond.js";
|
||||
import { viewerState } from "./state.js";
|
||||
import {
|
||||
readLocalColorBlindMode,
|
||||
saveLocalColorBlindMode,
|
||||
} from "./preferences.js";
|
||||
export const RULES_URL =
|
||||
"https://s3.fr-par.scw.cloud/bgs-assets/assets/primordial-soup/rules-en/69e877694adc4a15/rules-en.pdf";
|
||||
export const SIMPLE_RULES_URL =
|
||||
|
|
@ -43,8 +62,19 @@ export const esc = (x) =>
|
|||
c
|
||||
],
|
||||
);
|
||||
const OZONE_HELP =
|
||||
"Ozone layer: protection from radiation. In phase 2, sensitivity above this limit must be covered by paying BP or discarding genes.";
|
||||
const SENSITIVITY_HELP =
|
||||
"Sensitivity: add up the values of your genes and compare the total with the ozone layer. Negative values reduce your total.";
|
||||
const ROUND_LIMIT = ENVIRONMENTS.length - 1;
|
||||
const nutrients = (vector) =>
|
||||
vector.map((n, p) => (n ? food(p, n) : "")).join("");
|
||||
const placementCost = (state) =>
|
||||
state.tasks[0]?.kind === "setup-place" || state.tasks[0]?.target !== undefined
|
||||
? 0
|
||||
: divisionCost(state, state.actor);
|
||||
const placementPrice = (state) =>
|
||||
placementCost(state) ? `${placementCost(state)} BP` : "free";
|
||||
export function moveLabel(m, s) {
|
||||
const t = s.tasks[0],
|
||||
a = findAmoeba(s, t?.a);
|
||||
|
|
@ -56,7 +86,7 @@ export function moveLabel(m, s) {
|
|||
case "score":
|
||||
return `Start at ${m.score}`;
|
||||
case "place":
|
||||
return `Place #${m.n}`;
|
||||
return `Place #${m.n} · free`;
|
||||
case "drift":
|
||||
return `${m.cell === a?.cell ? "Stay" : "Drift"} · free`;
|
||||
case "hold":
|
||||
|
|
@ -80,17 +110,35 @@ export function moveLabel(m, s) {
|
|||
case "feed-now":
|
||||
return "Finish moving";
|
||||
case "eat":
|
||||
return `Eat ${nutrients(m.food)}${m.host === undefined ? "" : `<small>${bp(-1)} for ${esc(s.players[m.host].name)}</small>`}`;
|
||||
return `Eat ${nutrients(m.food)}${m.borrowed ? `<small>Take ${nutrients(m.borrowed)} from ${coordinate(m.source)}</small>` : ""}${m.host === undefined ? "" : `<small>${bp(-1)} for ${esc(s.players[m.host].name)}</small>`}`;
|
||||
case "starve":
|
||||
return `Take ${injury(1)}`;
|
||||
case "pay-defect":
|
||||
return `Pay ${bp(m.amount)}`;
|
||||
case "discard":
|
||||
return `Give up ${geneLabel(m.gene)} ${sensitivity(GENE[m.gene].mutation)}`;
|
||||
return `Give up ${geneLabel(m.gene)} ${sensitivity(GENE[m.gene].defectRelief ?? geneFor(m.gene, s.players.length).mutation)}`;
|
||||
case "buy":
|
||||
return `Evolve · ${bp(GENE[m.gene].cost)}`;
|
||||
return `Evolve · ${bp(genePurchaseCost(s, s.actor, m.gene))}`;
|
||||
case "exchange":
|
||||
return `Exchange ${geneLabel(m.exchange)} · ${bp(genePurchaseCost(s, s.actor, m.gene, m.exchange))}`;
|
||||
case "eat-first":
|
||||
return "Fast Food · eat before moving";
|
||||
case "excrete":
|
||||
return `Excrete at ${coordinate(m.cell)}`;
|
||||
case "take-income":
|
||||
return `Receive ${bp(roundIncome(s.players.length))}`;
|
||||
case "population-explosion":
|
||||
return `Population Explosion · give up all BP, grow to ${t.target}`;
|
||||
case "heal":
|
||||
return `Heal ${ref(m.amoeba)} · ${bp(3)}`;
|
||||
case "transfer-injury":
|
||||
return `Heal ${ref(m.amoeba)} · sacrifice ${ref(m.target)}`;
|
||||
case "pay-crust":
|
||||
return `Complete attack · ${bp(1)} extra`;
|
||||
case "abandon-attack":
|
||||
return "Abandon attack";
|
||||
case "divide":
|
||||
return `New amoeba #${m.n}`;
|
||||
return `New amoeba #${m.n} · ${placementPrice(s)}`;
|
||||
case "done":
|
||||
return "Done";
|
||||
case "attack":
|
||||
|
|
@ -125,7 +173,7 @@ function instruction(s, seat) {
|
|||
case "setup-place":
|
||||
return `Click an empty space for your ${s.phase === "setup-first" ? "first" : "second"} amoeba${t.injury ? " (starts with one injury)" : ""}.`;
|
||||
case "movement":
|
||||
return `Amoeba #${a.n} · Click the drift destination, or swim to roll for a direction.`;
|
||||
return `Amoeba #${a.n} · Click the drift destination, or swim ${s.players[a.p].genes.some((g) => g.id === "movement2") ? "in a direction of your choice" : "to roll for a direction"}.`;
|
||||
case "direction":
|
||||
return `Amoeba #${a.n} · ${s.players[a.p].genes.some((g) => g.id === "movement2") ? "Choose your direction." : `Rolled ${t.dice.join(" / ")}. Click a highlighted destination.`}`;
|
||||
case "feeding":
|
||||
|
|
@ -141,7 +189,15 @@ function instruction(s, seat) {
|
|||
case "genes":
|
||||
return "Evolve your colony with new genes, then choose Done.";
|
||||
case "division":
|
||||
return "You received 10 BP. Click a highlighted space to grow your colony, or finish with Done.";
|
||||
return t.target === undefined
|
||||
? `New amoeba: ${placementPrice(s)}.${s.players[s.actor].bp < placementCost(s) ? " Not enough BP to place one." : " Click a highlighted space to place one."} You may also use Healing or finish with Done.`
|
||||
: `Population Explosion · Free placement until you have ${t.target} amoebas. You may also use Healing.`;
|
||||
case "population":
|
||||
return "Receive your usual income, or give up all BP to match the score leader’s population.";
|
||||
case "excrete":
|
||||
return "Cleanliness · Choose where to leave both nutrients. Toxic Excretions, if owned, goes to the same space.";
|
||||
case "crust":
|
||||
return "Hard Crust · Pay one more BP to complete the attack, or let the defender survive.";
|
||||
case "aggression":
|
||||
return "You may make one attack with Aggression, or finish with Done.";
|
||||
case "combat":
|
||||
|
|
@ -156,18 +212,36 @@ function instruction(s, seat) {
|
|||
}
|
||||
export function mountGame(
|
||||
target,
|
||||
{ onMove, onFullscreen, onOpenPlayer, chat, practice = false } = {},
|
||||
{
|
||||
onMove,
|
||||
onFullscreen,
|
||||
onOpenPlayer,
|
||||
onColorBlindChange,
|
||||
chat,
|
||||
practice = false,
|
||||
} = {},
|
||||
) {
|
||||
const root = document.createElement("div");
|
||||
root.className = "soup game-shell";
|
||||
let colonySymbols = onColorBlindChange ? false : readLocalColorBlindMode();
|
||||
root.classList.toggle("colony-symbols", colonySymbols);
|
||||
target.append(root);
|
||||
root.innerHTML = `<header class="topbar"><div class="brand"><span>${amoeba("green", 0)}</span><div><h1>primordial soup<span class="title-dot">.</span></h1><span class="byline">DORIS MATTHÄUS & FRANK NESTEL</span></div></div><nav class="utilities" aria-label="Game options"><button class="quiet-button" data-ui="genes">${icon("gene")} Genes</button><button class="icon-button" data-ui="rules" aria-label="How to play">${icon("help")}</button><button class="icon-button" data-ui="fullscreen" aria-label="Fullscreen">${icon("expand")}</button></nav></header>
|
||||
root.innerHTML = `<header class="topbar"><div class="brand"><span>${amoeba("green", 0)}</span><div><h1>primordial soup<span class="title-dot">.</span></h1><span class="byline">DORIS MATTHÄUS & FRANK NESTEL</span></div></div><nav class="utilities" aria-label="Game options"><button class="quiet-button" data-ui="genes" aria-label="Genes" title="Gene pool">${icon("gene")}<span class="utility-label">Genes</span></button><button class="icon-button" data-ui="colony-symbols" aria-label="Color-blind mode" aria-pressed="${colonySymbols}" title="Color-blind mode: match colonies by symbol">${icon("colony-symbols")}</button><button class="icon-button" data-ui="rules" aria-label="How to play">${icon("help")}</button><button class="icon-button" data-ui="fullscreen" aria-label="Fullscreen">${icon("expand")}</button></nav></header>
|
||||
<div class="tutorial-slot"></div><section class="players" aria-label="The colonies" data-tutorial="colonies"></section>
|
||||
<main class="play-area"><section class="pond-section" aria-label="Primordial soup board"><div class="pond-toolbar"><div><span class="eyebrow">A LITTLE LIFE IN A BIG SOUP</span><span class="pond-subtitle" id="turn-order"></span></div><div class="pond-tools">${chat ? `<button class="quiet-button" data-ui="chat">${icon("chat")} Chat</button>` : ""}<button class="quiet-button" data-ui="journal">${icon("history")} Journal</button></div></div><div class="board-wrap"><div class="board" data-tutorial="board"><svg id="pond-art" viewBox="0 0 900 650" preserveAspectRatio="none" aria-hidden="true">${pondArt()}</svg><div class="cells"></div><div class="organisms"></div><div class="current-compass" data-tutorial="current"><span>CURRENT</span><div class="compass-arrow">➜</div><b class="compass-label"></b><small>Ozone <strong class="ozone"></strong></small></div><aside class="soup-board-key" data-tutorial="scoring" aria-label="Scoring reference"></aside></div></div><div class="pond-bottom"><span class="last-move" aria-live="polite"></span><span class="food-reserve" title="Food cubes remaining in the common supply"></span></div></section><aside class="colony-panel" data-tutorial="colony"></aside></main>
|
||||
<footer class="turnbar" data-tutorial="actions"><div class="round"><span>ROUND</span><strong class="round-number"></strong></div><div class="turn-details"><div class="phase-label"></div><div class="phase-instruction" aria-live="polite"></div><div class="phase-dots"></div></div><div class="action-buttons"></div></footer><div class="game-message" role="alert"></div>
|
||||
<main class="play-area"><section class="pond-section" aria-label="Primordial soup board"><div class="board-wrap"><div class="board" data-tutorial="board"><div class="pond-tools">${chat ? `<button class="quiet-button" data-ui="chat">${icon("chat")} Chat</button>` : ""}<button class="quiet-button" data-ui="journal">${icon("history")} Journal</button></div><svg id="pond-art" viewBox="0 0 900 650" preserveAspectRatio="none" aria-hidden="true">${pondArt()}</svg><div class="cells"></div><div class="organisms"></div><div class="board-actions" hidden></div><div class="current-compass" data-tutorial="current"><div class="environment-current"><span>CURRENT</span><div class="compass-arrow">➜</div><b class="compass-label"></b></div><div class="environment-ozone" role="img" tabindex="0" title="${OZONE_HELP}"><span class="ozone-value">${icon("ozone")}<strong class="ozone"></strong></span></div></div></div><div class="board-reference"><div class="game-progress"></div><aside class="soup-board-key" data-tutorial="scoring" aria-label="Scoring reference"></aside></div></div><div class="private-forecast" hidden></div><div class="pond-bottom"><div class="last-move" aria-live="polite"></div><span class="food-reserve" title="Food cubes remaining in the common supply"></span></div></section><aside class="colony-panel" data-tutorial="colony"></aside></main>
|
||||
<footer class="turnbar" data-tutorial="actions"><div class="round"><span>ROUND</span><strong class="round-number"></strong></div><div class="turn-details"><div class="phase-label"></div><div class="phase-instruction" aria-live="polite"></div><ol class="phase-steps" aria-label="Round phases"></ol></div><div class="action-buttons"></div></footer><div class="game-message" role="alert"></div>
|
||||
<div class="activity-slot"></div><dialog><button class="close-modal icon-button" data-ui="close" aria-label="Close">×</button><div class="modal-content"></div></dialog>`;
|
||||
const $ = (q) => root.querySelector(q),
|
||||
$$ = (q) => [...root.querySelectorAll(q)];
|
||||
function setColorBlind(enabled) {
|
||||
colonySymbols = enabled;
|
||||
root.classList.toggle("colony-symbols", enabled);
|
||||
$('[data-ui="colony-symbols"]').setAttribute(
|
||||
"aria-pressed",
|
||||
String(enabled),
|
||||
);
|
||||
if (!onColorBlindChange) saveLocalColorBlindMode(enabled);
|
||||
}
|
||||
let state,
|
||||
seat,
|
||||
selected,
|
||||
|
|
@ -176,7 +250,9 @@ export function mountGame(
|
|||
busy = false,
|
||||
locked = false,
|
||||
modalKind,
|
||||
oldTask;
|
||||
modalPlayer,
|
||||
oldTask,
|
||||
mealSource;
|
||||
const dialog = $("dialog");
|
||||
const activity = mountActivity($(".activity-slot"), {
|
||||
chat,
|
||||
|
|
@ -224,6 +300,7 @@ export function mountGame(
|
|||
actor = state.actor;
|
||||
if (oldTask !== taskKey) {
|
||||
oldTask = taskKey;
|
||||
mealSource = undefined;
|
||||
if (t?.a) selected = t.a;
|
||||
viewPlayer = seat ?? actor ?? 0;
|
||||
}
|
||||
|
|
@ -231,17 +308,15 @@ export function mountGame(
|
|||
selected = a?.id;
|
||||
const shown = viewPlayer ?? seat ?? actor ?? 0,
|
||||
pl = state.players[shown];
|
||||
$(".soup-board-key").innerHTML = scoringLegend(
|
||||
colony(state, shown).length,
|
||||
geneCount(state, shown),
|
||||
pl.color,
|
||||
$(".soup-board-key").innerHTML = renderScoring(shown);
|
||||
$(".players").style.setProperty(
|
||||
"--player-columns",
|
||||
Math.min(4, state.players.length),
|
||||
);
|
||||
$(".players").style.gridTemplateColumns =
|
||||
`repeat(${state.players.length},1fr)`;
|
||||
$(".players").innerHTML = state.players
|
||||
.map(
|
||||
(p, i) =>
|
||||
`<button class="player ${i === actor ? "active" : ""}" data-player="${i}" style="--player:${colors[p.color].shade}"><span class="player-color"></span><span class="player-portrait">${amoeba(p.color, i, colonyTraits(p.genes))}</span><span class="player-info"><span class="player-name">${esc(p.name)}${i === seat && p.name !== "You" ? '<span class="you-tag">You</span>' : ""}</span><span class="player-stat">${bp(p.bp)}<span aria-hidden="true">·</span><span>${colony(state, i).length} amoeba${colony(state, i).length === 1 ? "" : "s"}</span><span aria-hidden="true">·</span><span class="resource-amount" role="img" aria-label="${geneCount(state, i)} genes" title="Genes">${icon("gene")}${geneCount(state, i)}</span></span></span><span class="player-score" title="Evolution points">${icon("spark")}${p.score}</span></button>`,
|
||||
`<button class="player ${i === actor ? "active" : ""}" data-player="${i}" style="--player:${colors[p.color].shade}"><span class="player-color"></span><span class="player-portrait">${amoeba(p.color, i, colonyTraits(p.genes))}</span><span class="player-info"><span class="player-name">${esc(p.name)}${i === seat && p.name !== "You" ? '<span class="you-tag">You</span>' : ""}</span><span class="player-stat"><span class="resource-amount player-population" role="img" aria-label="${colony(state, i).length} living amoebas" title="Living amoebas">${amoeba(p.color)}<span>${colony(state, i).length}</span></span><span aria-hidden="true">·</span><span class="resource-amount" role="img" aria-label="${geneCount(state, i)} genes" title="Genes">${icon("gene")}${geneCount(state, i)}</span></span></span><span class="player-balances"><span class="player-bp">${bp(p.bp)}</span><span class="player-sensitivity ${mutation(state, i) < 0 ? "protective" : ""}" role="img" aria-label="Total sensitivity ${mutation(state, i)}" title="${SENSITIVITY_HELP}">${icon("sun")}<b>${mutation(state, i)}</b></span><span class="player-score-group"><span class="player-score" title="Evolution points">${icon("spark")}${p.score}</span>${state.closed ? "" : `<span class="player-income" role="img" aria-label="${evolution(state, i)} evolution points per round with the current colony" title="Projected evolution points per round with the current amoebas and genes. Occupied score spaces are skipped in addition."><b>+${evolution(state, i)}</b><span class="income-unit"> / round</span></span>`}</span></span></button>`,
|
||||
)
|
||||
.join("");
|
||||
const positions = actions().filter((m) =>
|
||||
|
|
@ -251,14 +326,19 @@ export function mountGame(
|
|||
number = positions[0].n;
|
||||
const cellMoves = actions().filter(
|
||||
(m) =>
|
||||
["drift", "direction", "place", "divide"].includes(m.type) &&
|
||||
["drift", "direction", "place", "divide", "excrete"].includes(m.type) &&
|
||||
(!("n" in m) || m.n === number),
|
||||
);
|
||||
$(".cells").innerHTML = Array.from({ length: 25 }, (_, cell) => {
|
||||
if (!CELLS.includes(cell)) return '<span class="land-cell"></span>';
|
||||
const move = cellMoves.find((m) => m.cell === cell),
|
||||
last = state.lastCells.includes(cell);
|
||||
return `<button class="water-cell ${move ? "valid" : ""} ${move?.type === "drift" ? "drift" : ""} ${last ? "last-cell" : ""}" data-cell="${cell}" data-destination="${move ? esc(["place", "divide"].includes(move.type) ? `#${number}` : moveLabel(move, state)) : ""}" aria-label="Space ${coordinate(cell)}${move ? " · " + esc(moveLabel(move, state)) : ""}" ${move ? "" : 'aria-disabled="true"'}><span class="cell-coord">${coordinate(cell)}</span><span class="nutrients">${nutrients(state.food[cell])}</span></button>`;
|
||||
const destination = move
|
||||
? ["place", "divide"].includes(move.type)
|
||||
? `#${number} · ${placementPrice(state)}`
|
||||
: moveLabel(move, state)
|
||||
: "";
|
||||
return `<button class="water-cell ${move ? "valid" : ""} ${move?.type === "drift" ? "drift" : ""} ${last ? "last-cell" : ""}" data-cell="${cell}" data-destination="${esc(destination)}" aria-label="Space ${coordinate(cell)}${move ? " · " + esc(moveLabel(move, state)) : ""}" ${move ? "" : 'aria-disabled="true"'}>${move ? `<span class="cell-destination" aria-hidden="true">${richText(destination)}</span>` : ""}<span class="cell-coord">${coordinate(cell)}</span><span class="nutrients">${nutrients(state.food[cell])}</span>${state.toxins?.[cell] ? `<span class="toxin-marker" title="${state.toxins[cell]} toxic injuries for the next entrant">☣ ${state.toxins[cell]}</span>` : ""}</button>`;
|
||||
}).join("");
|
||||
$(".organisms").innerHTML = state.amoebas
|
||||
.map((a) => {
|
||||
|
|
@ -267,28 +347,58 @@ export function mountGame(
|
|||
scale = group.length > 4 ? 0.55 : group.length > 2 ? 0.72 : 1,
|
||||
dx =
|
||||
((i % 3) - (Math.min(group.length, 3) - 1) / 2) *
|
||||
(group.length > 2 ? 37 : 45),
|
||||
dy = group.length > 3 ? Math.floor(i / 3) * 30 - 15 : 0;
|
||||
(group.length > 2 ? 54 : 45),
|
||||
dy = group.length > 3 ? Math.floor(i / 3) * 48 - 24 : 0;
|
||||
const hp = a.hp
|
||||
? `<span class="injury" title="${a.hp} injuries">${injury(a.hp)}</span>`
|
||||
: "";
|
||||
return `<button class="amoeba-button ${selected === a.id ? "selected" : ""} ${t?.a === a.id ? "acting" : ""}" data-amoeba="${a.id}" aria-label="${esc(state.players[a.p].name)} amoeba #${a.n}, ${coordinate(a.cell)}${a.hp ? ", " + a.hp + " injuries" : ""}" aria-pressed="${selected === a.id}" style="left:${(60 + (a.cell % 5) * 156 + 78 + dx) / 9}%;top:${(55 + Math.floor(a.cell / 5) * 105 + 49 + dy) / 6.5}%;--scale:${scale};--delay:-${a.n * 0.7}s">${amoeba(COLORS[a.p], a.n, colonyTraits(state.players[a.p].genes))}<span class="amoeba-number">${a.n}</span>${hp}</button>`;
|
||||
return `<button class="amoeba-button ${selected === a.id ? "selected" : ""} ${t?.a === a.id ? "acting" : ""}" data-amoeba="${a.id}" aria-label="${esc(state.players[a.p].name)} amoeba #${a.n}, ${coordinate(a.cell)}${a.hp ? ", " + a.hp + " injuries" : ""}" aria-pressed="${selected === a.id}" style="--x:${(60 + (a.cell % 5) * 156 + 78 + dx) / 9}%;--y:${(55 + Math.floor(a.cell / 5) * 105 + 49 + dy) / 6.5}%;--scale:${scale};--delay:-${a.n * 0.7}s;--amoeba-paper:${colors[COLORS[a.p]].light};--amoeba-ink:${colors[COLORS[a.p]].stroke}">${amoeba(COLORS[a.p], a.n, colonyTraits(state.players[a.p].genes))}<span class="amoeba-number">${a.n}</span>${hp}</button>`;
|
||||
})
|
||||
.join("");
|
||||
const swimIndex = actions().findIndex((m) =>
|
||||
["swim", "swim-again"].includes(m.type),
|
||||
);
|
||||
$(".board-actions").hidden = swimIndex < 0;
|
||||
if (swimIndex >= 0) {
|
||||
const again = actions()[swimIndex].type === "swim-again";
|
||||
const free =
|
||||
again || state.players[seat].genes.some((g) => g.id === "streamline");
|
||||
const title = again
|
||||
? "Swim again for free before feeding."
|
||||
: state.players[seat].genes.some((g) => g.id === "movement2")
|
||||
? "Swim: choose a direction."
|
||||
: "Swim: roll for a direction.";
|
||||
$(".board-actions").innerHTML =
|
||||
`<button class="action primary board-swim" data-move="${swimIndex}" title="${title}" aria-label="${again ? "Swim again" : "Swim"} · ${free ? "free" : "1 biological point"}"><span class="board-swim-title">${icon("wave")} Swim</span><small>${free ? "Free" : bp(1)}</small></button>`;
|
||||
} else $(".board-actions").innerHTML = "";
|
||||
const direction = state.environment.direction;
|
||||
$(".board").dataset.current = ["west", "north", "east", "south", "still"][
|
||||
direction
|
||||
];
|
||||
$(".compass-arrow").textContent = direction === 4 ? "·" : "➜";
|
||||
$(".compass-arrow").style.transform =
|
||||
`rotate(${[180, 270, 0, 90, 0][direction]}deg)`;
|
||||
$(".compass-label").textContent = DIRECTIONS[direction].toUpperCase();
|
||||
$(".ozone").textContent = state.environment.ozone;
|
||||
$("#turn-order").textContent = state.closed
|
||||
? "Game ended."
|
||||
: `${state.deckRemaining} environment cards left · ${state.actor === seat ? "Your turn" : ` ${state.players[state.actor].name}'s turn`}`;
|
||||
$(".last-move").innerHTML = richText(state.log.at(-1)?.text ?? "");
|
||||
$(".environment-ozone").setAttribute(
|
||||
"aria-label",
|
||||
`Ozone layer ${state.environment.ozone}. ${OZONE_HELP}`,
|
||||
);
|
||||
const forecast = state.foreseenEnvironment;
|
||||
$(".private-forecast").hidden = !forecast;
|
||||
$(".private-forecast").textContent = forecast
|
||||
? `Private forecast · Next environment: ${DIRECTIONS[forecast.direction]}, ozone ${forecast.ozone}. Only you can see this.`
|
||||
: "";
|
||||
$(".game-progress").innerHTML =
|
||||
`<div class="round-progress"><span>${state.round ? `Round <strong>${state.round}</strong>` : "Setup"}</span><span class="round-meter" role="img" aria-label="${state.round} of ${ROUND_LIMIT} rounds">${Array.from({ length: ROUND_LIMIT }, (_, i) => `<span class="${i < state.round ? "reached" : ""}"></span>`).join("")}</span></div><span class="game-finish" title="The game ends after round ${ROUND_LIMIT}, or earlier if a colony reaches 42 evolution points at the end of a round. Highest score wins.">Ends: round <strong>${ROUND_LIMIT}</strong> or ${evolutionPoints(42)}</span>`;
|
||||
$(".last-move").innerHTML = journalEntryHtml(
|
||||
state.log.at(-1),
|
||||
state.players,
|
||||
);
|
||||
$(".food-reserve").innerHTML =
|
||||
`<small>Supply</small>${nutrients(state.supply)}`;
|
||||
$(".colony-panel").innerHTML =
|
||||
`<div class="colony-heading"><div><span class="eyebrow">${shown === seat ? "YOUR COLONY" : "THE COLONY"}</span><h2>${esc(pl.name)}</h2></div><div class="bio-balance" data-tutorial="bp" title="Biological points">${icon("bio")}<strong>${pl.bp}</strong><span>BP</span></div></div><div class="specimen"><div class="specimen-orbit"></div><div id="selected-portrait">${amoeba(pl.color, a?.n ?? 1, colonyTraits(pl.genes))}</div><span class="specimen-coord">${a ? coordinate(a.cell) : "—"}</span></div><div class="specimen-heading"><h3>${a ? `Amoeba #${a.n}` : "Ready to grow"}</h3><span class="health ${a?.hp ? "hurt" : ""}">${a?.hp ? injury(a.hp) : "Feeling great"}</span></div><div class="diet"><span>Food colours</span><div>${state.players.map((_, p) => (p !== shown ? food(p) : "")).join("")}</div></div>${positions.length ? `<label class="amoeba-picker">New amoeba <select aria-label="Amoeba number">${[...new Set(positions.map((m) => m.n))].map((n) => `<option value="${n}" ${n === number ? "selected" : ""}>#${n}</option>`).join("")}</select></label>` : ""}<div class="gene-heading"><h3>Genes <span>${geneCount(state, shown)}</span></h3><button class="text-button" data-ui="genes">${t?.kind === "genes" && canAct() ? "Evolve ↗" : "Gene pool ↗"}</button></div><div class="gene-list" data-tutorial="genes">${pl.genes.map((g) => `<button class="gene" data-gene="${g.id}"><span class="gene-art">${geneIcon(g.id)}</span><span class="gene-text"><strong>${GENE[g.id].name}</strong><p>${richText(geneSummary(g.id, state.players.length))}</p></span><span class="gene-sensitivity" title="Mutation sensitivity">${icon("sun")}${GENE[g.id].mutation}</span></button>`).join("") || '<p class="empty-genes">No genes yet. New abilities evolve in phase 3.</p>'}</div><div class="colony-metrics"><span>${icon("sun")} <strong>${mutation(state, shown)}</strong> mutation</span><span title="Evolution points earned at the end of the round with the current amoebas and genes">${evolutionPoints(`+${evolution(state, shown)}`)}</span></div>`;
|
||||
`<div class="colony-heading"><div><span class="eyebrow">${shown === seat ? "YOUR COLONY" : "THE COLONY"}</span><h2>${esc(pl.name)}</h2></div><div class="bio-balance" data-tutorial="bp" title="Biological points">${icon("bio")}<strong>${pl.bp}</strong><span>BP</span></div></div><div class="specimen"><div class="specimen-orbit"></div><div id="selected-portrait">${amoeba(pl.color, a?.n ?? 1, colonyTraits(pl.genes))}</div><span class="specimen-coord">${a ? coordinate(a.cell) : "—"}</span></div><div class="specimen-heading"><h3>${a ? `Amoeba #${a.n}` : "Ready to grow"}</h3><span class="health ${a?.hp ? "hurt" : ""}">${a?.hp ? injury(a.hp) : "Feeling great"}</span></div><div class="diet"><span>Food colours</span><div>${state.players.map((_, p) => (p !== shown ? food(p) : "")).join("")}</div></div>${positions.length ? `<label class="amoeba-picker">New amoeba <select aria-label="Amoeba number">${[...new Set(positions.map((m) => m.n))].map((n) => `<option value="${n}" ${n === number ? "selected" : ""}>#${n}</option>`).join("")}</select><span class="placement-price">${placementCost(state) ? bp(placementCost(state)) : "Free"}</span></label>` : ""}<div class="gene-heading"><h3>Genes <span>${geneCount(state, shown)}</span></h3><button class="text-button" data-ui="genes">${t?.kind === "genes" && canAct() ? "Evolve ↗" : "Gene pool ↗"}</button></div><div class="gene-list" data-tutorial="genes">${pl.genes.map((g) => `<button class="gene ${isNewGene(g.id) ? "gene--new" : ""}" data-gene="${g.id}"><span class="gene-art">${geneIcon(g.id)}</span><span class="gene-text"><strong>${newGeneMark(g.id)}${GENE[g.id].name} ${geneScoringMark(g.id)}</strong><p>${richText(geneSummary(g.id, state.players.length))}</p></span><span class="gene-sensitivity ${geneFor(g.id, state.players.length).mutation < 0 ? "protective" : ""}" title="${SENSITIVITY_HELP}" aria-label="${geneFor(g.id, state.players.length).mutation} mutation sensitivity. ${SENSITIVITY_HELP}">${icon("sun")}<b>${geneFor(g.id, state.players.length).mutation}</b></span></button>`).join("") || '<p class="empty-genes">No genes yet. New abilities evolve in phase 3.</p>'}</div><div class="colony-metrics"><span>${icon("sun")} <strong>${mutation(state, shown)}</strong> mutation</span><span title="Evolution points earned at the end of the round with the current amoebas and genes">${evolutionPoints(`+${evolution(state, shown)}`)}</span></div>`;
|
||||
$(".round-number").textContent = state.round || "—";
|
||||
$(".phase-label").textContent = state.closed
|
||||
? state.finished
|
||||
|
|
@ -297,45 +407,142 @@ export function mountGame(
|
|||
: typeof state.phase === "number"
|
||||
? `${state.phase + 1} / 6 · ${PHASES[state.phase]}`
|
||||
: "Life begins · Setup";
|
||||
$(".phase-instruction").innerHTML = richText(instruction(state, seat));
|
||||
$(".phase-dots").innerHTML = PHASES.map(
|
||||
(p, i) =>
|
||||
`<span title="${i + 1}. ${p}" class="${typeof state.phase === "number" && i <= state.phase ? "active" : ""}"></span>`,
|
||||
).join("");
|
||||
const prompt = instruction(state, seat);
|
||||
const actingAmoeba = findAmoeba(state, t?.a);
|
||||
$(".phase-instruction").innerHTML =
|
||||
actingAmoeba && state.actor === seat
|
||||
? prompt
|
||||
.split(`Amoeba #${actingAmoeba.n}`)
|
||||
.map(richText)
|
||||
.join(
|
||||
playerReference(state.players[actingAmoeba.p], actingAmoeba.n),
|
||||
)
|
||||
: richText(prompt);
|
||||
$(".phase-steps").innerHTML = PHASES.map((p, i) => {
|
||||
const income = i === 3 ? roundIncome(state.players.length) : undefined;
|
||||
const label = `${i + 1}. ${p}${income ? ` · Receive ${income} biological points` : ""}`;
|
||||
return `<li tabindex="0" title="${esc(label)}" aria-label="${esc(label)}" ${!state.closed && state.phase === i ? 'aria-current="step"' : ""} class="${typeof state.phase === "number" && i < state.phase ? "complete" : ""}"><span aria-hidden="true">${i + 1}</span>${income ? `<span class="phase-income">${bp(`+${income}`)}</span><span class="phase-division" aria-hidden="true">${icon(PHASE_ICONS[i])}</span>` : icon(PHASE_ICONS[i])}</li>`;
|
||||
}).join("");
|
||||
const meals = actions().filter((m) => m.type === "eat");
|
||||
const sources = [...new Set(meals.map((m) => m.source ?? "local"))];
|
||||
if (!sources.includes(mealSource)) mealSource = sources[0];
|
||||
const sourcePicker =
|
||||
sources.length > 1
|
||||
? `<label class="meal-source">Food source <select aria-label="Food source">${sources.map((source) => `<option value="${source}" ${source === mealSource ? "selected" : ""}>${source === "local" ? "This space only" : `Suction from ${coordinate(source)}`}</option>`).join("")}</select></label>`
|
||||
: "";
|
||||
$(".action-buttons").innerHTML =
|
||||
sourcePicker +
|
||||
`${canAct() && t.kind === "genes" ? '<button class="action primary" data-ui="genes">' + icon("gene") + " Evolve genes</button>" : ""}${actions()
|
||||
.map((m, i) =>
|
||||
["place", "divide", "buy", "direction", "drift"].includes(m.type)
|
||||
[
|
||||
"place",
|
||||
"divide",
|
||||
"buy",
|
||||
"exchange",
|
||||
"direction",
|
||||
"drift",
|
||||
"excrete",
|
||||
].includes(m.type) ||
|
||||
(m.type === "eat" && (m.source ?? "local") !== mealSource)
|
||||
? ""
|
||||
: actionButton(m, i),
|
||||
)
|
||||
.join(
|
||||
"",
|
||||
)}${state.closed ? `<button class="action primary" data-ui="results">${state.finished ? "Final scores" : "Scores"}</button>` : ""}`;
|
||||
if (canAct() && state.undoPlayer === seat)
|
||||
$(".turnbar .action-buttons").insertAdjacentHTML(
|
||||
"beforeend",
|
||||
`<button class="action secondary" data-undo title="Undo the last action. Available before a roll, reveal or turn handoff.">${icon("undo")} Undo</button>`,
|
||||
);
|
||||
if (dialog.open) renderModal();
|
||||
}
|
||||
function renderScoring(player, expandable = true) {
|
||||
return scoringLegend(
|
||||
colony(state, player).length,
|
||||
geneCount(state, player),
|
||||
state.players[player].color,
|
||||
expandable,
|
||||
state.players.length,
|
||||
state.players.map((p, i) => ({
|
||||
name: p.name,
|
||||
color: p.color,
|
||||
population: colony(state, i).length,
|
||||
genes: geneCount(state, i),
|
||||
})),
|
||||
);
|
||||
}
|
||||
function sensitivityBadge(g) {
|
||||
return `<div class="sensitivity-badge ${g.mutation < 0 ? "protective" : ""}" role="img" tabindex="0" title="${SENSITIVITY_HELP}" aria-label="${g.mutation} mutation sensitivity. ${SENSITIVITY_HELP}"><span class="sensitivity-value">${icon("sun")}<strong>${g.mutation < 0 ? "−" + Math.abs(g.mutation) : g.mutation}</strong></span></div>`;
|
||||
}
|
||||
function renderGeneCard(g) {
|
||||
const held = state.players.reduce(
|
||||
(n, p) => n + p.genes.filter((x) => x.id === g.id).length,
|
||||
0,
|
||||
);
|
||||
const remaining = copiesOf(g, state.players.length) - held;
|
||||
const viewer = seat ?? state.actor ?? 0;
|
||||
const price =
|
||||
seat === undefined ? g.cost : genePurchaseCost(state, seat, g.id);
|
||||
const moves = actions()
|
||||
.map((m, i) => ({ m, i }))
|
||||
.filter(
|
||||
({ m }) => ["buy", "exchange"].includes(m.type) && m.gene === g.id,
|
||||
);
|
||||
const owned = state.players[viewer].genes.some((x) => x.id === g.id);
|
||||
const trading = g.id === "social" && held && !owned;
|
||||
let unavailable = owned
|
||||
? "Already owned"
|
||||
: !remaining
|
||||
? trading
|
||||
? "May transfer to the last colony"
|
||||
: "All copies owned"
|
||||
: "";
|
||||
if (!unavailable && canAct() && state.tasks[0]?.kind === "genes") {
|
||||
if (g.id === "social") unavailable = "Only the last colony can buy";
|
||||
else if (
|
||||
g.base.length &&
|
||||
!state.players[viewer].genes.some(
|
||||
(x) => g.base.includes(x.id) && x.round < state.round,
|
||||
)
|
||||
)
|
||||
unavailable = "Requires an earlier gene";
|
||||
else if (state.players[viewer].bp < price) unavailable = "Not enough BP";
|
||||
}
|
||||
const buttons = moves
|
||||
.map(({ m, i }) =>
|
||||
m.type === "buy"
|
||||
? `<button class="action primary" data-move="${i}">${icon("gene")} Evolve${m.base ? ` with ${geneLabel(m.base)}` : ""}</button>`
|
||||
: actionButton(m, i),
|
||||
)
|
||||
.join("");
|
||||
return `<article class="shop-card ${isNewGene(g.id) ? "shop-card--new" : ""}" data-tutorial="gene-${g.id}"><div class="shop-art"><div class="shop-illustration">${geneArt(g.id)}</div>${sensitivityBadge(g)}</div><div class="shop-body"><div class="shop-title"><h3>${newGeneMark(g.id)}${g.name}</h3>${geneScoringMark(g.id)}</div><div class="gene-facts"><div class="gene-cost"><span>${price !== g.cost ? "Your cost" : "Cost"}</span><strong>${bp(price)}<small>BP</small></strong></div><div class="gene-stock ${remaining ? "" : "is-empty"}"><span>Available</span><strong>${remaining}<small>left</small></strong></div></div><p>${richText(g.text)}</p>${g.base.length ? `<small class="gene-prerequisite">Trade in ${g.base.map((id) => geneLabel(id)).join(" or ")}, owned since a previous round.</small>` : ""}${buttons || (unavailable ? `<span class="gene-unavailable">${unavailable}</span>` : "")}</div></article>`;
|
||||
}
|
||||
function renderModal() {
|
||||
if (!state) return;
|
||||
let html = "";
|
||||
if (modalKind === "genes")
|
||||
html = `<span class="eyebrow">THE GENE POOL</span><h2>Little changes. New possibilities.</h2><p>Each gene affects your whole colony. ${canAct() && state.tasks[0].kind === "genes" ? `You have ${bp(state.players[seat].bp)} to evolve.` : "Buy genes during phase 3."}</p><div class="shop-grid">${GENES.filter(
|
||||
(g) => g.copies[state.players.length - 3],
|
||||
)
|
||||
.map((g) => {
|
||||
const held = state.players.reduce(
|
||||
(n, p) => n + p.genes.filter((x) => x.id === g.id).length,
|
||||
0,
|
||||
),
|
||||
remaining = g.copies[state.players.length - 3] - held;
|
||||
const moves = actions()
|
||||
.map((m, i) => ({ m, i }))
|
||||
.filter(({ m }) => m.type === "buy" && m.gene === g.id);
|
||||
return `<article class="shop-card" data-tutorial="gene-${g.id}"><div class="shop-art">${geneArt(g.id)}</div><div class="shop-body"><h3>${g.name}</h3><span class="gene-price">${bp(g.cost)} · ${sensitivity(g.mutation)} · ${remaining} left</span><p>${richText(g.text)}</p>${g.base.length ? `<small>Trade in ${g.base.map((id) => geneLabel(id)).join(" or ")}, owned since a previous round.</small>` : ""}${moves.map(({ m, i }) => actionButton(m, i)).join("") || `<span class="gene-unavailable">${state.players[seat ?? 0].genes.some((x) => x.id === g.id) ? "Already owned" : !remaining ? "All copies owned" : g.base.length ? "Requires an earlier gene" : bp(g.cost)}</span>`}</div></article>`;
|
||||
})
|
||||
.join("")}</div>`;
|
||||
else if (modalKind === "scoring") {
|
||||
if (modalKind === "genes") {
|
||||
const families = geneFamilies(genesInGame(state));
|
||||
const groups = [
|
||||
{
|
||||
title: "New genes",
|
||||
extra: true,
|
||||
families: families.filter((family) =>
|
||||
family.some((g) => isNewGene(g.id)),
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "Standard genes",
|
||||
extra: false,
|
||||
families: families.filter(
|
||||
(family) => !family.some((g) => isNewGene(g.id)),
|
||||
),
|
||||
},
|
||||
].filter((group) => group.families.length);
|
||||
html = `<div class="pool-header"><div><h2>Gene pool</h2><p>${canAct() && state.tasks[0].kind === "genes" ? `${bp(state.players[seat].bp)} to spend` : "Buy during phase 3"}</p></div><div class="pool-guide" role="img" tabindex="0" title="${OZONE_HELP}" aria-label="Ozone layer ${state.environment.ozone}. ${OZONE_HELP}">${icon("ozone")}<strong>${state.environment.ozone}</strong></div></div>${groups.map((group) => `<section class="pool-section ${group.extra ? "pool-section--new" : ""}" aria-label="${group.title}"><div class="pool-heading"><h3>${group.extra ? '<span class="new-gene-star" aria-hidden="true">★</span>' : icon("gene")}${group.title}</h3><span>${group.families.flat().filter((g) => !group.extra || isNewGene(g.id)).length} ${group.extra ? "revealed" : "types"}</span></div>${group.extra ? `<p class="market-status" title="Two new genes are revealed in phase 3, after the leader finishes buying.">${state.newGeneMarket.remaining} unrevealed · +2 per round</p>` : ""}<div class="shop-grid">${group.families.map((family) => `<div class="shop-family" style="--gene-count:${family.length}"${family.length > 1 ? ` role="group" aria-label="${esc(family.map((g) => g.name).join(" / "))}"` : ""}>${family.map(renderGeneCard).join("")}</div>`).join("")}</div></section>`).join("")}`;
|
||||
} else if (modalKind === "scoring") {
|
||||
const player = viewPlayer ?? seat ?? state.actor ?? 0;
|
||||
html = `<h2>Scoring each round</h2><p>Look up your living amoebas and your gene total, then add the two rows. These points belong to the whole colony.</p><div class="scoring-detail">${scoringLegend(colony(state, player).length, geneCount(state, player), state.players[player].color, false)}</div><p>Advanced genes count as two; Ray Protection counts as zero. Score every round. Skip occupied scores on the track.</p>`;
|
||||
html = `<h2>Scoring each round</h2><p>Look up your living amoebas and your gene total, then add the two rows. These points belong to the whole colony.</p><div class="scoring-detail">${renderScoring(player, false)}</div><p>Advanced genes count as two; Ray Protection counts as zero. Score every round. Skip occupied scores on the track.</p>`;
|
||||
} else if (modalKind === "results")
|
||||
html = `<h2>${state.finished ? "Final scores" : "Scores"}</h2>${state.finished ? `<p>${esc(state.players[state.winner]?.name ?? "")} wins.</p>` : ""}<ol class="results-list">${state.players
|
||||
.map((p, i) => ({ ...p, index: i }))
|
||||
|
|
@ -344,16 +551,19 @@ export function mountGame(
|
|||
(p) =>
|
||||
`<li>${amoeba(p.color)}<strong>${esc(p.name)}</strong><b>${p.score}</b></li>`,
|
||||
)
|
||||
.join("")}</ol>`;
|
||||
.join(
|
||||
"",
|
||||
)}</ol>${state.nextGameChooser !== undefined ? `<p>${esc(state.players[state.nextGameChooser].name)} chooses the next game with ${geneLabel("doris-frank")}.</p>` : ""}`;
|
||||
else if (GENE[modalKind]) {
|
||||
const g = GENE[modalKind];
|
||||
html = `<div class="gene-explainer-art">${geneArt(g.id)}</div><span class="eyebrow">${g.points === 2 ? "ADVANCED GENE" : "COLONY GENE"}</span><h2>${g.name}</h2><p>${richText(g.text)}</p><p>${bp(g.cost)} · ${sensitivity(g.mutation)} · counts as ${g.points} gene${g.points === 1 ? "" : "s"} when calculating evolution points.</p><div class="action-buttons">${actions()
|
||||
const g = geneFor(modalKind, state.players.length);
|
||||
const color = state.players[modalPlayer].color;
|
||||
html = `<div class="gene-detail-hero"><div class="gene-explainer-art">${geneArt(g.id, color)}</div>${sensitivityBadge(g)}</div>${newGeneMark(g.id, true)}<h2>${g.name} ${geneScoringMark(g.id)}</h2><p>${richText(g.text)}</p><div class="gene-detail-cost"><span>Cost</span><strong>${bp(g.cost)} BP</strong></div><p>Counts as ${g.points} gene${g.points === 1 ? "" : "s"} when calculating evolution points.</p><div class="action-buttons">${actions()
|
||||
.map((m, i) =>
|
||||
m.type === "discard" && m.gene === g.id ? actionButton(m, i) : "",
|
||||
)
|
||||
.join("")}</div>`;
|
||||
} else
|
||||
html = `<span class="eyebrow">HOW LIFE WORKS</span><h2>Welcome to the soup.</h2><p>Grow your population and evolve genes. At the end of each round, earn evolution points from your amoebas and genes. Advance along the evolution track, skipping occupied scores. When a colony reaches 42 points — or the last environment card is revealed — finish the round. The highest score wins.</p><div class="help-steps"><section><h3>1 · Move & feed</h3><p>Lowest score first; amoebas act in number order. Drift with the current for free, or pay 1 BP to swim: roll a die for direction. 1 west, 2 north, 3 east, 4 south, 5 stay, 6 choose. A blocked move stays in place.</p></section><section><h3>Food & injuries</h3><p>Eat three nutrients, never your own colour. With four colonies, eat one of each other colour; with three, eat two of one and one of the other. After eating, excrete two nutrients of your own colour onto the same space. If you cannot eat, excrete nothing and take one injury instead.</p></section><section><h3>2 · Environment</h3><p>A new card sets the next current and ozone layer. If your mutation exceeds the ozone, pay the difference in BP or discard genes. No defects in round one.</p></section><section><h3>3 · New genes</h3><p>Highest score first. Buy as many genes as you can afford. Advanced genes replace a prerequisite owned since a previous round.</p></section><section><h3>4 · Cell division</h3><p>Receive 10 BP. Each new amoeba costs 6 BP and goes next to one of yours, without sharing your colour's space. With one amoeba, the second may go anywhere. With none, the first returns anywhere for free.</p></section><section><h3>5 · Survival</h3><p>Two injuries cause death, or three with Longevity. Return two food cubes of every colour to that space. Aggression happens after natural deaths.</p></section><section><h3>6 · Evolution points</h3><p>Your living amoebas and genes earn points automatically. See the scoring table on the board.</p></section><section><h3>Food supply</h3><p>There are 55 cubes of each colour. If the supply runs out, place only the cubes still available. Dead amoeba numbers may be used again.</p></section></div><p class="rules-links"><a href="${SIMPLE_RULES_URL}" target="_blank" rel="noopener">Simplified rules ↗</a><a href="${RULES_URL}" target="_blank" rel="noopener">Original rules (PDF) ↗</a></p>`;
|
||||
html = `<span class="eyebrow">HOW LIFE WORKS</span><h2>Welcome to the soup.</h2><p>Grow your population and evolve genes. At the end of each round, earn evolution points from your amoebas and genes. Advance along the evolution track, skipping occupied scores. When a colony reaches 42 points — or the last environment card is revealed — finish the round. The highest score wins.</p><div class="help-steps"><section><h3>1 · Move & feed</h3><p>Lowest score first; amoebas act in number order. Drift with the current for free, or pay 1 BP to swim: roll a die for direction. 1 west, 2 north, 3 east, 4 south, 5 stay, 6 choose. A blocked move stays in place.</p></section><section><h3>Food & injuries</h3><p>${state.players.length >= 5 ? "Eat four nutrients of four different colours, never your own. With six colonies, choose which other colour to leave out." : "Eat three nutrients, never your own colour. With four colonies, eat one of each other colour; with three, eat two of one and one of the other."} After eating, excrete two nutrients of your own colour onto the same space. If you cannot eat, excrete nothing and take one injury instead.</p></section><section><h3>2 · Environment</h3><p>A new card sets the next current and ozone layer. If your mutation exceeds the ozone, pay the difference in BP or discard genes. No defects in round one.</p></section><section><h3>3 · New genes</h3><p>Highest score first. Buy as many genes as you can afford. Advanced genes replace a prerequisite owned since a previous round.</p></section>${state.newGeneMarket ? "<section><h3>Freshly Spiced genes</h3><p>Social Gene and Population Explosion start in the pool. Two shuffled genes appear after the leader finishes buying each round. Revealed genes remain available. Select any gene to read its effect.</p></section>" : ""}<section><h3>4 · Cell division</h3><p>Receive ${roundIncome(state.players.length)} BP. You can have at most ${amoebaLimit(state.players.length)} amoebas. Each new amoeba costs 6 BP and goes next to one of yours, without sharing your colour's space. With one amoeba, the second may go anywhere. With none, the first returns anywhere for free.</p></section><section><h3>5 · Survival</h3><p>Two injuries cause death, or three with Longevity. Return two food cubes of every colour to that space. Aggression happens after natural deaths.</p></section><section><h3>6 · Evolution points</h3><p>Your living amoebas and genes earn points automatically. See the scoring table on the board.</p></section><section><h3>Food supply</h3><p>There are 55 cubes of each colour. If the supply runs out, place only the cubes still available. Dead amoeba numbers may be used again.</p></section></div><p class="rules-links"><a href="${SIMPLE_RULES_URL}" target="_blank" rel="noopener">Simplified rules ↗</a><a href="${RULES_URL}" target="_blank" rel="noopener">Original rules (PDF) ↗</a></p>`;
|
||||
$(".modal-content").innerHTML = html;
|
||||
if (modalKind === "rules") {
|
||||
for (const text of $(".modal-content").querySelectorAll(
|
||||
|
|
@ -365,6 +575,7 @@ export function mountGame(
|
|||
}
|
||||
function open(kind) {
|
||||
modalKind = kind;
|
||||
modalPlayer = viewPlayer ?? seat ?? state?.actor ?? 0;
|
||||
renderModal();
|
||||
if (!dialog.open) dialog.showModal();
|
||||
}
|
||||
|
|
@ -383,6 +594,10 @@ export function mountGame(
|
|||
root.addEventListener("click", (e) => {
|
||||
const el = e.target.closest("button");
|
||||
if (!el) return;
|
||||
if (el.hasAttribute("data-undo")) {
|
||||
void doMove({ type: "undo" });
|
||||
return;
|
||||
}
|
||||
if (el.dataset.move !== undefined) {
|
||||
void doMove(actions()[Number(el.dataset.move)]);
|
||||
return;
|
||||
|
|
@ -427,6 +642,11 @@ export function mountGame(
|
|||
activity.open(el.dataset.ui);
|
||||
return;
|
||||
}
|
||||
if (el.dataset.ui === "colony-symbols") {
|
||||
setColorBlind(!colonySymbols);
|
||||
onColorBlindChange?.(colonySymbols);
|
||||
return;
|
||||
}
|
||||
if (el.dataset.ui === "fullscreen") {
|
||||
void toggleFullscreen();
|
||||
return;
|
||||
|
|
@ -434,7 +654,11 @@ export function mountGame(
|
|||
if (el.dataset.ui) open(el.dataset.ui);
|
||||
});
|
||||
root.addEventListener("change", (e) => {
|
||||
if (e.target.matches("select")) {
|
||||
if (e.target.matches('[aria-label="Food source"]')) {
|
||||
mealSource =
|
||||
e.target.value === "local" ? "local" : Number(e.target.value);
|
||||
render();
|
||||
} else if (e.target.matches("select")) {
|
||||
number = Number(e.target.value);
|
||||
render();
|
||||
}
|
||||
|
|
@ -442,6 +666,7 @@ export function mountGame(
|
|||
return {
|
||||
root,
|
||||
guide: $(".tutorial-slot"),
|
||||
setColorBlind,
|
||||
render(s) {
|
||||
state = viewerState(s);
|
||||
render();
|
||||
|
|
|
|||
160
viewer/water-preview.css
Normal file
160
viewer/water-preview.css
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
.water-controls {
|
||||
margin: 8px 0 16px;
|
||||
padding: 18px;
|
||||
border: 1px solid #c4d3b6;
|
||||
border-radius: 16px;
|
||||
background: #fafbf2;
|
||||
color: #315d4e;
|
||||
}
|
||||
.water-controls-heading,
|
||||
.water-playback {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.water-controls h2 {
|
||||
margin: 0;
|
||||
font-size: 21px;
|
||||
}
|
||||
.water-controls p {
|
||||
margin: 4px 0 0;
|
||||
font-size: 13px;
|
||||
color: #657a5e;
|
||||
}
|
||||
.water-playback label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.water-playback select,
|
||||
.water-playback button {
|
||||
padding: 8px 10px;
|
||||
border: 1px solid #bdcdb2;
|
||||
background: #fffef6;
|
||||
color: #315d4e;
|
||||
border-radius: 8px;
|
||||
font: inherit;
|
||||
}
|
||||
.water-playback button {
|
||||
min-width: 128px;
|
||||
}
|
||||
.water-options {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.water-options button {
|
||||
display: flex;
|
||||
align-items: start;
|
||||
gap: 10px;
|
||||
padding: 12px;
|
||||
border: 1px solid #c8d6bd;
|
||||
border-radius: 10px;
|
||||
text-align: left;
|
||||
background: #fffef6;
|
||||
color: #315d4e;
|
||||
font: inherit;
|
||||
}
|
||||
.water-options button[aria-pressed="true"] {
|
||||
background: #e9f1dd;
|
||||
border-color: #678853;
|
||||
box-shadow: inset 0 0 0 1px #678853;
|
||||
}
|
||||
.water-options button:focus-visible,
|
||||
.water-playback :focus-visible {
|
||||
outline: 2px solid #52753c;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
.water-option-number {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 50%;
|
||||
background: #e2ecd7;
|
||||
flex: none;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.water-options strong,
|
||||
.water-options small {
|
||||
display: block;
|
||||
}
|
||||
.water-options small {
|
||||
margin-top: 4px;
|
||||
line-height: 1.4;
|
||||
font-size: 12px;
|
||||
color: #657a5e;
|
||||
}
|
||||
.water-study .pond-flow,
|
||||
.water-study .players,
|
||||
.water-study .turnbar,
|
||||
.water-study .activity-slot,
|
||||
.water-study .pond-tools,
|
||||
.water-controls .water-reduced-note {
|
||||
display: none;
|
||||
}
|
||||
.water-study[data-water-style="ripples"] .water-ripple,
|
||||
.water-study[data-water-style="light"] .water-light,
|
||||
.water-study[data-water-style="trails"] .water-trail {
|
||||
display: inline;
|
||||
}
|
||||
.water-study .water-light {
|
||||
--flow-opacity: 0.42;
|
||||
}
|
||||
.water-study .water-trail {
|
||||
--flow-opacity: 0.55;
|
||||
}
|
||||
.water-study .water-ripple {
|
||||
--flow-opacity: 0.3;
|
||||
}
|
||||
.water-study .board {
|
||||
--water-orientation-angle: 0deg;
|
||||
}
|
||||
.water-study[data-water-orientation="perpendicular"]
|
||||
.board:is([data-current="west"], [data-current="east"]) {
|
||||
--water-orientation-angle: 90deg;
|
||||
}
|
||||
.soup.water-study .pond-ripple {
|
||||
transform: rotate(var(--water-orientation-angle));
|
||||
transform-box: fill-box;
|
||||
transform-origin: center;
|
||||
}
|
||||
.water-study[data-motion="paused"] .board * {
|
||||
animation-play-state: paused !important;
|
||||
}
|
||||
@media (min-width: 761px) {
|
||||
.water-study .board {
|
||||
height: clamp(360px, calc(100dvh - 390px), 660px);
|
||||
}
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.water-options {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@media (max-width: 500px) {
|
||||
.water-controls {
|
||||
padding: 12px;
|
||||
}
|
||||
.water-options button {
|
||||
padding: 10px 8px;
|
||||
gap: 6px;
|
||||
}
|
||||
.water-playback {
|
||||
gap: 10px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.water-options small {
|
||||
font-size: 11px;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.water-controls .water-reduced-note {
|
||||
display: block;
|
||||
margin-top: 12px;
|
||||
}
|
||||
}
|
||||
121
viewer/water-preview.js
Normal file
121
viewer/water-preview.js
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import "./water-preview.css";
|
||||
import { mountGame } from "./ui.js";
|
||||
import { prepared } from "./tutorials.js";
|
||||
import { stripSecret } from "../engine/index.js";
|
||||
|
||||
// These alternatives are only loaded by the local preview entry point.
|
||||
const styles = [
|
||||
["bubbles", "Bubbles only", "Just the drifting bubbles."],
|
||||
["light", "Soft light", "Broad, gentle reflections."],
|
||||
["trails", "Fine trails", "Short strokes carried by the current."],
|
||||
["ripples", "Ripples", "Paired, curved wavelets."],
|
||||
];
|
||||
|
||||
export function mountWaterPreview(target, params) {
|
||||
const state = prepared({ players: 6, round: 3 });
|
||||
state.players.forEach((p, i) => {
|
||||
p.name = ["You", "Maya", "Leo", "Nina", "Sam", "Alex"][i];
|
||||
p.score = 6 - i;
|
||||
});
|
||||
state.amoebas = [[6, 21], [8, 16], [18], [23], [7], [14]].flatMap(
|
||||
(cells, p) =>
|
||||
cells.map((cell, i) => ({
|
||||
id: `${p}-${i + 1}`,
|
||||
p,
|
||||
n: i + 1,
|
||||
cell,
|
||||
hp: 0,
|
||||
})),
|
||||
);
|
||||
const requestedDirection = Number(params.get("direction") ?? 2);
|
||||
state.environment.direction = [0, 1, 2, 3, 4].includes(requestedDirection)
|
||||
? requestedDirection
|
||||
: 2;
|
||||
const ui = mountGame(target);
|
||||
ui.setPlayer(0);
|
||||
ui.setEnabled(false);
|
||||
const root = target.querySelector(".soup");
|
||||
root.classList.add("water-study");
|
||||
root.dataset.waterOrientation =
|
||||
params.get("orientation") === "perpendicular"
|
||||
? "perpendicular"
|
||||
: "horizontal";
|
||||
const controls = document.createElement("section");
|
||||
controls.className = "water-controls";
|
||||
controls.setAttribute("aria-label", "Water animation comparison");
|
||||
controls.innerHTML = `<div class="water-controls-heading"><div><h2>Water motion</h2><p>Same bubbles, four finishes. Select one to compare.</p></div><div class="water-playback"><label>Current <select aria-label="Preview current">${["← West", "↑ North", "→ East", "↓ South", "· Still"].map((label, i) => `<option value="${i}" ${i === state.environment.direction ? "selected" : ""}>${label}</option>`).join("")}</select></label><label>Orientation <select aria-label="Water orientation"><option value="perpendicular">Perpendicular to current</option><option value="horizontal">Always horizontal</option></select></label><button type="button" data-pause aria-pressed="false">Pause motion</button></div></div><div class="water-options" role="group" aria-label="Water style">${styles.map(([id, title, description], i) => `<button type="button" data-water-choice="${id}" aria-pressed="false"><span class="water-option-number">${i + 1}</span><span><strong>${title}</strong><small>${description}</small></span></button>`).join("")}</div><p class="water-reduced-note">Your reduced-motion setting is on, so the animation is stopped.</p>`;
|
||||
const orientationSelect = controls.querySelector(
|
||||
'[aria-label="Water orientation"]',
|
||||
);
|
||||
orientationSelect.value = root.dataset.waterOrientation;
|
||||
root.querySelector(".topbar").after(controls);
|
||||
function render() {
|
||||
ui.render(stripSecret(state, 0));
|
||||
}
|
||||
render();
|
||||
|
||||
const svg = root.querySelector("#pond-art");
|
||||
svg.querySelectorAll(".pond-flow").forEach((flow) => flow.remove());
|
||||
svg
|
||||
.querySelector("defs")
|
||||
.insertAdjacentHTML(
|
||||
"beforeend",
|
||||
`<linearGradient id="water-preview-trail"><stop stop-color="#f0ffe9" stop-opacity="0"/><stop offset=".65" stop-color="#f0ffe9" stop-opacity=".8"/><stop offset="1" stop-color="#f0ffe9" stop-opacity="0"/></linearGradient>`,
|
||||
);
|
||||
const reflections = document.createElementNS(
|
||||
"http://www.w3.org/2000/svg",
|
||||
"g",
|
||||
);
|
||||
reflections.innerHTML = Array.from({ length: 14 }, (_, n) => {
|
||||
const x = 100 + ((n * 193) % 730),
|
||||
y = 90 + ((n * 127) % 470);
|
||||
const timing = `--delay:-${n * 1.7}s;--flow-duration:${18 + (n % 4) * 2}s`;
|
||||
return `<g transform="translate(${x} ${y})"><g class="pond-flow water-light" style="${timing}"><ellipse class="pond-ripple" rx="${70 + (n % 3) * 12}" ry="32" fill="url(#soup-light)"/></g><g class="pond-flow water-trail" style="${timing}"><path class="pond-ripple" d="M-25 1Q-2-4 26 0" fill="none" stroke="url(#water-preview-trail)" stroke-width="1.5" stroke-linecap="round"/></g><g class="pond-flow water-ripple" style="${timing}"><path class="pond-ripple" d="M-16 1q8-4 16 0t16 0M-6 6q6-2 12 0" fill="none" stroke="#f0ffe9" stroke-width="1.3" stroke-linecap="round"/></g></g>`;
|
||||
}).join("");
|
||||
const water = svg.querySelector('g[clip-path="url(#soup-pond-clip)"]');
|
||||
water.insertBefore(reflections, water.querySelector(".grid-lines"));
|
||||
|
||||
function updateUrl() {
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.set("style", root.dataset.waterStyle);
|
||||
url.searchParams.set("direction", state.environment.direction);
|
||||
url.searchParams.set("orientation", root.dataset.waterOrientation);
|
||||
history.replaceState(null, "", url);
|
||||
}
|
||||
function selectStyle(style) {
|
||||
root.dataset.waterStyle = style;
|
||||
for (const button of controls.querySelectorAll("[data-water-choice]"))
|
||||
button.setAttribute(
|
||||
"aria-pressed",
|
||||
String(button.dataset.waterChoice === style),
|
||||
);
|
||||
updateUrl();
|
||||
}
|
||||
selectStyle(
|
||||
styles.some(([id]) => id === params.get("style"))
|
||||
? params.get("style")
|
||||
: "light",
|
||||
);
|
||||
controls.addEventListener("click", (event) => {
|
||||
const choice = event.target.closest("[data-water-choice]");
|
||||
if (choice) selectStyle(choice.dataset.waterChoice);
|
||||
const pause = event.target.closest("[data-pause]");
|
||||
if (pause) {
|
||||
const paused = root.dataset.motion !== "paused";
|
||||
root.dataset.motion = paused ? "paused" : "playing";
|
||||
pause.setAttribute("aria-pressed", String(paused));
|
||||
pause.textContent = paused ? "Resume motion" : "Pause motion";
|
||||
}
|
||||
});
|
||||
controls
|
||||
.querySelector('[aria-label="Preview current"]')
|
||||
.addEventListener("change", (event) => {
|
||||
state.environment.direction = Number(event.target.value);
|
||||
render();
|
||||
updateUrl();
|
||||
});
|
||||
orientationSelect.addEventListener("change", () => {
|
||||
root.dataset.waterOrientation = orientationSelect.value;
|
||||
updateUrl();
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue