Add optional stock swaps before buying shares

This commit is contained in:
coyotte508 2026-10-26 20:10:01 +01:00
commit 2c7b26a927
41 changed files with 952 additions and 10 deletions

View file

@ -93,6 +93,34 @@
"label": "31 tiles (shorter game)"
}
]
},
{
"name": "stockSwap",
"label": "Stock swap (shares per turn, optional variant)",
"type": "select",
"default": "off",
"items": [
{
"name": "off",
"label": "Off"
},
{
"name": "3",
"label": "3"
},
{
"name": "5",
"label": "5"
},
{
"name": "7",
"label": "7"
},
{
"name": "unlimited",
"label": "Unlimited"
}
]
}
],
"settings": [],

View file

@ -1,10 +1,17 @@
# Acquire private beta — 24 October 2026
# Acquire — 26 October 2026
Private BGS registration: `acquire`, version `1`. Engine `0.0.3`, viewer `0.0.16`.
Source: <https://github.com/boardgamers/mergers-game>. Keep `public: false`.
BGS registration: `acquire`, version `1`. Engine `0.0.4`, viewer `0.0.17`.
Source: <https://github.com/boardgamers/mergers-game>. The live game is now public; preserve its current visibility when updating.
## Validation
- Optional stock swaps default to Off, with 3/5/7/Unlimited shares per turn shared across exchanges.
Only active chains may swap 1:1 at current prices after all mergers, respecting bank stock,
holdings and cash. Normal three-share purchases remain separate. Engine checks cover allowance
resets, refunds, equal prices, bank/cash limits, malformed moves, merger timing, old replays,
public replay reconstruction, four hands, private undo and one clock increment per turn.
The compact pre-buy controls and public swap log are translated into all 17 languages.
- Public-holdings games show projected net worth and an expandable cash/share/bonus breakdown.
BGS scores use the same valuation, combining teammates or taking the richest four-hands seat.
Future bank-mode bonuses are excluded. Checks cover ties/rounding, inactive shares, partial
@ -39,7 +46,7 @@ Source: <https://github.com/boardgamers/mergers-game>. Keep `public: false`.
requests, hidden-information masking, replay, bank mode, four-hands, teams and dropped players.
Desktop/phone checks exercise repeated undo, saved-state refreshes, final history and clock totals.
- `pnpm check`: formatting, lint, TypeScript/Svelte checks, 214 engine tests,
- `pnpm check`: formatting, lint, TypeScript/Svelte checks, 222 engine tests,
66 viewer/tutorial tests, and the production build. Two pre-existing lint warnings
remain (an unused test import and Svelte's `bind:this` assignment).
- Protocol diagnostics: all eight required engine methods; full core/chat/replay

View file

@ -59,6 +59,22 @@ Then the survivor absorbs all the tiles. The names of the chains taken over are
After placing, you may buy up to 3 shares in total, in one or more chains on the board. Prices depend on each chain's current size and stay fixed for the rest of your turn. You can't borrow, and you can't sell stock except in a merger or at the end.
### Optional stock swaps
If the game uses **Stock swap**, after your tile and any mergers are fully resolved you
may exchange shares with the bank **one for one**, before buying. Both chains must be on
the board. Give shares you own and take the same number from the bank, paying the current
price difference or receiving cash if the new shares are cheaper. You must afford the
payment, and the bank must have enough stock.
For example, two Tower shares at $300 each exchanged for two Continental shares at $700
each cost $800. Reversing that exchange pays you $800.
The setting is **Off** (default), **3**, **5**, **7** or **Unlimited** shares per turn.
The allowance is shared across exchanges: giving three shares and receiving three uses
three of the allowance. You can still buy your usual **up to 3 shares** afterward.
Swaps can be undone until you finish buying. This is an optional house rule.
## Price table
Find a chain's size in the column for its tier.
@ -100,6 +116,7 @@ Your tiles are private. Unless the game was created with **public holdings**, ea
## Game options
- **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.
- **Two-player mode:** *Bank as third shareholder* (above) or *Four hands*, where each player controls two seats in a normal four-seat game and the player with the single richest seat wins.

View file

@ -10,6 +10,7 @@ export * from "./src/bonuses.js";
export * from "./src/merger.js";
export * from "./src/scoring.js";
export * from "./src/net-worth.js";
export { stockSwapsRemaining, stockSwapCost, maxStockSwap } from "./src/stock-swap.js";
export * from "./src/bank.js";
export * from "./src/options.js";
export * from "./src/autoplay.js";

View file

@ -1,6 +1,6 @@
{
"name": "acquire-engine",
"version": "0.0.3",
"version": "0.0.4",
"description": "Acquire rules engine for boardgamers.space",
"license": "AGPL-3.0-only",
"files": [

View file

@ -2,6 +2,7 @@ import { activeChains } from "./board.js";
import { CHAIN_IDS, MAX_BUY, type ChainId } from "./config.js";
import { merger } from "./merger.js";
import { currentSeat, sanitizeMove } from "./moves.js";
import { maxStockSwap } from "./stock-swap.js";
import { tileLabel } from "./tiles.js";
import type { GameState, Move, Shares } from "./types.js";
@ -69,8 +70,19 @@ function phaseCandidates(state: GameState): Move[] {
}
return moves;
}
case "buy":
return buyCombinations(activeChains(state.board)).map((shares) => ({ type: "buy", shares }));
case "buy": {
const active = activeChains(state.board);
const moves: Move[] = buyCombinations(active).map((shares) => ({ type: "buy", shares }));
for (const from of active) {
for (const to of active) {
const max = maxStockSwap(state, from, to);
for (let count = 1; count <= max; count++) {
moves.push({ type: "swap", from, to, count });
}
}
}
return moves;
}
default:
return [];
}

View file

@ -11,6 +11,7 @@ import {
startMerger,
survivorCandidates,
} from "./merger.js";
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";
@ -60,6 +61,15 @@ export function sanitizeMove(state: GameState, raw: unknown, seat: number): Move
}
return { type: "pass" };
}
if (raw.type === "swap") {
if (!isChainId(raw.from) || !isChainId(raw.to) || !Number.isInteger(raw.count) || (raw.count as number) < 1) {
throw new Error("Choose two different active chains and a positive whole number of shares");
}
if ((raw.count as number) > maxStockSwap(state, raw.from, raw.to)) {
throw new Error("That stock swap exceeds the allowance, your holdings, available bank stock or cash");
}
return { type: "swap", from: raw.from, to: raw.to, count: raw.count as number };
}
if (raw.type !== state.phase) {
throw new Error(`Expected a "${state.phase}" move`);
}
@ -252,6 +262,9 @@ function perform(state: GameState, move: Move, seat: number, auto: boolean): voi
case "dispose":
dispose(state, seat, move.sell, move.trade);
break;
case "swap":
swapStock(state, move.from, move.to, move.count);
break;
case "buy":
buyShares(state, move.shares);
endTurn(state);

View file

@ -7,6 +7,8 @@ export interface GameOptions {
twoPlayerMode: "bank" | "fourHands";
autoEnd: boolean;
endSize: number;
/** Omitted when off, preserving the init log of games created before this variant. */
stockSwap?: 3 | 5 | 7 | "unlimited";
}
export interface IgnoredOption {
@ -68,6 +70,16 @@ export function normalizeOptions(
}
}
if (raw.stockSwap === "unlimited") {
options.stockSwap = "unlimited";
} else if (raw.stockSwap !== undefined && raw.stockSwap !== "off") {
if ([3, 5, 7, "3", "5", "7"].includes(raw.stockSwap as number | string)) {
options.stockSwap = Number(raw.stockSwap) as 3 | 5 | 7;
} else {
ignored.push({ option: "stockSwap", value: raw.stockSwap, reason: "unknown value" });
}
}
return { options, ignored };
}

View file

@ -109,6 +109,15 @@ export function positionAt(state: GameState, to: number): PublicPosition {
bank[merger!.survivor!] -= entry.traded / 2;
break;
}
case "swapped": {
const seat = seats[entry.seat]!;
seat.cash -= entry.cost;
seat.shares[entry.from] -= entry.count;
bank[entry.from] += entry.count;
seat.shares[entry.to] += entry.count;
bank[entry.to] -= entry.count;
break;
}
case "bought": {
const seat = seats[entry.seat]!;
seat.cash -= entry.cost;

View file

@ -76,6 +76,8 @@ export function turnSummary(state: GameState, index: number): string {
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 === "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) {
parts.push(`bought ${shareList(entry.shares)}`);
} else if (entry.type === "announced") {
@ -117,6 +119,8 @@ export function simpleLine(state: GameState, entry: LogEntry): string {
return `${name} chose the order ${list(move.chains.map(chainName))}${auto}`;
case "dispose":
return `${name} sold ${move.sell} and traded ${move.trade}${auto}`;
case "swap":
return `${name} swapped ${move.count} ${chainName(move.from)} for ${move.count} ${chainName(move.to)}`;
case "buy": {
const bought = shareList(move.shares);
return bought ? `${name} bought ${bought}${auto}` : `${name} bought nothing${auto}`;
@ -174,6 +178,8 @@ export function simpleLine(state: GameState, entry: LogEntry): string {
return `${chainName(entry.survivor)} now has ${count(entry.size, "tile")}`;
case "bankTile":
return `The bank's tile ${tileLabel(entry.tile)} ${BANK_TILE[entry.result]}`;
case "swapped":
return `${seat(entry.seat)} swapped ${entry.count} ${chainName(entry.from)} for ${entry.count} ${chainName(entry.to)} (${entry.cost > 0 ? "paid " + money(entry.cost) : entry.cost < 0 ? "received " + money(-entry.cost) : "no cash difference"})`;
case "bought": {
const bought = shareList(entry.shares);
return bought

View file

@ -0,0 +1,225 @@
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 } from "./moves.js";
import { normalizeOptions } from "./options.js";
import { positionAt } from "./position.js";
import { initGame } from "./setup.js";
import { maxStockSwap, stockSwapCost, stockSwapsRemaining } from "./stock-swap.js";
import { buyStepAvailable } from "./turn.js";
import { chainAt, checkInvariants, row, scenario } from "./test/helpers.js";
import type { Move } from "./types.js";
const exchange: Move = { type: "swap", from: "tower", to: "continental", count: 2 };
const buy: Move = { type: "buy", shares: {} };
function position(limit: unknown = "3") {
const state = scenario({
board: { ...chainAt("tower", row("A", 1, 3)), ...chainAt("continental", row("E", 1, 5)) },
hands: [["12I"], ["11I"], ["10I"]],
shares: [{ tower: 10, continental: 5 }],
options: { stockSwap: limit },
});
applyMove(state, { type: "place", tile: "12I" }, 0);
return state;
}
test("stock swap defaults off, accepts all five settings and preserves historical option shape", () => {
for (const raw of [undefined, "off"]) {
const { options, ignored } = normalizeOptions(3, raw === undefined ? {} : { stockSwap: raw });
assert.equal("stockSwap" in options, false);
assert.deepEqual(ignored, []);
assert.equal(
legalMoves(position(raw ?? "off")).some((m) => m.type === "swap"),
false
);
}
for (const raw of [3, 5, 7, "3", "5", "7", "unlimited"]) {
assert.equal(normalizeOptions(3, { stockSwap: raw }).options.stockSwap, raw === "unlimited" ? raw : Number(raw));
}
for (const stockSwap of [null, true, 0, 4, -1, [], {}, "Infinity", "3.0"]) {
const { options, ignored } = normalizeOptions(3, { stockSwap });
assert.equal(options.stockSwap, undefined);
assert.equal(ignored.length, 1);
}
const old = initGame(3, {}, "before-swaps");
assert.deepEqual(wrapper.replay(old), old);
});
test("one-for-one swaps pay or receive the current price difference and preserve all stock", () => {
const state = position("unlimited");
assert.equal(stockSwapCost(state, "tower", "continental", 2), 800);
applyMove(state, exchange, 0);
assert.equal(state.seats[0]!.cash, 5200);
assert.equal(state.seats[0]!.shares.tower, 8);
assert.equal(state.seats[0]!.shares.continental, 7);
assert.equal(state.bank.tower, 17);
assert.equal(state.bank.continental, 18);
applyMove(state, { type: "swap", from: "continental", to: "tower", count: 2 }, 0);
assert.equal(state.seats[0]!.cash, 6000);
assert.equal(state.seats[0]!.shares.tower, 10);
assert.equal(state.seats[0]!.shares.continental, 5);
checkInvariants(state);
const equal = scenario({
board: { ...chainAt("tower", row("A", 1, 3)), ...chainAt("luxor", row("E", 1, 3)) },
hands: [["12I"]],
shares: [{ tower: 1 }],
options: { stockSwap: 3 },
});
applyMove(equal, { type: "place", tile: "12I" }, 0);
applyMove(equal, { type: "swap", from: "tower", to: "luxor", count: 1 }, 0);
assert.equal(equal.seats[0]!.cash, 6000);
checkInvariants(equal);
});
test("the shared 3/5/7 allowance counts only outgoing shares and buying three remains separate", () => {
for (const limit of [3, 5, 7]) {
const state = position(limit);
applyMove(state, exchange, 0);
assert.equal(stockSwapsRemaining(state), limit - 2);
applyMove(state, { type: "swap", from: "continental", to: "tower", count: limit - 2 }, 0);
assert.equal(stockSwapsRemaining(state), 0);
assert.equal(
legalMoves(state).some((m) => m.type === "swap"),
false
);
assert.throws(() => applyMove(state, exchange, 0));
applyMove(state, { type: "buy", shares: { tower: 3 } }, 0);
assert.equal(stockSwapsRemaining(state), limit, "allowance resets for the next seat");
checkInvariants(state);
}
});
test("invalid swaps are rejected atomically: wrong seat/phase, inactive chain, funds, stock and malformed counts", () => {
const base = position();
for (const patch of [
{ count: 0 },
{ count: -1 },
{ count: 1.5 },
{ count: "2" },
{ count: Infinity },
{ count: 4 },
{ from: "continental", to: "continental" },
{ from: "missing" },
{ to: "luxor" },
]) {
const before = structuredClone(base);
assert.throws(() => applyMove(base, { ...exchange, ...patch }, 0));
assert.deepEqual(base, before);
}
assert.throws(() => applyMove(base, exchange, 1), /not your turn/);
for (const phase of ["place", "found", "survivor", "defunctOrder"] as const) {
const state = { ...structuredClone(base), phase };
assert.throws(() => applyMove(state, exchange, 0));
}
base.seats[0]!.cash = 700;
assert.equal(maxStockSwap(base, "tower", "continental"), 1);
assert.throws(() => applyMove(base, exchange, 0));
base.seats[0]!.cash = 6000;
base.bank.continental = 1;
assert.equal(maxStockSwap(base, "tower", "continental"), 1);
base.bank.continental = 20;
base.seats[0]!.shares.tower = 1;
assert.equal(maxStockSwap(base, "tower", "continental"), 1);
base.options.stockSwap = undefined;
assert.throws(() => applyMove(base, exchange, 0));
});
test("buying is not auto-skipped when swaps can release cash, regardless of hidden holdings", () => {
for (const publicHoldings of [false, true]) {
const state = position();
state.options.publicHoldings = publicHoldings;
state.seats[0]!.cash = 0;
assert.equal(buyStepAvailable(state), true);
assert.equal(maxStockSwap(state, "continental", "tower"), 3);
applyMove(state, { type: "swap", from: "continental", to: "tower", count: 3 }, 0);
assert.equal(state.seats[0]!.cash, 1200);
applyMove(state, { type: "buy", shares: { tower: 3 } }, 0);
assert.equal(state.seats[0]!.cash, 300);
checkInvariants(state);
}
const state = position();
state.seats[0]!.cash = 0;
state.seats[0]!.shares.tower = state.seats[0]!.shares.continental = 0;
assert.equal(buyStepAvailable(state), true, "auto-skip does not expose secret holdings");
});
test("swaps wait for the entire merger and use the survivor's grown price", () => {
const state = scenario({
board: {
...chainAt("tower", ["1A", "2A", "3A"]),
...chainAt("luxor", ["5A", "6A"]),
...chainAt("continental", ["1E", "2E"]),
},
hands: [["4A"], ["11I"], ["10I"]],
shares: [{ tower: 2, luxor: 1 }, { luxor: 1 }],
options: { stockSwap: 3 },
});
applyMove(state, { type: "place", tile: "4A" }, 0);
assert.equal(state.phase, "dispose");
assert.throws(() => applyMove(state, { ...exchange, count: 1 }, 0));
applyMove(state, { type: "dispose", sell: 1, trade: 0 }, 0);
applyMove(state, { type: "dispose", sell: 1, trade: 0 }, 1);
assert.equal(state.phase, "buy");
assert.equal(stockSwapCost(state, "tower", "continental", 1), -200);
const cash = state.seats[0]!.cash;
applyMove(state, { ...exchange, count: 1 }, 0);
assert.equal(state.seats[0]!.cash, cash + 200);
checkInvariants(state);
});
test("swap revisions and unlimited sequences stay private; only the final turn adds history and one increment", () => {
const base = position("unlimited");
const original = structuredClone(base);
for (let i = 0; i < 20; i++) {
const preview = wrapper.move(
base,
{ type: "turn", from: base.log.length, moves: [{ ...exchange, count: (i % 2) + 1 }] },
0
);
assert.equal(wrapper.toSave(preview), undefined);
assert.deepEqual(wrapper.timeIncrements(preview), [0, 0, 0]);
assert.equal(wrapper.logSlice(preview, { player: 1 }).preview, undefined);
assert.equal(wrapper.stripSecret(preview, 0).seats[1]!.cash, -1);
}
assert.deepEqual(base, original);
const swaps: Move[] = Array.from({ length: 24 }, (_, i) => ({
type: "swap",
from: i % 2 ? "continental" : "tower",
to: i % 2 ? "tower" : "continental",
count: 1,
}));
const saved = wrapper.move(base, { type: "turn", from: base.log.length, moves: [...swaps, buy] }, 0);
assert.equal(wrapper.toSave(saved), saved);
assert.equal(saved.log.filter((e) => e.type === "swapped").length, 24);
assert.deepEqual(wrapper.timeIncrements(saved), [1, 0, 0]);
assert.equal(saved.seats[0]!.cash, 6000);
checkInvariants(saved);
});
test("real seeded games with swaps replay identically, including public stock/cash reconstruction", () => {
for (const options of [{ stockSwap: "3" }, { stockSwap: "unlimited", twoPlayerMode: "fourHands" }, {}]) {
const state = initGame(options.twoPlayerMode ? 2 : 3, options, "swap-replay");
let exchanged = 0;
for (let i = 0; i < 180 && !state.ended; i++) {
const moves = legalMoves(state);
const swap = moves.find((m) => m.type === "swap");
const move =
swap && exchanged < 3 ? swap : moves.filter((m) => m.type !== "swap" && m.type !== "announce").at(-1)!;
if (move.type === "swap") {
exchanged++;
}
applyMove(state, move, currentSeat(state)!);
}
assert.ok(!options.stockSwap || exchanged > 0);
assert.deepEqual(wrapper.replay(state), state);
const publicState = positionAt(state, state.log.length);
assert.deepEqual(publicState.board, state.board);
assert.deepEqual(publicState.bank, state.bank);
assert.deepEqual(
publicState.seats.map((s) => [s.cash, s.shares]),
state.seats.map((s) => [s.cash, s.shares])
);
checkInvariants(state);
}
});

View file

@ -0,0 +1,63 @@
import { activeChains, chainSize } from "./board.js";
import type { ChainId } from "./config.js";
import { sharePrice } from "./prices.js";
import type { GameState } from "./types.js";
/** The shared allowance counts shares given, across every exchange in this seat's turn. */
export function stockSwapsRemaining(state: GameState): number {
const limit = state.options.stockSwap;
if (limit === "unlimited") {
return Infinity;
}
if (!limit) {
return 0;
}
let used = 0;
for (let i = state.log.length - 1; i >= 0; i--) {
const entry = state.log[i]!;
if (entry.type === "turn") {
break;
}
if (entry.type === "swapped") {
used += entry.count;
}
}
return Math.max(0, limit - used);
}
/** Positive means paying the bank; negative means receiving cash from it. */
export function stockSwapCost(state: GameState, from: ChainId, to: ChainId, count: number): number {
return count * (sharePrice(to, chainSize(state.board, to)) - sharePrice(from, chainSize(state.board, from)));
}
export function maxStockSwap(state: GameState, from: ChainId, to: ChainId): number {
if (state.ended || state.phase !== "buy" || state.merger || from === to) {
return 0;
}
const active = activeChains(state.board);
if (!active.includes(from) || !active.includes(to)) {
return 0;
}
const seat = state.seats[state.activeSeat]!;
const cost = stockSwapCost(state, from, to, 1);
return Math.max(
0,
Math.min(
stockSwapsRemaining(state),
seat.shares[from],
state.bank[to],
cost > 0 ? Math.floor(seat.cash / cost) : Infinity
)
);
}
export function swapStock(state: GameState, from: ChainId, to: ChainId, count: number): void {
const seat = state.seats[state.activeSeat]!;
const cost = stockSwapCost(state, from, to, count);
seat.shares[from] -= count;
state.bank[from] += count;
seat.shares[to] += count;
state.bank[to] -= count;
seat.cash -= cost;
state.log.push({ type: "swapped", seat: state.activeSeat, from, to, count, cost });
}

View file

@ -1,7 +1,8 @@
import { applyMove, currentSeat } from "./moves.js";
import type { GameState, TurnRequest } from "./types.js";
export const MAX_TURN_MOVES = 16;
// Bound untrusted request work while allowing many optional swaps in a private turn.
export const MAX_TURN_MOVES = 256;
/** A private draft ends before any new hidden information or another decision is exposed. */
export function draftCanContinue(before: GameState, after: GameState, player: number): boolean {

View file

@ -15,6 +15,12 @@ export function drawTile(state: GameState): Tile | undefined {
*/
export function buyStepAvailable(state: GameState): boolean {
const seat = state.seats[state.activeSeat]!;
// A swap may release cash even when buying is unaffordable. Do not use hidden holdings
// to decide whether this step is shown; opponents must not learn them from an auto-skip.
const active = activeChains(state.board);
if (state.options.stockSwap && active.length > 1 && active.some((chain) => state.bank[chain] > 0)) {
return true;
}
const cashIsPublic = state.options.publicHoldings;
return activeChains(state.board).some(
(chain) => state.bank[chain] > 0 && (!cashIsPublic || sharePrice(chain, chainSize(state.board, chain)) <= seat.cash)

View file

@ -25,6 +25,7 @@ export type Move =
| { type: "survivor"; chain: ChainId }
| { type: "defunctOrder"; chains: ChainId[] }
| { type: "dispose"; sell: number; trade: number }
| { type: "swap"; from: ChainId; to: ChainId; count: number }
| { type: "buy"; shares: Partial<Shares> };
/** The complete private move sequence since the last saved position. */
@ -70,6 +71,7 @@ export type LogEntry =
| { type: "bankTile"; tile: Tile; result: "loose" | "joined" | "merger" | "removed" }
| { type: "disposed"; seat: number; chain: ChainId; sold: number; traded: number; held: number; proceeds: number }
| { type: "merged"; survivor: ChainId; size: number }
| { type: "swapped"; seat: number; from: ChainId; to: ChainId; count: number; cost: number }
| { type: "bought"; seat: number; shares: Partial<Shares>; cost: number }
| { type: "discarded"; seat: number; tiles: Tile[] }
| { type: "drew"; seat: number; count: number }

View file

@ -1,6 +1,6 @@
{
"name": "acquire-viewer",
"version": "0.0.16",
"version": "0.0.17",
"private": true,
"description": "Browser viewer for Acquire on boardgamers.space",
"license": "AGPL-3.0-only",

View file

@ -34,7 +34,7 @@ for (const key of ["publicHoldings", "teamPlay", "autoEnd"]) {
options[key] = true;
}
}
for (const key of ["twoPlayerMode", "endSize"]) {
for (const key of ["twoPlayerMode", "endSize", "stockSwap"]) {
const value = params.get(key);
if (value) {
options[key] = value;

View file

@ -11,6 +11,7 @@
type Shares,
} from "acquire-engine";
import ChainMark from "./ChainMark.svelte";
import StockSwap from "./StockSwap.svelte";
import { mergerPreview } from "./mergerPreview";
import {
adjustShares,
@ -36,6 +37,7 @@
// Choices being built up before they are sent; reset whenever a new state arrives.
let confirmAnnounce = $state(false);
let swapOpen = $state(false);
let order = $state<ChainId[]>([]);
let sell = $state(0);
let trade = $state(0);
@ -293,6 +295,7 @@
>{t("dispose.confirm")}</button
>
{:else if game.phase === "buy"}
{#if game.options.stockSwap}<StockSwap {store} bind:open={swapOpen} />{/if}
<p>{t("buy.prompt")}</p>
{#if buyable.length > 0}
<table class="buy">

View file

@ -0,0 +1,174 @@
<script lang="ts">
import {
activeChains,
chainSize,
sharePrice,
stockSwapCost,
stockSwapsRemaining,
type ChainId,
} from "acquire-engine";
import ChainMark from "./ChainMark.svelte";
import { ofType } from "./decisions";
import { chainName } from "./format";
import type { ViewerStore } from "./store.svelte";
let { store, open = $bindable(false) }: { store: ViewerStore; open?: boolean } = $props();
const game = $derived(store.state!);
const t = $derived(store.lang.t);
const money = $derived(store.lang.money);
const choices = $derived(ofType(store.moves, "swap"));
const active = $derived(activeChains(game.board));
const held = $derived(game.seats[game.activeSeat]!.shares);
const remaining = $derived(stockSwapsRemaining(game));
let from = $state<ChainId>("tower");
let to = $state<ChainId>("continental");
let count = $state<number | undefined>(1);
$effect(() => {
void store.state;
const first = choices[0];
if (first) {
from = first.from;
to = first.to;
}
count = 1;
});
const pair = $derived(choices.filter((move) => move.from === from && move.to === to));
const max = $derived(pair.at(-1)?.count ?? 0);
const selected = $derived(pair.find((move) => move.count === count));
const cost = $derived(selected ? stockSwapCost(game, from, to, selected.count) : 0);
const cash = $derived(
cost === 0 ? t("swap.even") : t(cost > 0 ? "swap.pay" : "swap.receive", { amount: money(Math.abs(cost)) })
);
const price = (chain: ChainId) => money(sharePrice(chain, chainSize(game.board, chain)));
</script>
<details class="stock-swap" bind:open>
<summary
><span aria-hidden="true">⇄</span>
{t("swap.title")}
<small>· {remaining === Infinity ? t("swap.unlimited") : t("swap.remaining", { count: remaining })}</small></summary
>
<p class="note">{t("swap.note")}</p>
{#if choices.length}
<div class="chains">
<label
>{t("swap.give")}
<select
bind:value={from}
aria-label={t("swap.give")}
onchange={(event) => {
count = 1;
to = choices.find((move) => move.from === event.currentTarget.value)?.to ?? to;
}}
>
{#each active.filter((chain) => held[chain] > 0) as chain (chain)}
<option value={chain}>{chainName(chain)} · {held[chain]} · {price(chain)}</option>
{/each}
</select>
</label>
<label
>{t("swap.take")}
<select aria-label={t("swap.take")} bind:value={to} onchange={() => (count = 1)}>
{#each active.filter((chain) => chain !== from) as chain (chain)}
<option value={chain}>{chainName(chain)} · {game.bank[chain]} · {price(chain)}</option>
{/each}
</select>
</label>
</div>
<div class="swap-controls">
<label>{t("swap.count")}<input type="number" min="1" {max} step="1" bind:value={count} /></label>
<div class="exchange" aria-live="polite">
<ChainMark chain={from} /><span aria-hidden="true">→</span><ChainMark chain={to} />
<strong>{selected ? cash : t("swap.unavailable")}</strong>
</div>
</div>
<button
type="button"
class:actionable={!!selected}
disabled={!selected}
onclick={() => selected && store.send(selected)}>{t("swap.confirm")}</button
>
{:else}
<p>{t("swap.unavailable")}</p>
{/if}
</details>
<style>
.stock-swap {
border-bottom: 1px solid var(--ink-muted);
padding-bottom: 10px;
margin-bottom: 12px;
}
summary {
cursor: pointer;
font-weight: 600;
}
small,
.note {
color: var(--ink-muted);
font-size: 13px;
font-weight: 400;
}
p {
margin: 8px 0;
}
.chains {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(220px, 100%), 1fr));
gap: 8px;
}
label {
display: grid;
gap: 4px;
font-size: 13px;
min-width: 0;
}
select,
input {
box-sizing: border-box;
width: 100%;
min-height: 44px;
font: inherit;
color: var(--ink);
background: var(--page);
border: 1px solid var(--ink-muted);
padding: 6px;
}
.swap-controls {
display: flex;
align-items: end;
gap: 12px;
margin: 10px 0;
}
.swap-controls label {
flex: 0 0 72px;
}
.exchange {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
min-width: 0;
}
.exchange strong {
flex-basis: 100%;
font-size: 14px;
font-variant-numeric: tabular-nums;
}
button {
min-height: 44px;
padding: 6px 12px;
color: var(--ink);
background: var(--page);
border: none;
font: inherit;
}
button:disabled {
color: var(--ink-muted);
}
@media (max-width: 400px) {
.chains {
grid-template-columns: minmax(0, 1fr);
}
}
</style>

View file

@ -8,6 +8,9 @@ test("styled log preserves translations, lists and cash formatting", () => {
const state = initGame(3, {}, "log-colors");
const entries: LogEntry[] = [
...state.log,
{ type: "swapped", seat: 0, from: "tower", to: "continental", count: 2, cost: 800 },
{ type: "swapped", seat: 0, from: "continental", to: "tower", count: 1, cost: -400 },
{ type: "swapped", seat: 0, from: "tower", to: "luxor", count: 1, cost: 0 },
{ type: "bought", seat: 0, shares: { tower: 1, luxor: 2 }, cost: 1200 },
{ type: "merger", seat: 0, tile: 3, sizes: { tower: 5, luxor: 5 } },
{ type: "mergerPlan", survivor: "tower", defunct: ["luxor", "imperial"] },

View file

@ -173,6 +173,17 @@ export function describeEntry(
return t("log.merged", { chain: chain(entry.survivor), tiles: tiles(entry.size) });
case "bankTile":
return t(BANK_TILE_KEYS[entry.result], { tile: tileLabel(entry.tile) });
case "swapped":
return t("log.swapped", {
name: seat(entry.seat),
count: entry.count,
from: chain(entry.from),
to: chain(entry.to),
cash:
entry.cost === 0
? t("swap.even")
: t(entry.cost > 0 ? "swap.pay" : "swap.receive", { amount: money(Math.abs(entry.cost)) }),
});
case "bought": {
const bought = Object.entries(entry.shares).map(([id, n]) => `${n} ${chain(id as ChainId)}`);
return bought.length > 0

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const da: Catalog = {
"swap.title": "Aktiebytte",
"swap.note": "Byt 1:1 til aktuelle priser før køb. Du kan stadig købe op til 3 aktier.",
"swap.remaining": "{count} tilbage denne tur",
"swap.unlimited": "Ubegrænset",
"swap.give": "Afgiv (dine aktier)",
"swap.take": "Modtag (bankens aktier)",
"swap.count": "Aktier",
"swap.confirm": "Byt aktier",
"swap.pay": "Betal {amount}",
"swap.receive": "Modtag {amount}",
"swap.even": "Ingen prisforskel",
"swap.unavailable": "Intet bytte muligt med dette antal, grænsen, aktierne og kontanterne.",
"log.swapped": "{name} bytter {count} {from} for {count} {to} · {cash}",
loading: "Indlæser spillet…",
"status.place": "{name} skal lægge en brik",
"status.found": "{name} skal navngive en ny kæde",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const de: Catalog = {
"swap.title": "Aktientausch",
"swap.note": "Vor dem Kauf 1:1 zu aktuellen Kursen tauschen. Du darfst weiterhin bis zu 3 Aktien kaufen.",
"swap.remaining": "{count} in diesem Zug übrig",
"swap.unlimited": "Unbegrenzt",
"swap.give": "Abgeben (dein Bestand)",
"swap.take": "Erhalten (Bankbestand)",
"swap.count": "Aktien",
"swap.confirm": "Aktien tauschen",
"swap.pay": "{amount} zahlen",
"swap.receive": "{amount} erhalten",
"swap.even": "Keine Preisdifferenz",
"swap.unavailable": "Mit dieser Menge, dem Limit, Aktienbestand und Bargeld ist kein Tausch möglich.",
"log.swapped": "{name} tauscht {count} {from} gegen {count} {to} · {cash}",
loading: "Spiel wird geladen…",
"status.place": "{name} legt ein Plättchen",
"status.found": "{name} benennt eine neue Kette",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const el: Catalog = {
"swap.title": "Ανταλλαγή μετοχών",
"swap.note": "Ανταλλάξτε 1:1 στις τρέχουσες τιμές πριν αγοράσετε. Μπορείτε ακόμα να αγοράσετε έως 3 μετοχές.",
"swap.remaining": "Απομένουν {count} σε αυτόν τον γύρο",
"swap.unlimited": "Απεριόριστες",
"swap.give": "Δίνετε (μετοχές σας)",
"swap.take": "Παίρνετε (τράπεζα)",
"swap.count": "Μετοχές",
"swap.confirm": "Ανταλλαγή",
"swap.pay": "Πληρωμή {amount}",
"swap.receive": "Είσπραξη {amount}",
"swap.even": "Χωρίς διαφορά τιμής",
"swap.unavailable": "Δεν γίνεται ανταλλαγή με αυτή την ποσότητα, το όριο, τις μετοχές και τα μετρητά.",
"log.swapped": "{name}: ανταλλαγή {count} {from} με {count} {to} · {cash}",
loading: "Φόρτωση παιχνιδιού…",
"status.place": "{name}: τοποθέτηση πλακιδίου",
"status.found": "{name}: ονομασία νέας αλυσίδας",

View file

@ -2,6 +2,20 @@
// system and by i18n.spec.ts). {name} placeholders must be kept; plural messages give one form
// per CLDR plural category of the language. Chain names are never translated.
export const en = {
"swap.title": "Stock swap",
"swap.note": "Swap 1:1 at current prices before buying. You may still buy up to 3 shares.",
"swap.remaining": "{count} left this turn",
"swap.unlimited": "Unlimited",
"swap.give": "Give (your stock)",
"swap.take": "Receive (bank stock)",
"swap.count": "Shares",
"swap.confirm": "Swap shares",
"swap.pay": "Pay {amount}",
"swap.receive": "Receive {amount}",
"swap.even": "No cash difference",
"swap.unavailable": "No swap available with this quantity, allowance, stock and cash.",
"log.swapped": "{name} swapped {count} {from} for {count} {to} · {cash}",
loading: "Loading game…",
// Status bar

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const fa: Catalog = {
"swap.title": "تعویض سهام",
"swap.note": "پیش از خرید، با قیمت فعلی یک‌به‌یک تعویض کنید. همچنان می‌توانید تا ۳ سهم بخرید.",
"swap.remaining": "{count} سهم باقی‌مانده در این نوبت",
"swap.unlimited": "نامحدود",
"swap.give": "واگذاری (سهام شما)",
"swap.take": "دریافت (سهام بانک)",
"swap.count": "تعداد سهم",
"swap.confirm": "تعویض سهام",
"swap.pay": "پرداخت {amount}",
"swap.receive": "دریافت {amount}",
"swap.even": "بدون اختلاف قیمت",
"swap.unavailable": "با این تعداد، سقف تعویض، سهام و وجه نقد، تعویض ممکن نیست.",
"log.swapped": "{name} تعداد {count} سهم {from} را با {count} سهم {to} تعویض کرد · {cash}",
loading: "در حال بارگذاری بازی…",
"status.place": "{name} باید یک کاشی بگذارد",
"status.found": "{name} باید برای زنجیره‌ی جدید نام انتخاب کند",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const fr: Catalog = {
"swap.title": "Échange d’actions",
"swap.note": "Échangez à 1 contre 1 au prix actuel avant d’acheter. Vous pouvez toujours acheter jusqu’à 3 actions.",
"swap.remaining": "{count} restantes ce tour",
"swap.unlimited": "Illimité",
"swap.give": "Donner (vos actions)",
"swap.take": "Recevoir (banque)",
"swap.count": "Actions",
"swap.confirm": "Échanger",
"swap.pay": "Payer {amount}",
"swap.receive": "Recevoir {amount}",
"swap.even": "Sans différence de prix",
"swap.unavailable": "Échange impossible avec cette quantité, la limite, les actions et les fonds disponibles.",
"log.swapped": "{name} échange {count} {from} contre {count} {to} · {cash}",
loading: "Chargement de la partie…",
"status.place": "{name} doit poser une tuile",
"status.found": "{name} doit nommer une nouvelle chaîne",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const hi: Catalog = {
"swap.title": "शेयर अदला-बदली",
"swap.note": "खरीदने से पहले मौजूदा कीमतों पर 1:1 अदला-बदली करें। फिर भी 3 शेयर तक खरीद सकते हैं।",
"swap.remaining": "इस बारी में {count} बाकी",
"swap.unlimited": "असीमित",
"swap.give": "दें (आपके शेयर)",
"swap.take": "लें (बैंक के शेयर)",
"swap.count": "शेयर",
"swap.confirm": "शेयर बदलें",
"swap.pay": "{amount} दें",
"swap.receive": "{amount} लें",
"swap.even": "कीमत में कोई अंतर नहीं",
"swap.unavailable": "इस मात्रा, सीमा, शेयरों और नकद के साथ अदला-बदली उपलब्ध नहीं है।",
"log.swapped": "{name} ने {count} {from} के बदले {count} {to} लिए · {cash}",
loading: "खेल लोड हो रहा है…",
"status.place": "{name} को एक टाइल रखनी है",
"status.found": "{name} को नई श्रृंखला का नाम चुनना है",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const it: Catalog = {
"swap.title": "Scambio di azioni",
"swap.note": "Scambia 1:1 ai prezzi attuali prima di acquistare. Puoi ancora comprare fino a 3 azioni.",
"swap.remaining": "{count} rimaste nel turno",
"swap.unlimited": "Illimitato",
"swap.give": "Cedi (le tue azioni)",
"swap.take": "Ricevi (azioni della banca)",
"swap.count": "Azioni",
"swap.confirm": "Scambia azioni",
"swap.pay": "Paga {amount}",
"swap.receive": "Ricevi {amount}",
"swap.even": "Nessuna differenza di prezzo",
"swap.unavailable": "Scambio impossibile con questa quantità, il limite, le azioni e il denaro disponibili.",
"log.swapped": "{name} scambia {count} {from} con {count} {to} · {cash}",
loading: "Caricamento della partita…",
"status.place": "{name} deve piazzare una tessera",
"status.found": "{name} deve dare un nome a una nuova catena",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const ko: Catalog = {
"swap.title": "주식 교환",
"swap.note": "구매 전에 현재 가격으로 1:1 교환합니다. 이후에도 주식을 최대 3주 구매할 수 있습니다.",
"swap.remaining": "이번 차례에 {count}주 남음",
"swap.unlimited": "무제한",
"swap.give": "제공 (보유 주식)",
"swap.take": "수령 (은행 주식)",
"swap.count": "주식 수",
"swap.confirm": "주식 교환",
"swap.pay": "{amount} 지불",
"swap.receive": "{amount} 수령",
"swap.even": "차액 없음",
"swap.unavailable": "이 수량, 교환 한도, 주식 및 현금으로는 교환할 수 없습니다.",
"log.swapped": "{name}: {from} {count}주를 {to} {count}주로 교환 · {cash}",
loading: "게임을 불러오는 중…",
"status.place": "{name}: 타일을 놓을 차례",
"status.found": "{name}: 새 체인의 이름을 정할 차례",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const nl: Catalog = {
"swap.title": "Aandelen ruilen",
"swap.note": "Ruil vóór het kopen 1:1 tegen de huidige prijzen. Je mag daarna nog maximaal 3 aandelen kopen.",
"swap.remaining": "Nog {count} deze beurt",
"swap.unlimited": "Onbeperkt",
"swap.give": "Geef (jouw aandelen)",
"swap.take": "Ontvang (bankaandelen)",
"swap.count": "Aandelen",
"swap.confirm": "Ruil aandelen",
"swap.pay": "Betaal {amount}",
"swap.receive": "Ontvang {amount}",
"swap.even": "Geen prijsverschil",
"swap.unavailable": "Geen ruil mogelijk met dit aantal, de limiet, aandelen en contanten.",
"log.swapped": "{name} ruilt {count} {from} voor {count} {to} · {cash}",
loading: "Spel laden…",
"status.place": "{name} moet een tegel leggen",
"status.found": "{name} moet een nieuwe keten een naam geven",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const pl: Catalog = {
"swap.title": "Wymiana akcji",
"swap.note": "Przed zakupem wymieniaj 1:1 po bieżących cenach. Nadal możesz kupić do 3 akcji.",
"swap.remaining": "Pozostało w turze: {count}",
"swap.unlimited": "Bez limitu",
"swap.give": "Oddaj (twoje akcje)",
"swap.take": "Otrzymaj (akcje banku)",
"swap.count": "Akcje",
"swap.confirm": "Wymień akcje",
"swap.pay": "Zapłać {amount}",
"swap.receive": "Otrzymaj {amount}",
"swap.even": "Bez dopłaty",
"swap.unavailable": "Wymiana niemożliwa przy tej liczbie, limicie, akcjach i gotówce.",
"log.swapped": "{name} wymienia {count} {from} na {count} {to} · {cash}",
loading: "Wczytywanie gry…",
"status.place": "{name} kładzie płytkę",
"status.found": "{name} nazywa nową sieć",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const ptBR: Catalog = {
"swap.title": "Troca de ações",
"swap.note": "Troque 1:1 pelos preços atuais antes de comprar. Você ainda pode comprar até 3 ações.",
"swap.remaining": "{count} restantes neste turno",
"swap.unlimited": "Ilimitado",
"swap.give": "Dar (suas ações)",
"swap.take": "Receber (ações do banco)",
"swap.count": "Ações",
"swap.confirm": "Trocar ações",
"swap.pay": "Pagar {amount}",
"swap.receive": "Receber {amount}",
"swap.even": "Sem diferença de preço",
"swap.unavailable": "Troca indisponível com esta quantidade, limite, ações e dinheiro.",
"log.swapped": "{name} trocou {count} {from} por {count} {to} · {cash}",
loading: "Carregando o jogo…",
"status.place": "{name} deve colocar uma peça",
"status.found": "{name} deve dar nome a uma nova rede",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const ro: Catalog = {
"swap.title": "Schimb de acțiuni",
"swap.note": "Schimbă 1:1 la prețurile curente înainte de cumpărare. Poți cumpăra în continuare până la 3 acțiuni.",
"swap.remaining": "{count} rămase în această tură",
"swap.unlimited": "Nelimitat",
"swap.give": "Dai (acțiunile tale)",
"swap.take": "Primești (stocul băncii)",
"swap.count": "Acțiuni",
"swap.confirm": "Schimbă acțiuni",
"swap.pay": "Plătești {amount}",
"swap.receive": "Primești {amount}",
"swap.even": "Fără diferență de preț",
"swap.unavailable": "Schimb imposibil cu această cantitate, limită, stoc și numerar.",
"log.swapped": "{name} schimbă {count} {from} pentru {count} {to} · {cash}",
loading: "Se încarcă jocul…",
"status.place": "{name} trebuie să plaseze o piesă",
"status.found": "{name} trebuie să numească un lanț nou",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const ru: Catalog = {
"swap.title": "Обмен акций",
"swap.note": "Обменивайте 1:1 по текущим ценам перед покупкой. После этого можно купить до 3 акций.",
"swap.remaining": "Осталось за ход: {count}",
"swap.unlimited": "Без ограничений",
"swap.give": "Отдать (ваши акции)",
"swap.take": "Получить (акции банка)",
"swap.count": "Акции",
"swap.confirm": "Обменять акции",
"swap.pay": "Заплатить {amount}",
"swap.receive": "Получить {amount}",
"swap.even": "Без доплаты",
"swap.unavailable": "Обмен невозможен с этим количеством, лимитом, запасом акций и наличными.",
"log.swapped": "{name} обменивает {count} {from} на {count} {to} · {cash}",
loading: "Загрузка игры…",
"status.place": "{name}: выложить фишку",
"status.found": "{name}: назвать новую сеть",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const vi: Catalog = {
"swap.title": "Đổi cổ phiếu",
"swap.note": "Đổi 1:1 theo giá hiện tại trước khi mua. Bạn vẫn được mua tối đa 3 cổ phiếu.",
"swap.remaining": "Còn {count} trong lượt này",
"swap.unlimited": "Không giới hạn",
"swap.give": "Đưa (cổ phiếu của bạn)",
"swap.take": "Nhận (cổ phiếu ngân hàng)",
"swap.count": "Số cổ phiếu",
"swap.confirm": "Đổi cổ phiếu",
"swap.pay": "Trả {amount}",
"swap.receive": "Nhận {amount}",
"swap.even": "Không chênh lệch tiền",
"swap.unavailable": "Không thể đổi với số lượng, hạn mức, cổ phiếu và tiền mặt này.",
"log.swapped": "{name} đổi {count} {from} lấy {count} {to} · {cash}",
loading: "Đang tải ván chơi…",
"status.place": "{name} cần đặt một ô",
"status.found": "{name} cần đặt tên cho chuỗi mới",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const zhCN: Catalog = {
"swap.title": "股票交换",
"swap.note": "购买前可按现价一换一。交换后仍可购买最多 3 股。",
"swap.remaining": "本回合剩余 {count} 股",
"swap.unlimited": "不限",
"swap.give": "交出(持有股票)",
"swap.take": "取得(银行股票)",
"swap.count": "股数",
"swap.confirm": "交换股票",
"swap.pay": "支付 {amount}",
"swap.receive": "收取 {amount}",
"swap.even": "无价差",
"swap.unavailable": "此数量、交换限额、股票与现金不足以完成交换。",
"log.swapped": "{name} 以 {count} 股 {from} 交换 {count} 股 {to} · {cash}",
loading: "正在加载游戏…",
"status.place": "{name}:放置一块板块",
"status.found": "{name}:为新连锁命名",

View file

@ -1,6 +1,20 @@
import type { Catalog } from "../i18n.ts";
export const zhTW: Catalog = {
"swap.title": "股票交換",
"swap.note": "購買前可按現價一換一。交換後仍可購買最多 3 股。",
"swap.remaining": "本回合剩餘 {count} 股",
"swap.unlimited": "不限",
"swap.give": "交出(持有股票)",
"swap.take": "取得(銀行股票)",
"swap.count": "股數",
"swap.confirm": "交換股票",
"swap.pay": "支付 {amount}",
"swap.receive": "收取 {amount}",
"swap.even": "無價差",
"swap.unavailable": "此數量、交換限額、股票與現金不足以完成交換。",
"log.swapped": "{name} 以 {count} 股 {from} 交換 {count} 股 {to} · {cash}",
loading: "正在載入遊戲…",
"status.place": "{name}:放置一塊板塊",
"status.found": "{name}:為新連鎖命名",

View file

@ -57,6 +57,7 @@ export function cueForEntries(entries: readonly LogEntry[]): SoundCue | undefine
entries.some(
(entry) =>
entry.type === "bonuses" ||
entry.type === "swapped" ||
(entry.type === "bought" && entry.cost > 0) ||
(entry.type === "disposed" && (entry.sold > 0 || entry.traded > 0))
)

View file

@ -201,6 +201,23 @@ can be renamed later without touching game logic.
share, since that would reveal their cash; they get the step and may buy nothing. When
`publicHoldings` is on, it is also skipped when the player cannot afford any share.
### 9.1 Optional stock swaps (house rule)
With `stockSwap` enabled, after placement (or a skipped placement) and **all** merger
and bank-tile resolution, the active seat may exchange shares with the bank before buying.
Each exchange gives N shares of one active chain for N of a different active chain.
Pay N × (receiving price − giving price), or receive the difference if negative, at current
post-merger prices. The seat must hold the shares, the bank must have the receiving stock,
and the seat must afford any payment. No borrowing or direct player trades.
Off is the default. Limits 3, 5 or 7 count shares **given** across all exchanges that turn;
Unlimited has no share-count cap. Allowances reset for each seat's turn, including four hands.
Normal purchases of up to 3 shares remain separate and end the turn. An exchange may fund
those purchases. A swap-enabled buy step is not skipped for lack of cash or secret holdings
when at least two chains are active and the bank has stock in one. Dropped players skip swaps.
Swaps and their cash differences are public once committed. Until buying ends the turn,
swap choices can be undone through the normal private turn draft without extra history or time.
## 10. Majority Bonuses
Bonuses are paid by the bank, based on how many shares each player holds in the chain
@ -336,6 +353,7 @@ switches on one engine, not as separate code paths. Defaults reproduce the stand
| `teamPlay` | true / false | false | Only applies with exactly 4 players. Seats 1 and 3 form one team, seats 2 and 4 the other. All rules are unchanged; at final scoring each team's cash is added together and the team with more wins. **[DECISION]** With `publicHoldings` off, teammates still cannot see each other's holdings. |
| `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. |
| `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

@ -103,6 +103,98 @@ try {
assert.equal(report.diagnostics.compatible, true);
assert.equal(report.diagnostics.recommended.percent, 100);
// Optional swaps are private drafts, with one shared allowance and separate purchases.
for (const width of [1280, 390, 320]) {
await page.setViewportSize({ width, height: 900 });
await open("players=3&hotseat=0&view=0&theme=dark&stockSwap=3");
await page.evaluate((state) => {
const { parseTile, allTiles, CHAIN_IDS } = window.acquireDev.rules;
state.options.stockSwap = 3;
state.board.fill(null);
for (const label of ["1A", "2A", "3A"]) {
state.board[parseTile(label)] = "tower";
}
for (const label of ["1E", "2E", "3E", "4E", "5E"]) {
state.board[parseTile(label)] = "continental";
}
state.seats.forEach((seat, index) => {
seat.hand = [parseTile(`${9 + index}I`)];
for (const chain of CHAIN_IDS) {
seat.shares[chain] = 0;
}
});
state.seats[0].shares.tower = 10;
state.seats[0].shares.continental = 5;
for (const chain of CHAIN_IDS) {
state.bank[chain] = 25 - state.seats.reduce((sum, seat) => sum + seat.shares[chain], 0);
}
const used = new Set(state.seats.flatMap((seat) => seat.hand));
state.pool = allTiles().filter((tile) => state.board[tile] === null && !used.has(tile));
state.phase = "buy";
state.placedThisTurn = true;
window.acquireDev.load(state);
}, preparedPosition("founding"));
await page.locator(".stock-swap summary").click();
await page.getByRole("spinbutton", { name: "Shares", exact: true }).fill("2");
assert.match(await page.locator(".exchange").innerText(), /Pay \$800/);
for (const theme of ["dark", "light"]) {
await page.evaluate((theme) => window.acquireDev.emitter.emit("theme", { dark: theme === "dark" }), theme);
for (const locale of locales) {
await preferences({ locale });
assert.ok(
await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1),
`stock swap ${locale} ${theme} ${width}px`
);
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 });
}
const original = await page.evaluate(() => JSON.stringify(window.acquireDev.state));
for (let revision = 0; revision < 3; revision++) {
await page.getByRole("spinbutton", { name: "Shares", exact: true }).fill("2");
await page.getByRole("button", { name: "Swap shares", exact: true }).click();
await page.waitForFunction(() => document.querySelector(".stock-swap summary")?.textContent.includes("1 left"));
assert.equal(
await page.evaluate(() => JSON.stringify(window.acquireDev.state)),
original,
"swap remains a private draft"
);
await page.getByRole("button", { name: "Undo", exact: true }).click();
await page.waitForFunction(() => document.querySelector(".stock-swap summary")?.textContent.includes("3 left"));
}
await page.getByRole("spinbutton", { name: "Shares", exact: true }).fill("2");
await page.getByRole("button", { name: "Swap shares", exact: true }).click();
await page.waitForFunction(() => document.querySelector(".stock-swap summary")?.textContent.includes("1 left"));
await page.getByLabel("Give (your stock)", { exact: true }).selectOption("continental");
await settle();
assert.match(await page.locator(".exchange").innerText(), /Receive \$400/);
await page.getByRole("button", { name: "Swap shares", exact: true }).click();
await page.waitForFunction(() => document.querySelector(".stock-swap summary")?.textContent.includes("0 left"));
for (let i = 0; i < 3; i++) {
await page.getByRole("button", { name: "Buy one more Tower", exact: true }).click();
}
await page.getByRole("button", { name: "Buy for $900 and end turn", exact: true }).click();
await page.waitForFunction(() => window.acquireDev.state.turn === 2);
assert.deepEqual(
await page.evaluate(() => ({
cash: window.acquireDev.state.seats[0].cash,
swaps: window.acquireDev.state.log.filter((e) => e.type === "swapped").length,
increments: window.acquireDev.engine.timeIncrements(window.acquireDev.state),
})),
{ cash: 4700, swaps: 2, increments: [1, 0, 0] }
);
}
await open("players=3&hotseat=0&view=0");
await page.evaluate((state) => {
state.phase = "buy";
window.acquireDev.load(state);
}, preparedPosition("scoring"));
assert.equal(await page.locator(".stock-swap").count(), 0, "off never adds UI to existing games");
report.scenarios.push(
"stock swaps in 17 languages and both themes at 1280/390/320px, pay/receive previews, shared allowance, undo without saved history and a separate three-share purchase"
);
for (const width of [1280, 390, 320]) {
await page.setViewportSize({ width, height: 900 });
await open("players=3&hotseat=0&view=0&theme=dark");