From c60de9595cbb581fbb2d3966a6bb41eb7dda815e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 02:21:25 +0000 Subject: [PATCH] Add Golomb's Game (experimental) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pentomino placement for 2-4 players: the last player able to place a pentomino wins (Misère: the first player with no legal move wins). - Boards 7x7, 8x7, 8x8, 8x8 with the center blocked, and 10x6; optional random blockers (one per square beyond 60, at least one). - Shared pool, random distribution, or choose up; Concealed hands (stripped state, unseen-pieces list, no exploration). - Capture (community variant by Arthur J. O'Dwyer): 3+ shared edges captures; captured pieces can be removed before placing and return to the pool after the move; a fifth occurrence of a position with the same player to move is a draw. - Simple pie (2 players only, silently dropped otherwise): after the first choice or placement, the second player may pass to swap hands. - Input: click the squares a pentomino covers; once one placement fits it is shown placed (with captures) and another empty square confirms. Dots mark coverable squares; small squares mark clicked ones. Moves are stored as removals then all five squares, each sorted. - Pieces and blockers are outlined; hands and pool show the shapes, with pieces being removed crossed out in the remover's colour. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014dzXa1d8Ddr28ZVsDKnLZm --- CHANGELOG.md | 2 +- locale-src/de/apgames.json | 4 + .../en/apresults/apresults-path-map.json | 60 + locale-src/es-US/apgames.json | 4 + locale-src/fr/apgames.json | 4 + locale-src/it/apgames.json | 4 + locales/de/apgames.json | 1 + locales/en/apgames.json | 81 ++ locales/en/apresults.json | 20 + locales/es-US/apgames.json | 1 + locales/fr/apgames.json | 1 + locales/it/apgames.json | 1 + src/games/golomb.ts | 1183 +++++++++++++++++ test/games/golomb.test.ts | 732 ++++++++++ 14 files changed, 2097 insertions(+), 1 deletion(-) create mode 100644 src/games/golomb.ts create mode 100644 test/games/golomb.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 88ceb376..90b3e3ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ Since the `1.0.0-beta` release, the version in `package.json` has stayed at `1.0 ### Added -- **New games (dev / experimental only):** Agents of MARS, Bagh Chal, DVONN, GIPF, Ice Palace, LYNGK, Polypods, Skisma, Squares, TZAAR, YINSH, ZERTZ. +- **New games (dev / experimental only):** Agents of MARS, Bagh Chal, DVONN, GIPF, Golomb's Game, Ice Palace, LYNGK, Polypods, Skisma, Squares, TZAAR, YINSH, ZERTZ. ## [1.0.0-ci] - 2026-11-25 diff --git a/locale-src/de/apgames.json b/locale-src/de/apgames.json index 18be8525..154a7df2 100644 --- a/locale-src/de/apgames.json +++ b/locale-src/de/apgames.json @@ -4047,6 +4047,10 @@ "src": "Go", "out": "Go" }, + "names.golomb": { + "src": "Golomb's Game", + "out": "Golomb's Game" + }, "names.gomoku": { "src": "Gomoku", "out": "Gomoku" diff --git a/locale-src/en/apresults/apresults-path-map.json b/locale-src/en/apresults/apresults-path-map.json index fd6be226..dffa1d4d 100644 --- a/locale-src/en/apresults/apresults-path-map.json +++ b/locale-src/en/apresults/apresults-path-map.json @@ -3832,6 +3832,66 @@ "newFullKey": "apresults:go.EOG.repetition", "english": "The game has ended because the same position was repeated (super-ko)." }, + { + "oldPath": "CAPTURE.golomb", + "oldFullKey": "apresults:CAPTURE.golomb", + "uid": "golomb", + "resultType": "CAPTURE", + "newLeaf": "default", + "newPath": "golomb.CAPTURE.default", + "newFullKey": "apresults:golomb.CAPTURE.default", + "english": "{{player}} captured the {{what}} pentomino." + }, + { + "oldPath": "EOG.golomb_repetition", + "oldFullKey": "apresults:EOG.golomb_repetition", + "uid": "golomb", + "resultType": "EOG", + "newLeaf": "repetition", + "newPath": "golomb.EOG.repetition", + "newFullKey": "apresults:golomb.EOG.repetition", + "english": "The game has ended in a draw because the same position occurred five times with the same player to move." + }, + { + "oldPath": "PLACE.golomb", + "oldFullKey": "apresults:PLACE.golomb", + "uid": "golomb", + "resultType": "PLACE", + "newLeaf": "default", + "newPath": "golomb.PLACE.default", + "newFullKey": "apresults:golomb.PLACE.default", + "english": "{{player}} placed the {{what}} pentomino on {{where}}." + }, + { + "oldPath": "REMOVE.golomb", + "oldFullKey": "apresults:REMOVE.golomb", + "uid": "golomb", + "resultType": "REMOVE", + "newLeaf": "default", + "newPath": "golomb.REMOVE.default", + "newFullKey": "apresults:golomb.REMOVE.default", + "english": "{{player}} removed the {{what}} pentomino from the board." + }, + { + "oldPath": "SELECT.golomb", + "oldFullKey": "apresults:SELECT.golomb", + "uid": "golomb", + "resultType": "SELECT", + "newLeaf": "default", + "newPath": "golomb.SELECT.default", + "newFullKey": "apresults:golomb.SELECT.default", + "english": "{{player}} chose the {{what}} pentomino." + }, + { + "oldPath": "SWAP.golomb", + "oldFullKey": "apresults:SWAP.golomb", + "uid": "golomb", + "resultType": "SWAP", + "newLeaf": "default", + "newPath": "golomb.SWAP.default", + "newFullKey": "apresults:golomb.SWAP.default", + "english": "{{player}} passed and swapped hands." + }, { "oldPath": "EOG.gonnect_cascading_subboard", "oldFullKey": "apresults:EOG.gonnect_cascading_subboard", diff --git a/locale-src/es-US/apgames.json b/locale-src/es-US/apgames.json index 46976d5d..07b7f8b0 100644 --- a/locale-src/es-US/apgames.json +++ b/locale-src/es-US/apgames.json @@ -4047,6 +4047,10 @@ "src": "Go", "out": "Go" }, + "names.golomb": { + "src": "Golomb's Game", + "out": "Golomb's Game" + }, "names.gomoku": { "src": "Gomoku", "out": "Gomoku" diff --git a/locale-src/fr/apgames.json b/locale-src/fr/apgames.json index 6fba0a3f..e7654ca9 100644 --- a/locale-src/fr/apgames.json +++ b/locale-src/fr/apgames.json @@ -4047,6 +4047,10 @@ "src": "Go", "out": "Go" }, + "names.golomb": { + "src": "Golomb's Game", + "out": "Golomb's Game" + }, "names.gomoku": { "src": "Gomoku", "out": "Gomoku" diff --git a/locale-src/it/apgames.json b/locale-src/it/apgames.json index 514ab41f..4ceae58c 100644 --- a/locale-src/it/apgames.json +++ b/locale-src/it/apgames.json @@ -4047,6 +4047,10 @@ "src": "Go", "out": "Go" }, + "names.golomb": { + "src": "Golomb's Game", + "out": "Golomb's Game" + }, "names.gomoku": { "src": "Gomoku", "out": "Gomoku" diff --git a/locales/de/apgames.json b/locales/de/apgames.json index b6d2c92e..9d559561 100644 --- a/locales/de/apgames.json +++ b/locales/de/apgames.json @@ -4810,6 +4810,7 @@ "gipf": "GIPF", "gliss": "Gliss", "go": "Go", + "golomb": "Golomb's Game", "gomoku": "Gomoku", "gonnect": "Gonnect", "gorogo": "GoRoGo", diff --git a/locales/en/apgames.json b/locales/en/apgames.json index 8f503234..ad248800 100644 --- a/locales/en/apgames.json +++ b/locales/en/apgames.json @@ -2163,6 +2163,30 @@ "KO": "Ko rule: you may not immediately recapture your opponent's single stone if they just used it to capture one of yours.", "SELF_CAPTURE": "You may not place your stones in self-capture." }, + "golomb": { + "INITIAL_INSTRUCTIONS": "Click the empty squares your pentomino will cover. Once only one placement fits, click any other empty square to confirm, or click another piece to start over.", + "INITIAL_INSTRUCTIONS_CAPTURE": "Click the empty squares your pentomino will cover. Before that, you may click pieces you have captured to remove them from the board; they return to the pool after your move. Once only one placement fits, click any other empty square to confirm.", + "INITIAL_INSTRUCTIONS_CHOOSE": "Click a pentomino in the pool to add it to your hand.", + "INITIAL_INSTRUCTIONS_SWAP": "Place a pentomino to keep your hand, or press the button to pass and swap hands with your opponent.", + "INITIAL_INSTRUCTIONS_SWAP_CHOOSE": "Choose a pentomino to keep your hand, or press the button to pass and swap hands with your opponent.", + "PARTIAL": "Keep clicking squares the pentomino will cover until only one placement fits.", + "UNIQUE": "Only one placement fits. Click any other empty square to confirm, or click another piece to start over.", + "BAD_TOKEN": "\"{{token}}\" is not a square, a removal, or a pentomino.", + "OFF_BOARD": "{{cell}} is not a square on this board.", + "OCCUPIED": "{{cell}} is already occupied.", + "DUPLICATE": "{{cell}} was selected more than once.", + "NO_PLACEMENT": "None of your available pentominoes can cover all of the selected squares.", + "NO_REMOVAL": "Pieces can only be removed in the Capture variant.", + "NOT_CAPTURED": "You can only remove pieces you have captured, and the piece at {{cell}} is not one of them.", + "DUPLICATE_REMOVAL": "The piece at {{cell}} is already being removed.", + "MUST_CHOOSE": "You must choose a pentomino from the pool before play begins.", + "NOT_CHOOSING": "Pentominoes can only be chosen before play begins.", + "UNAVAILABLE": "That pentomino is not in the pool.", + "NO_SWAP": "You can only pass to swap hands right after your opponent's first move.", + "LABEL_HAND": "{{player}}'s hand", + "LABEL_POOL": "Pool", + "LABEL_UNSEEN": "Unseen pieces" + }, "gonnect": { "INITIAL_INSTRUCTIONS": "Select an intersection to place a piece.", "INVALID_PASS": "You cannot pass currently.", @@ -4498,6 +4522,7 @@ "gipf": "Players push pieces from dots onto a hex line board, forming rows of four to capture. Win by emptying the opponent's reserve or removing their last GIPF piece.", "gliss": "Establish bases and deploy gliders to capture opposing gliders and control towers. Eliminate all opposing bases or establish a critical number of control towers to win.", "go": "The traditional game of Go", + "golomb": "Players take turns placing pentominoes on the board. The last player able to place one wins.", "gomoku": "A classic game where you try to get exactly five stones in a row. Six in a row does not count as a win. The game ends in a draw if no player gets a five-in-a-row or on two consecutive passes.", "gonnect": "Gonnect is a connection game where players try to connect any two opposite sides. All rules of Go apply except that players may not pass.", "gorogo": "A Go variant played on a small board where the goal is to capture more pieces than your opponent, rather than to claim territory.", @@ -4810,6 +4835,7 @@ "gipf": "GIPF", "gliss": "Gliss", "go": "Go", + "golomb": "Golomb's Game", "gomoku": "Gomoku", "gonnect": "Gonnect", "gorogo": "GoRoGo", @@ -5032,6 +5058,7 @@ "forms": "Forms was designed by Steven Meyers in 2007. After each move, all pieces outside the group that contains the last-moved piece are captured. The last player to move loses (so Forms is a misère game). The first version allowed a piece to capture any opponent's piece. Later, in 2011, Meyers developed a second version, **Advanced Forms**, where you could only capture orthogonally adjacent pieces, but a piece could also move to an empty cell if both were connected by a sequence of orthogonal steps over empty cells. The setup also changed to a checkered pattern. This second version is the default variant here at AP. More information can be found at [WAG](https://jpneto.github.io/world_abstract_games/forms.htm).", "frogger": "As in other Decktet games at Abstract Play, the deck is displayed at the bottom of the board and includes both cards in the deck and unknown cards in other players' hands. After the first hand, all cards are drawn from the open draw pool, so hands gradually become open. The discards pile is also displayed.\n\nForced passes are no longer used when a player refills the draw pool (and submits) in the middle of his turn. That player's second partial turn is handled automatically by the server. There's also a draw pool variant that avoids the double-ply, if desired.\n\nThe Crocodiles variant is by Jorge Arroyo, the translator of the English rules. The Advanced rules and other minor variants are by P. D. Magnus; they appear in The Decktet Book, where the game is called Xing.", "garden": "To make it very clear what happened on a previous turn, each move is displayed over four separate boards. The first board shows the game after the piece was first placed. The second board shows the state after adjacent pieces were flipped. The third board shows any harvests. The fourth board is the final game state and is where you make your moves.\n\nIn our implementation, black is always the \"tome\" or tie-breaker colour. The last player to harvest black will have a `0.1` after their score.", + "golomb": "To place a pentomino, click the empty squares it will cover. Once only one legal placement covers every selected square, the move is ready and the piece is shown as placed, along with anything it would capture: click any other empty square to confirm it, or click another piece to start over. In move notation, a placement lists all 5 covered squares, and a capture-variant removal is an `x` followed by the removed piece's first square, as in `xa1`. With 3 or 4 players, the game ends as soon as the player to move has no legal move: the last player who moved wins, or, in Misère, the player who cannot move wins. In Capture, pieces removed during the move being entered are crossed out in the pool, since they cannot be placed until the next turn, and a position that occurs for the fifth time with the same player to move ends the game in a draw. Simple pie only applies to 2-player games and is ignored in larger games.", "gonnect": "In the base game, passing is not allowed. The **Cascading Connection Goals** variant allows passing and ends after two consecutive passes. An outright connection wins immediately, otherwise find the largest centered subboard where exactly one player connects opposite sides: that player wins.", "guerrilla": "Either player wins by removing all of the opponent's pieces. The security player also wins if they survive long enough that the insurgents run out of stones to place.\n\nBy default, a match consists of two games with roles reversed. Each player plays one game as insurgents and one as security. When both players win as insurgents, the match goes to whoever used fewer stones (`66 − remaining` at the end of that game; lower score wins). Equal insurgent scores are the only draw in that case. A security win in a game scores 67. If one player sweeps both games (wins as insurgents in one and security in the other), they win the match outright. If both players only win as security, the match is drawn.", "gyges": "The goal squares are adjacent to all the cells in the back row. The renderer cannot currently handle \"floating\" cells.", @@ -7244,6 +7271,60 @@ "name": "Positional Superko" } }, + "golomb": { + "size-7x7": { + "name": "7x7", + "description": "Recommended for the Capture variant." + }, + "size-8x7": { + "name": "8x7" + }, + "#board": { + "name": "8x8" + }, + "center-blocked": { + "name": "8x8 (center blocked)", + "description": "An 8x8 board missing its 4 center squares." + }, + "size-10x6": { + "name": "10x6" + }, + "#blockers": { + "name": "No blockers" + }, + "random-blockers": { + "name": "Random blockers", + "description": "Before the game starts, blockers are placed on random squares: one for each square beyond 60, and at least one." + }, + "#distribution": { + "name": "Shared pool", + "description": "Players place pentominoes from a shared pool." + }, + "random-hands": { + "name": "Random distribution", + "description": "The 12 pentominoes are dealt evenly among the players before the game starts." + }, + "choose-up": { + "name": "Choose up", + "description": "Before the game starts, players take turns choosing their pentominoes." + }, + "concealed": { + "name": "Concealed hands", + "description": "Players can only see their own pentominoes. In 2-player games, 2 pentominoes are set aside unseen and not used." + }, + "capture": { + "name": "Capture", + "description": "A placement that shares 3 or more edges with a previously placed piece captures that piece, which takes the capturing player's colour. Captured pieces can be recaptured. Before placing, you may remove any pieces you have captured; they return to the pool after your move. A position that occurs for the fifth time with the same player to move is a draw." + }, + "misere": { + "name": "Misère", + "description": "The last player to move loses: the first player with no legal move wins." + }, + "simple-pie": { + "name": "Simple pie", + "description": "2-player games only. After the first pentomino is chosen or placed, the second player may pass to swap hands instead of moving." + } + }, "gomoku": { "#board": { "name": "Default 15x15 board" diff --git a/locales/en/apresults.json b/locales/en/apresults.json index 81f60a03..ea551d6d 100644 --- a/locales/en/apresults.json +++ b/locales/en/apresults.json @@ -900,6 +900,26 @@ "repetition": "The game has ended because the same position was repeated (super-ko)." } }, + "golomb": { + "SELECT": { + "default": "{{player}} chose the {{what}} pentomino." + }, + "PLACE": { + "default": "{{player}} placed the {{what}} pentomino on {{where}}." + }, + "REMOVE": { + "default": "{{player}} removed the {{what}} pentomino from the board." + }, + "CAPTURE": { + "default": "{{player}} captured the {{what}} pentomino." + }, + "SWAP": { + "default": "{{player}} passed and swapped hands." + }, + "EOG": { + "repetition": "The game has ended in a draw because the same position occurred five times with the same player to move." + } + }, "gonnect": { "EOG": { "cascading_subboard": "{{player}} won on the {{size}}x{{size}} subboard.", diff --git a/locales/es-US/apgames.json b/locales/es-US/apgames.json index 9b6d4d54..0c215325 100644 --- a/locales/es-US/apgames.json +++ b/locales/es-US/apgames.json @@ -4810,6 +4810,7 @@ "gipf": "GIPF", "gliss": "Gliss", "go": "Go", + "golomb": "Golomb's Game", "gomoku": "Gomoku", "gonnect": "Gonnect", "gorogo": "GoRoGo", diff --git a/locales/fr/apgames.json b/locales/fr/apgames.json index cff51a54..b4230fb9 100644 --- a/locales/fr/apgames.json +++ b/locales/fr/apgames.json @@ -4810,6 +4810,7 @@ "gipf": "GIPF", "gliss": "Gliss", "go": "Go", + "golomb": "Golomb's Game", "gomoku": "Gomoku", "gonnect": "Gonnect", "gorogo": "GoRoGo", diff --git a/locales/it/apgames.json b/locales/it/apgames.json index b4104b3f..2b9de164 100644 --- a/locales/it/apgames.json +++ b/locales/it/apgames.json @@ -4810,6 +4810,7 @@ "gipf": "GIPF", "gliss": "Gliss", "go": "Go", + "golomb": "Golomb's Game", "gomoku": "Gomoku", "gonnect": "Gonnect", "gorogo": "GoRoGo", diff --git a/src/games/golomb.ts b/src/games/golomb.ts new file mode 100644 index 00000000..ae0a574c --- /dev/null +++ b/src/games/golomb.ts @@ -0,0 +1,1183 @@ +import { GameBase, IAPGameState, IClickResult, ICustomButton, IIndividualState, IRenderOpts, IValidationResult, type ChatLogCollectContext, type ChatLogLine, type FlagContext, type GameFlag } from "./_base.js"; +import type { APGamesInformation } from "../schemas/gameinfo.js"; +import type { AnnotationBasic, APRenderRep, AreaPieces, MarkerFenceData, MarkerFence, MarkerFlood, RowCol } from "@abstractplay/renderer/build/schemas/schema"; +import type { APMoveResult } from "../schemas/moveresults.js"; +import { reviver, shuffle, UserFacingError } from "../common/index.js"; +import i18next from "i18next"; + +export const gameApgamesEn = { + validation: { + INITIAL_INSTRUCTIONS: "Click the empty squares your pentomino will cover. Once only one placement fits, click any other empty square to confirm, or click another piece to start over.", + INITIAL_INSTRUCTIONS_CAPTURE: "Click the empty squares your pentomino will cover. Before that, you may click pieces you have captured to remove them from the board; they return to the pool after your move. Once only one placement fits, click any other empty square to confirm.", + INITIAL_INSTRUCTIONS_CHOOSE: "Click a pentomino in the pool to add it to your hand.", + INITIAL_INSTRUCTIONS_SWAP: "Place a pentomino to keep your hand, or press the button to pass and swap hands with your opponent.", + INITIAL_INSTRUCTIONS_SWAP_CHOOSE: "Choose a pentomino to keep your hand, or press the button to pass and swap hands with your opponent.", + PARTIAL: "Keep clicking squares the pentomino will cover until only one placement fits.", + UNIQUE: "Only one placement fits. Click any other empty square to confirm, or click another piece to start over.", + BAD_TOKEN: "\"{{token}}\" is not a square, a removal, or a pentomino.", + OFF_BOARD: "{{cell}} is not a square on this board.", + OCCUPIED: "{{cell}} is already occupied.", + DUPLICATE: "{{cell}} was selected more than once.", + NO_PLACEMENT: "None of your available pentominoes can cover all of the selected squares.", + NO_REMOVAL: "Pieces can only be removed in the Capture variant.", + NOT_CAPTURED: "You can only remove pieces you have captured, and the piece at {{cell}} is not one of them.", + DUPLICATE_REMOVAL: "The piece at {{cell}} is already being removed.", + MUST_CHOOSE: "You must choose a pentomino from the pool before play begins.", + NOT_CHOOSING: "Pentominoes can only be chosen before play begins.", + UNAVAILABLE: "That pentomino is not in the pool.", + NO_SWAP: "You can only pass to swap hands right after your opponent's first move.", + LABEL_HAND: "{{player}}'s hand", + LABEL_POOL: "Pool", + LABEL_UNSEEN: "Unseen pieces", + }, + variants: { + "size-7x7": { + name: "7x7", + description: "Recommended for the Capture variant.", + }, + "size-8x7": { + name: "8x7", + }, + "#board": { + name: "8x8", + }, + "center-blocked": { + name: "8x8 (center blocked)", + description: "An 8x8 board missing its 4 center squares.", + }, + "size-10x6": { + name: "10x6", + }, + "#blockers": { + name: "No blockers", + }, + "random-blockers": { + name: "Random blockers", + description: "Before the game starts, blockers are placed on random squares: one for each square beyond 60, and at least one.", + }, + "#distribution": { + name: "Shared pool", + description: "Players place pentominoes from a shared pool.", + }, + "random-hands": { + name: "Random distribution", + description: "The 12 pentominoes are dealt evenly among the players before the game starts.", + }, + "choose-up": { + name: "Choose up", + description: "Before the game starts, players take turns choosing their pentominoes.", + }, + concealed: { + name: "Concealed hands", + description: "Players can only see their own pentominoes. In 2-player games, 2 pentominoes are set aside unseen and not used.", + }, + capture: { + name: "Capture", + description: "A placement that shares 3 or more edges with a previously placed piece captures that piece, which takes the capturing player's colour. Captured pieces can be recaptured. Before placing, you may remove any pieces you have captured; they return to the pool after your move. A position that occurs for the fifth time with the same player to move is a draw.", + }, + misere: { + name: "Misère", + description: "The last player to move loses: the first player with no legal move wins.", + }, + "simple-pie": { + name: "Simple pie", + description: "2-player games only. After the first pentomino is chosen or placed, the second player may pass to swap hands instead of moving.", + }, + }, +}; + +export const gameApresultsEn = { + SELECT: { + default: "{{player}} chose the {{what}} pentomino.", + }, + PLACE: { + default: "{{player}} placed the {{what}} pentomino on {{where}}.", + }, + REMOVE: { + default: "{{player}} removed the {{what}} pentomino from the board.", + }, + CAPTURE: { + default: "{{player}} captured the {{what}} pentomino.", + }, + SWAP: { + default: "{{player}} passed and swapped hands.", + }, + EOG: { + repetition: "The game has ended in a draw because the same position occurred five times with the same player to move.", + }, +}; + +export type playerid = 1 | 2 | 3 | 4; +export type Pentomino = "F" | "I" | "L" | "N" | "P" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"; +export const PENTOMINOES: readonly Pentomino[] = ["F", "I", "L", "N", "P", "T", "U", "V", "W", "X", "Y", "Z"]; + +/** A pentomino on the board. `owner` is 0 until the piece is captured (Capture variant). */ +export interface IPlacedPiece { + piece: Pentomino; + /** sorted lexicographically */ + cells: string[]; + owner: number; +} + +interface IMoveState extends IIndividualState { + currplayer: playerid; + placed: IPlacedPiece[]; + blockers: string[]; + pool: Pentomino[]; + hands: Pentomino[][]; + kitty: Pentomino[]; + lastmove?: string; +} + +export interface IGolombState extends IAPGameState { + winner: playerid[]; + stack: Array; +} + +interface IPlacement { + piece: Pentomino; + /** sorted lexicographically */ + cells: string[]; +} + +interface IGeometry { + width: number; + height: number; + cells: string[]; + cellSet: Set; + placements: IPlacement[]; +} + +interface IParsed { + removals: string[]; + cells: string[]; +} + +interface IAnalysis { + result: IValidationResult; + parsed?: IParsed; + removed?: number[]; + compatible?: IPlacement[]; +} + +// The display orientation of each pentomino, top row first. +const SHAPES: Record = { + F: [[0, 1, 1], [1, 1, 0], [0, 1, 0]], + I: [[1, 1, 1, 1, 1]], + L: [[1, 1, 1, 1], [1, 0, 0, 0]], + N: [[1, 1, 0, 0], [0, 1, 1, 1]], + P: [[1, 1, 1], [1, 1, 0]], + T: [[1, 1, 1], [0, 1, 0], [0, 1, 0]], + U: [[1, 0, 1], [1, 1, 1]], + V: [[1, 0, 0], [1, 0, 0], [1, 1, 1]], + W: [[1, 0, 0], [1, 1, 0], [0, 1, 1]], + X: [[0, 1, 0], [1, 1, 1], [0, 1, 0]], + Y: [[0, 1, 0, 0], [1, 1, 1, 1]], + Z: [[1, 1, 0], [0, 1, 0], [0, 1, 1]], +}; + +const BOARDS: Record = { + "size-7x7": { width: 7, height: 7, holes: [] }, + "size-8x7": { width: 8, height: 7, holes: [] }, + "#board": { width: 8, height: 8, holes: [] }, + "center-blocked": { width: 8, height: 8, holes: ["d4", "d5", "e4", "e5"] }, + "size-10x6": { width: 10, height: 6, holes: [] }, +}; + +type Offset = [number, number]; + +const normaliseOffsets = (offsets: Offset[]): Offset[] => { + const minX = Math.min(...offsets.map(([x]) => x)); + const minY = Math.min(...offsets.map(([, y]) => y)); + return offsets.map(([x, y]) => [x - minX, y - minY] as Offset).sort((a, b) => a[1] - b[1] || a[0] - b[0]); +}; + +const offsetsKey = (offsets: Offset[]): string => offsets.map(([x, y]) => `${x},${y}`).join(";"); + +/** Every distinct rotation and reflection of each pentomino. */ +const ORIENTATIONS: Map = new Map(PENTOMINOES.map(pc => { + const base: Offset[] = []; + SHAPES[pc].forEach((row, y) => row.forEach((v, x) => { if (v === 1) { base.push([x, y]); } })); + const transforms: ((o: Offset) => Offset)[] = [ + ([x, y]) => [x, y], ([x, y]) => [-y, x], ([x, y]) => [-x, -y], ([x, y]) => [y, -x], + ([x, y]) => [-x, y], ([x, y]) => [y, x], ([x, y]) => [x, -y], ([x, y]) => [-y, -x], + ]; + const seen = new Map(); + for (const t of transforms) { + const o = normaliseOffsets(base.map(t)); + seen.set(offsetsKey(o), o); + } + return [pc, [...seen.values()]]; +})); + +const geometryCache = new Map(); + +export class GolombGame extends GameBase { + public static readonly gameinfo: APGamesInformation = { + name: "Golomb's Game", + uid: "golomb", + playercounts: [2, 3, 4], + version: "20261125", + dateAdded: "2026-11-25", + description: "Players take turns placing pentominoes on the board. The last player able to place one wins.", + notes: "To place a pentomino, click the empty squares it will cover. Once only one legal placement covers every selected square, the move is ready and the piece is shown as placed, along with anything it would capture: click any other empty square to confirm it, or click another piece to start over. In move notation, a placement lists all 5 covered squares, and a capture-variant removal is an `x` followed by the removed piece's first square, as in `xa1`. With 3 or 4 players, the game ends as soon as the player to move has no legal move: the last player who moved wins, or, in Misère, the player who cannot move wins. In Capture, pieces removed during the move being entered are crossed out in the pool, since they cannot be placed until the next turn, and a position that occurs for the fifth time with the same player to move ends the game in a draw. Simple pie only applies to 2-player games and is ignored in larger games.", + urls: [ + "https://nrich.maths.org/content/01/10/game/game.html", + "https://club.cc.cmu.edu/~ajo/free-software/pento/pento.html", + ], + people: [ + { + type: "designer", + name: "Solomon W. Golomb", + }, + { + type: "coder", + name: "Samraku", + urls: [], + apid: "6ea91933-1262-41a5-b5f3-a6af70692296", + }, + ], + variants: [ + { uid: "size-7x7", group: "board" }, + { uid: "size-8x7", group: "board" }, + { uid: "#board" }, + { uid: "center-blocked", group: "board" }, + { uid: "size-10x6", group: "board" }, + { uid: "#blockers" }, + { uid: "random-blockers", group: "blockers" }, + { uid: "#distribution" }, + { uid: "random-hands", group: "distribution" }, + { uid: "choose-up", group: "distribution" }, + { + uid: "concealed", + enabledWhen: { distribution: ["random-hands"] }, + conflictsWith: ["simple-pie"], + }, + { + uid: "capture", + enabledWhen: { distribution: ["#distribution"] }, + conflictsWith: ["misere"], + fans: true, + people: [ + { + type: "designer", + name: "Arthur J. O'Dwyer", + urls: ["https://club.cc.cmu.edu/~ajo/free-software/pento/pento.html"], + }, + ], + }, + { uid: "misere", conflictsWith: ["capture"] }, + { + uid: "simple-pie", + enabledWhen: { distribution: ["random-hands", "choose-up"] }, + conflictsWith: ["concealed"], + }, + ], + categories: ["goal>immobilize", "mechanic>place", "mechanic>block", "mechanic>share", "board>shape>rect", "board>connect>rect", "components>poly", "other>2+players"], + flags: ["experimental", "custom-buttons", "random-start"], + }; + + public static resolveFlags(context: FlagContext = {}): readonly GameFlag[] { + const flags: GameFlag[] = [...(this.gameinfo.flags ?? [])]; + // the client only holds its own hand, so it cannot look ahead + if (context.variants?.includes("concealed")) { + flags.push("no-explore"); + } + return flags; + } + + private static geometry(variants: string[]): IGeometry { + const uid = Object.keys(BOARDS).find(k => variants.includes(k)) ?? "#board"; + const cached = geometryCache.get(uid); + if (cached !== undefined) { + return cached; + } + const { width, height, holes } = BOARDS[uid]; + const cells: string[] = []; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const cell = GameBase.coords2algebraic(x, y, height); + if (!holes.includes(cell)) { + cells.push(cell); + } + } + } + const cellSet = new Set(cells); + const placements: IPlacement[] = []; + for (const pc of PENTOMINOES) { + for (const offsets of ORIENTATIONS.get(pc)!) { + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const covered = offsets.map(([dx, dy]) => (x + dx < width && y + dy < height) ? GameBase.coords2algebraic(x + dx, y + dy, height) : ""); + if (covered.every(c => cellSet.has(c))) { + placements.push({ piece: pc, cells: covered.sort() }); + } + } + } + } + } + const geo: IGeometry = { width, height, cells, cellSet, placements }; + geometryCache.set(uid, geo); + return geo; + } + + public numplayers!: number; + public currplayer!: playerid; + public placed!: IPlacedPiece[]; + public blockers!: string[]; + public pool!: Pentomino[]; + public hands!: Pentomino[][]; + public kitty!: Pentomino[]; + public gameover = false; + public winner: playerid[] = []; + public variants: string[] = []; + public stack!: Array; + public results: Array = []; + private geo!: IGeometry; + // while a move is being entered: empty squares some fitting placement could cover, and the squares clicked so far + private candidates: string[] = []; + private selected: string[] = []; + private previewing = false; + // pieces removed by the move being entered: back in the pool, but not placeable yet + private removing: Pentomino[] = []; + + constructor(state?: number | IGolombState | string, variants?: string[]) { + super(); + if (state === undefined || typeof state === "number") { + this.numplayers = state ?? 2; + if (variants !== undefined && variants.length > 0) { + this.variants = this.applyVariantConstraints(variants); + } + // Simple pie is a 2-player rule: larger games start without it. + if (this.numplayers !== 2) { + this.variants = this.variants.filter(v => v !== "simple-pie"); + } + const geo = GolombGame.geometry(this.variants); + let blockers: string[] = []; + if (this.variants.includes("random-blockers")) { + const count = Math.max(1, geo.cells.length - 60); + blockers = shuffle([...geo.cells]).slice(0, count).sort(); + } + const hands: Pentomino[][] = []; + for (let p = 0; p < this.numplayers; p++) { + hands.push([]); + } + let pool: Pentomino[] = []; + let kitty: Pentomino[] = []; + if (this.variants.includes("random-hands")) { + const deck = shuffle([...PENTOMINOES]); + if (this.variants.includes("concealed") && this.numplayers === 2) { + kitty = deck.splice(0, 2).sort(); + } + const each = deck.length / this.numplayers; + for (let p = 0; p < this.numplayers; p++) { + hands[p] = deck.slice(p * each, (p + 1) * each).sort(); + } + } else { + pool = [...PENTOMINOES]; + } + const fresh: IMoveState = { + _version: GolombGame.gameinfo.version, + _results: [], + _timestamp: new Date(), + currplayer: 1, + placed: [], + blockers, + pool, + hands, + kitty, + }; + this.stack = [fresh]; + } else { + if (typeof state === "string") { + state = JSON.parse(state, reviver) as IGolombState; + } + if (state.game !== GolombGame.gameinfo.uid) { + throw new Error(`The Golomb's Game engine cannot process a game of '${state.game}'.`); + } + this.numplayers = state.numplayers; + this.gameover = state.gameover; + this.winner = [...state.winner]; + this.variants = [...state.variants]; + this.stack = [...state.stack]; + } + this.load(); + } + + public load(idx = -1): GolombGame { + if (idx < 0) { + idx += this.stack.length; + } + if (idx < 0 || idx >= this.stack.length) { + throw new Error("Could not load the requested state from the stack."); + } + const state = this.stack[idx]; + this.currplayer = state.currplayer; + this.placed = state.placed.map(p => ({ ...p, cells: [...p.cells] })); + this.blockers = [...state.blockers]; + this.pool = [...state.pool]; + this.hands = state.hands.map(h => [...h]); + this.kitty = [...state.kitty]; + this.lastmove = state.lastmove; + this.results = [...state._results]; + this.geo = GolombGame.geometry(this.variants); + this.candidates = []; + this.selected = []; + this.previewing = false; + this.removing = []; + return this; + } + + private get usesHands(): boolean { + return this.variants.includes("random-hands") || this.variants.includes("choose-up"); + } + + private isChoosing(): boolean { + return this.variants.includes("choose-up") && this.pool.length > 0; + } + + /** The second player's first turn of a Simple pie game, when passing swaps the hands. */ + private isSwapTurn(): boolean { + return this.variants.includes("simple-pie") && this.numplayers === 2 && this.stack.length === 2 && !this.gameover; + } + + private available(player: playerid): Pentomino[] { + return this.usesHands ? this.hands[player - 1] : this.pool; + } + + /** Maps each occupied cell to the index of its piece in `placed`, or -1 for a blocker. */ + private occupancy(): Map { + const occ = new Map(); + for (const cell of this.blockers) { + occ.set(cell, -1); + } + this.placed.forEach((p, i) => p.cells.forEach(c => occ.set(c, i))); + return occ; + } + + private ownCaptured(player: playerid): number[] { + if (!this.variants.includes("capture")) { + return []; + } + return this.placed.map((p, i) => p.owner === player ? i : -1).filter(i => i >= 0); + } + + /** + * For each placement of an available piece, the pieces that would have to be removed first. + * Placements needing a blocker or a piece the player cannot remove are skipped. + */ + private reachablePlacements(player: playerid): { placement: IPlacement; needs: number[] }[] { + const avail = new Set(this.available(player)); + const occ = this.occupancy(); + const own = new Set(this.ownCaptured(player)); + const out: { placement: IPlacement; needs: number[] }[] = []; + for (const placement of this.geo.placements) { + if (!avail.has(placement.piece)) { + continue; + } + const needs = new Set(); + let ok = true; + for (const cell of placement.cells) { + const unit = occ.get(cell); + if (unit === undefined) { + continue; + } + if (!own.has(unit)) { + ok = false; + break; + } + needs.add(unit); + } + if (ok) { + out.push({ placement, needs: [...needs] }); + } + } + return out; + } + + private hasAnyMove(player: playerid): boolean { + if (this.isChoosing() || this.isSwapTurn()) { + return true; + } + return this.reachablePlacements(player).length > 0; + } + + /** A removal is written as `x` and the removed piece's first square. */ + private removalToken(i: number): string { + return `x${this.placed[i].cells[0]}`; + } + + private formatPlacement(removed: number[], cells: string[]): string { + return [...removed.map(i => this.removalToken(i)).sort(), ...cells].join(" "); + } + + public moves(player?: playerid): string[] { + if (this.gameover) { + return []; + } + player ??= this.currplayer; + const moves: string[] = []; + if (this.isSwapTurn()) { + moves.push("pass"); + } + if (this.isChoosing()) { + moves.push(...this.pool); + return moves.sort(); + } + const own = this.ownCaptured(player); + for (const { placement, needs } of this.reachablePlacements(player)) { + // any extra removals of the player's captured pieces are also legal + const optional = own.filter(i => !needs.includes(i)); + for (let mask = 0; mask < (1 << optional.length); mask++) { + const removed = [...needs, ...optional.filter((_, b) => (mask & (1 << b)) !== 0)]; + moves.push(this.formatPlacement(removed, placement.cells)); + } + } + return moves.sort(); + } + + /** Lowercases squares and removals, uppercases pentomino letters, and collapses whitespace. */ + private static cleanInput(m: string): string { + return m.trim().split(/\s+/).filter(t => t.length > 0).map(t => t.length === 1 ? t.toUpperCase() : t.toLowerCase()).join(" "); + } + + private analyse(m: string): IAnalysis { + const result: IValidationResult = { valid: false, message: i18next.t("apgames:validation._general.DEFAULT_HANDLER") }; + const fail = (message: string): IAnalysis => ({ result: { valid: false, message } }); + + if (m.length === 0) { + result.valid = true; + result.complete = -1; + if (this.isSwapTurn()) { + result.message = this.isChoosing() ? + i18next.t("apgames:validation.golomb.INITIAL_INSTRUCTIONS_SWAP_CHOOSE") : + i18next.t("apgames:validation.golomb.INITIAL_INSTRUCTIONS_SWAP"); + } else if (this.isChoosing()) { + result.message = i18next.t("apgames:validation.golomb.INITIAL_INSTRUCTIONS_CHOOSE"); + } else if (this.variants.includes("capture")) { + result.message = i18next.t("apgames:validation.golomb.INITIAL_INSTRUCTIONS_CAPTURE"); + } else { + result.message = i18next.t("apgames:validation.golomb.INITIAL_INSTRUCTIONS"); + } + return { result }; + } + + if (m === "pass") { + if (!this.isSwapTurn()) { + return fail(i18next.t("apgames:validation.golomb.NO_SWAP")); + } + return { result: { valid: true, complete: 1, message: i18next.t("apgames:validation._general.VALID_MOVE") } }; + } + + if (/^[A-Z]$/.test(m)) { + if (!this.isChoosing()) { + return fail(i18next.t("apgames:validation.golomb.NOT_CHOOSING")); + } + if (!this.pool.includes(m as Pentomino)) { + return fail(i18next.t("apgames:validation.golomb.UNAVAILABLE")); + } + return { result: { valid: true, complete: 1, message: i18next.t("apgames:validation._general.VALID_MOVE") } }; + } + + if (this.isChoosing()) { + return fail(i18next.t("apgames:validation.golomb.MUST_CHOOSE")); + } + + const parsed: IParsed = { removals: [], cells: [] }; + for (const token of m.split(" ")) { + const match = token.match(/^(x?)([a-z]\d+)$/); + if (match === null) { + return fail(i18next.t("apgames:validation.golomb.BAD_TOKEN", { token })); + } + if (match[1] === "x") { + parsed.removals.push(match[2]); + } else { + parsed.cells.push(match[2]); + } + } + + const occ = this.occupancy(); + const removed: number[] = []; + for (const cell of parsed.removals) { + if (!this.variants.includes("capture")) { + return fail(i18next.t("apgames:validation.golomb.NO_REMOVAL")); + } + const unit = occ.get(cell); + if (unit === undefined || unit < 0 || this.placed[unit].owner !== this.currplayer) { + return fail(i18next.t("apgames:validation.golomb.NOT_CAPTURED", { cell })); + } + if (removed.includes(unit)) { + return fail(i18next.t("apgames:validation.golomb.DUPLICATE_REMOVAL", { cell })); + } + removed.push(unit); + } + + const isFree = (cell: string): boolean => { + const unit = occ.get(cell); + return unit === undefined || removed.includes(unit); + }; + for (let i = 0; i < parsed.cells.length; i++) { + const cell = parsed.cells[i]; + if (!this.geo.cellSet.has(cell)) { + return fail(i18next.t("apgames:validation.golomb.OFF_BOARD", { cell })); + } + if (!isFree(cell)) { + return fail(i18next.t("apgames:validation.golomb.OCCUPIED", { cell })); + } + if (parsed.cells.indexOf(cell) !== i) { + return fail(i18next.t("apgames:validation.golomb.DUPLICATE", { cell })); + } + } + + const avail = new Set(this.available(this.currplayer)); + const compatible = this.geo.placements.filter(p => + avail.has(p.piece) && + parsed.cells.every(c => p.cells.includes(c)) && + p.cells.every(isFree) + ); + + result.valid = true; + result.canrender = true; + if (parsed.cells.length === 0) { + result.complete = -1; + result.message = i18next.t("apgames:validation.golomb.INITIAL_INSTRUCTIONS_CAPTURE"); + } else if (compatible.length === 0) { + return fail(i18next.t("apgames:validation.golomb.NO_PLACEMENT")); + } else if (compatible.length === 1) { + // a complete placement is never auto-submitted + result.complete = 0; + result.message = i18next.t("apgames:validation.golomb.UNIQUE"); + } else { + result.complete = -1; + result.message = i18next.t("apgames:validation.golomb.PARTIAL"); + } + return { result, parsed, removed, compatible }; + } + + public validateMove(m: string): IValidationResult { + return this.analyse(GolombGame.cleanInput(m)).result; + } + + /** The stored form of a move: removals, then all five covered squares, each sorted. */ + public normaliseMove(m: string): string { + m = GolombGame.cleanInput(m); + const { result, removed, compatible } = this.analyse(m); + if (result.valid && result.complete === 0 && removed !== undefined && compatible !== undefined) { + return this.formatPlacement(removed, compatible[0].cells); + } + return m; + } + + public handleClick(move: string, row: number, col: number, piece?: string): IClickResult { + try { + move = GolombGame.cleanInput(move); + const keep = (): IClickResult => ({ ...this.validateMove(move), move }); + // the client sends the Swap button as a click on "_btn_pass" + if (piece === "_btn_pass") { + const result = this.validateMove("pass"); + return { ...result, move: result.valid ? "pass" : move }; + } + if (row < 0 || col < 0) { + if (this.isChoosing() && piece !== undefined && this.pool.includes(piece as Pentomino)) { + const result = this.validateMove(piece); + return { ...result, move: result.valid ? piece : move }; + } + return keep(); + } + if (this.isChoosing()) { + return keep(); + } + const cell = this.coords2algebraic(col, row); + if (!this.geo.cellSet.has(cell)) { + return keep(); + } + const current = this.analyse(move); + const parsed = current.parsed ?? { removals: [], cells: [] }; + const removed = current.removed ?? []; + const removals = removed.map(i => this.removalToken(i)); + const reset = (): IClickResult => ({ ...this.validateMove(""), move: "" }); + + const unit = this.occupancy().get(cell); + if (unit !== undefined && !removed.includes(unit)) { + // clicking your own captured piece removes it (and drops any partial placement) + if (unit >= 0 && this.variants.includes("capture") && this.placed[unit].owner === this.currplayer) { + const newmove = [...removals, this.removalToken(unit)].join(" "); + return { ...this.validateMove(newmove), move: newmove }; + } + // clicking any other piece or blocker cancels the move + return reset(); + } + + if (current.result.valid && current.result.complete === 0 && current.compatible !== undefined) { + if (current.compatible[0].cells.includes(cell)) { + // clicking the previewed piece changes nothing + return { ...current.result, move }; + } + // clicking any other empty square confirms the placement + return { + valid: true, + complete: 1, + canrender: true, + move: this.normaliseMove(move), + message: i18next.t("apgames:validation._general.VALID_MOVE"), + }; + } + + // a square that is already selected changes nothing + if (parsed.cells.includes(cell)) { + return { ...current.result, move }; + } + const newmove = [...removals, ...parsed.cells, cell].join(" "); + const result = this.validateMove(newmove); + if (result.valid) { + return { ...result, move: newmove }; + } + // an impossible square cancels the partial placement but keeps any removals + const kept = removals.join(" "); + return { ...this.validateMove(kept), move: kept, message: result.message }; + } catch (e) { + return { + move, + valid: false, + message: i18next.t("apgames:validation._general.GENERIC", { move, row, col, piece, emessage: (e as Error).message }), + }; + } + } + + public move(m: string, { partial = false, trusted = false } = {}): GolombGame { + if (this.gameover) { + throw new UserFacingError("MOVES_GAMEOVER", i18next.t("apgames:validation._general.MOVES_GAMEOVER")); + } + m = GolombGame.cleanInput(m); + const analysis = this.analyse(m); + if (!trusted || partial) { + if (!analysis.result.valid) { + throw new UserFacingError("VALIDATION_GENERAL", analysis.result.message); + } + if (!partial && analysis.result.complete === -1) { + throw new UserFacingError("VALIDATION_FAILSAFE", i18next.t("apgames:validation._general.FAILSAFE", { move: m })); + } + } + + this.results = []; + this.candidates = []; + this.selected = []; + this.previewing = false; + this.removing = []; + + if (partial) { + if (analysis.parsed === undefined || analysis.removed === undefined) { + return this; + } + this.previewing = true; + // show removed pieces off the board and back in the pool + this.removing = this.liftPieces(analysis.removed); + this.pool = [...this.pool, ...this.removing].sort(); + if (analysis.parsed.cells.length > 0 && analysis.compatible?.length === 1) { + // the squares are settled: show the piece, and any captures, as they will be + this.placePiece(analysis.compatible[0]); + } else { + this.selected = [...analysis.parsed.cells]; + this.candidates = [...new Set((analysis.compatible ?? []).flatMap(p => p.cells))]; + } + return this; + } + + if (m === "pass") { + [this.hands[0], this.hands[1]] = [this.hands[1], this.hands[0]]; + this.results.push({ type: "pie" }); + } else if (/^[A-Z]$/.test(m)) { + const pc = m as Pentomino; + this.pool = this.pool.filter(p => p !== pc); + this.hands[this.currplayer - 1] = [...this.hands[this.currplayer - 1], pc].sort(); + this.results.push({ type: "select", what: pc }); + } else { + const placement = analysis.compatible![0]; + m = this.formatPlacement(analysis.removed!, placement.cells); + const returning = this.liftPieces(analysis.removed!); + this.placePiece(placement); + // removed pieces only return to the pool once the move is over + this.pool = [...this.pool, ...returning].sort(); + } + + this.lastmove = m; + this.currplayer = (this.currplayer % this.numplayers + 1) as playerid; + this.checkEOG(); + this.saveState(); + return this; + } + + /** Takes the given pieces off the board, recording each removal, and returns them. */ + private liftPieces(indices: number[]): Pentomino[] { + const lifted = indices.map(i => this.placed[i]); + for (const p of lifted) { + this.results.push({ type: "remove", what: p.piece, where: p.cells.join(" ") }); + } + this.placed = this.placed.filter((_, i) => !indices.includes(i)); + return lifted.map(p => p.piece); + } + + /** Takes the piece from the mover's supply, places it, and captures what it touches enough. */ + private placePiece(placement: IPlacement): void { + if (this.usesHands) { + this.hands[this.currplayer - 1] = this.hands[this.currplayer - 1].filter(p => p !== placement.piece); + } else { + this.pool = this.pool.filter(p => p !== placement.piece); + } + this.results.push({ type: "place", what: placement.piece, where: placement.cells.join(" ") }); + if (this.variants.includes("capture")) { + for (const other of this.placed) { + if (this.sharedEdges(placement.cells, other.cells) >= 3 && other.owner !== this.currplayer) { + this.results.push({ type: "capture", what: other.piece, where: other.cells.join(" "), whose: other.owner }); + other.owner = this.currplayer; + } + } + } + this.placed.push({ piece: placement.piece, cells: [...placement.cells], owner: 0 }); + } + + private sharedEdges(a: string[], b: string[]): number { + const other = new Set(b); + let count = 0; + for (const cell of a) { + const [x, y] = this.algebraic2coords(cell); + for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { + const nx = x + dx; + const ny = y + dy; + if (nx >= 0 && ny >= 0 && nx < this.geo.width && ny < this.geo.height && other.has(this.coords2algebraic(nx, ny))) { + count++; + } + } + } + return count; + } + + public coords2algebraic(x: number, y: number): string { + return GameBase.coords2algebraic(x, y, this.geo.height); + } + + public algebraic2coords(cell: string): [number, number] { + return GameBase.algebraic2coords(cell, this.geo.height); + } + + protected checkEOG(): GolombGame { + if (!this.hasAnyMove(this.currplayer)) { + this.gameover = true; + const mover = ((this.currplayer + this.numplayers - 2) % this.numplayers + 1) as playerid; + this.winner = this.variants.includes("misere") ? [this.currplayer] : [mover]; + this.results.push( + { type: "eog", reason: "stalemate" }, + { type: "winners", players: [...this.winner] }, + ); + } else if (this.variants.includes("capture") && this.repetitions() >= 5) { + this.gameover = true; + this.winner = Array.from({ length: this.numplayers }, (_, i) => (i + 1) as playerid); + this.results.push( + { type: "eog", reason: "repetition" }, + { type: "winners", players: [...this.winner] }, + ); + } + return this; + } + + /** The board, captured colours and player to move; the shared pool follows from the board. */ + private static positionKey(state: { currplayer: playerid; placed: IPlacedPiece[] }): string { + return `${state.currplayer}|${state.placed.map(p => `${p.owner}:${p.cells.join(".")}`).sort().join(",")}`; + } + + /** + * How many times the current, not yet saved, position has occurred, counting itself. + * Only Capture games can repeat a position, since otherwise every move fills the board further. + */ + private repetitions(): number { + const seen = new Map(); + for (const entry of this.stack) { + const key = GolombGame.positionKey(entry); + seen.set(key, (seen.get(key) ?? 0) + 1); + } + return (seen.get(GolombGame.positionKey(this)) ?? 0) + 1; + } + + public getButtons(): ICustomButton[] { + if (this.isSwapTurn()) { + return [{ label: "apgames:buttons.swap", move: "pass" }]; + } + return []; + } + + public getStartingPosition(): string { + const start = this.stack[0]; + const parts: string[] = []; + if (start.blockers.length > 0) { + parts.push(start.blockers.join(",")); + } + if (this.variants.includes("random-hands")) { + parts.push(...start.hands.map(h => h.join(""))); + if (start.kitty.length > 0) { + parts.push(start.kitty.join("")); + } + } + return parts.join(";"); + } + + public state(opts?: { strip?: boolean, player?: number }): IGolombState { + const state: IGolombState = { + game: GolombGame.gameinfo.uid, + numplayers: this.numplayers, + variants: this.variants, + gameover: this.gameover, + winner: [...this.winner], + stack: [...this.stack], + }; + if (opts?.strip && this.variants.includes("concealed")) { + state.stack = state.stack.map(entry => ({ + ...entry, + hands: entry.hands.map((h, i) => i + 1 === opts.player ? [...h] : []), + kitty: [], + })); + } + return state; + } + + protected moveState(): IMoveState { + return { + _version: GolombGame.gameinfo.version, + _results: [...this.results], + _timestamp: new Date(), + currplayer: this.currplayer, + lastmove: this.lastmove, + placed: this.placed.map(p => ({ ...p, cells: [...p.cells] })), + blockers: [...this.blockers], + pool: [...this.pool], + hands: this.hands.map(h => [...h]), + kitty: [...this.kitty], + }; + } + + public render(opts: IRenderOpts = {}): APRenderRep { + const { width, height } = this.geo; + const markers = this.boardMarkers(); + + let pieces: string | null = null; + if (this.selected.length > 0) { + const selected = new Set(this.selected); + const rows: string[] = []; + for (let y = 0; y < height; y++) { + const row: string[] = []; + for (let x = 0; x < width; x++) { + row.push(selected.has(this.coords2algebraic(x, y)) ? "CAND" : "-"); + } + rows.push(row.join(",")); + } + pieces = rows.join("\n"); + } + // before any input, every empty square some placement could cover gets a dot + const dotted = this.previewing ? this.candidates : this.coverable(); + + const legend: NonNullable = { + // marks a clicked square; 0.707 ≈ sqrt(0.5), so it covers about half the cell's area + CAND: { name: "piece-square-borderless", colour: "_context_fill", scale: 0.707 }, + }; + // Hand and pool pentominoes are vector glyphs so they size like other pieces; + // every shape is centred in the same 5x5 box to keep them proportional. + const glyphDefs: NonNullable = {}; + for (const pc of PENTOMINOES) { + const shape = SHAPES[pc]; + const ox = (5 - shape[0].length) * 50; + const oy = (5 - shape.length) * 50; + const markup = shape.flatMap((row, y) => row.map((v, x) => v === 1 ? + `` : "" + )).join(""); + glyphDefs[`golomb-${pc}`] = { viewBox: [0, 0, 500, 500], markup }; + legend[pc] = { def: `golomb-${pc}`, scale: 1.4, paint: { fill: "_context_fill" } }; + } + // removed this turn, so not placeable until the move is over + for (const pc of this.removing) { + legend[`${pc}-removed`] = [ + { def: `golomb-${pc}`, scale: 1.4, paint: { fill: "_context_fill" } }, + // only the player to move can remove pieces, so the cross is theirs + { name: "cross-diag", scale: 1.1, paint: { fill: this.currplayer } }, + ]; + } + + const areas = this.pieceAreas(opts); + + const blocked = this.holes().map(c => this.toRowCol(c)); + const rep: APRenderRep = { + board: { + style: "squares", + width, + height, + ...(blocked.length > 0 ? { blocked: blocked as [RowCol, ...RowCol[]] } : {}), + ...(markers.length > 0 ? { markers } : {}), + }, + glyphDefs, + legend, + pieces, + ...(areas.length > 0 ? { areas } : {}), + }; + + const annotations: AnnotationBasic[] = []; + for (const r of this.results) { + if (r.type === "place") { + annotations.push({ type: "enter", targets: r.where!.split(" ").map(c => this.toRowCol(c)) as [RowCol, ...RowCol[]] }); + } else if (r.type === "remove") { + annotations.push({ type: "exit", targets: r.where!.split(" ").map(c => this.toRowCol(c)) as [RowCol, ...RowCol[]] }); + } + } + const dots = dotted.filter(c => !this.selected.includes(c)).map(c => this.toRowCol(c)); + if (dots.length > 0) { + annotations.push({ type: "dots", targets: dots as [RowCol, ...RowCol[]] }); + } + if (annotations.length > 0) { + rep.annotations = annotations; + } + return rep; + } + + private toRowCol(cell: string): RowCol { + const [col, row] = this.algebraic2coords(cell); + return { row, col }; + } + + /** Fills pieces and blockers, and outlines their outside edges. */ + private boardMarkers(): (MarkerFlood | MarkerFence)[] { + const { width, height } = this.geo; + // pieces and blockers share the foreground colour unless captured + const units: { cells: string[]; colour: string | number }[] = [ + ...this.placed.map(p => ({ cells: p.cells, colour: p.owner === 0 ? "_context_fill" : p.owner })), + ...this.blockers.map(c => ({ cells: [c], colour: "_context_fill" })), + ]; + const unitOf = new Map(); + units.forEach((u, i) => u.cells.forEach(c => unitOf.set(c, i))); + const floods = new Map(); + for (const u of units) { + floods.set(u.colour, [...(floods.get(u.colour) ?? []), ...u.cells.map(c => this.toRowCol(c))]); + } + const markers: (MarkerFlood | MarkerFence)[] = []; + for (const [colour, points] of floods.entries()) { + // drawn over the grid so pieces show no internal lines + markers.push({ type: "flood", colour, opacity: 1, belowGrid: false, points: points as [RowCol, ...RowCol[]] }); + } + // outline every outside edge of each piece and blocker, but not the edges between its own squares + const fences: MarkerFenceData[] = []; + const sides: [number, number, "N" | "E" | "S" | "W"][] = [[0, -1, "N"], [1, 0, "E"], [0, 1, "S"], [-1, 0, "W"]]; + for (const [cell, u] of unitOf.entries()) { + const [x, y] = this.algebraic2coords(cell); + for (const [dx, dy, side] of sides) { + const nx = x + dx; + const ny = y + dy; + const onBoard = nx >= 0 && ny >= 0 && nx < width && ny < height; + const other = onBoard ? unitOf.get(this.coords2algebraic(nx, ny)) : undefined; + if (other === u) { + continue; + } + // an edge shared by two pieces is drawn once, from its west or north side + if (other !== undefined && (side === "N" || side === "W")) { + continue; + } + fences.push({ cell: { row: y, col: x }, side, colour: "_context_background", width: 3 }); + } + } + for (const f of fences) { + markers.push({ type: "fence", ...f }); + } + return markers; + } + + /** Hands, the pool and (with Concealed hands) the unseen pieces, as this viewer may see them. */ + private pieceAreas(opts: IRenderOpts): AreaPieces[] { + const areas: AreaPieces[] = []; + const asPieces = (list: string[]) => list as AreaPieces["pieces"]; + const concealed = this.variants.includes("concealed"); + const reveal = !concealed || this.gameover || opts.omniscient === true; + const seen = new Set(this.placed.map(p => p.piece)); + if (this.usesHands) { + for (let p = 1; p <= this.numplayers; p++) { + if (!reveal && opts.perspective !== undefined && opts.perspective !== p) { + continue; + } + const hand = this.hands[p - 1]; + hand.forEach(pc => seen.add(pc)); + if (hand.length > 0) { + areas.push({ + type: "pieces", + label: this.seatAreaLabel(p, "apgames:validation.golomb.LABEL_HAND"), + pieces: asPieces(hand), + ownerMark: p, + spacing: 0.3, + }); + } + } + } + if (this.pool.length > 0) { + areas.push({ + type: "pieces", + label: this.neutralAreaLabel("apgames:validation.golomb.LABEL_POOL"), + pieces: asPieces(this.pool.map(pc => this.removing.includes(pc) ? `${pc}-removed` : pc)), + spacing: 0.3, + }); + } + if (concealed) { + // only says which pieces are elsewhere, never whose they are + const unseen = PENTOMINOES.filter(pc => !seen.has(pc)); + if (unseen.length > 0) { + areas.push({ + type: "pieces", + label: this.neutralAreaLabel("apgames:validation.golomb.LABEL_UNSEEN"), + pieces: asPieces(unseen), + spacing: 0.3, + }); + } + } + return areas; + } + + /** Empty squares the player to move could cover with some placement, without removing anything. */ + private coverable(): string[] { + if (this.gameover || this.isChoosing()) { + return []; + } + const free = this.reachablePlacements(this.currplayer).filter(r => r.needs.length === 0); + return [...new Set(free.flatMap(r => r.placement.cells))]; + } + + private holes(): string[] { + const all: string[] = []; + for (let y = 0; y < this.geo.height; y++) { + for (let x = 0; x < this.geo.width; x++) { + const cell = this.coords2algebraic(x, y); + if (!this.geo.cellSet.has(cell)) { + all.push(cell); + } + } + } + return all; + } + + public collectChatLogLine(lines: ChatLogLine[], r: APMoveResult, ctx: ChatLogCollectContext): boolean { + switch (r.type) { + case "select": + this.pushSeatChatLine(lines, ctx.defaultSeat, "apresults:golomb.SELECT.default", { what: r.what! }); + return true; + case "place": + this.pushSeatChatLine(lines, ctx.defaultSeat, "apresults:golomb.PLACE.default", { what: r.what!, where: r.where!.split(" ").join(", ") }); + return true; + case "remove": + this.pushSeatChatLine(lines, ctx.defaultSeat, "apresults:golomb.REMOVE.default", { what: r.what! }); + return true; + case "capture": + this.pushSeatChatLine(lines, ctx.defaultSeat, "apresults:golomb.CAPTURE.default", { what: r.what! }); + return true; + case "pie": + this.pushSeatChatLine(lines, ctx.defaultSeat, "apresults:golomb.SWAP.default"); + return true; + default: + return super.collectChatLogLine(lines, r, ctx); + } + } + + public clone(): GolombGame { + return new GolombGame(this.serialize()); + } +} diff --git a/test/games/golomb.test.ts b/test/games/golomb.test.ts new file mode 100644 index 00000000..dc58688b --- /dev/null +++ b/test/games/golomb.test.ts @@ -0,0 +1,732 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions */ + +import "mocha"; +import { expect } from "chai"; +import { addResource } from "../../src"; +import { GolombGame } from "../../src/games"; +import type { Pentomino } from "../../src/games/golomb"; +import { assertChatLogParity } from "../fixtures/chat/helpers"; + +// Squares are named by file letter and rank number, a1 bottom-left. A +// placement is written as space-separated squares; any set of squares that +// only one legal placement covers names that placement, and moves are stored +// with all five squares, sorted. In the Capture variant, `xa1` removes the +// mover's captured piece whose first square is a1. + +const ALL: Pentomino[] = ["F", "I", "L", "N", "P", "T", "U", "V", "W", "X", "Y", "Z"]; + +interface IFixture { + placed?: [Pentomino, string[], number][]; + blockers?: string[]; + pool?: Pentomino[]; + hands?: Pentomino[][]; + kitty?: Pentomino[]; + currplayer?: 1 | 2 | 3 | 4; +} + +const setUp = (g: GolombGame, f: IFixture): GolombGame => { + if (f.placed !== undefined) { + g.placed = f.placed.map(([piece, cells, owner]) => ({ piece, cells: [...cells].sort(), owner })); + } + if (f.blockers !== undefined) { + g.blockers = [...f.blockers]; + } + if (f.pool !== undefined) { + g.pool = [...f.pool]; + } + if (f.hands !== undefined) { + g.hands = f.hands.map(h => [...h]); + } + if (f.kitty !== undefined) { + g.kitty = [...f.kitty]; + } + if (f.currplayer !== undefined) { + g.currplayer = f.currplayer; + } + // the fixture is also the saved position, so the game reloads exactly as set up + const top = g.stack.length - 1; + g.stack[top] = { + ...g.stack[top], + currplayer: g.currplayer, + placed: g.placed.map(pc => ({ ...pc, cells: [...pc.cells] })), + blockers: [...g.blockers], + pool: [...g.pool], + hands: g.hands.map(h => [...h]), + kitty: [...g.kitty], + }; + return g; +}; + +/** A copy of the game showing the move being entered. */ +const preview = (g: GolombGame, m: string): GolombGame => { + const copy = new GolombGame(g.serialize()); + copy.move(m, { partial: true }); + return copy; +}; + +// mulberry32: random blockers and deals shuffle with Math.random, which every test reseeds +const seeded = (seed: number) => (): number => { + seed = (seed + 0x6d2b79f5) | 0; + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; +}; + +const squares = (width: number, height: number): string[] => { + const out: string[] = []; + for (let x = 0; x < width; x++) { + for (let y = 1; y <= height; y++) { + out.push(`${String.fromCharCode(97 + x)}${y}`); + } + } + return out; +}; + +// Bounding boxes (width, height) of the 63 fixed pentominoes: I has 2 +// orientations; L, N and Y have 8 each (2x4 or 4x2); P has 8 and U 4 (2x3 or +// 3x2); F, T, V, W, X and Z fill 3x3 boxes in 25 orientations between them. +const FIXED_BOXES: [number, number, number][] = [ + [1, 5, 1], [5, 1, 1], + [2, 4, 12], [4, 2, 12], + [2, 3, 6], [3, 2, 6], + [3, 3, 25], +]; +const placementCount = (width: number, height: number): number => + FIXED_BOXES.reduce((sum, [w, h, n]) => sum + n * Math.max(0, width - w + 1) * Math.max(0, height - h + 1), 0); + +const movedCells = (m: string): string[] => m.split(" ").filter(t => !t.startsWith("x")); + +// 8x8 board: rank 8 is display row 0 +const rc = (cell: string, height = 8): [number, number] => [height - Number(cell.slice(1)), cell.charCodeAt(0) - 97]; + +describe("Golomb's Game", () => { + const realRandom = Math.random; + before(() => { + addResource("en"); + }); + beforeEach(() => { + Math.random = seeded(20261125); + }); + afterEach(() => { + Math.random = realRandom; + }); + + describe("setup", () => { + it("starts with an empty 8x8 board, all 12 pentominoes in a shared pool, and player 1 to move", () => { + const g = new GolombGame(); + expect(g.numplayers).to.equal(2); + expect(g.currplayer).to.equal(1); + expect(g.placed).to.be.empty; + expect(g.blockers).to.be.empty; + expect([...g.pool].sort()).to.deep.equal(ALL); + const moves = g.moves(); + expect(moves).to.include("a1 a2 a3 a4 a5"); + expect(moves).to.include("h4 h5 h6 h7 h8"); + expect(moves.some(m => /\b(i\d|[a-h]9)\b/.test(m))).to.be.false; + }); + + it("offers every placement of every pentomino on each rectangular board", () => { + expect(new GolombGame().moves()).to.have.length(placementCount(8, 8)); + expect(new GolombGame(2, ["size-7x7"]).moves()).to.have.length(placementCount(7, 7)); + expect(new GolombGame(2, ["size-8x7"]).moves()).to.have.length(placementCount(8, 7)); + expect(new GolombGame(2, ["size-10x6"]).moves()).to.have.length(placementCount(10, 6)); + }); + + it("8x7 and 10x6 boards are wider than they are tall", () => { + expect(new GolombGame(2, ["size-8x7"]).validateMove("h3 h7").complete).to.equal(0); + expect(new GolombGame(2, ["size-8x7"]).validateMove("a8").valid).to.be.false; + expect(new GolombGame(2, ["size-10x6"]).validateMove("f1 j1").complete).to.equal(0); + expect(new GolombGame(2, ["size-10x6"]).validateMove("a7").valid).to.be.false; + }); + + it("the center-blocked board is missing its four center squares", () => { + const g = new GolombGame(2, ["center-blocked"]); + for (const cell of ["d4", "d5", "e4", "e5"]) { + expect(g.validateMove(cell).valid).to.be.false; + expect(g.moves().some(m => movedCells(m).includes(cell))).to.be.false; + } + expect(g.validateMove("d3").valid).to.be.true; + }); + + it("random blockers fill one square for each square beyond 60, and at least one", () => { + const expected: [string[], number][] = [ + [[], 4], + [["size-7x7"], 1], + [["size-8x7"], 1], + [["size-10x6"], 1], + [["center-blocked"], 1], + ]; + for (const [board, count] of expected) { + const g = new GolombGame(2, [...board, "random-blockers"]); + expect(g.blockers, board.join()).to.have.length(count); + expect(new Set(g.blockers).size).to.equal(count); + for (const b of g.blockers) { + expect(["d4", "d5", "e4", "e5"].includes(b) && board.includes("center-blocked")).to.be.false; + expect(g.validateMove(b).valid).to.be.false; + expect(g.moves().some(m => movedCells(m).includes(b))).to.be.false; + } + } + }); + + it("drops variant combinations the rules don't allow", () => { + // requested variants, and variants that must not all survive together + const cases: [string[], string[]][] = [ + [["concealed"], ["concealed"]], + [["choose-up", "concealed"], ["concealed"]], + [["random-hands", "capture"], ["capture"]], + [["choose-up", "capture"], ["capture"]], + [["capture", "misere"], ["capture", "misere"]], + [["simple-pie"], ["simple-pie"]], + [["random-hands", "concealed", "simple-pie"], ["concealed", "simple-pie"]], + ]; + for (const [requested, forbidden] of cases) { + const kept = new GolombGame(2, requested).variants; + expect(forbidden.every(v => kept.includes(v)), requested.join("+")).to.be.false; + } + }); + + }); + + describe("placing pentominoes", () => { + it("any squares that identify one placement name it, and the move is stored with all five squares sorted", () => { + const g = new GolombGame(); + g.move("a5 a1"); + expect(g.lastmove).to.equal("a1 a2 a3 a4 a5"); + expect(g.placed).to.deep.equal([{ piece: "I", cells: ["a1", "a2", "a3", "a4", "a5"], owner: 0 }]); + expect(g.pool).to.not.include("I"); + expect(g.currplayer).to.equal(2); + }); + + it("squares that several placements cover are not yet a move", () => { + const g = new GolombGame(); + const result = g.validateMove("a1 a2"); + expect(result.valid).to.be.true; + expect(result.complete).to.equal(-1); + expect(() => g.move("a1 a2")).to.throw(); + }); + + it("rejects squares that no single pentomino can cover", () => { + const g = new GolombGame(); + expect(g.validateMove("a1 e5").valid).to.be.false; + expect(g.validateMove("a1 a2 a3 a4 a5 a6").valid).to.be.false; + expect(g.validateMove("a1 a2 b4 c4 d4").valid).to.be.false; + }); + + it("pentominoes may not overlap", () => { + const g = new GolombGame(); + g.move("a1 a5"); + expect(g.validateMove("a5 b5 c5 d5 e5").valid).to.be.false; + expect(g.moves().some(m => movedCells(m).includes("a3"))).to.be.false; + }); + + it("each pentomino can only be placed once", () => { + const g = new GolombGame(); + g.move("a1 a5"); + expect(g.validateMove("c1 c5").valid).to.be.false; + expect(g.moves()).to.not.include("c1 c2 c3 c4 c5"); + expect(g.moves()).to.not.include("b8 c8 d8 e8 f8"); + }); + + it("removing pieces is only possible in the Capture variant", () => { + const g = setUp(new GolombGame(), { placed: [["I", ["a1", "a2", "a3", "a4", "a5"], 1]] }); + expect(g.validateMove("xa1 a1 a2 a3 b1 c1").valid).to.be.false; + }); + }); + + describe("end of game", () => { + // a 7x7 board blocked everywhere except two 1x5 strips: a1-a5 and g1-g5 + const strips = (): string[] => squares(7, 7).filter(c => !/^[ag][1-5]$/.test(c)); + + it("the last player able to move wins", () => { + const g = setUp(new GolombGame(2, ["size-7x7"]), { blockers: strips(), pool: ["I", "L"] }); + g.move("a1 a5"); + expect(g.gameover).to.be.true; + expect(g.winner).to.deep.equal([1]); + expect(g.moves()).to.be.empty; + }); + + it("in Misère, the first player with no legal move wins", () => { + const g = setUp(new GolombGame(2, ["size-7x7", "misere"]), { blockers: strips(), pool: ["I", "L"] }); + g.move("a1 a5"); + expect(g.gameover).to.be.true; + expect(g.winner).to.deep.equal([2]); + }); + + it("with three players, the game ends when the player to move cannot place, and the last mover wins", () => { + const g = setUp(new GolombGame(3, ["size-7x7"]), { blockers: strips(), pool: ["I", "L"] }); + g.move("a1 a5"); + expect(g.gameover).to.be.true; + expect(g.winner).to.deep.equal([1]); + }); + }); + + describe("piece distribution", () => { + it("random distribution deals the 12 pentominoes evenly", () => { + for (const n of [2, 3, 4]) { + const g = new GolombGame(n, ["random-hands"]); + expect(g.pool).to.be.empty; + expect(g.kitty).to.be.empty; + expect(g.hands).to.have.length(n); + for (const h of g.hands) { + expect(h).to.have.length(12 / n); + } + expect(g.hands.flat().sort()).to.deep.equal(ALL); + } + }); + + it("players may only place pentominoes from their own hand", () => { + const g = setUp(new GolombGame(2, ["random-hands"]), { + hands: [["F", "I", "L", "N", "P", "T"], ["U", "V", "W", "X", "Y", "Z"]], + }); + // a1-a5 can only be the I + expect(g.validateMove("a1 a5").complete).to.equal(0); + // the V is in player 2's hand + expect(g.validateMove("a1 a3 c1").valid).to.be.false; + g.move("a1 a5"); + expect(g.hands[0]).to.deep.equal(["F", "L", "N", "P", "T"]); + expect(g.validateMove("c1 c3 e1").complete).to.equal(0); + expect(g.validateMove("c1 c2 c3 c4 d4").valid).to.be.false; + }); + + it("concealed hands set two pentominoes aside in 2-player games only", () => { + const two = new GolombGame(2, ["random-hands", "concealed"]); + expect(two.hands.map(h => h.length)).to.deep.equal([5, 5]); + expect(two.kitty).to.have.length(2); + expect([...two.hands.flat(), ...two.kitty].sort()).to.deep.equal(ALL); + const three = new GolombGame(3, ["random-hands", "concealed"]); + expect(three.hands.map(h => h.length)).to.deep.equal([4, 4, 4]); + expect(three.kitty).to.be.empty; + }); + + it("choose up: players take turns choosing pentominoes, then player 1 places first", () => { + const g = new GolombGame(2, ["choose-up"]); + expect(g.moves()).to.deep.equal(ALL); + expect(g.validateMove("a1 a5").valid).to.be.false; + g.move("f"); + expect(g.hands[0]).to.deep.equal(["F"]); + expect(g.validateMove("F").valid).to.be.false; + for (const pc of ALL.slice(1)) { + expect(g.moves()).to.not.include("pass"); + g.move(pc); + } + expect(g.pool).to.be.empty; + expect(g.hands).to.deep.equal([["F", "L", "P", "U", "W", "Y"], ["I", "N", "T", "V", "X", "Z"]]); + expect(g.currplayer).to.equal(1); + expect(g.validateMove("X").valid).to.be.false; + expect(g.moves()).to.not.include("a1 a2 a3 a4 a5"); + expect(g.moves()).to.include("a1 a2 a3 a4 b1"); + }); + }); + + describe("concealed hands", () => { + const dealt = (): GolombGame => setUp(new GolombGame(2, ["random-hands", "concealed"]), { + hands: [["F", "I", "L", "N", "P"], ["T", "U", "V", "W", "X"]], + kitty: ["Y", "Z"], + }); + + it("a stripped state only contains the viewing player's hand", () => { + const g = dealt(); + g.move("a1 a5"); + const full = g.state(); + const mine = g.state({ strip: true, player: 1 }); + for (const entry of mine.stack) { + expect(entry.hands[1]).to.be.empty; + expect(entry.kitty).to.be.empty; + } + expect(mine.stack[mine.stack.length - 1].hands[0]).to.deep.equal(["F", "L", "N", "P"]); + expect(full.stack[full.stack.length - 1].hands[1]).to.deep.equal(["T", "U", "V", "W", "X"]); + expect(full.stack[full.stack.length - 1].kitty).to.deep.equal(["Y", "Z"]); + // hands that are not concealed are never stripped + const open = setUp(new GolombGame(2, ["random-hands"]), { hands: [["F"], ["I"]] }); + expect(open.state({ strip: true, player: 1 }).stack[0].hands[1]).to.deep.equal(["I"]); + }); + + it("the display lists the unseen pentominoes without saying where they are", () => { + const g = dealt(); + g.move("a1 a5"); + const shown = (rep: ReturnType) => + (rep.areas ?? []).map(a => ("pieces" in a ? (a.pieces as string[]) : [])); + for (const viewer of [g, new GolombGame(g.serialize({ strip: true, player: 1 }))]) { + const areas = shown(viewer.render({ perspective: 1 })); + expect(areas).to.deep.include(["F", "L", "N", "P"]); + expect(areas).to.deep.include(["T", "U", "V", "W", "X", "Y", "Z"]); + expect(areas).to.not.deep.include(["T", "U", "V", "W", "X"]); + expect(areas.flat()).to.not.include("I"); + } + }); + + it("exploration is disabled only when hands are concealed", () => { + expect(new GolombGame(2, ["random-hands", "concealed"]).getFlags()).to.include("no-explore"); + expect(new GolombGame(2, ["random-hands"]).getFlags()).to.not.include("no-explore"); + expect(new GolombGame().getFlags()).to.not.include("no-explore"); + }); + + }); + + describe("capture", () => { + const I_A = ["a1", "a2", "a3", "a4", "a5"]; + + it("a placement sharing 3 or more edges with a piece captures it", () => { + const g = setUp(new GolombGame(2, ["capture"]), { placed: [["I", I_A, 0]], pool: ALL.filter(p => p !== "I") }); + g.move("b1 b2 b3 b4 c1"); + expect(g.placed.find(p => p.piece === "I")!.owner).to.equal(1); + // the new piece itself is not owned + expect(g.placed.find(p => p.piece === "L")!.owner).to.equal(0); + }); + + it("two shared edges do not capture", () => { + const g = setUp(new GolombGame(2, ["capture"]), { placed: [["I", I_A, 0]], pool: ALL.filter(p => p !== "I") }); + g.move("b1 b2 c1 d1 e1"); + expect(g.placed.find(p => p.piece === "I")!.owner).to.equal(0); + }); + + it("captured pieces can be recaptured", () => { + const g = setUp(new GolombGame(2, ["capture"]), { placed: [["I", I_A, 1]], pool: ALL.filter(p => p !== "I") }); + g.move("g1 h1 h2 h3 h4"); + g.move("b1 b2 b3 c1 c2"); + expect(g.placed.find(p => p.piece === "I")!.owner).to.equal(2); + }); + + it("a player may first remove pieces they captured; those return to the pool after the move", () => { + const g = setUp(new GolombGame(2, ["capture"]), { placed: [["I", I_A, 1]], pool: ALL.filter(p => p !== "I") }); + g.move("a1 a2 a3 b1 c1 xa3"); + expect(g.lastmove).to.equal("xa1 a1 a2 a3 b1 c1"); + expect(g.placed.map(p => p.piece)).to.deep.equal(["V"]); + expect(g.pool).to.include("I"); + expect(g.pool).to.not.include("V"); + }); + + it("a removed piece cannot be placed again in the same turn", () => { + const g = setUp(new GolombGame(2, ["capture"]), { placed: [["I", I_A, 1]], pool: ALL.filter(p => p !== "I") }); + expect(g.validateMove("xa1 a1 a2 a3 a4 a5").valid).to.be.false; + expect(g.validateMove("xa1 c1 c5").valid).to.be.false; + }); + + it("only your own captured pieces can be removed", () => { + const theirs = setUp(new GolombGame(2, ["capture"]), { placed: [["I", I_A, 2]], pool: ALL.filter(p => p !== "I") }); + expect(theirs.validateMove("xa1 a1 a2 a3 b1 c1").valid).to.be.false; + const neutral = setUp(new GolombGame(2, ["capture"]), { placed: [["I", I_A, 0]], pool: ALL.filter(p => p !== "I") }); + expect(neutral.validateMove("xa1").valid).to.be.false; + }); + + it("the move list includes placements with and without optional removals", () => { + const g = setUp(new GolombGame(2, ["capture"]), { placed: [["I", I_A, 1]], pool: ALL.filter(p => p !== "I") }); + const moves = g.moves(); + expect(moves).to.include("c1 c2 c3 c4 d1"); + expect(moves).to.include("xa1 c1 c2 c3 c4 d1"); + expect(moves).to.include("xa1 a1 a2 a3 b1 c1"); + expect(moves).to.not.include("a1 a2 a3 b1 c1"); + for (const m of moves.filter((_, i) => i % 50 === 0)) { + expect(g.validateMove(m).complete, m).to.equal(0); + expect(g.normaliseMove(m)).to.equal(m); + } + }); + + it("a player whose only room is under their own captured piece can still move", () => { + // free squares: the a1-c3 block (filled by player 1's captured X but + // for its corners) and the g1-g5 strip + const g = setUp(new GolombGame(2, ["capture", "size-7x7"]), { + placed: [["X", ["a2", "b1", "b2", "b3", "c2"], 1]], + blockers: squares(7, 7).filter(c => !/^([a-c][1-3]|g[1-5])$/.test(c)), + pool: ["I", "T", "V"], + currplayer: 2, + }); + g.move("g1 g5"); + expect(g.gameover).to.be.false; + const moves = g.moves(); + expect(moves).to.include("xa2 a1 a2 a3 b1 c1"); + expect(moves.every(m => m.startsWith("xa2 "))).to.be.true; + }); + + it("a position occurring for the fifth time with the same player to move is a draw", () => { + // Each player runs a "pump" of two adjacent holes: they remove the piece they + // captured in one hole and place a piece there that captures the piece next door. + // Player 1 cycles T, U and V through a1-c3 and d1-f3; player 2 cycles L, N and Y + // through a5-b8 and c5-d8. After these 12 plies the board is back where it began. + const open = /^([a-f][1-3]|[a-d][5-8])$/; + const g = setUp(new GolombGame(2, ["capture"]), { + blockers: squares(8, 8).filter(c => !open.test(c)), + placed: [ + ["T", ["a2", "b2", "c1", "c2", "c3"], 1], + ["V", ["d1", "d2", "d3", "e1", "f1"], 0], + ["L", ["a8", "b5", "b6", "b7", "b8"], 2], + ["Y", ["c5", "c6", "c7", "c8", "d6"], 0], + ], + pool: ["F", "I", "N", "P", "U", "W", "X", "Z"], + }); + const cycle = [ + "xa2 b1 b3 c1 c2 c3", "xa8 a7 a8 b5 b6 b7", + "xd1 d1 d2 d3 e2 f2", "xc5 c5 c6 c7 c8 d5", + "xb1 a1 b1 c1 c2 c3", "xa7 a6 b5 b6 b7 b8", + "xd1 d1 d2 d3 e1 e3", "xc5 c5 c6 c7 d7 d8", + "xa1 a2 b2 c1 c2 c3", "xa6 a8 b5 b6 b7 b8", + "xd1 d1 d2 d3 e1 f1", "xc5 c5 c6 c7 c8 d6", + ]; + const start = JSON.stringify(g.placed.map(p => [p.piece, p.owner]).sort()); + // the starting position recurs every 12 plies, so it occurs for the fifth time after 48 + let plies = 0; + while (!g.gameover && plies < 100) { + g.move(cycle[plies % cycle.length]); + plies++; + } + expect(plies).to.equal(48); + expect(JSON.stringify(g.placed.map(p => [p.piece, p.owner]).sort())).to.equal(start); + expect(g.winner).to.deep.equal([1, 2]); + expect(g.results.some(r => r.type === "eog" && r.reason === "repetition")).to.be.true; + assertChatLogParity(g, ["Alice", "Bob"]); + }); + + }); + + describe("simple pie", () => { + const hands = (): Pentomino[][] => [["F", "I", "L", "N", "P", "T"], ["U", "V", "W", "X", "Y", "Z"]]; + + it("after the first placement, the second player may pass to swap hands", () => { + const g = setUp(new GolombGame(2, ["random-hands", "simple-pie"]), { hands: hands() }); + expect(g.moves()).to.not.include("pass"); + expect(g.getButtons()).to.be.empty; + g.move("a1 a5"); + expect(g.moves()).to.include("pass"); + expect(g.getButtons().map(b => b.move)).to.deep.equal(["pass"]); + g.move("pass"); + expect(g.hands).to.deep.equal([["U", "V", "W", "X", "Y", "Z"], ["F", "L", "N", "P", "T"]]); + expect(g.currplayer).to.equal(1); + expect(g.validateMove("pass").valid).to.be.false; + expect(g.getButtons()).to.be.empty; + }); + + it("the swap button passes", () => { + const g = setUp(new GolombGame(2, ["random-hands", "simple-pie"]), { hands: hands() }); + g.move("a1 a5"); + // the client sends a custom "pass" button as a click on "_btn_pass" + const r = g.handleClick("", -1, -1, "_btn_pass"); + expect(r.move).to.equal("pass"); + expect(r.complete).to.equal(1); + const later = setUp(new GolombGame(2, ["random-hands", "simple-pie"]), { hands: hands() }); + expect(later.handleClick("", -1, -1, "_btn_pass").move).to.equal(""); + }); + + it("placing a piece instead keeps the hands", () => { + const g = setUp(new GolombGame(2, ["random-hands", "simple-pie"]), { hands: hands() }); + g.move("a1 a5"); + g.move("c1 c3 e1"); + expect(g.hands).to.deep.equal([["F", "L", "N", "P", "T"], ["U", "W", "X", "Y", "Z"]]); + expect(g.moves()).to.not.include("pass"); + }); + + it("with choose up, passing after the first choice swaps the hands", () => { + const g = new GolombGame(2, ["choose-up", "simple-pie"]); + g.move("F"); + expect(g.moves()).to.include("pass"); + g.move("pass"); + expect(g.hands).to.deep.equal([[], ["F"]]); + expect(g.currplayer).to.equal(1); + expect(g.moves()).to.not.include("pass"); + }); + + it("is silently dropped from games with more than two players", () => { + const g = new GolombGame(3, ["random-hands", "simple-pie"]); + expect(g.variants).to.deep.equal(["random-hands"]); + g.move(g.moves()[0]); + expect(g.moves()).to.not.include("pass"); + expect(g.validateMove("pass").valid).to.be.false; + }); + + }); + + describe("clicking", () => { + it("clicking squares builds a placement, which another empty square confirms", () => { + const g = new GolombGame(); + let r = g.handleClick("", ...rc("a1")); + expect(r.move).to.equal("a1"); + expect(r.complete).to.equal(-1); + r = g.handleClick(r.move, ...rc("a5")); + expect(r.move).to.equal("a1 a5"); + expect(r.complete).to.equal(0); + r = g.handleClick(r.move, ...rc("h8")); + expect(r.move).to.equal("a1 a2 a3 a4 a5"); + expect(r.complete).to.equal(1); + }); + + it("clicking the previewed piece changes nothing, while clicking a placed piece cancels the move", () => { + const g = new GolombGame(); + const same = g.handleClick("a1 a5", ...rc("a3")); + expect(same.move).to.equal("a1 a5"); + expect(same.complete).to.equal(0); + g.move("c1 c5"); + expect(g.handleClick("a1 a5", ...rc("c2")).move).to.equal(""); + expect(g.handleClick("a1", ...rc("c2")).move).to.equal(""); + }); + + it("clicking an already selected square changes nothing", () => { + const g = new GolombGame(); + const r = g.handleClick("a1 a2", ...rc("a2")); + expect(r.valid).to.be.true; + expect(r.move).to.equal("a1 a2"); + expect(r.complete).to.equal(-1); + }); + + it("a square no placement can add cancels the partial placement", () => { + const g = new GolombGame(); + const r = g.handleClick("a1", ...rc("h8")); + expect(r.valid).to.be.true; + expect(r.move).to.equal(""); + }); + + it("in Capture, clicking your captured piece removes it and drops any partial placement", () => { + const g = setUp(new GolombGame(2, ["capture"]), { + placed: [["I", ["a1", "a2", "a3", "a4", "a5"], 1], ["L", ["c1", "c2", "c3", "c4", "d1"], 2]], + pool: ALL.filter(p => p !== "I" && p !== "L"), + }); + let r = g.handleClick("f1 f2", ...rc("a3")); + expect(r.move).to.equal("xa1"); + expect(r.valid).to.be.true; + r = g.handleClick(r.move, ...rc("a1")); + expect(r.move).to.equal("xa1 a1"); + // the opponent's captured piece cancels instead + expect(g.handleClick("xa1 a1", ...rc("c2")).move).to.equal(""); + }); + + it("pieces removed by the move being entered are crossed out in the pool, in the remover's colour", () => { + type Layer = { name?: string; paint?: { fill?: unknown } }; + // the colour of each crossed-out piece shown in an area + const crosses = (game: GolombGame) => { + const rep = game.render(); + const pieces = (rep.areas ?? []).flatMap(a => "pieces" in a ? (a.pieces as string[]) : []); + return pieces.flatMap(key => { + const entry = rep.legend![key]; + const cross = (Array.isArray(entry) ? entry as Layer[] : []).find(l => l.name === "cross-diag"); + return cross === undefined ? [] : [cross.paint?.fill]; + }); + }; + for (const player of [1, 2] as const) { + const g = setUp(new GolombGame(2, ["capture"]), { + placed: [["I", ["a1", "a2", "a3", "a4", "a5"], player]], + pool: ALL.filter(p => p !== "I"), + currplayer: player, + }); + const shown = preview(g, "xa1 c1"); + expect(crosses(shown)).to.deep.equal([player]); + expect(shown.pool).to.include("I"); + // once the move is made, the piece is back in the pool and placeable + g.move("xa1 a1 a2 a3 b1 c1"); + expect(crosses(g)).to.be.empty; + } + }); + + it("during choose up, clicking a pentomino in the pool chooses it", () => { + const g = new GolombGame(2, ["choose-up"]); + const r = g.handleClick("", -1, -1, "X"); + expect(r.move).to.equal("X"); + expect(r.complete).to.equal(1); + expect(g.handleClick("", ...rc("a1")).move).to.equal(""); + }); + + it("once only one placement fits, the piece is shown placed, with its captures", () => { + const g = setUp(new GolombGame(2, ["capture"]), { + placed: [["I", ["a1", "a2", "a3", "a4", "a5"], 0]], + pool: ALL.filter(p => p !== "I"), + }); + const shown = preview(g, "b1 b2 b3 b4 c1"); + expect(shown.placed.find(p => p.piece === "I")!.owner).to.equal(1); + expect(shown.pool).to.not.include("L"); + const rep = shown.render(); + // no preview squares: the piece is drawn like any placed piece + expect(rep.pieces).to.be.null; + const floods = (rep.board as { markers: { type: string; colour: unknown; points: { row: number; col: number }[] }[] }).markers + .filter(m => m.type === "flood"); + const colourAt = (cell: string) => { + const [row, col] = rc(cell); + return floods.find(f => f.points.some(p => p.row === row && p.col === col))?.colour; + }; + expect(colourAt("a3")).to.equal(1); + expect(colourAt("b2")).to.not.be.undefined; + expect(colourAt("b2")).to.not.equal(1); + // the real game is untouched until the move is submitted + expect(g.placed.find(p => p.piece === "I")!.owner).to.equal(0); + }); + + // squares marked with dots, and squares marked as clicked, in a render + const marks = (rep: ReturnType) => { + const dots = new Set(); + for (const a of (rep.annotations ?? []) as { type: string; targets: { row: number; col: number }[] }[]) { + if (a.type === "dots") { + a.targets.forEach(t => dots.add(`${t.row},${t.col}`)); + } + } + const clicked = new Set(); + if (typeof rep.pieces === "string") { + rep.pieces.split("\n").forEach((row, y) => row.split(",").forEach((v, x) => { if (v !== "-") { clicked.add(`${y},${x}`); } })); + } + return { dots, clicked }; + }; + const key = (cell: string) => rc(cell).join(","); + + it("before any input, every empty square some placement could cover has a dot", () => { + const fresh = marks(new GolombGame().render()); + expect(fresh.dots.size).to.equal(64); + expect(fresh.clicked.size).to.equal(0); + // with the I placed along a1-a5, only the X left, a corner square nothing can reach loses its dot + const g = setUp(new GolombGame(), { placed: [["I", ["a1", "a2", "a3", "a4", "a5"], 0]], pool: ["X"] }); + const { dots } = marks(g.render()); + expect(dots.has(key("a3"))).to.be.false; + expect(dots.has(key("h8"))).to.be.false; + expect(dots.has(key("g7"))).to.be.true; + expect(dots.has(key("b1"))).to.be.false; + expect(dots.has(key("c1"))).to.be.true; + }); + + it("while a placement is partly entered, clicked squares are marked and other coverable squares have dots", () => { + const g = new GolombGame(); + const covering = g.moves().filter(m => m.split(" ").includes("a1") && m.split(" ").includes("a2")).flatMap(m => m.split(" ")); + const { dots, clicked } = marks(preview(g, "a1 a2").render()); + expect(clicked).to.deep.equal(new Set([key("a1"), key("a2")])); + expect(dots).to.deep.equal(new Set(covering.filter(c => c !== "a1" && c !== "a2").map(key))); + }); + + it("removing a captured piece frees its squares for the dots", () => { + const g = setUp(new GolombGame(2, ["capture"]), { + placed: [["I", ["a1", "a2", "a3", "a4", "a5"], 1]], + pool: ALL.filter(p => p !== "I"), + }); + expect(marks(g.render()).dots.has(key("a3"))).to.be.false; + expect(marks(preview(g, "xa1").render()).dots.has(key("a3"))).to.be.true; + }); + }); + + describe("records", () => { + it("serializes and restores mid-game", () => { + const g = new GolombGame(2, ["capture"]); + for (const m of ["a1 a5", "b1 b2 b3 b4 c1", "g1 g2 h1 h2 h3"]) { + g.move(m); + } + const restored = new GolombGame(g.serialize()); + expect(restored.currplayer).to.equal(g.currplayer); + expect(restored.placed).to.deep.equal(g.placed); + expect(restored.pool).to.deep.equal(g.pool); + expect(restored.moves()).to.deep.equal(g.moves()); + }); + + it("move log matches the structured chat log", () => { + const pie = new GolombGame(2, ["choose-up", "simple-pie"]); + pie.move("F"); + pie.move("pass"); + for (const pc of ALL.slice(1)) { + pie.move(pc); + } + pie.move(pie.moves()[0]); + assertChatLogParity(pie, ["Alice", "Bob"]); + + const cap = setUp(new GolombGame(2, ["capture", "size-7x7"]), { + placed: [["I", ["a1", "a2", "a3", "a4", "a5"], 1]], + pool: ALL.filter(p => p !== "I"), + }); + cap.move("xa1 a1 a2 a3 b1 c1"); + cap.move("b2 b3 b4 b5 c2"); + while (!cap.gameover) { + cap.move(cap.moves()[0]); + } + assertChatLogParity(cap, ["Alice", "Bob"]); + }); + }); +});