Merge pull request #1 from MikeIsom/new-options

Adds two optional setup option checkboxes, both off by default
This commit is contained in:
MikeIsom 2026-10-28 08:00:22 -06:00 • committed by GitHub
commit 16277e7ae7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
49 changed files with 934 additions and 105 deletions

View file

@ -36,7 +36,7 @@ play every seat. The toolbar plays random moves, jumps to the next merger, and s
player, theme and language.
URL parameters: `players=2..6`, `seed=...`, `publicHoldings=1`, `teamPlay=1`, `autoEnd=1`,
`endSize=31`, `twoPlayerMode=fourHands`, `stockSwap=3` (or `5`, `7`, `unlimited`), `theme=light|dark`, `locale=de`, `moves=50` (random
`endSize=31`, `twoPlayerMode=fourHands`, `stockSwap=3` (or `5`, `7`, `unlimited`), `twoTiles=1`, `limitedLog=1`, `theme=light|dark`, `locale=de`, `moves=50` (random
moves on load), `merger=1` (continue to the next merger).
## What ships

View file

@ -121,6 +121,18 @@
"label": "Unlimited"
}
]
},
{
"name": "twoTiles",
"label": "Two tiles per turn (hands of 8)",
"type": "checkbox",
"default": false
},
{
"name": "limitedLog",
"label": "Limited game log (only last round)",
"type": "checkbox",
"default": false
}
],
"settings": [],

View file

@ -37,6 +37,20 @@ A chain of 11 or more tiles is **safe**: it can never be taken over.
- A tile that would found an 8th chain can't be played while all 7 chains are on the board. You keep it; it becomes playable when a chain disappears.
- If none of your tiles can be played, you skip placing and may still buy stock.
### Two tiles per turn
If the game uses **Two tiles per turn**, each player holds 8 tiles instead of 6 and places two tiles every turn.
At the start of your turn, swap out any dead tiles. Then place your first tile and settle anything it causes, including a full merger with everyone's sell, trade or keep decisions, before placing your second. After both tiles, buy up to 3 shares at the prices on the board, then draw back up to 8.
You may found only one chain per turn, and you can't found a chain and cause a merger in the same turn, in either order. You can cause two mergers, one with each tile. Example: your first tile merges Luxor into Tower, so your second tile can merge again or grow a chain, but it can't found a new one.
You must play a second tile if any tile in your hand is legal after the first. If none is, go straight to buying. A tile that becomes dead during your turn, for example because your first tile made a chain safe, can't be your second tile; it's swapped out at the start of your next turn.
You can announce the end of the game before your first tile, between your two tiles, or while buying, as long as an end condition holds at that moment.
In a two-player game, the bank's tiles are placed right after the merger that drew them, so between your two tiles if your first tile caused it. Mergers caused by the bank's tiles don't count toward your two mergers or the founding rule. If a player leaves, the game places their first two legal tiles for them.
## Mergers
The **largest** chain survives and takes over the others. If chains tie for largest, the player who placed the tile chooses the survivor. Sizes are counted before the merging tile is placed.
@ -112,10 +126,18 @@ With two players, the bank also acts as a shareholder whenever bonuses are paid.
## What you can see
Your tiles are private. Unless the game was created with **public holdings**, each player's cash and shares are private too; the game log is always public, so a careful player can work them out.
Your tiles are private. Unless the game was created with **public holdings**, each player's cash and shares are private too; the game log is public (unless the game uses a limited game log, below), so a careful player can work them out.
### Limited game log
Much of Acquire is remembering who bought what. If the game uses **Limited game log**, the log only shows what has happened since your last turn. During a merger, the log still shows everything about that merger, even if it started before your last turn. The full log opens up once the game ends.
Because replaying the game would show the full history, replay is only available after the game ends when this setting is on.
## Game options
- **Limited game log:** the log shows only what happened since your last turn, until the game ends (see above).
- **Two tiles per turn:** hands of 8 tiles and two tiles placed every turn (see above).
- **Stock swap:** optional 1:1 exchanges with the bank before buying; Off / 3 / 5 / 7 / Unlimited shares per turn (see above).
- **Public holdings:** everyone's cash and shares are visible.
- **Team play** (4 players only): seats 1 and 3 play against seats 2 and 4; each team's money is added together at the end.

View file

@ -18,3 +18,5 @@ export * from "./src/view.js";
export * from "./src/replay.js";
export * from "./src/position.js";
export * from "./src/simple.js";
export { logWindowStart } from "./src/limited-log.js";
export { blockedThisTurn, secondPlacementDue, turnPlacements } from "./src/two-tiles.js";

View file

@ -1,7 +1,7 @@
import { connectedLoose, placementEffect, tileLegality, chainSize } from "./board.js";
import { startMerger } from "./merger.js";
import { tileColumn } from "./tiles.js";
import { drawTile, enterBuyPhase } from "./turn.js";
import { afterPlacement, drawTile } from "./turn.js";
import type { BankHolding, GameState } from "./types.js";
/** rules.md §12/§15: the bank is a third shareholder with exactly 2 players and twoPlayerMode "bank". */
@ -31,14 +31,15 @@ export function bankHolding(state: GameState, fate: "wait" | "setAside"): Omit<B
}
/**
* rules.md §12.1.4: place waiting bank tiles in draw order, before the active player's buy step.
* rules.md §12.1.4: place waiting bank tiles in draw order, before the active player's buy step
* (or, with twoTiles, before their second tile).
* A tile that causes a merger starts it; when that merger completes it calls back here, so the
* queue (including tiles drawn by that merger) continues where it left off.
*/
export function placeNextBankTile(state: GameState): void {
const tile = state.bankTiles.shift();
if (tile === undefined) {
enterBuyPhase(state);
afterPlacement(state);
return;
}
if (tileLegality(state.board, tile) === "permanentlyUnplayable") {

View file

@ -1,5 +1,6 @@
import { CHAIN_IDS, END_SIZE, SAFE_SIZE, type ChainId } from "./config.js";
import { neighbours, type Tile } from "./tiles.js";
import { blockedThisTurn } from "./two-tiles.js";
import type { Cell, GameState } from "./types.js";
export type Placement =
@ -47,8 +48,11 @@ export function tileLegality(board: Cell[], tile: Tile): Legality {
return "playable";
}
/** Tiles `seat` may place now, including the rules.md §15 twoTiles limits on the active turn. */
export function playableTiles(state: GameState, seat: number): Tile[] {
return (state.seats[seat]?.hand ?? []).filter((tile) => tileLegality(state.board, tile) === "playable");
return (state.seats[seat]?.hand ?? []).filter(
(tile) => tileLegality(state.board, tile) === "playable" && !blockedThisTurn(state, tile)
);
}
/** The tile plus every loose tile connected to it through other loose tiles. */

View file

@ -21,6 +21,7 @@ export const BOARD_ROWS = 9;
export const TILE_COUNT = BOARD_COLUMNS * BOARD_ROWS;
export const STARTING_CASH = 6000;
export const HAND_SIZE = 6;
export const TWO_TILE_HAND_SIZE = 8;
export const SHARES_PER_CHAIN = 25;
export const SAFE_SIZE = 11;
export const END_SIZE = 41;

View file

@ -0,0 +1,139 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import * as wrapper from "../wrapper.js";
import { legalMoves } from "./legal.js";
import { logWindowStart } from "./limited-log.js";
import { applyMove, currentSeat } from "./moves.js";
import { normalizeOptions } from "./options.js";
import { initGame } from "./setup.js";
import type { GameState, LogEntry } from "./types.js";
const LIMITED = { limitedLog: true };
function lcg(seed: number): () => number {
let s = seed >>> 0;
return () => {
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
return s / 2 ** 32;
};
}
/** Plays random legal moves (never announcing) until `done` holds or the game ends. */
function playUntil(state: GameState, random: () => number, done: (state: GameState) => boolean = () => false) {
while (!state.ended && !done(state)) {
const moves = legalMoves(state).filter((move) => move.type !== "announce");
applyMove(state, moves[Math.floor(random() * moves.length)]!, currentSeat(state)!);
}
}
function turnIndexes(state: GameState, seat: number): number[] {
return state.log.flatMap((entry, index) => (entry.type === "turn" && entry.seat === seat ? [index] : []));
}
const hiddenCount = (log: LogEntry[]) => log.filter((entry) => entry.type === "hidden").length;
test("§15 limitedLog defaults off: every viewer gets the whole log", () => {
assert.equal("limitedLog" in normalizeOptions(3, {}).options, false);
assert.equal(normalizeOptions(3, { limitedLog: "true" }).options.limitedLog, undefined);
assert.equal(normalizeOptions(3, LIMITED).options.limitedLog, true);
const state = initGame(3, {}, "full-log");
playUntil(state, lcg(1), (s) => s.turn > 12);
for (const player of [0, 1, 2, undefined]) {
assert.deepEqual(wrapper.stripSecret(state, player).log, state.log);
}
});
test("§13 limitedLog: a player sees the log from the start of their last turn, with setup kept", () => {
const state = initGame(4, LIMITED, "window");
playUntil(state, lcg(2), (s) => s.turn > 14 && s.phase === "place");
const active = state.activeSeat;
for (let player = 0; player < 4; player++) {
const view = wrapper.stripSecret(state, player);
assert.equal(view.log.length, state.log.length, "the log keeps its length for turn drafts");
const turns = turnIndexes(state, player);
// While it is your turn, the window starts at your previous one.
const start = player === active ? turns.at(-2)! : turns.at(-1)!;
assert.equal(logWindowStart(state, player), start);
view.log.forEach((entry, index) => {
const setup = ["init", "optionIgnored", "turnOrder"].includes(state.log[index]!.type);
assert.deepEqual(entry, index >= start || setup ? state.log[index] : { type: "hidden" }, `entry ${index}`);
});
assert.ok(hiddenCount(view.log) > 0);
}
assert.deepEqual(
wrapper.stripSecret(state, undefined).log,
wrapper.stripSecret(state, active).log,
"spectators see what the active player sees"
);
});
test("§13 limitedLog: a merger in progress stays fully visible to every disposer", () => {
const state = initGame(4, LIMITED, "mergers");
const random = lcg(6);
let disposals = 0;
while (!state.ended && disposals < 20) {
if (state.phase === "dispose") {
const current = state.log.map((entry) => entry.type).lastIndexOf("turn");
const view = wrapper.stripSecret(state, state.seatOwner[currentSeat(state)!]);
assert.deepEqual(view.log.slice(current), state.log.slice(current));
disposals++;
}
const moves = legalMoves(state).filter((move) => move.type !== "announce");
applyMove(state, moves[Math.floor(random() * moves.length)]!, currentSeat(state)!);
}
assert.ok(disposals > 0, "the game reached a stock disposal");
});
test("§13 limitedLog: the whole log is revealed once the game ends", () => {
const state = initGame(3, LIMITED, "revealed");
playUntil(state, lcg(3));
assert.equal(state.ended, true);
for (const player of [0, 1, 2, undefined]) {
assert.deepEqual(wrapper.stripSecret(state, player).log, state.log);
assert.equal(hiddenCount(wrapper.logSlice(state, { player }).log), 0);
}
});
test("§13 limitedLog: logSlice hides the same entries, and new entries are never hidden", () => {
const state = initGame(3, LIMITED, "slice");
const random = lcg(4);
playUntil(state, random, (s) => s.turn > 10);
for (const player of [0, 1, 2, undefined]) {
const { log } = wrapper.logSlice(state, { player });
assert.deepEqual(
log.map(({ simple: _simple, ...entry }) => entry),
wrapper.stripSecret(state, player).log
);
for (const entry of log) {
assert.ok(entry.simple.length > 0);
}
}
const before = state.log.length;
playUntil(state, random, (s) => s.log.length > before + 5);
for (const player of [0, 1, 2]) {
assert.equal(hiddenCount(wrapper.logSlice(state, { player, start: before }).log), 0);
}
});
test("§13 limitedLog: legal moves and turn drafts work from a player's limited view", () => {
for (let players = 2; players <= 6; players++) {
for (const options of [LIMITED, { ...LIMITED, twoTiles: true, stockSwap: "unlimited" }]) {
const state = initGame(players, options, `view-${players}`);
const random = lcg(players);
for (let i = 0; i < 300 && !state.ended; i++) {
const seat = currentSeat(state)!;
const view = wrapper.stripSecret(state, state.seatOwner[seat]);
assert.deepEqual(legalMoves(view), legalMoves(state), `${players} players, move ${i}`);
const moves = legalMoves(state).filter((move) => move.type !== "announce");
applyMove(state, moves[Math.floor(random() * moves.length)]!, seat);
}
}
}
const state = initGame(3, LIMITED, "draft");
playUntil(state, lcg(5), (s) => s.turn > 9 && s.phase === "place");
const player = wrapper.currentPlayer(state)!;
const view = wrapper.stripSecret(state, player);
const move = legalMoves(view).find((m) => m.type === "place")!;
const result = wrapper.move(state, { type: "turn", from: view.log.length, moves: [move] }, player);
assert.equal(result.log.length > state.log.length || result.tentative !== undefined, true);
});

View file

@ -0,0 +1,38 @@
import type { GameState, LogEntry } from "./types.js";
import { seatsOf } from "./view.js";
/** Setup entries describe options and turn order, not play, so they always stay visible. */
const SETUP: LogEntry["type"][] = ["init", "optionIgnored", "turnOrder"];
/**
* rules.md §13 limitedLog: the first log index `player` may read (undefined for a
* spectator). Players see from the start of their own last turn before the current one, so
* the current turn, including a merger in progress, is always visible. Spectators see as much
* as the active player. The whole log is visible when the option is off or the game is over.
*/
export function logWindowStart(state: GameState, player: number | undefined): number {
if (!state.options.limitedLog || state.ended) {
return 0;
}
const own = player === undefined ? [state.activeSeat] : seatsOf(state, player);
let current = true;
for (let index = state.log.length - 1; index >= 0; index--) {
const entry = state.log[index]!;
if (entry.type !== "turn") {
continue;
}
if (!current && own.includes(entry.seat)) {
return index;
}
current = false;
}
return 0;
}
/** The log as `player` may read it: earlier entries become placeholders, keeping its length. */
export function visibleLog(state: GameState, player: number | undefined): LogEntry[] {
const start = logWindowStart(state, player);
return state.log.map((entry, index) =>
index >= start || SETUP.includes(entry.type) ? structuredClone(entry) : { type: "hidden" }
);
}

View file

@ -15,7 +15,8 @@ import { maxStockSwap, swapStock } from "./stock-swap.js";
import { sharePrice } from "./prices.js";
import { canAnnounce, endGame } from "./scoring.js";
import { parseTile, tileLabel, type Tile } from "./tiles.js";
import { endTurn, enterBuyPhase } from "./turn.js";
import { afterPlacement, endTurn, enterBuyPhase } from "./turn.js";
import { blockedThisTurn } from "./two-tiles.js";
import type { GameState, Move, Shares } from "./types.js";
export function currentSeat(state: GameState): number | undefined {
@ -45,7 +46,8 @@ export function sanitizeMove(state: GameState, raw: unknown, seat: number): Move
throw new Error("A move must be an object");
}
if (raw.type === "announce") {
// rules.md §4/§11.1: before placing or during the buy step, checked at this moment.
// rules.md §4/§11.1: before placing (with twoTiles, also before the second tile) or
// during the buy step, checked at this moment.
if (state.phase !== "place" && state.phase !== "buy") {
throw new Error("The end can only be announced before placing a tile or while buying");
}
@ -85,6 +87,9 @@ export function sanitizeMove(state: GameState, raw: unknown, seat: number): Move
if (tileLegality(state.board, tile) !== "playable") {
throw new Error(`Tile ${tileLabel(tile)} cannot be played now`);
}
if (blockedThisTurn(state, tile)) {
throw new Error("A turn cannot found two chains, or both found a chain and cause a merger");
}
return { type: "place", tile: tileLabel(tile) };
}
case "found": {
@ -251,7 +256,7 @@ function perform(state: GameState, move: Move, seat: number, auto: boolean): voi
break;
case "found":
foundChain(state, move.chain);
enterBuyPhase(state);
afterPlacement(state);
break;
case "survivor":
setSurvivor(state, move.chain);
@ -297,7 +302,7 @@ function placeTile(state: GameState, tile: Tile): void {
}
foundChain(state, available[0]!);
}
enterBuyPhase(state);
afterPlacement(state);
}
/** rules.md §6. */

View file

@ -1,4 +1,4 @@
import { END_SIZE } from "./config.js";
import { END_SIZE, HAND_SIZE, TWO_TILE_HAND_SIZE } from "./config.js";
/** rules.md §15, after normalisation against the player count. */
export interface GameOptions {
@ -9,6 +9,10 @@ export interface GameOptions {
endSize: number;
/** Omitted when off, preserving the init log of games created before this variant. */
stockSwap?: 3 | 5 | 7 | "unlimited";
/** Omitted when off, like stockSwap. */
twoTiles?: true;
/** Omitted when off, like stockSwap. */
limitedLog?: true;
}
export interface IgnoredOption {
@ -80,9 +84,21 @@ export function normalizeOptions(
}
}
if (raw.twoTiles === true) {
options.twoTiles = true;
}
if (raw.limitedLog === true) {
options.limitedLog = true;
}
return { options, ignored };
}
/** rules.md §15 twoTiles: hands hold 8 tiles instead of 6. */
export function handSize(options: GameOptions): number {
return options.twoTiles ? TWO_TILE_HAND_SIZE : HAND_SIZE;
}
/** Internal seats per real player: fourHands gives each of the 2 players two seats. */
export function seatOwners(players: number, options: GameOptions): number[] {
if (players === 2 && options.twoPlayerMode === "fourHands") {

View file

@ -1,5 +1,6 @@
import { connectedLoose, placementEffect } from "./board.js";
import { CHAIN_IDS, HAND_SIZE, SHARES_PER_CHAIN, STARTING_CASH, type ChainId } from "./config.js";
import { CHAIN_IDS, SHARES_PER_CHAIN, STARTING_CASH, type ChainId } from "./config.js";
import { handSize } from "./options.js";
import { parseTile, type Tile } from "./tiles.js";
import type { Cell, GameState, Shares } from "./types.js";
@ -24,6 +25,7 @@ export function positionAt(state: GameState, to: number): PublicPosition {
const bank = sharesOf(SHARES_PER_CHAIN);
let seats: PublicPosition["seats"] = [];
let lastTile: Tile | undefined;
let hand = 0;
let merger: { tile: Tile; chains: ChainId[]; survivor?: ChainId } | undefined;
const place = (tile: Tile) => {
@ -41,6 +43,7 @@ export function positionAt(state: GameState, to: number): PublicPosition {
switch (entry.type) {
case "init":
seats = Array.from({ length: entry.seats }, () => ({ cash: STARTING_CASH, shares: sharesOf(0), tiles: 0 }));
hand = handSize(entry.options);
break;
case "turnOrder":
for (const tile of entry.tiles) {
@ -48,7 +51,7 @@ export function positionAt(state: GameState, to: number): PublicPosition {
}
// rules.md §3.4: every seat then draws a full hand, which is not logged as a draw.
for (const seat of seats) {
seat.tiles = HAND_SIZE;
seat.tiles = hand;
}
break;
case "move":

View file

@ -1,5 +1,5 @@
import { CHAIN_IDS, HAND_SIZE, MAX_PLAYERS, MIN_PLAYERS, SHARES_PER_CHAIN, STARTING_CASH } from "./config.js";
import { normalizeOptions, seatOwners } from "./options.js";
import { CHAIN_IDS, MAX_PLAYERS, MIN_PLAYERS, SHARES_PER_CHAIN, STARTING_CASH } from "./config.js";
import { handSize, normalizeOptions, seatOwners } from "./options.js";
import { shuffle } from "./prng.js";
import { allTiles } from "./tiles.js";
import { drawTile, startTurn } from "./turn.js";
@ -60,7 +60,7 @@ export function initGame(players: number, rawOptions: Record<string, unknown>, s
state.log.push({ type: "turnOrder", tiles: orderTiles, first });
for (const seat of state.seats) {
for (let i = 0; i < HAND_SIZE; i++) {
for (let i = 0; i < handSize(options); i++) {
seat.hand.push(drawTile(state)!);
}
}

View file

@ -22,17 +22,20 @@ function lcg(seed: number): () => number {
function optionCombinations(players: number): Record<string, unknown>[] {
const combos: Record<string, unknown>[] = [];
for (const publicHoldings of [false, true]) {
for (const autoEnd of [false, true]) {
for (const endSize of ["41", "31"]) {
for (const twoPlayerMode of players === 2 ? ["bank", "fourHands"] : ["bank"]) {
for (const teamPlay of players === 4 ? [false, true] : [false]) {
combos.push({
...(publicHoldings ? { publicHoldings } : {}),
...(autoEnd ? { autoEnd } : {}),
...(teamPlay ? { teamPlay } : {}),
twoPlayerMode,
endSize,
});
for (const twoTiles of [false, true]) {
for (const autoEnd of [false, true]) {
for (const endSize of ["41", "31"]) {
for (const twoPlayerMode of players === 2 ? ["bank", "fourHands"] : ["bank"]) {
for (const teamPlay of players === 4 ? [false, true] : [false]) {
combos.push({
...(publicHoldings ? { publicHoldings } : {}),
...(autoEnd ? { autoEnd } : {}),
...(twoTiles ? { twoTiles } : {}),
...(teamPlay ? { teamPlay } : {}),
twoPlayerMode,
endSize,
});
}
}
}
}
@ -133,6 +136,6 @@ for (let players = 2; players <= 6; players++) {
test("§15 the simulation covers every valid option combination", () => {
assert.deepEqual(
[2, 3, 4, 5, 6].map((players) => optionCombinations(players).length),
[16, 8, 16, 8, 8]
[32, 16, 32, 16, 16]
);
});

View file

@ -52,7 +52,7 @@ export function simpleLineAt(state: GameState, index: number): string {
/**
* The turn that ended just before the "turn" entry at `index`, most important first: the
* placement (or the founding or merger it caused), then purchases, then an announcement.
* placements (or the foundings or mergers they caused), then purchases, then an announcement.
* For example "Ann merged Luxor into Tower, bought 2 Tower".
*/
export function turnSummary(state: GameState, index: number): string {
@ -64,18 +64,20 @@ export function turnSummary(state: GameState, index: number): string {
return "The game started";
}
const seat = (state.log[start] as Extract<LogEntry, { type: "turn" }>).seat;
let placement = "placed no tile";
// One line per placed tile (two with twoTiles), each replaced by what it caused.
const placements: string[] = [];
let bankMerger = false;
const parts: string[] = [];
for (const entry of state.log.slice(start + 1, index)) {
if (entry.type === "move" && entry.move.type === "place") {
placement = `placed ${entry.move.tile}`;
placements.push(`placed ${entry.move.tile}`);
} else if (entry.type === "founded") {
placement = `founded ${chainName(entry.chain)}`;
placements[placements.length - 1] = `founded ${chainName(entry.chain)}`;
} else if (entry.type === "merger") {
bankMerger = entry.byBank === true;
} else if (entry.type === "mergerPlan" && !bankMerger && !placement.startsWith("merged")) {
placement = `merged ${list(entry.defunct.map(chainName))} into ${chainName(entry.survivor)}`;
} else if (entry.type === "mergerPlan" && !bankMerger && !placements.at(-1)!.startsWith("merged")) {
placements[placements.length - 1] =
`merged ${list(entry.defunct.map(chainName))} into ${chainName(entry.survivor)}`;
} else if (entry.type === "swapped") {
parts.push(`swapped ${entry.count} ${chainName(entry.from)} for ${entry.count} ${chainName(entry.to)}`);
} else if (entry.type === "bought" && Object.keys(entry.shares).length > 0) {
@ -86,7 +88,7 @@ export function turnSummary(state: GameState, index: number): string {
parts.push("left the game");
}
}
return `${seatName(state, seat)} ${[placement, ...parts].join(", ")}`;
return `${seatName(state, seat)} ${[...(placements.length > 0 ? placements : ["placed no tile"]), ...parts].join(", ")}`;
}
export function simpleLine(state: GameState, entry: LogEntry): string {
@ -200,6 +202,8 @@ export function simpleLine(state: GameState, entry: LogEntry): string {
return `${seat(entry.seat)} sold ${entry.shares} ${chainName(entry.chain)} for ${money(entry.proceeds)}`;
case "result":
return `Final cash: ${list(entry.cash.map((cash, s) => `${seat(s)} ${money(cash)}`))}`;
case "hidden":
return "An earlier move (hidden until the game ends)";
}
return "";
}

View file

@ -1,8 +1,10 @@
import { activeChains, chainSize, playableTiles, tileLegality } from "./board.js";
import { AUTO_TURN_LIMIT, HAND_SIZE } from "./config.js";
import { AUTO_TURN_LIMIT } from "./config.js";
import { handSize } from "./options.js";
import { sharePrice } from "./prices.js";
import { canAnnounce, endConditionMet, endGame } from "./scoring.js";
import type { Tile } from "./tiles.js";
import { secondPlacementDue } from "./two-tiles.js";
import type { GameState } from "./types.js";
export function drawTile(state: GameState): Tile | undefined {
@ -40,6 +42,10 @@ export function startTurn(state: GameState): void {
state.turn += 1;
state.placedThisTurn = false;
state.log.push({ type: "turn", seat: state.activeSeat });
if (state.options.twoTiles) {
// rules.md §15 twoTiles: dead tiles are replaced at the start of the turn instead.
replaceDeadTiles(state);
}
if (playableTiles(state, state.activeSeat).length > 0 || canAnnounce(state)) {
state.phase = "place";
return;
@ -55,7 +61,18 @@ export function startTurn(state: GameState): void {
}
}
/** Called once placement (and any founding or merger) is resolved. */
/**
* Called once a placement and everything it caused (a founding, a merger, bank tiles) is
* resolved. With twoTiles the seat then places its second tile, if any is playable.
*/
export function afterPlacement(state: GameState): void {
if (secondPlacementDue(state) && playableTiles(state, state.activeSeat).length > 0) {
state.phase = "place";
return;
}
enterBuyPhase(state);
}
export function enterBuyPhase(state: GameState): void {
if (buyStepAvailable(state) || canAnnounce(state)) {
state.phase = "buy";
@ -70,12 +87,8 @@ export function endTurn(state: GameState): void {
}
}
/**
* rules.md §4.4-4.5: replace permanently unplayable tiles and refill the hand. Then either end
* the game (an announcement this turn, or the §11.1 stall rule) or pass the turn on.
* Returns whether the game ended.
*/
function finishTurn(state: GameState): boolean {
/** rules.md §5.3: discard the active seat's permanently unplayable tiles and refill the hand. */
function replaceDeadTiles(state: GameState): void {
const seat = state.seats[state.activeSeat]!;
const dead = seat.hand.filter((tile) => tileLegality(state.board, tile) === "permanentlyUnplayable");
if (dead.length > 0) {
@ -83,8 +96,13 @@ function finishTurn(state: GameState): boolean {
state.removed.push(...dead);
state.log.push({ type: "discarded", seat: state.activeSeat, tiles: dead });
}
refillHand(state);
}
function refillHand(state: GameState): void {
const seat = state.seats[state.activeSeat]!;
let drawn = 0;
while (seat.hand.length < HAND_SIZE) {
while (seat.hand.length < handSize(state.options)) {
const tile = drawTile(state);
if (tile === undefined) {
break;
@ -95,6 +113,19 @@ function finishTurn(state: GameState): boolean {
if (drawn > 0) {
state.log.push({ type: "drew", seat: state.activeSeat, count: drawn });
}
}
/**
* rules.md §4.4-4.5: replace permanently unplayable tiles (with twoTiles, only refill) and
* draw. Then either end the game (an announcement this turn, or the §11.1 stall rule) or pass
* the turn on. Returns whether the game ended.
*/
function finishTurn(state: GameState): boolean {
if (state.options.twoTiles) {
refillHand(state);
} else {
replaceDeadTiles(state);
}
state.turnsWithoutPlacement = state.placedThisTurn ? 0 : state.turnsWithoutPlacement + 1;
if (state.endAnnounced !== null) {
endGame(state, "announced");

View file

@ -0,0 +1,260 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import * as wrapper from "../wrapper.js";
import { legalMoves } from "./legal.js";
import { applyMove, currentSeat, dropPlayerSeats } from "./moves.js";
import { normalizeOptions } from "./options.js";
import { positionAt } from "./position.js";
import { initGame } from "./setup.js";
import { turnSummary } from "./simple.js";
import { chainAt, checkInvariants, row, scenario, t } from "./test/helpers.js";
import type { GameState, LogEntry, Move } from "./types.js";
const TWO_TILES = { twoTiles: true };
function play(state: GameState, seat: number, move: Move): GameState {
applyMove(state, move, seat);
checkInvariants(state);
return state;
}
const place = (tile: string): Move => ({ type: "place", tile });
const buy: Move = { type: "buy", shares: {} };
function placeable(state: GameState): string[] {
return legalMoves(state).flatMap((move) => (move.type === "place" ? [move.tile] : []));
}
function entries<T extends LogEntry["type"]>(state: GameState, type: T): Extract<LogEntry, { type: T }>[] {
return state.log.filter((e): e is Extract<LogEntry, { type: T }> => e.type === type);
}
test("§15 twoTiles defaults off and leaves the init log of standard games unchanged", () => {
assert.equal("twoTiles" in normalizeOptions(3, {}).options, false);
for (const twoTiles of [false, "true", 1, null]) {
const { options, ignored } = normalizeOptions(3, { twoTiles });
assert.equal("twoTiles" in options, false);
assert.deepEqual(ignored, []);
}
assert.equal(normalizeOptions(3, TWO_TILES).options.twoTiles, true);
const standard = initGame(3, {}, "standard");
assert.equal("twoTiles" in (standard.log[0] as Extract<LogEntry, { type: "init" }>).options, false);
assert.ok(standard.seats.every((seat) => seat.hand.length === 6));
});
test("§15 twoTiles: hands hold 8 tiles, both tiles are placed before one buy step, then the hand refills", () => {
for (const players of [2, 3, 4, 5, 6]) {
const state = initGame(players, TWO_TILES, `eight-${players}`);
assert.ok(state.seats.every((seat) => seat.hand.length === 8));
assert.ok(positionAt(state, state.log.length).seats.every((seat) => seat.tiles === 8));
}
const state = scenario({
board: chainAt("tower", ["1A", "2A"]),
hands: [["5E", "9I", "12A", "12C", "12E", "12G", "3I", "1I"], ["10C"], ["10E"]],
poolTop: ["7G", "7I"],
poolOnly: true,
options: TWO_TILES,
});
play(state, 0, place("5E"));
assert.equal(state.phase, "place", "the second tile comes before buying");
assert.deepEqual(placeable(state), ["9I", "12A", "12C", "12E", "12G", "3I", "1I"]);
play(state, 0, place("9I"));
assert.equal(state.phase, "buy");
assert.equal(currentSeat(state), 0);
play(state, 0, { type: "buy", shares: { tower: 3 } });
assert.deepEqual(state.seats[0]!.hand.slice(-2), [t("7G"), t("7I")]);
assert.equal(state.seats[0]!.hand.length, 8, "draws back up to 8");
assert.equal(state.activeSeat, 1);
assert.equal(turnSummary(state, state.log.length - 1), "Player 1 placed 5E, placed 9I, bought 3 Tower");
});
test("§15 twoTiles: the second tile is skipped when none is playable", () => {
// 2A founds a chain with 1A; 2C would found a second one, so it cannot follow.
const state = scenario({
board: { "1A": "loose", "1C": "loose" },
hands: [["2A", "2C"], ["12C"], ["12E"]],
poolOnly: true,
options: TWO_TILES,
});
play(state, 0, place("2A"));
play(state, 0, { type: "found", chain: "tower" });
assert.equal(state.phase, "buy");
assert.deepEqual(placeable(state), []);
});
test("§15 twoTiles: after founding, a tile that would found or merge is blocked; growing is allowed", () => {
const state = scenario({
board: { ...chainAt("tower", ["1E", "2E"]), ...chainAt("luxor", ["4E", "5E"]), "8A": "loose", "1A": "loose" },
hands: [["9A", "3E", "6E", "2A"], ["12C"], ["12E"]],
poolOnly: true,
options: TWO_TILES,
});
assert.deepEqual(placeable(state), ["9A", "3E", "6E", "2A"]);
play(state, 0, place("9A"));
play(state, 0, { type: "found", chain: "american" });
assert.deepEqual(placeable(state), ["6E"]);
for (const tile of ["3E", "2A"]) {
assert.throws(() => applyMove(state, place(tile), 0), /cannot found two chains/);
}
play(state, 0, place("6E"));
assert.equal(state.phase, "buy");
});
test("§15 twoTiles: a turn may cause two mergers, but not a merger and a founding", () => {
const state = scenario({
board: {
...chainAt("tower", ["1A", "2A"]),
...chainAt("luxor", ["4A", "5A"]),
...chainAt("american", ["1E", "2E"]),
...chainAt("festival", ["4E", "5E"]),
"8G": "loose",
},
hands: [["3A", "3E", "9G"], ["12C"], ["12E"]],
poolOnly: true,
options: TWO_TILES,
});
play(state, 0, place("3A"));
play(state, 0, { type: "survivor", chain: "tower" });
assert.equal(state.phase, "place");
assert.deepEqual(placeable(state), ["3E"], "9G would found a chain after a merger");
play(state, 0, place("3E"));
play(state, 0, { type: "survivor", chain: "american" });
assert.equal(state.phase, "buy");
play(state, 0, buy);
assert.equal(
turnSummary(state, state.log.length - 1),
"Player 1 merged Luxor into Tower, merged Festival into American"
);
});
test("§15 twoTiles: a founding first rules out a merger with the second tile", () => {
const state = scenario({
board: { ...chainAt("tower", ["1A", "2A"]), ...chainAt("luxor", ["4A", "5A"]), "8G": "loose" },
hands: [["9G", "3A"], ["12C"], ["12E"]],
poolOnly: true,
options: TWO_TILES,
});
play(state, 0, place("9G"));
play(state, 0, { type: "found", chain: "american" });
assert.deepEqual(placeable(state), [], "3A would merge after a founding");
assert.equal(state.phase, "buy");
});
test("§15 twoTiles: a tile made dead by the first tile cannot be the second and is replaced next turn", () => {
// 11A makes Tower safe, so 2B would then merge two safe chains.
const state = scenario({
board: {
...chainAt("tower", row("A", 1, 10)),
...chainAt("continental", row("C", 1, 11)),
...chainAt("luxor", ["1G", "2G"]),
},
hands: [["11A", "2B"], ["12E"], ["12G"]],
poolOnly: true,
options: TWO_TILES,
});
assert.deepEqual(placeable(state), ["11A", "2B"]);
play(state, 0, place("11A"));
assert.equal(state.phase, "buy");
play(state, 0, buy);
assert.ok(state.seats[0]!.hand.includes(t("2B")), "dead tiles stay in hand at the end of the turn");
assert.equal(entries(state, "discarded").length, 0);
for (const seat of [1, 2]) {
play(
state,
seat,
legalMoves(state).find((move) => move.type === "place")!
);
play(state, seat, buy);
}
assert.equal(state.activeSeat, 0);
const turn = state.log.map((entry) => entry.type).lastIndexOf("turn");
assert.deepEqual(state.log.slice(turn, turn + 2), [
{ type: "turn", seat: 0 },
{ type: "discarded", seat: 0, tiles: [t("2B")] },
]);
assert.ok(!state.seats[0]!.hand.includes(t("2B")));
});
test("§15 twoTiles: the end may be announced between the two tiles once a condition holds", () => {
const state = scenario({
board: chainAt("tower", row("A", 1, 10)),
hands: [["11A", "5E"], ["12E"], ["12G"]],
poolOnly: true,
options: TWO_TILES,
});
assert.equal(
legalMoves(state).some((move) => move.type === "announce"),
false
);
play(state, 0, place("11A"));
assert.equal(state.phase, "place");
play(state, 0, { type: "announce" });
play(state, 0, place("5E"));
play(state, 0, buy);
assert.equal(state.ended, true);
assert.deepEqual(entries(state, "gameEnd"), [{ type: "gameEnd", reason: "announced" }]);
});
test("§15 twoTiles with §12: bank tiles are placed between the two tiles", () => {
const state = scenario({
seats: 2,
board: { ...chainAt("tower", ["1A", "2A", "3A"]), ...chainAt("luxor", ["5A", "6A"]) },
hands: [["4A", "9I", "9G", "12A", "12C", "12E", "12G", "12I"], ["1I"]],
shares: [{}, { luxor: 3 }],
poolTop: ["9C"],
poolOnly: true,
options: TWO_TILES,
});
play(state, 0, place("4A"));
play(state, 1, { type: "dispose", sell: 3, trade: 0 });
assert.equal(state.phase, "place");
assert.equal(currentSeat(state), 0);
assert.deepEqual(state.log.at(-1), { type: "bankTile", tile: t("9C"), result: "loose" });
assert.equal(state.board[t("9C")], "loose");
play(state, 0, place("9I"));
assert.equal(state.phase, "buy");
});
test("§15 twoTiles with §16: a dropped seat places its first two playable tiles", () => {
const state = scenario({
hands: [["5E", "9I", "1A"], ["12C"], ["12E"]],
poolOnly: true,
options: TWO_TILES,
});
dropPlayerSeats(state, 0);
const placed = entries(state, "move").filter((entry) => entry.seat === 0 && entry.move.type === "place");
assert.deepEqual(
placed.map((entry) => entry.move),
[place("1A"), place("5E")]
);
assert.ok(placed.every((entry) => entry.auto));
assert.equal(currentSeat(state), 1);
});
test("§15 twoTiles: both placements can be drafted privately before committing", () => {
const state = scenario({
board: chainAt("tower", ["1A", "2A"]),
hands: [["5E", "9I"], ["12C"], ["12E"]],
poolOnly: true,
options: TWO_TILES,
});
const player = 0;
const draft = wrapper.move(
state,
{ type: "turn", from: state.log.length, moves: [place("5E"), place("9I")] },
player
);
assert.equal(draft.phase, "buy");
assert.deepEqual(draft.tentative, { player, from: state.log.length });
assert.equal(wrapper.toSave(draft), undefined);
});
test("§14.7 twoTiles games replay exactly", () => {
let state = wrapper.init(4, [], TWO_TILES, "replay-two-tiles");
for (let i = 0; i < 60 && !state.ended; i++) {
const player = wrapper.currentPlayer(state)!;
const moves = legalMoves(state).filter((move) => move.type !== "announce");
state = wrapper.move(state, moves[i % moves.length]!, player);
}
assert.deepEqual(wrapper.replay(state), state);
});

View file

@ -0,0 +1,41 @@
import { placementEffect } from "./board.js";
import type { Tile } from "./tiles.js";
import type { GameState } from "./types.js";
/** What the active seat's placements have done so far this turn, read from the log. */
export function turnPlacements(state: GameState): { placed: number; founded: boolean; merged: boolean } {
const result = { placed: 0, founded: false, merged: false };
for (let i = state.log.length - 1; i >= 0; i--) {
const entry = state.log[i]!;
if (entry.type === "turn") {
break;
}
if (entry.type === "move" && entry.move.type === "place") {
result.placed++;
} else if (entry.type === "founded") {
result.founded = true;
} else if (entry.type === "merger" && !entry.byBank) {
// rules.md §15 twoTiles: mergers caused by bank tiles do not count.
result.merged = true;
}
}
return result;
}
/**
* rules.md §15 twoTiles: a turn founds at most one chain, and never both founds a chain and
* causes a merger. Whether `tile` is ruled out by what this turn's placements already did.
*/
export function blockedThisTurn(state: GameState, tile: Tile): boolean {
if (!state.options.twoTiles) {
return false;
}
const { founded, merged } = turnPlacements(state);
const effect = placementEffect(state.board, tile).kind;
return (effect === "found" && (founded || merged)) || (effect === "merge" && founded);
}
/** rules.md §15 twoTiles: whether the active seat places another tile before buying. */
export function secondPlacementDue(state: GameState): boolean {
return state.options.twoTiles === true && turnPlacements(state).placed === 1;
}

View file

@ -78,7 +78,9 @@ export type LogEntry =
| { type: "announced"; seat: number }
| { type: "gameEnd"; reason: "announced" | "condition" | "stall" | "dropped" }
| { type: "finalSale"; seat: number; chain: ChainId; shares: number; proceeds: number }
| { type: "result"; cash: number[]; ranks: number[] };
| { type: "result"; cash: number[]; ranks: number[] }
/** Only in a player's view: an entry from before the limitedLog window (rules.md §13). */
| { type: "hidden" };
export interface GameState {
/** Transient response only; toSave never persists this private draft. */

View file

@ -1,4 +1,5 @@
import { CHAIN_IDS } from "./config.js";
import { visibleLog } from "./limited-log.js";
import type { GameState, Shares } from "./types.js";
/** Value sent in place of anything the viewer may not see. */
@ -15,7 +16,8 @@ export function seatsOf(state: GameState, player: number | undefined): number[]
* rules.md §13: the state as `player` may see it (undefined for a spectator). Hidden numbers
* are replaced by HIDDEN so the shape stays the same. Hands and the pool order are always
* private; holdings and cash are private unless publicHoldings is on or the game has ended.
* The seed is removed because it determines the pool order.
* With limitedLog, older log entries are replaced. The seed is removed because it determines
* the pool order.
*/
export function viewFor(state: GameState, player: number | undefined): GameState {
const own = seatsOf(state, player);
@ -25,6 +27,7 @@ export function viewFor(state: GameState, player: number | undefined): GameState
seed: "",
rngCounter: 0,
pool: state.pool.map(() => HIDDEN),
log: visibleLog(state, player),
seats: state.seats.map((seat, index) => {
if (own.includes(index)) {
return structuredClone(seat);

View file

@ -1,9 +1,10 @@
import { applyTurnRequest, earnedTimeIncrements, isTurnRequest } from "./src/turn-draft.js";
import { visibleLog } from "./src/limited-log.js";
import { applyMove, currentSeat, dropPlayerSeats } from "./src/moves.js";
import { replayGame } from "./src/replay.js";
import { playerRankings, playerScores } from "./src/scoring.js";
import { initGame } from "./src/setup.js";
import { simpleLineAt } from "./src/simple.js";
import { simpleLine, simpleLineAt } from "./src/simple.js";
import type { GameState, LogEntry } from "./src/types.js";
import { seatsOf, viewFor } from "./src/view.js";
@ -71,8 +72,9 @@ export interface LogSliceOptions {
end?: number;
}
// Both endpoints are inclusive. The log is public (rules.md §13), so every viewer gets the same
// slice. Each entry gets a `simple` line for BGS's last-move display.
// Both endpoints are inclusive. The log is public (rules.md §13) except with limitedLog, where
// entries before the player's window are placeholders. Each entry gets a `simple` line for
// BGS's last-move display.
export function logSlice(
data: GameState,
options?: LogSliceOptions
@ -82,8 +84,12 @@ export function logSlice(
} {
const start = Math.max(0, options?.start ?? 0);
const end = options?.end ?? data.log.length - 1;
const log = visibleLog(data, options?.player);
return {
log: data.log.slice(start, end + 1).map((entry, i) => ({ ...entry, simple: simpleLineAt(data, start + i) })),
log: log.slice(start, end + 1).map((entry, i) => ({
...entry,
simple: entry.type === "hidden" ? simpleLine(data, entry) : simpleLineAt(data, start + i),
})),
...(data.tentative && data.tentative.player === options?.player
? { preview: stripSecret(data, options.player) }
: {}),

View file

@ -29,7 +29,7 @@ async function loadBuiltViewer(): Promise<typeof import("./viewer").viewer> {
const players = Math.min(6, Math.max(2, Number(params.get("players") ?? 4)));
const seed = params.get("seed") ?? "dev";
const options: Record<string, unknown> = {};
for (const key of ["publicHoldings", "teamPlay", "autoEnd"]) {
for (const key of ["publicHoldings", "teamPlay", "autoEnd", "twoTiles", "limitedLog"]) {
if (params.get(key) === "1") {
options[key] = true;
}

View file

@ -9,7 +9,7 @@
type GameState,
type Tile,
} from "acquire-engine";
import { ofType } from "./decisions";
import { ofType, turnLimit } from "./decisions";
import { chainName } from "./format";
import { CHAIN_STYLES } from "./palette";
import { safeBorders } from "./safeBorders";
@ -36,6 +36,20 @@
const t = $derived(store.lang.t);
const playable = $derived(new Set(ofType(store.moves, "place").map((move) => parseTile(move.tile)!)));
const borders = $derived(safeBorders(state.board));
/** Why one of the viewer's tiles can't be placed now, or undefined. */
function heldNote(tile: Tile): string | undefined {
const legality = tileLegality(state.board, tile);
if (legality === "permanentlyUnplayable") {
return t("hand.dead");
}
if (legality === "temporarilyUnplayable") {
return t("hand.eighth");
}
const seat = store.seats.find((s) => state.seats[s]?.hand.includes(tile));
const limit = seat === undefined ? undefined : turnLimit(state, seat, tile);
return limit && t(`hand.${limit}`);
}
const safeChains = $derived(new Set(borders.map(({ chain }) => chain)));
const held = $derived(
new Set(
@ -61,6 +75,7 @@
{@const cell = state.board[tile] ?? null}
{@const label = tileLabel(tile)}
{@const legality = held.has(tile) ? tileLegality(state.board, tile) : undefined}
{@const note = held.has(tile) ? heldNote(tile) : undefined}
{#if playable.has(tile) && cell === null}
<button
type="button"
@ -76,20 +91,14 @@
<div
class="square empty"
class:held={held.has(tile)}
class:unavailable={legality !== undefined && legality !== "playable"}
class:unavailable={note !== undefined}
class:dead={legality === "permanentlyUnplayable"}
aria-label={legality === "permanentlyUnplayable"
? `${label} — ${t("hand.dead")}`
: legality === "temporarilyUnplayable"
? `${label} — ${t("hand.eighth")}`
: held.has(tile)
? `${label} — ${t("hand.yours")}`
: t("board.empty", { tile: label })}
title={legality === "permanentlyUnplayable"
? t("hand.dead")
: legality === "temporarilyUnplayable"
? t("hand.eighth")
: undefined}
aria-label={note !== undefined
? `${label} — ${note}`
: held.has(tile)
? `${label} — ${t("hand.yours")}`
: t("board.empty", { tile: label })}
title={note}
>
<span class="coord">{label}</span>
</div>

View file

@ -1,6 +1,6 @@
<script lang="ts">
import { HIDDEN, parseTile, sortTiles, tileLabel, tileLegality, type Tile } from "acquire-engine";
import { ofType } from "./decisions";
import { ofType, turnLimit } from "./decisions";
import { seatName } from "./format";
import type { ViewerStore } from "./store.svelte";
import TileStatusIcon from "./TileStatusIcon.svelte";
@ -12,15 +12,19 @@
// Tiles the engine would accept right now; only these are actionable.
const playable = $derived(new Set(ofType(store.moves, "place").map((move) => parseTile(move.tile)!)));
function why(tile: Tile): string {
// With two tiles per turn, dead tiles are swapped at the start of the turn (rules.md §4.1).
const replacement = $derived(t(state.options.twoTiles ? "hand.deadNextTurn" : "hand.deadReplacement"));
function why(seat: number, tile: Tile): string {
const legality = tileLegality(state.board, tile);
if (legality === "permanentlyUnplayable") {
return `${t("hand.dead")}. ${t("hand.deadReplacement")}.`;
return `${t("hand.dead")}. ${replacement}.`;
}
if (legality === "temporarilyUnplayable") {
return t("hand.eighth");
}
return "";
const limit = turnLimit(state, seat, tile);
return limit ? t(`hand.${limit}`) : "";
}
function choose(tile: Tile): void {
@ -33,12 +37,13 @@
{@const hand = sortTiles(state.seats[seat]!.hand.filter((tile) => tile !== HIDDEN))}
{@const dead = hand.filter((tile) => tileLegality(state.board, tile) === "permanentlyUnplayable")}
{@const paused = hand.filter((tile) => tileLegality(state.board, tile) === "temporarilyUnplayable")}
{@const limited = hand.filter((tile) => turnLimit(state, seat, tile) !== undefined)}
<section class="hand" aria-label={t("hand.of", { name: seatName(state, seat, store.lang) })}>
<h2>{store.seats.length > 1 ? t("hand.seat", { seat: seat + 1 }) : t("hand.yours")}</h2>
<div class="tiles">
<div class="tiles" class:eight={state.options.twoTiles}>
{#each hand as tile, index (index)}
{@const permanent = dead.includes(tile)}
{@const blocked = permanent || paused.includes(tile)}
{@const blocked = permanent || paused.includes(tile) || limited.includes(tile)}
{#if playable.has(tile)}
<button
type="button"
@ -53,10 +58,10 @@
<span
class="tile"
class:dead={permanent}
class:paused={paused.includes(tile)}
title={why(tile)}
class:paused={paused.includes(tile) || limited.includes(tile)}
title={why(seat, tile)}
role="img"
aria-label={blocked ? `${tileLabel(tile)} — ${why(tile)}` : tileLabel(tile)}
aria-label={blocked ? `${tileLabel(tile)} — ${why(seat, tile)}` : tileLabel(tile)}
>
<span class="coordinate">{tileLabel(tile)}</span>
{#if blocked}<span class="tile-status"><TileStatusIcon {permanent} /></span>{/if}
@ -66,12 +71,12 @@
<span class="none">{t("hand.none")}</span>
{/each}
</div>
{#if dead.length || paused.length}
{#if dead.length || paused.length || limited.length}
<ul class="tile-notes">
{#if dead.length}
<li class="dead-note">
<TileStatusIcon permanent={true} />
<span><bdi>{dead.map(tileLabel).join(", ")}</bdi> — {t("hand.deadReplacement")}</span>
<span><bdi>{dead.map(tileLabel).join(", ")}</bdi> — {replacement}</span>
</li>
{/if}
{#if paused.length}
@ -80,6 +85,15 @@
<span><bdi>{paused.map(tileLabel).join(", ")}</bdi> — {t("hand.eighth")}</span>
</li>
{/if}
{#each ["oneFounding", "foundOrMerge"] as const as limit (limit)}
{@const tiles = limited.filter((tile) => turnLimit(state, seat, tile) === limit)}
{#if tiles.length}
<li class="paused-note">
<TileStatusIcon permanent={false} />
<span><bdi>{tiles.map(tileLabel).join(", ")}</bdi> — {t(`hand.${limit}`)}</span>
</li>
{/if}
{/each}
</ul>
{/if}
</section>
@ -102,6 +116,15 @@
width: max-content;
max-width: 100%;
}
/* Eight tiles (two tiles per turn) take one row where it fits and two rows of four on phones. */
.tiles.eight {
grid-template-columns: repeat(8, minmax(0, 52px));
}
@media (max-width: 560px) {
.tiles.eight {
grid-template-columns: repeat(4, minmax(0, 52px));
}
}
.tile {
position: relative;
display: inline-flex;

View file

@ -14,15 +14,24 @@
const t = $derived(store.lang.t);
let showAll = $state(false);
// Newest first; "turn" entries become headings that group the lines below them.
// Newest first; "turn" entries become headings that group the lines below them. With a
// limited log (rules.md §13), each run of entries the engine withheld becomes one note.
const lines = $derived(
game.log
.map((entry, index) => ({
index,
turn: entry.type === "turn",
parts: describeEntryParts(game, entry, store.lang),
hidden: entry.type === "hidden",
parts:
entry.type === "hidden"
? game.log[index - 1]?.type === "hidden"
? undefined
: [{ kind: "text" as const, text: t("log.limited") }]
: describeEntryParts(game, entry, store.lang),
}))
.filter((line): line is { index: number; turn: boolean; parts: LogPart[] } => line.parts !== undefined)
.filter(
(line): line is { index: number; turn: boolean; hidden: boolean; parts: LogPart[] } => line.parts !== undefined
)
.reverse()
);
</script>
@ -31,7 +40,7 @@
<h2>{t("log.title")}</h2>
<ol class="log">
{#each showAll ? lines : lines.slice(0, RECENT) as line (line.index)}
<li class:turn={line.turn}>
<li class:turn={line.turn} class:hidden={line.hidden}>
{#each line.parts as part}
{#if part.kind === "player" || part.kind === "chain"}
{@const color =
@ -72,6 +81,11 @@
font-weight: 600;
background: var(--panel-alt);
}
.log li.hidden {
margin-top: 6px;
color: var(--ink-muted);
font-style: italic;
}
.name,
.money {
font-weight: 600;

View file

@ -1,9 +1,27 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { applyMove, currentSeat, initGame, legalMoves, type GameState, type Move } from "acquire-engine";
import {
applyMove,
currentSeat,
initGame,
legalMoves,
placementEffect,
tileLabel,
turnPlacements,
type GameState,
type Move,
} from "acquire-engine";
import { stripSecret } from "acquire-engine/wrapper.js";
import { preparedPosition } from "../tutorial/lessons.ts";
import { adjustShares, canBuy, canDispose, disposalPresets, movesFor, nextDefunctChoices } from "./decisions.ts";
import {
adjustShares,
canBuy,
canDispose,
disposalPresets,
movesFor,
nextDefunctChoices,
turnLimit,
} from "./decisions.ts";
function playUntil(state: GameState, done: (state: GameState) => boolean): GameState {
for (let step = 0; !done(state); step++) {
@ -104,3 +122,25 @@ test("disposal presets sell all or trade the available pairs without selling lef
}
assert.deepEqual(disposalPresets([]), { sell: undefined, trade: undefined });
});
test("two-tile limits explain exactly the tiles the engine blocks this turn", () => {
const state = initGame(4, { twoTiles: true }, "limits");
const limited = () =>
state.phase === "place" &&
state.seats[state.activeSeat]!.hand.some((tile) => turnLimit(state, state.activeSeat, tile) !== undefined);
playUntil(state, limited);
const seat = state.activeSeat;
const placeable = legalMoves(state).flatMap((move) => (move.type === "place" ? [move.tile] : []));
for (const tile of state.seats[seat]!.hand) {
const limit = turnLimit(state, seat, tile);
if (limit === undefined) {
continue;
}
assert.ok(!placeable.includes(tileLabel(tile)));
const founding = placementEffect(state.board, tile).kind === "found";
assert.equal(limit, founding && turnPlacements(state).founded ? "oneFounding" : "foundOrMerge");
assert.equal(turnLimit(state, (seat + 1) % 4, tile), undefined, "limits apply only to the active seat");
}
const view = stripSecret(state, seat);
assert.deepEqual(movesFor(view, [seat]), legalMoves(state));
});

View file

@ -1,11 +1,13 @@
// Which choices the viewer offers. Validity always comes from the engine: these helpers only
// filter and look up engine.legalMoves(), so no rule is re-implemented here.
import {
blockedThisTurn,
CHAIN_IDS,
chainSize,
currentSeat,
legalMoves,
placementEffect,
turnPlacements,
type ChainId,
type GameState,
type Move,
@ -43,6 +45,19 @@ export function describePlacement(state: GameState, tile: Tile, lang: Lang): str
}
}
/**
* Why `tile` in `seat`'s hand can't be placed this turn under the two-tiles limits
* (rules.md §4.1), or undefined when they don't block it.
*/
export function turnLimit(state: GameState, seat: number, tile: Tile): "oneFounding" | "foundOrMerge" | undefined {
if (seat !== state.activeSeat || state.ended || !blockedThisTurn(state, tile)) {
return undefined;
}
return placementEffect(state.board, tile).kind === "found" && turnPlacements(state).founded
? "oneFounding"
: "foundOrMerge";
}
function sameShares(a: Partial<Shares>, b: Partial<Shares>): boolean {
return CHAIN_IDS.every((chain) => (a[chain] ?? 0) === (b[chain] ?? 0));
}

View file

@ -3,6 +3,7 @@ import {
HIDDEN,
currentSeat,
merger,
secondPlacementDue,
tileLabel,
type ChainId,
type GameState,
@ -53,7 +54,7 @@ export function pendingDecision(state: GameState, lang: Lang): string {
const name = seatName(state, seat, lang);
switch (state.phase) {
case "place":
return lang.t("status.place", { name });
return lang.t(secondPlacementDue(state) ? "status.placeSecond" : "status.place", { name });
case "found":
return lang.t("status.found", { name });
case "survivor":
@ -209,6 +210,8 @@ export function describeEntry(
});
case "result":
return t("log.result", { results: list(entry.cash.map((cash, s) => `${seat(s)} ${money(cash)}`)) });
case "hidden":
return undefined;
}
}

View file

@ -17,6 +17,7 @@ export const da: Catalog = {
loading: "Indlæser spillet…",
"status.place": "{name} skal lægge en brik",
"status.placeSecond": "{name} skal lægge en brik mere",
"status.found": "{name} skal navngive en ny kæde",
"status.survivor": "{name} skal vælge, hvilken kæde der overlever fusionen",
"status.defunctOrder": "{name} skal vælge rækkefølgen af de opslugte kæder",
@ -89,6 +90,9 @@ export const da: Catalog = {
"hand.dead": "død: ville fusionere sikre kæder",
"hand.deadReplacement": "Udskiftes ved slutningen af din tur",
"hand.eighth": "kan ikke grundlægge en 8. kæde",
"hand.deadNextTurn": "Udskiftes ved starten af din næste tur",
"hand.oneFounding": "kan ikke grundlægge en kæde mere i denne tur",
"hand.foundOrMerge": "kan ikke både grundlægge en kæde og fusionere i samme tur",
"chains.label": "Hotelkæder",
"chains.title": "Kæder",
"chains.chain": "Kæde",
@ -132,6 +136,7 @@ export const da: Catalog = {
"seat.name": "{name} (plads {seat})",
"log.label": "Spillets log",
"log.title": "Log",
"log.limited": "Tidligere træk er skjult, indtil spillet slutter.",
"log.recent": "Vis kun de seneste linjer",
"log.all": { one: "Vis hele loggen ({count} mere)", other: "Vis hele loggen ({count} mere)" },
"log.init": { one: "Nyt spil for {count} spiller", other: "Nyt spil for {count} spillere" },

View file

@ -17,6 +17,7 @@ export const de: Catalog = {
loading: "Spiel wird geladen…",
"status.place": "{name} legt ein Plättchen",
"status.placeSecond": "{name} legt ein zweites Plättchen",
"status.found": "{name} benennt eine neue Kette",
"status.survivor": "{name} wählt, welche Kette die Fusion übersteht",
"status.defunctOrder": "{name} wählt die Reihenfolge der übernommenen Ketten",
@ -89,6 +90,9 @@ export const de: Catalog = {
"hand.dead": "tot: würde sichere Ketten fusionieren",
"hand.deadReplacement": "Werden am Ende deines Zuges ersetzt",
"hand.eighth": "keine 8. Kette möglich",
"hand.deadNextTurn": "Werden zu Beginn deines nächsten Zuges ersetzt",
"hand.oneFounding": "keine zweite Kettengründung in diesem Zug",
"hand.foundOrMerge": "nicht Gründung und Fusion im selben Zug",
"chains.label": "Hotelketten",
"chains.title": "Ketten",
"chains.chain": "Kette",
@ -132,6 +136,7 @@ export const de: Catalog = {
"seat.name": "{name} (Platz {seat})",
"log.label": "Spielprotokoll",
"log.title": "Protokoll",
"log.limited": "Frühere Züge bleiben bis zum Spielende verborgen.",
"log.recent": "Nur die letzten Zeilen zeigen",
"log.all": { one: "Ganzes Protokoll zeigen ({count} weitere)", other: "Ganzes Protokoll zeigen ({count} weitere)" },
"log.init": { one: "Neues Spiel für {count} Spieler", other: "Neues Spiel für {count} Spieler" },

View file

@ -17,6 +17,7 @@ export const el: Catalog = {
loading: "Φόρτωση παιχνιδιού…",
"status.place": "{name}: τοποθέτηση πλακιδίου",
"status.placeSecond": "{name}: τοποθέτηση δεύτερου πλακιδίου",
"status.found": "{name}: ονομασία νέας αλυσίδας",
"status.survivor": "{name}: επιλογή αλυσίδας που επιβιώνει από τη συγχώνευση",
"status.defunctOrder": "{name}: επιλογή σειράς των αλυσίδων που απορροφώνται",
@ -89,6 +90,9 @@ export const el: Catalog = {
"hand.dead": "νεκρό: θα συγχώνευε ασφαλείς αλυσίδες",
"hand.deadReplacement": "Αντικατάσταση στο τέλος του γύρου σου",
"hand.eighth": "δεν ιδρύεται 8η αλυσίδα",
"hand.deadNextTurn": "Αντικατάσταση στην αρχή του επόμενου γύρου σου",
"hand.oneFounding": "δεν ιδρύεται δεύτερη αλυσίδα σε αυτόν τον γύρο",
"hand.foundOrMerge": "όχι ίδρυση αλυσίδας και συγχώνευση στον ίδιο γύρο",
"chains.label": "Αλυσίδες ξενοδοχείων",
"chains.title": "Αλυσίδες",
"chains.chain": "Αλυσίδα",
@ -132,6 +136,7 @@ export const el: Catalog = {
"seat.name": "{name} (θέση {seat})",
"log.label": "Ημερολόγιο παιχνιδιού",
"log.title": "Ημερολόγιο",
"log.limited": "Οι προηγούμενες κινήσεις κρύβονται μέχρι το τέλος του παιχνιδιού.",
"log.recent": "Μόνο οι τελευταίες γραμμές",
"log.all": { one: "Όλο το ημερολόγιο ({count} ακόμη)", other: "Όλο το ημερολόγιο ({count} ακόμη)" },
"log.init": { one: "Νέο παιχνίδι για {count} παίκτη", other: "Νέο παιχνίδι για {count} παίκτες" },

View file

@ -20,6 +20,7 @@ export const en = {
// Status bar
"status.place": "{name} to place a tile",
"status.placeSecond": "{name} to place a second tile",
"status.found": "{name} to name a new chain",
"status.survivor": "{name} to choose which chain survives the merger",
"status.defunctOrder": "{name} to choose the order of the defunct chains",
@ -96,6 +97,9 @@ export const en = {
"hand.dead": "dead: would merge safe chains",
"hand.deadReplacement": "Replaced at the end of your turn",
"hand.eighth": "can't found an 8th chain",
"hand.deadNextTurn": "Replaced at the start of your next turn",
"hand.oneFounding": "can't found a second chain this turn",
"hand.foundOrMerge": "can't both found a chain and merge in one turn",
// Chain and price tables
"chains.label": "Hotel chains",
@ -144,6 +148,7 @@ export const en = {
// Log
"log.label": "Game log",
"log.title": "Log",
"log.limited": "Earlier moves are hidden until the game ends.",
"log.recent": "Show recent lines only",
"log.all": { one: "Show the whole log ({count} more)", other: "Show the whole log ({count} more)" },
"log.init": { one: "New game for {count} player", other: "New game for {count} players" },

View file

@ -17,6 +17,7 @@ export const fa: Catalog = {
loading: "در حال بارگذاری بازی…",
"status.place": "{name} باید یک کاشی بگذارد",
"status.placeSecond": "{name} باید کاشی دوم را بگذارد",
"status.found": "{name} باید برای زنجیره‌ی جدید نام انتخاب کند",
"status.survivor": "{name} باید زنجیره‌ای را که در ادغام می‌ماند انتخاب کند",
"status.defunctOrder": "{name} باید ترتیب زنجیره‌های ادغام‌شونده را انتخاب کند",
@ -89,6 +90,9 @@ export const fa: Catalog = {
"hand.dead": "مرده: زنجیره‌های امن را ادغام می‌کند",
"hand.deadReplacement": "در پایان نوبت شما جایگزین می‌شوند",
"hand.eighth": "زنجیره‌ی هشتم ممکن نیست",
"hand.deadNextTurn": "در آغاز نوبت بعدی شما جایگزین می‌شوند",
"hand.oneFounding": "در این نوبت زنجیره‌ی دوم ممکن نیست",
"hand.foundOrMerge": "تأسیس زنجیره و ادغام در یک نوبت ممکن نیست",
"chains.label": "زنجیره‌های هتل",
"chains.title": "زنجیره‌ها",
"chains.chain": "زنجیره",
@ -131,6 +135,7 @@ export const fa: Catalog = {
"seat.name": "{name} (جایگاه {seat})",
"log.label": "گزارش بازی",
"log.title": "گزارش",
"log.limited": "حرکت‌های قبلی تا پایان بازی پنهان هستند.",
"log.recent": "فقط خط‌های اخیر",
"log.all": { one: "نمایش کل گزارش ({count} خط دیگر)", other: "نمایش کل گزارش ({count} خط دیگر)" },
"log.init": { one: "بازی جدید برای {count} بازیکن", other: "بازی جدید برای {count} بازیکن" },

View file

@ -17,6 +17,7 @@ export const fr: Catalog = {
loading: "Chargement de la partie…",
"status.place": "{name} doit poser une tuile",
"status.placeSecond": "{name} doit poser une deuxième tuile",
"status.found": "{name} doit nommer une nouvelle chaîne",
"status.survivor": "{name} doit choisir la chaîne qui survit à la fusion",
"status.defunctOrder": "{name} doit choisir l’ordre des chaînes absorbées",
@ -93,6 +94,9 @@ export const fr: Catalog = {
"hand.dead": "morte : fusionnerait des chaînes sûres",
"hand.deadReplacement": "Remplacement à la fin de votre tour",
"hand.eighth": "impossible de fonder une 8e chaîne",
"hand.deadNextTurn": "Remplacement au début de votre prochain tour",
"hand.oneFounding": "impossible de fonder une deuxième chaîne ce tour-ci",
"hand.foundOrMerge": "impossible de fonder une chaîne et de fusionner dans le même tour",
"chains.label": "Chaînes d’hôtels",
"chains.title": "Chaînes",
"chains.chain": "Chaîne",
@ -136,6 +140,7 @@ export const fr: Catalog = {
"seat.name": "{name} (place {seat})",
"log.label": "Journal de la partie",
"log.title": "Journal",
"log.limited": "Les coups précédents sont masqués jusqu'à la fin de la partie.",
"log.recent": "Afficher seulement les dernières lignes",
"log.all": {
one: "Afficher tout le journal ({count} de plus)",

View file

@ -17,6 +17,7 @@ export const hi: Catalog = {
loading: "खेल लोड हो रहा है…",
"status.place": "{name} को एक टाइल रखनी है",
"status.placeSecond": "{name} को दूसरी टाइल रखनी है",
"status.found": "{name} को नई श्रृंखला का नाम चुनना है",
"status.survivor": "{name} को चुनना है कि विलय में कौन सी श्रृंखला बचेगी",
"status.defunctOrder": "{name} को विलय होने वाली श्रृंखलाओं का क्रम चुनना है",
@ -88,6 +89,9 @@ export const hi: Catalog = {
"hand.dead": "बेकार: सुरक्षित श्रृंखलाओं का विलय कर देगी",
"hand.deadReplacement": "आपकी बारी के अंत में बदल दी जाएँगी",
"hand.eighth": "8वीं श्रृंखला स्थापित नहीं हो सकती",
"hand.deadNextTurn": "आपकी अगली बारी की शुरुआत में बदल दी जाएँगी",
"hand.oneFounding": "इस बारी में दूसरी श्रृंखला स्थापित नहीं हो सकती",
"hand.foundOrMerge": "एक ही बारी में श्रृंखला स्थापित करना और विलय दोनों नहीं हो सकते",
"chains.label": "होटल श्रृंखलाएँ",
"chains.title": "श्रृंखलाएँ",
"chains.chain": "श्रृंखला",
@ -129,6 +133,7 @@ export const hi: Catalog = {
"seat.name": "{name} (सीट {seat})",
"log.label": "खेल का लॉग",
"log.title": "लॉग",
"log.limited": "पिछली चालें खेल समाप्त होने तक छिपी रहती हैं।",
"log.recent": "केवल हाल की पंक्तियाँ दिखाएँ",
"log.all": { one: "पूरा लॉग दिखाएँ ({count} और)", other: "पूरा लॉग दिखाएँ ({count} और)" },
"log.init": { one: "{count} खिलाड़ी के लिए नया खेल", other: "{count} खिलाड़ियों के लिए नया खेल" },

View file

@ -17,6 +17,7 @@ export const it: Catalog = {
loading: "Caricamento della partita…",
"status.place": "{name} deve piazzare una tessera",
"status.placeSecond": "{name} deve piazzare una seconda tessera",
"status.found": "{name} deve dare un nome a una nuova catena",
"status.survivor": "{name} deve scegliere quale catena sopravvive alla fusione",
"status.defunctOrder": "{name} deve scegliere l'ordine delle catene assorbite",
@ -93,6 +94,9 @@ export const it: Catalog = {
"hand.dead": "morta: fonderebbe catene sicure",
"hand.deadReplacement": "Sostituite alla fine del tuo turno",
"hand.eighth": "non si può fondare un'8ª catena",
"hand.deadNextTurn": "Sostituite all'inizio del tuo prossimo turno",
"hand.oneFounding": "non si può fondare una seconda catena in questo turno",
"hand.foundOrMerge": "non si può fondare una catena e fondere nello stesso turno",
"chains.label": "Catene alberghiere",
"chains.title": "Catene",
"chains.chain": "Catena",
@ -137,6 +141,7 @@ export const it: Catalog = {
"seat.name": "{name} (posto {seat})",
"log.label": "Registro della partita",
"log.title": "Registro",
"log.limited": "Le mosse precedenti restano nascoste fino alla fine della partita.",
"log.recent": "Mostra solo le righe recenti",
"log.all": {
one: "Mostra tutto il registro (altre {count})",

View file

@ -17,6 +17,7 @@ export const ko: Catalog = {
loading: "게임을 불러오는 중…",
"status.place": "{name}: 타일을 놓을 차례",
"status.placeSecond": "{name}: 두 번째 타일을 놓을 차례",
"status.found": "{name}: 새 체인의 이름을 정할 차례",
"status.survivor": "{name}: 합병에서 살아남을 체인을 고를 차례",
"status.defunctOrder": "{name}: 흡수되는 체인의 순서를 정할 차례",
@ -89,6 +90,9 @@ export const ko: Catalog = {
"hand.dead": "죽은 타일: 안전한 체인끼리 합병하게 됨",
"hand.deadReplacement": "내 차례가 끝나면 교체됩니다",
"hand.eighth": "8번째 체인은 세울 수 없음",
"hand.deadNextTurn": "다음 차례가 시작될 때 교체됩니다",
"hand.oneFounding": "이번 차례에 두 번째 체인은 세울 수 없음",
"hand.foundOrMerge": "한 차례에 체인 설립과 합병을 모두 할 수 없음",
"chains.label": "호텔 체인",
"chains.title": "체인",
"chains.chain": "체인",
@ -131,6 +135,7 @@ export const ko: Catalog = {
"seat.name": "{name} ({seat}번 자리)",
"log.label": "게임 기록",
"log.title": "기록",
"log.limited": "이전 수는 게임이 끝날 때까지 숨겨집니다.",
"log.recent": "최근 줄만 보기",
"log.all": { other: "전체 기록 보기 ({count}줄 더)" },
"log.init": { other: "{count}인 새 게임" },

View file

@ -17,6 +17,7 @@ export const nl: Catalog = {
loading: "Spel laden…",
"status.place": "{name} moet een tegel leggen",
"status.placeSecond": "{name} moet een tweede tegel leggen",
"status.found": "{name} moet een nieuwe keten een naam geven",
"status.survivor": "{name} moet kiezen welke keten de fusie overleeft",
"status.defunctOrder": "{name} moet de volgorde van de overgenomen ketens kiezen",
@ -89,6 +90,9 @@ export const nl: Catalog = {
"hand.dead": "dood: zou veilige ketens fuseren",
"hand.deadReplacement": "Worden aan het einde van je beurt vervangen",
"hand.eighth": "kan geen 8e keten stichten",
"hand.deadNextTurn": "Worden aan het begin van je volgende beurt vervangen",
"hand.oneFounding": "kan deze beurt geen tweede keten stichten",
"hand.foundOrMerge": "kan niet in één beurt een keten stichten én fuseren",
"chains.label": "Hotelketens",
"chains.title": "Ketens",
"chains.chain": "Keten",
@ -132,6 +136,7 @@ export const nl: Catalog = {
"seat.name": "{name} (plaats {seat})",
"log.label": "Spelverslag",
"log.title": "Verslag",
"log.limited": "Eerdere zetten blijven verborgen tot het einde van het spel.",
"log.recent": "Alleen recente regels tonen",
"log.all": { one: "Hele verslag tonen (nog {count})", other: "Hele verslag tonen (nog {count})" },
"log.init": { one: "Nieuw spel voor {count} speler", other: "Nieuw spel voor {count} spelers" },

View file

@ -17,6 +17,7 @@ export const pl: Catalog = {
loading: "Wczytywanie gry…",
"status.place": "{name} kładzie płytkę",
"status.placeSecond": "{name} kładzie drugą płytkę",
"status.found": "{name} nazywa nową sieć",
"status.survivor": "{name} wybiera sieć, która przetrwa fuzję",
"status.defunctOrder": "{name} wybiera kolejność przejmowanych sieci",
@ -94,6 +95,9 @@ export const pl: Catalog = {
"hand.dead": "martwa: połączyłaby bezpieczne sieci",
"hand.deadReplacement": "Wymiana na koniec twojej tury",
"hand.eighth": "nie można założyć 8. sieci",
"hand.deadNextTurn": "Wymiana na początku twojej następnej tury",
"hand.oneFounding": "nie można założyć drugiej sieci w tej turze",
"hand.foundOrMerge": "nie można w jednej turze założyć sieci i połączyć sieci",
"chains.label": "Sieci hoteli",
"chains.title": "Sieci",
"chains.chain": "Sieć",
@ -136,6 +140,7 @@ export const pl: Catalog = {
"seat.name": "{name} (miejsce {seat})",
"log.label": "Dziennik gry",
"log.title": "Dziennik",
"log.limited": "Wcześniejsze ruchy są ukryte do końca gry.",
"log.recent": "Pokaż tylko ostatnie wpisy",
"log.all": {
one: "Pokaż cały dziennik (jeszcze {count})",

View file

@ -17,6 +17,7 @@ export const ptBR: Catalog = {
loading: "Carregando o jogo…",
"status.place": "{name} deve colocar uma peça",
"status.placeSecond": "{name} deve colocar uma segunda peça",
"status.found": "{name} deve dar nome a uma nova rede",
"status.survivor": "{name} deve escolher qual rede sobrevive à fusão",
"status.defunctOrder": "{name} deve escolher a ordem das redes absorvidas",
@ -93,6 +94,9 @@ export const ptBR: Catalog = {
"hand.dead": "morta: fundiria redes seguras",
"hand.deadReplacement": "Substituição no fim do seu turno",
"hand.eighth": "não dá para fundar uma 8ª rede",
"hand.deadNextTurn": "Substituição no início do seu próximo turno",
"hand.oneFounding": "não dá para fundar uma segunda rede neste turno",
"hand.foundOrMerge": "não dá para fundar uma rede e fundir no mesmo turno",
"chains.label": "Redes de hotéis",
"chains.title": "Redes",
"chains.chain": "Rede",
@ -136,6 +140,7 @@ export const ptBR: Catalog = {
"seat.name": "{name} (lugar {seat})",
"log.label": "Registro do jogo",
"log.title": "Registro",
"log.limited": "As jogadas anteriores ficam ocultas até o fim da partida.",
"log.recent": "Mostrar só as linhas recentes",
"log.all": {
one: "Mostrar o registro inteiro (mais {count})",

View file

@ -17,6 +17,7 @@ export const ro: Catalog = {
loading: "Se încarcă jocul…",
"status.place": "{name} trebuie să plaseze o piesă",
"status.placeSecond": "{name} trebuie să plaseze a doua piesă",
"status.found": "{name} trebuie să numească un lanț nou",
"status.survivor": "{name} trebuie să aleagă lanțul care supraviețuiește fuziunii",
"status.defunctOrder": "{name} trebuie să aleagă ordinea lanțurilor absorbite",
@ -93,6 +94,9 @@ export const ro: Catalog = {
"hand.dead": "moartă: ar uni lanțuri sigure",
"hand.deadReplacement": "Înlocuire la sfârșitul turei tale",
"hand.eighth": "nu se poate înființa un al 8-lea lanț",
"hand.deadNextTurn": "Înlocuire la începutul turei tale următoare",
"hand.oneFounding": "nu se poate înființa un al doilea lanț în această tură",
"hand.foundOrMerge": "nu se poate înființa un lanț și face o fuziune în aceeași tură",
"chains.label": "Lanțuri hoteliere",
"chains.title": "Lanțuri",
"chains.chain": "Lanț",
@ -136,6 +140,7 @@ export const ro: Catalog = {
"seat.name": "{name} (locul {seat})",
"log.label": "Jurnalul jocului",
"log.title": "Jurnal",
"log.limited": "Mutările anterioare sunt ascunse până la sfârșitul jocului.",
"log.recent": "Arată doar ultimele rânduri",
"log.all": {
one: "Arată tot jurnalul (încă {count})",

View file

@ -17,6 +17,7 @@ export const ru: Catalog = {
loading: "Загрузка игры…",
"status.place": "{name}: выложить фишку",
"status.placeSecond": "{name}: выложить вторую фишку",
"status.found": "{name}: назвать новую сеть",
"status.survivor": "{name}: выбрать сеть, которая уцелеет при слиянии",
"status.defunctOrder": "{name}: выбрать порядок поглощаемых сетей",
@ -94,6 +95,9 @@ export const ru: Catalog = {
"hand.dead": "мёртвая: слила бы защищённые сети",
"hand.deadReplacement": "Заменяются в конце вашего хода",
"hand.eighth": "нельзя основать 8-ю сеть",
"hand.deadNextTurn": "Заменяются в начале вашего следующего хода",
"hand.oneFounding": "нельзя основать вторую сеть за этот ход",
"hand.foundOrMerge": "нельзя за один ход и основать сеть, и провести слияние",
"chains.label": "Гостиничные сети",
"chains.title": "Сети",
"chains.chain": "Сеть",
@ -136,6 +140,7 @@ export const ru: Catalog = {
"seat.name": "{name} (место {seat})",
"log.label": "Журнал игры",
"log.title": "Журнал",
"log.limited": "Предыдущие ходы скрыты до конца игры.",
"log.recent": "Показать только последние строки",
"log.all": {
one: "Показать весь журнал (ещё {count})",

View file

@ -17,6 +17,7 @@ export const vi: Catalog = {
loading: "Đang tải ván chơi…",
"status.place": "{name} cần đặt một ô",
"status.placeSecond": "{name} cần đặt ô thứ hai",
"status.found": "{name} cần đặt tên cho chuỗi mới",
"status.survivor": "{name} cần chọn chuỗi tồn tại sau sáp nhập",
"status.defunctOrder": "{name} cần chọn thứ tự các chuỗi bị thâu tóm",
@ -89,6 +90,9 @@ export const vi: Catalog = {
"hand.dead": "ô chết: sẽ sáp nhập các chuỗi an toàn",
"hand.deadReplacement": "Được thay khi kết thúc lượt của bạn",
"hand.eighth": "không thể lập chuỗi thứ 8",
"hand.deadNextTurn": "Được thay khi bắt đầu lượt sau của bạn",
"hand.oneFounding": "không thể lập chuỗi thứ hai trong lượt này",
"hand.foundOrMerge": "không thể vừa lập chuỗi vừa sáp nhập trong cùng một lượt",
"chains.label": "Chuỗi khách sạn",
"chains.title": "Chuỗi",
"chains.chain": "Chuỗi",
@ -132,6 +136,7 @@ export const vi: Catalog = {
"seat.name": "{name} (ghế {seat})",
"log.label": "Nhật ký ván chơi",
"log.title": "Nhật ký",
"log.limited": "Các nước đi trước bị ẩn cho đến khi ván chơi kết thúc.",
"log.recent": "Chỉ hiện các dòng gần đây",
"log.all": { other: "Hiện toàn bộ nhật ký (thêm {count})" },
"log.init": { other: "Ván mới cho {count} người chơi" },

View file

@ -17,6 +17,7 @@ export const zhCN: Catalog = {
loading: "正在加载游戏…",
"status.place": "{name}:放置一块板块",
"status.placeSecond": "{name}:放置第二块板块",
"status.found": "{name}:为新连锁命名",
"status.survivor": "{name}:选择合并后存续的连锁",
"status.defunctOrder": "{name}:选择被吞并连锁的顺序",
@ -88,6 +89,9 @@ export const zhCN: Catalog = {
"hand.dead": "死板块:会合并安全连锁",
"hand.deadReplacement": "在你的回合结束时更换",
"hand.eighth": "无法创立第 8 个连锁",
"hand.deadNextTurn": "在你下一回合开始时更换",
"hand.oneFounding": "本回合不能再创立第二个连锁",
"hand.foundOrMerge": "同一回合内不能既创立连锁又进行合并",
"chains.label": "酒店连锁",
"chains.title": "连锁",
"chains.chain": "连锁",
@ -129,6 +133,7 @@ export const zhCN: Catalog = {
"seat.name": "{name}(座位 {seat})",
"log.label": "游戏记录",
"log.title": "记录",
"log.limited": "更早的行动在游戏结束前隐藏。",
"log.recent": "只显示最近几行",
"log.all": { other: "显示全部记录(还有 {count} 行)" },
"log.init": { other: "{count} 人新游戏" },

View file

@ -17,6 +17,7 @@ export const zhTW: Catalog = {
loading: "正在載入遊戲…",
"status.place": "{name}:放置一塊板塊",
"status.placeSecond": "{name}:放置第二塊板塊",
"status.found": "{name}:為新連鎖命名",
"status.survivor": "{name}:選擇合併後存續的連鎖",
"status.defunctOrder": "{name}:選擇被併購連鎖的順序",
@ -88,6 +89,9 @@ export const zhTW: Catalog = {
"hand.dead": "死板塊:會合併安全連鎖",
"hand.deadReplacement": "在你的回合結束時更換",
"hand.eighth": "無法創立第 8 個連鎖",
"hand.deadNextTurn": "在你下一回合開始時更換",
"hand.oneFounding": "本回合不能再創立第二個連鎖",
"hand.foundOrMerge": "同一回合內不能既創立連鎖又進行合併",
"chains.label": "飯店連鎖",
"chains.title": "連鎖",
"chains.chain": "連鎖",
@ -129,6 +133,7 @@ export const zhTW: Catalog = {
"seat.name": "{name}(座位 {seat})",
"log.label": "遊戲紀錄",
"log.title": "紀錄",
"log.limited": "更早的行動在遊戲結束前隱藏。",
"log.recent": "只顯示最近幾行",
"log.all": { other: "顯示全部紀錄(還有 {count} 行)" },
"log.init": { other: "{count} 人新遊戲" },

View file

@ -107,9 +107,13 @@ export class ViewerStore {
}
}
/** With a limited log (rules.md §13), replay waits until the game ends and the log is whole. */
replayable = $derived(!this.state?.log.some((entry) => entry.type === "hidden"));
/** The replay range BGS shows in its controls: setup done, up to the live position. */
replayRange(): { start: number; end: number } {
return { start: replayStart(this.state!), end: this.state!.log.length };
const end = this.state!.log.length;
return { start: this.replayable ? replayStart(this.state!) : end, end };
}
send(move: Move): void {

View file

@ -50,15 +50,19 @@ export const viewer = registerViewer<GameState, Move | TurnRequest>(
store.theme = dark ? "dark" : "light";
},
onReplayStart() {
sounds.onReplayStart();
const { start, end } = store.replayRange();
store.replayAt = end;
if (store.replayable) {
sounds.onReplayStart();
store.replayAt = end;
}
setReplayInfo({ start, current: end, end });
},
onReplayTo(index) {
const { start, end } = store.replayRange();
store.replayAt = Math.min(end, Math.max(start, index));
setReplayInfo({ start, current: store.replayAt, end });
if (store.replayable) {
store.replayAt = Math.min(end, Math.max(start, index));
}
setReplayInfo({ start, current: store.replayAt ?? end, end });
},
onReplayEnd() {
sounds.onReplayEnd();

View file

@ -68,6 +68,27 @@ the player gets the placement step even with no playable tile (they may announce
pass). If an end condition holds at the buy step, the player gets the buy step even if
they cannot buy anything.
### 4.1 Two tiles per turn (house rule)
With `twoTiles` enabled (§15), hands hold **8** tiles instead of 6 (at setup and when
drawing), and each turn places two tiles:
1. At the start of the turn, the active seat discards its permanently unplayable tiles
(§5.2) and draws replacements. They are not replaced at the end of the turn.
2. Place the first tile and resolve everything it causes, including a full merger with
every player's disposal decisions and, in two-player bank mode, the bank's tiles
(§12.1.4), before the second tile.
3. Place the second tile if any tile in hand is playable now; otherwise go straight to
buying. A tile that became permanently unplayable during this turn cannot be placed and
is replaced at the start of the seat's next turn.
4. A turn founds at most one chain, and never both founds a chain and causes a merger, in
either order. It may cause two mergers, one per tile. Mergers caused by bank tiles do
not count towards these limits.
5. Buy (§9, including §9.1 swaps) once, after both tiles, then draw back up to 8.
The end may also be announced between the two tiles, if an end condition holds at that
moment. Dropped seats place their first two playable tiles by the §16 default.
## 5. Placing a Tile
### 5.1 Effects of a placement
@ -310,10 +331,16 @@ Each viewer must only receive information their player is entitled to.
- **[DECISION] Game option `publicHoldings` (default: `false`):** When off, each player's
current share holdings and cash are visible only to that player. When on, they are
public.
- **[DECISION] The game log is always public.** It records every action: tile
placements, stock purchases, bonuses paid, and each player's disposal choices. Only
the *current* holdings and cash are hidden, even though they can be reconstructed
from the log.
- **[DECISION] The game log is public** unless `limitedLog` is on (below). It records
every action: tile placements, stock purchases, bonuses paid, and each player's disposal
choices. Only the *current* holdings and cash are hidden, even though they can be
reconstructed from the log.
- **Game option `limitedLog` (default: `false`):** each player sees only the log from the
start of their own last turn before the current one, so the current turn, including a
merger in progress, is always shown. Spectators see as much as the active player.
Setup entries (options, turn order) stay visible. Earlier entries are replaced by
placeholders, keeping the log's length. The whole log is revealed when the game ends,
and replay is only available after that.
- **[DECISION] Scores during play:** When `publicHoldings` is off, every player's score
is 0 until the game ends. When it is on, the score is projected net worth: cash,
current share sale values and majority/minority bonuses at current holdings (including
@ -354,6 +381,8 @@ switches on one engine, not as separate code paths. Defaults reproduce the stand
| `twoPlayerMode` | `bank` / `fourHands` | `bank` | Only has an effect with exactly 2 players. `bank` uses §12. `fourHands` runs a normal 4-seat game where each player controls two seats (player A has seats 1 and 3, player B has seats 2 and 4), with no bank shareholder. **[DECISION]** The player who controls the single richest seat wins; seats are not combined. |
| `autoEnd` | true / false | false | When true, the game ends automatically at the end of the turn in which an end condition (§11.1) first holds, instead of waiting for an announcement. |
| `stockSwap` | `off` / 3 / 5 / 7 / `unlimited` | `off` | Optional 1:1 exchanges with the bank before buying, paying or receiving the price difference. See §9.1. |
| `twoTiles` | true / false | false | Hands of 8 tiles and two placements per turn (house rule). See §4.1. |
| `limitedLog` | true / false | false | The log shows only what happened since your last turn until the game ends (house rule). See §13. |
| `endSize` | 41 / 31 | 41 | The chain size that triggers the end condition in §11.1. Setting 31 gives a shorter game (house rule). Does not change the safe size (11) or the price table. |
**[DECISION]** Invalid combinations are never rejected. An option that does not apply to

View file

@ -2,6 +2,7 @@ import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdir, writeFile } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { chromium } from "playwright";
import { preparedPosition } from "../packages/viewer/src/tutorial/lessons.ts";
@ -148,7 +149,9 @@ try {
assert.equal(await page.locator(".stock-swap button").isEnabled(), true);
}
await preferences({ locale: "en" });
await page.locator(".panel").screenshot({ path: new URL(`stock-swap-${theme}-${width}.png`, output).pathname });
await page
.locator(".panel")
.screenshot({ path: fileURLToPath(new URL(`stock-swap-${theme}-${width}.png`, output)) });
}
const original = await page.evaluate(() => JSON.stringify(window.acquireDev.state));
for (let revision = 0; revision < 3; revision++) {
@ -224,7 +227,9 @@ try {
);
}
await preferences({ locale: "en" });
await page.locator(".players").screenshot({ path: new URL(`net-worth-${theme}-${width}.png`, output).pathname });
await page
.locator(".players")
.screenshot({ path: fileURLToPath(new URL(`net-worth-${theme}-${width}.png`, output)) });
}
await page.evaluate(() => {
const state = structuredClone(window.acquireDev.state);
@ -298,7 +303,7 @@ try {
);
}
await preferences({ locale: "en" });
await page.screenshot({ path: new URL(`merger-price-${width}.png`, output).pathname, fullPage: true });
await page.screenshot({ path: fileURLToPath(new URL(`merger-price-${width}.png`, output)), fullPage: true });
}
report.scenarios.push(
"post-merger price visible before trading; original sale price unchanged; all 17 locales at desktop, phone and 320px"
@ -361,7 +366,7 @@ try {
await settle();
await page
.locator(".controls")
.screenshot({ path: new URL(`merger-shortcuts-${theme}-${width}.png`, output).pathname });
.screenshot({ path: fileURLToPath(new URL(`merger-shortcuts-${theme}-${width}.png`, output)) });
}
}
}
@ -445,8 +450,10 @@ try {
await preferences({ locale: "en" });
await page
.locator("section.hand")
.screenshot({ path: new URL(`dead-tiles-${theme}-${width}.png`, output).pathname });
await page.locator(".frame").screenshot({ path: new URL(`safe-chains-${theme}-${width}.png`, output).pathname });
.screenshot({ path: fileURLToPath(new URL(`dead-tiles-${theme}-${width}.png`, output)) });
await page
.locator(".frame")
.screenshot({ path: fileURLToPath(new URL(`safe-chains-${theme}-${width}.png`, output)) });
}
}
report.scenarios.push(
@ -530,7 +537,7 @@ try {
assert.equal(amount.weight, "600");
assert.equal(amount.numbers, "tabular-nums");
}
await page.screenshot({ path: new URL(`fullscreen-${theme}.png`, output).pathname });
await page.screenshot({ path: fileURLToPath(new URL(`fullscreen-${theme}.png`, output)) });
}
report.scenarios.push("full-window theme background, no outer gutters, wider board and permanently visible chat");
report.scenarios.push("consistent player colors, distinct chain names and emphasized cash in light/dark logs");
@ -818,7 +825,7 @@ try {
await page.locator(".board").getByRole("button", { name: "Place 2A", exact: true }).click();
await page.locator(".choices button").filter({ hasText: "Luxor" }).click();
await page.waitForSelector("table.buy");
await page.screenshot({ path: new URL(`undo-${width}.png`, output).pathname, fullPage: true });
await page.screenshot({ path: fileURLToPath(new URL(`undo-${width}.png`, output)), fullPage: true });
await page.locator(".panel .primary").click();
await page.waitForFunction(() => window.acquireDev.state.turn === 2);
await settle();
@ -878,7 +885,7 @@ try {
await settle();
}
const screenshot = await page.screenshot({
path: new URL(`${name}-${theme}.png`, output).pathname,
path: fileURLToPath(new URL(`${name}-${theme}.png`, output)),
clip: { x: 0, y: 0, width, height: captureHeight },
});
assert.equal(screenshot.readUInt32BE(16), width);
@ -887,7 +894,7 @@ try {
}
}
await preferences({ locale: "fa", colorBlind: true });
await page.screenshot({ path: new URL("phone-fa.png", output).pathname, fullPage: true });
await page.screenshot({ path: fileURLToPath(new URL("phone-fa.png", output)), fullPage: true });
for (const width of [1280, 390]) {
await page.setViewportSize({ width, height: 900 });
for (const chapter of ["founding", "mergers", "scoring"]) {
@ -979,7 +986,10 @@ try {
assert.equal(await page.locator("main .prices").count(), 1, "resumed completed lesson keeps references usable");
await page.locator("main .market .toggle").click();
}
await page.screenshot({ path: new URL(`tutorial-${chapter}-${width}.png`, output).pathname, fullPage: true });
await page.screenshot({
path: fileURLToPath(new URL(`tutorial-${chapter}-${width}.png`, output)),
fullPage: true,
});
await page.locator(".guide nav button").first().click();
const lastStep = { founding: 4, mergers: 6, scoring: 2 }[chapter];
await page.waitForSelector(`.acquire-tutorial[data-step="${lastStep}"][data-completed="false"]`);
@ -1009,7 +1019,7 @@ try {
.click();
await page.locator("main .panel .primary").click();
await page.waitForSelector('.acquire-tutorial[data-step="1"]').catch(async (error) => {
await page.screenshot({ path: new URL("tutorial-failure.png", output).pathname, fullPage: true });
await page.screenshot({ path: fileURLToPath(new URL("tutorial-failure.png", output)), fullPage: true });
throw new Error(
`${chapter} ${locale} ${width}px: ${await page.locator("#app").innerText()}\n${errors.join("\n")}`,
{ cause: error }
@ -1065,7 +1075,7 @@ try {
report.tutorialLayouts.push({ width, locale, chapter });
if (["en", "fr", "fa"].includes(locale)) {
await page.screenshot({
path: new URL(`explanation-${chapter}-${locale}-${width}.png`, output).pathname,
path: fileURLToPath(new URL(`explanation-${chapter}-${locale}-${width}.png`, output)),
fullPage: true,
});
}