primordial-soup/test/turn-controls-browser.mjs

475 lines
18 KiB
JavaScript

import { serveAssets } from "./asset-server.mjs";
const assetBase = await serveAssets("dist");
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, 1000, 1400]) {
const page = await browser.newPage({
viewport: { width, height: 1000 },
hasTouch: width <= 390,
});
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({ url: assetBase + "/viewer.css" });
await page.addScriptTag({ url: assetBase + "/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");
const driftButton = page.locator(".board-drift");
assert.ok(await swim.isVisible());
assert.ok(await driftButton.isVisible());
assert.equal(await page.getByRole("button", { name: /^Swim/ }).count(), 1);
const swimBox = await swim.boundingBox(),
driftBox = await driftButton.boundingBox();
assert.ok(
Math.abs(swimBox.y - driftBox.y) < 1,
"Drift and Swim share a row",
);
assert.ok(driftBox.x + driftBox.width < swimBox.x, "Drift is beside Swim");
assert.ok(swimBox.height >= 44 && driftBox.height >= 44);
await page.screenshot({
path: `/tmp/soup-swim-${width}.png`,
fullPage: true,
});
// Food inspection is local, persists across updates, and never submits a move.
const crowded = structuredClone(s);
crowded.amoebas.slice(1, 4).forEach((a) => (a.cell = 6));
crowded.amoebas[0].hp = 1;
crowded.amoebas[1].hp = 2;
await show(crowded);
const foodToggle = page.locator('[data-ui="food-view"]');
const numbersToggle = page.locator('[data-ui="numbers-view"]');
const foodBefore = await page.locator(".nutrients").allTextContents();
await page
.locator(".board-wrap")
.screenshot({ path: `/tmp/soup-food-before-${width}.png` });
const amoebaLabels = await page
.locator(".organisms .amoeba-button")
.evaluateAll((buttons) =>
buttons.map((button) => button.getAttribute("aria-label")),
);
if (width <= 390) await numbersToggle.tap();
else await numbersToggle.click();
assert.equal(await numbersToggle.getAttribute("aria-pressed"), "true");
assert.equal(
await numbersToggle.getAttribute("aria-label"),
"Show amoeba numbers",
);
assert.equal(
await page.locator(".organisms .amoeba-number:visible").count(),
0,
);
assert.equal(await page.locator(".organisms .injury:visible").count(), 2);
assert.equal(
await page.locator(".amoeba-button:visible").count(),
crowded.amoebas.length,
);
assert.deepEqual(await page.evaluate(() => moves), []);
await show(crowded);
assert.equal(
await page.locator(".organisms .amoeba-number:visible").count(),
0,
);
assert.deepEqual(
await page
.locator(".organisms .amoeba-button")
.evaluateAll((buttons) =>
buttons.map((button) => button.getAttribute("aria-label")),
),
amoebaLabels,
"Number hiding preserves accessible identities and injuries",
);
await page
.locator(".board-wrap")
.screenshot({ path: `/tmp/soup-injuries-${width}.png` });
// Hold near the edge: a press animation must not move the target out
// from under the pointer before release, cancelling the click.
await foodToggle.scrollIntoViewIfNeeded();
const foodToggleBox = await foodToggle.boundingBox();
await page.mouse.move(foodToggleBox.x + 8, foodToggleBox.y + 22);
await page.mouse.down();
await page.waitForTimeout(200);
assert.deepEqual(
await foodToggle.boundingBox(),
foodToggleBox,
"The food toggle stays still while pressed",
);
await page.mouse.up();
assert.equal(await foodToggle.getAttribute("aria-pressed"), "true");
assert.equal(await foodToggle.getAttribute("aria-label"), "Show amoebas");
assert.equal(await page.locator(".amoeba-button:visible").count(), 0);
assert.ok(await page.locator(".player-portrait").first().isVisible());
assert.deepEqual(
await page.locator(".nutrients").allTextContents(),
foodBefore,
);
assert.equal(await page.locator(".water-cell.valid").count(), 0);
await page.locator('[data-cell="6"]').click({ force: true });
assert.deepEqual(await page.evaluate(() => moves), []);
await show(crowded);
assert.equal(await page.locator(".amoeba-button:visible").count(), 0);
await page
.locator(".board-wrap")
.screenshot({ path: `/tmp/soup-food-after-${width}.png` });
await swim.click();
assert.ok(await page.locator(".amoeba-button").first().isVisible());
assert.equal(await foodToggle.getAttribute("aria-pressed"), "false");
assert.equal(
await page.locator(".organisms .amoeba-number:visible").count(),
0,
);
assert.equal(await page.locator(".organisms .injury:visible").count(), 2);
await numbersToggle.click();
assert.equal(
await page.locator(".organisms .amoeba-number:visible").count(),
crowded.amoebas.length,
);
await show(s);
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 driftButton.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());
// Direct board destinations remain usable alongside the new button.
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);
await page.locator("[data-undo]").click();
s = E.move(s, { type: "undo" }, 0);
await show(s);
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()));
assert.ok(!(await driftButton.isVisible()));
// Free drift remains available when swimming is unaffordable, including
// still currents and blocked destinations that leave the amoeba in place.
for (const direction of [2, 0, 4]) {
s = prepared({ bp: 0 });
s.environment.direction = direction;
await show(s);
assert.ok(await driftButton.isVisible());
assert.equal(await swim.count(), 0);
const move = E.legalMoves(s).find((m) => m.type === "drift");
if (move.cell === s.amoebas[0].cell)
assert.match(await driftButton.textContent(), /Stay here/);
await driftButton.click();
assert.deepEqual(await page.evaluate(() => moves.at(-1)), move);
}
// Rebound must preserve both legal destinations, without moving on open.
s = prepared({ genes: ["rebound"] });
s.amoebas[0].cell = 11;
const rebounds = E.legalMoves(s).filter((m) => m.type === "drift");
assert.equal(rebounds.length, 2);
for (const [index, move] of rebounds.entries()) {
await show(s);
const before = await page.evaluate(() => moves.length);
await driftButton.focus();
await page.keyboard.press("Enter");
assert.equal(await page.evaluate(() => moves.length), before);
const destinations = page.locator(".board-drift-destinations button");
assert.equal(await destinations.count(), 2);
assert.ok(await destinations.nth(index).isVisible());
await destinations.nth(index).click();
assert.deepEqual(await page.evaluate(() => moves.at(-1)), move);
}
s = prepared({ bp: 0, genes: ["streamline", "movement2"] });
await show(s);
assert.match(await swim.getAttribute("aria-label"), /free/);
assert.equal(await swim.getAttribute("title"), "Swim: choose a direction.");
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(".board-drift, .board-swim").count(), 0);
s = prepared({ genes: ["speed"], task: { kind: "speed", a: "0-1" } });
await show(s);
assert.equal(await page.getByRole("button", { name: /^Swim/ }).count(), 1);
assert.equal(await driftButton.count(), 0);
assert.match(await swim.textContent(), /Swim again.*Free/);
assert.ok(
await page
.getByRole("button", { name: "Finish moving", exact: true })
.isVisible(),
);
await swim.click();
assert.deepEqual(await page.evaluate(() => moves.at(-1)), {
type: "swim-again",
});
s = prepared();
for (const [locale, driftName, swimName] of [
["fr", "Dériver", "Nager"],
["de", "Treiben", "Schwimmen"],
]) {
await page.evaluate(
(locale) => e.emit("preferences", { locale }),
locale,
);
await show(s);
assert.ok((await driftButton.textContent()).includes(driftName));
assert.ok((await swim.textContent()).includes(swimName));
assert.ok(
await page.evaluate(
() => document.documentElement.scrollWidth <= innerWidth,
),
);
await driftButton.click();
assert.deepEqual(
await page.evaluate(() => moves.at(-1)),
E.legalMoves(s).find((m) => m.type === "drift"),
);
}
await page.evaluate(() => {
e.emit("preferences", { locale: "en" });
e.emit("player", {});
});
await show(s);
assert.equal(await page.locator(".board-drift, .board-swim").count(), 0);
await foodToggle.click();
assert.equal(await page.locator(".amoeba-button:visible").count(), 0);
await foodToggle.click();
assert.ok(await page.locator(".amoeba-button").first().isVisible());
await page.evaluate(() => e.emit("player", { index: 0 }));
// 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: kind === "division" ? "Finish division" : "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);
}
// An opponent's picture must not swallow a valid placement tap.
// Use real touch events at phone widths, including the number badge.
s = prepared({ phase: 3, bp: 14, task: { kind: "division", p: 0 } });
s.tasks.push({ kind: "division", p: 1 });
s.amoebas.find((a) => a.id === "1-1").cell = 7;
await show(s);
const activate = (locator) =>
width <= 390 ? locator.tap() : locator.click();
const finishDivision = page.getByRole("button", {
name: /^(End division early|Finish division)$/,
});
assert.equal(await finishDivision.textContent(), "End division early");
assert.match(await finishDivision.getAttribute("class"), /secondary/);
const beforeSelection = await page.evaluate(() => moves.length);
await activate(page.locator('[data-amoeba="0-1"]'));
assert.equal(await page.evaluate(() => moves.length), beforeSelection);
await page.getByLabel("Amoeba number", { exact: true }).selectOption("5");
const occupied = page.locator('[data-amoeba="1-1"]');
assert.match(await occupied.getAttribute("aria-label"), /New amoeba #5/);
await activate(occupied.locator(".amoeba-number"));
const placement = await page.evaluate(() => moves.at(-1));
assert.deepEqual(placement, { type: "divide", cell: 7, n: 5 });
assert.ok(
!(await page.locator(".phase-instruction").textContent()).includes(
"places amoeba",
),
"No success notice before the server confirms placement",
);
s = E.move(s, placement, 0);
await show(s);
assert.equal(s.players[0].bp, 8);
assert.equal(await page.locator('[data-amoeba="0-5"].selected').count(), 1);
assert.match(
await page.locator(".phase-instruction").textContent(),
/places amoeba #5 at C2 for.*6/,
);
assert.equal(
(await page.locator(".player-bp").first().textContent()).trim(),
"8",
);
await page.screenshot({
path: `/tmp/soup-division-${width}.png`,
fullPage: true,
});
await activate(page.locator("[data-undo]"));
s = E.move(s, { type: "undo" }, 0);
await show(s);
assert.equal(s.players[0].bp, 14);
assert.equal(await page.locator('[data-amoeba="0-5"]').count(), 0);
assert.match(
await page.locator(".phase-instruction").textContent(),
/Tap a highlighted space/,
);
// Passing remains a single deliberate action; it never confirms a selection.
const beforeFinish = await page.evaluate(() => moves.length);
await activate(finishDivision);
assert.equal(await page.evaluate(() => moves.length), beforeFinish + 1);
assert.deepEqual(await page.evaluate(() => moves.at(-1)), { type: "done" });
s = E.move(s, { type: "done" }, 0);
await show(s);
assert.equal(E.colony(s, 0).length, 2);
assert.equal(s.players[0].bp, 14);
// With no placement available, an opponent is still inspectable.
s = prepared({ phase: 3, bp: 0, task: { kind: "division", p: 0 } });
s.amoebas.find((a) => a.id === "1-1").cell = 7;
await show(s);
const beforeInspection = await page.evaluate(() => moves.length);
await activate(occupied);
assert.equal(await page.evaluate(() => moves.length), beforeInspection);
assert.equal(
await page.locator(".colony-heading h2").textContent(),
"Maya",
);
assert.equal(await finishDivision.textContent(), "Finish division");
assert.match(await finishDivision.getAttribute("class"), /primary/);
// 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}: paired Drift/Swim, Rebound, free movement, Speed, translations, undo, dice boundary, automatic empty turns, occupied-space placement, placement feedback, final-action confirmation, income, six visible badges and colony gene colour passed`,
);
}
} finally {
await browser.close();
}