From 703764ee028b171a6c66c6ac95dd7b368f575b2a Mon Sep 17 00:00:00 2001 From: samtcifihi <43021399+samtcifihi@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:12:50 +0000 Subject: [PATCH] Arimaa: Basic and Advanced input modes, and Dicey Moves out of experimental Click entry now has two modes, picked in the input-mode picker. - Basic (the default) moves only the pieces you select, step by step in the order you enter them, so the order decides what traps capture. Pushes and pulls can be entered either way round, and chains work, except the two-piece loop. - Advanced takes a piece and where it should end the turn, and infers whatever else has to move, disturbing as few pieces as it can. Chains work, a triangle on a trap chooses whether the piece sent there is captured, and a click on an empty square with nothing selected moves a piece there when that narrows to one move. - In both, a click that means nothing is a control: an empty square completes the move, and an opposing piece takes back the last token. The same controls work during setup. Moves are stored in canonical Lightvector notation however they were entered, and compare by the position they reach, so premoves match. Old recorded games, including the few with moves the rules no longer allow, replay as before, and the saved-state version is unchanged. Also: - Dicey Moves is no longer experimental. - Standard setup's advice against hiding stronger pieces behind weaker ones now applies behind rabbits too (any piece but a cat). - New help notes; English strings for the input modes, and the changed move-box messages. - arimaa/input.ts holds click entry; setup and the legacy step lists move out of arimaa.ts into arimaa/setup.ts and arimaa/legacy.ts. - The English locale merge reads inputModes from gameApgamesEn. - The playground passes a click result's render options to its preview, as the site does. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_014dzXZzeKPEpGZo9QzCSJUN --- CHANGELOG.md | 17 + locales/en/apgames.json | 21 +- playground/playground.js | 3 +- scripts/lib/apgames-extract-ts.mjs | 2 +- src/games/arimaa.ts | 1111 +++++----------------- src/games/arimaa/input.ts | 919 ++++++++++++++++++ src/games/arimaa/legacy.ts | 317 +++++++ src/games/arimaa/notation.ts | 90 +- src/games/arimaa/setup.ts | 354 +++++++ src/games/arimaa/turns.ts | 575 +++++++++-- test/fixtures/arimaa/coverage.ts | 108 ++- test/games/arimaa-input-modes.test.ts | 1268 +++++++++++++++++++++++++ test/games/arimaa.test.ts | 573 +++++------ 13 files changed, 3985 insertions(+), 1373 deletions(-) create mode 100644 src/games/arimaa/input.ts create mode 100644 src/games/arimaa/legacy.ts create mode 100644 src/games/arimaa/setup.ts create mode 100644 test/games/arimaa-input-modes.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f11a85bc..9da280248 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,8 @@ Since the `1.0.0-beta` release, the version in `package.json` has stayed at `1.0 - **New games:** Clear Path, Kill-All Go, Selfo, Thue-Morse Go, Yodd, Yonkoma (Kill-All Go handicap opening variant remains unrated). - **Quax:** optional **Diamond board** display (`squares-diamonds` with connection flood fill; vertex board remains default). - **Locale tooling:** `npm run audit-locale` (dev-only catalog/shape/stale-MT audit with `locale-src/en/_locale-audit-allowlist.json`); `npm test` includes full-registry **missing catalog key** checks for runtime i18n. +- **Arimaa: Dicey Moves** + - Roll a weighted d4 (weights {1, 1, 1, 3}) and take up to that number of steps each turn (see wiki for details) ### Fixed @@ -53,6 +55,21 @@ Since the `1.0.0-beta` release, the version in `package.json` has stayed at `1.0 - **`handleClick` API:** optional fifth argument **`IHandleClickUi`** (`panelId`, `board` as **`IClickBoardContext`**) for composite panels and draw-grid-aware board clicks; clients pass `ui.board` from the visible `APRenderRep.board` (Abstract Play front and playground ship this for Quax diamond-board). - **Render annotations:** connection paths, win lines, and other undirected polylines use `type: "line"` instead of `type: "move"` with `arrow: false` (dozens of games; piece-slide highlights unchanged in Tintas, Chase, and Swarm; Even at Odds unchanged; Fractured score-track shifts stay `move` with arrows; Sentinel lines-of-sight stay `move` without arrowheads). - **Clear Path:** after a cut-off win the board no longer draws the winner's sealing chain (which steps diagonally and could pass a crosscut); it draws one of the winner's remaining possible connections instead, the one needing the fewest further stones, as a dashed line with the stones still to be placed shown faintly. A completed winning path is still drawn as a solid line. Game description states the cut-off ending, and the move-log line names the winner and the dashed line (`version` `20261117`). +- **Arimaa Input Update:** + - Control Inputs (lowest priority; actual input takes precedence) + - Click on an empty square to mark the move complete + - Click on an opposing piece to undo the last move token + - Basic Input Mode (default) + - Click on a piece and then its destination to move it (and never any other piece) there + - "Chains" work, except for the 2-piece loop chain, which was deemed too easy to accidentally input and get surprised by for Basic Mode (it works in Advanced Mode) + - Pushes and Pulls can be input in either order + - The order you move pieces in determines which pieces are captured and not captured in traps + - Advanced Input Mode + - Click on a piece and then its final destination to move it there + - "Chains" work + - Moves which are necessary to make your input legal are inferred + - When a triangle appears in the corner of a trap square, click it when it's hollow to try to not capture the piece you're moving there, click it when it's filled to try to capture the piece you're moving there + - Clicking on an empty square you can move a piece to without selecting a piece first (called a "target" click/move internally) moves a piece there if it can narrow your intention down to one possibility (see wiki for exact hierarchy) ### Fixed diff --git a/locales/en/apgames.json b/locales/en/apgames.json index 2f4e3610d..8f503234f 100644 --- a/locales/en/apgames.json +++ b/locales/en/apgames.json @@ -550,7 +550,17 @@ }, "inputModes": { "section": "Input mode", - "description": "How the board interprets your clicks for this game." + "description": "How the board interprets your clicks for this game.", + "arimaa": { + "basic": { + "name": "Basic", + "description": "Move only pieces you explicitly select, in the order you enter them. Every completed click sequence has an unambiguous result." + }, + "advanced": { + "name": "Advanced", + "description": "Select by origin or target, and use inferred movements and trap-capture controls." + } + } }, "status": { "_player": "{{player}}", @@ -1029,7 +1039,7 @@ "FROZEN": "The piece at {{where}} is frozen. It cannot move on its own.", "HOME_ROW": "You may only place pieces on the two ranks closest to you.", "INITIAL_INSTRUCTIONS_place": "Select a piece from your hand to place on the board.", - "INITIAL_INSTRUCTIONS_play": "Click a piece, then the square it should end the turn on. You can point at enemy pieces too; pushes and pulls are worked out for you.", + "INITIAL_INSTRUCTIONS_play": "Select a piece, then its destination. Select additional pieces to move them as a chain. Advanced mode also supports target clicks and inferred moves.", "INVALID_PUSH": "Pushes must be immediately completed by moving the pushing piece into the space vacated by the pushed enemy piece.", "INVALID_PUSHPULL": "You may only move enemy pieces when completing a pull or starting a push. Neither seem to apply in this case.", "LABEL_STASH": "{{player}}'s stash", @@ -1058,9 +1068,10 @@ "NO_MOVE_FROZEN": "The piece on {{from}} is frozen, and nothing can free it in time.", "NO_MOVE_REACH": "The piece on {{from}} cannot get to {{to}} within {{num}} steps.", "NO_MOVE_TOGETHER": "Each of those works on its own, but not all of them within {{num}} steps.", - "AMBIGUOUS": "That fits {{count}} different moves. Say where another piece ends up to settle it.", + "AMBIGUOUS": "That fits {{count}} different moves, and the one shown is the one that will be played. Say where another piece ends up to choose another.", + "IDLE": "Nothing moves yet. Say where a piece ends up.", "INFERRED": "Also moving: {{pieces}}.", - "INCOMPLETE": "A piece is selected. Click a square to send it there, or click it again to keep it where it is.", + "INCOMPLETE": "A piece is selected. Click a square to send it there.", "TOO_LONG": "What you have drawn needs more than {{num}} steps.", "DIE_one": "The die allows a single step this turn.", "DIE_other": "The die allows up to {{count}} steps this turn." @@ -4993,7 +5004,7 @@ "akimbo": "Akimbo, designed by Luis Bolaños Mures in 2026, is a drawless connection game for two players. A _naked diagonal_ is a pair of like-colored, diagonally adjacent pieces with no other like-colored piece adjacent to both. A _crosscut_ is a 2×2 area with two interlocking naked diagonals of opposite colors.\n\nOn their turn, the player places a friendly piece on an empty cell. If this completes a crosscut, the other piece in the crosscut is removed. There must never be more than one naked diagonal of each color on the board — not even momentarily before removing a piece. A player wins if, at the end of their turn, there is a chain of orthogonally connected pieces of their color touching the player's two opposite board edges.\n\nOkimba is a variant where only up to one naked diagonal can exist on the board (so while one player has the diagonal, the adversary cannot create another).", "alta": "There are two ways to place switches on the graphical interface: (1) Select the switch’s orientation in the panel, then click on the desired space on the board to place it, or (2) click on two vertices. The vertices are notated with an asterisk, followed by the algebraic notation of the space where the vertex is at the bottom-left corner. To toggle a switch, simply click on the space.", "anache": "This implementation follows David Ploog's rulesheet. Three notable changes are that (1) barriers are forbidden, (2) instead of a 16x16, we have a 15x15 variant, where pieces promote to knights on the centreline, and the dragon may not jump to the 7x7 space from the other corner, and (3) against the corners, pieces are captured via crushing capture instead of custodian capture, so there needs to be at least two opponent pieces in a line before a capture is made against the corners.\n\nNote: the stalemate check is expensive. If you cannot make a legal move, you should resign manually.", - "arimaa": "Made available under section 3 of the [Arimaa public license](https://arimaa.com/arimaa/license/).\n\nDuring standard setup, you only need to place your eight non-rabbits. Once they are down, Complete Move fills the rest of your setup area with rabbits. You can still place any or all of the rabbits yourself first if you want them somewhere in particular.\n\nTo enter a move, click a piece and then the square it should end your turn on. The engine finds the shortest legal way to get it there, pushes and pulls included, and draws one arrow per piece from where it started to where it ends up. You can point at enemy pieces too. Click an arrow's head to extend it, or its tail to remove it. Clicking a selected piece a second time keeps it where it stands, which is how you stop the engine moving it aside. A few rarer turns need one more click; the wiki page for this game lists them all.\n\nMoves are recorded in Lightvector notation, which names each piece and where it ends up rather than listing every step. You can type it into the move box, and the older step-by-step notation is still accepted. The wiki page explains the notation in full.\n\nHarlog is an accepted method for determining material advantage. Positive scores favour Gold, negative Silver. The hard range is ±112, but in practice ±20 is a very strong advantage.\n\nIn Dicey Moves, a player whose die allows a single step has no move, and loses, when only pushes and pulls remain.\n\nBecause we can't generate comprehensive lists of moves, the system cannot detect the rare cases where your only available moves are illegal due to position repetition. The system won't let you make those illegal repetitions, and you'll have to resign manually.", + "arimaa": "Made available under section 3 of the [Arimaa public license](https://arimaa.com/arimaa/license/).\n\nControl Inputs: Click on an empty square to mark the move complete. Click on an opposing piece to undo the last move token.\n\nBasic Input Mode (default): Click on pieces and where you want to move them in the order they must move as per the rules. This mode is intended to be in line with other AP games in terms of intuitiveness and ease of use. See the AP Wiki for more details.\n\nAdvanced Input Mode: Click on pieces and where you want them to end up at the end of the turn. For sending a piece to a trap square, a filled triangle means to capture the piece if possible, an empty triangle means to avoid capturing the piece if possible, and clicking elsewhere on the trap square tries the other/default, which is almost always what you want. Click on certain empty squares to expedite certain sets of steps (cf, AP Wiki: Target Clicks). The system heavily infers steps necessary to make your input legal. This mode is intended to strive for click-efficiency without being too unintuitive once you're used to it. See the AP Wiki for more details (highly recommended).\n\nMoves are recorded in Lightvector notation, which is modeled after algebraic chess notation, albeit more flexible (and using lowercase letters to denote silver pieces). It's backwards-compatible with the Arimaa Gameroom Notation, and the legacy AP notation is still accepted. See the AP Wiki for more details.\n\nHarlog is a method for estimating material advantage. The color of the icon indicates who it favors. The hard range for standard setup is ±112, but in practice ±20 is a very strong advantage.\n\nIn Dicey Moves, a player whose die allows a single step has no move (and loses), if only pushes and pulls remain.\n\nBecause we can't generate comprehensive lists of moves, the system cannot detect the rare cases where your only available moves are illegal due to position repetition. The system won't let you make those illegal repetitions, and you'll have to resign manually.", "armadas": "There are known issues with this game on iOS devices.\n\nThis game offers two scenarios:\n\n* The default is each player having two trios of pieces. In the placement phase, each player must place 1 to 3 ships until all ships are placed.\n* The \"Freeform\" variant allows you to place whatever ships you want (maximum of three at a time) until both players \"pass.\" This lets you create unbalanced or otherwise asymmetrical fleets.\n\nGames default to having one island in the centre of the field. Both a \"no islands\" and a \"two islands\" variant are available. You cannot move or fire through islands. To successfully hit a ship, at least one corner of your ship's triangle must have a clear view of at least one corner of the target ship.\n\nRemember that it is possible to get your ship in a position against an island or the edge of the board such that you can no longer move that ship! Be careful!", "ataxx": "On three-fold repetition, the game ends and the scores are calculated.", "bao": "Moves in Bao can be very complex, involving multiple laps around the board and changing directions. The annotations are, therefore, sparse. The initial cell and direction are highlighted, and captured cells are also marked. But detailed annotation of movement is not possible. If you believe you have encountered a bug, please let us know in Discord.", diff --git a/playground/playground.js b/playground/playground.js index 6dfc4f6d5..0e480195b 100644 --- a/playground/playground.js +++ b/playground/playground.js @@ -594,7 +594,8 @@ function applyPlaygroundClickResult(game, gamename, result) { movebox.classList.add("move-ready"); } if ( ( (result.hasOwnProperty("canrender")) && (result.canrender === true) ) || (result.complete >= 0) ) { - let renderOpts = playgroundRenderOpts(game, gamename); + // a click result's opts are meant for render(), as on the live site + let renderOpts = playgroundRenderOpts(game, gamename, result.opts); applyPlaygroundDisplayRenderOpts(renderOpts); const dotClearPartial = result.valid && diff --git a/scripts/lib/apgames-extract-ts.mjs b/scripts/lib/apgames-extract-ts.mjs index 3edd0d608..c399ffdba 100644 --- a/scripts/lib/apgames-extract-ts.mjs +++ b/scripts/lib/apgames-extract-ts.mjs @@ -263,7 +263,7 @@ export function discoverGameApgamesEnOverlay() { if (!plain) { continue; } - for (const section of ["validation", "variants", "displays", "buttons", "status"]) { + for (const section of ["validation", "variants", "displays", "buttons", "status", "inputModes"]) { if (plain[section] !== undefined) { if (!overlay[section]) { overlay[section] = {}; diff --git a/src/games/arimaa.ts b/src/games/arimaa.ts index 58bb5fee5..44af7a5e6 100644 --- a/src/games/arimaa.ts +++ b/src/games/arimaa.ts @@ -1,19 +1,32 @@ -import { GameBase, IAPGameState, IClickResult, ICustomButton, IIndividualState, IScores, IStatus, IValidationResult, type ChatLogCollectContext, type ChatLogLine, type FlagContext, type GameFlag } from "./_base.js"; +import { GameBase, IAPGameState, IClickResult, ICustomButton, IIndividualState, IScores, IStatus, IValidationResult, IHandleClickUi, IRenderOpts, type ChatLogCollectContext, type ChatLogLine, type FlagContext, type GameFlag } from "./_base.js"; import type { APGamesInformation } from "../schemas/gameinfo.js"; import { APRenderRep, AreaPieces, BoardBasic, Colourfuncs, Glyph, PaintEntry } from "@abstractplay/renderer/build/schemas/schema"; import type { APMoveResult } from "../schemas/moveresults.js"; -import { randomInt, RectGrid, reviver, shuffle, SquareOrthGraph, UserFacingError, cloneState } from "../common/index.js"; +import { reviver, UserFacingError, cloneState } from "../common/index.js"; import i18next from "i18next"; -import { arrowToken, captureToken, isArrow, isLegacy, isMark, isHold, joinMove, normalize, parseMove, pieceChar, holdToken, tokenText, NotationError, type ParsedMove, type Token } from "./arimaa/notation.js"; -import { hasAnyMove, inferred, resolve, serializeTurn, sqName, turnFromSteps, type Turn } from "./arimaa/turns.js"; +import { isArrow, isLegacy, isLower, isMark, normalize, parseMove, pc2name, pieceChar, tokenText, NotationError, type ParsedMove, type Token } from "./arimaa/notation.js"; +import { STRENGTH, display, hasAnyMove, inferred, isAlone, isFrozen, resolve, serializeTurn, sqName, turnFromSteps, type Turn } from "./arimaa/turns.js"; import { castDie, type IDie } from "./arimaa/dice.js"; +import { ARIMAA_CAPTURE_CHOICE, ARIMAA_SPARE_CHOICE, captureAlternatives, captureChoices, declared, inputClick, pendingPush, type InputClick } from "./arimaa/input.js"; +import { baseMove, classify, validateLegacyMovement, type StepKind } from "./arimaa/legacy.js"; +import { endlessEndgame, fillRabbits, placing, setupClick, standardSetup, validateSetup } from "./arimaa/setup.js"; export const gameApgamesEn = { + inputModes: { + basic: { + name: "Basic", + description: "Move only pieces you explicitly select, in the order you enter them. Every completed click sequence has an unambiguous result.", + }, + advanced: { + name: "Advanced", + description: "Select by origin or target, and use inferred movements and trap-capture controls.", + }, + }, validation: { BACKWARDS: "You may not move your own rabbits backwards.", FROZEN: "The piece at {{where}} is frozen. It cannot move on its own.", HOME_ROW: "You may only place pieces on the two ranks closest to you.", INITIAL_INSTRUCTIONS_place: "Select a piece from your hand to place on the board.", - INITIAL_INSTRUCTIONS_play: "Click a piece, then the square it should end the turn on. You can point at enemy pieces too; pushes and pulls are worked out for you.", + INITIAL_INSTRUCTIONS_play: "Select a piece, then its destination. Select additional pieces to move them as a chain. Advanced mode also supports target clicks and inferred moves.", INVALID_PUSH: "Pushes must be immediately completed by moving the pushing piece into the space vacated by the pushed enemy piece.", INVALID_PUSHPULL: "You may only move enemy pieces when completing a pull or starting a push. Neither seem to apply in this case.", LABEL_STASH: "{{player}}'s stash", @@ -42,9 +55,10 @@ export const gameApgamesEn = { NO_MOVE_FROZEN: "The piece on {{from}} is frozen, and nothing can free it in time.", NO_MOVE_REACH: "The piece on {{from}} cannot get to {{to}} within {{num}} steps.", NO_MOVE_TOGETHER: "Each of those works on its own, but not all of them within {{num}} steps.", - AMBIGUOUS: "That fits {{count}} different moves. Say where another piece ends up to settle it.", + AMBIGUOUS: "That fits {{count}} different moves, and the one shown is the one that will be played. Say where another piece ends up to choose another.", + IDLE: "Nothing moves yet. Say where a piece ends up.", INFERRED: "Also moving: {{pieces}}.", - INCOMPLETE: "A piece is selected. Click a square to send it there, or click it again to keep it where it is.", + INCOMPLETE: "A piece is selected. Click a square to send it there.", TOO_LONG: "What you have drawn needs more than {{num}} steps.", DIE_one: "The die allows a single step this turn.", DIE_other: "The die allows up to {{count}} steps this turn.", @@ -95,14 +109,8 @@ export type playerid = 1|2; export type Piece = "E" | "M" | "H" | "D" | "C" | "R"; export type CellContents = [Piece, playerid]; -export const pc2name = new Map([ - ["E", "Elephant"], - ["M", "Camel"], - ["H", "Horse"], - ["D", "Dog"], - ["C", "Cat"], - ["R", "Rabbit"], -]); +export { pc2name }; +// the order the free setup has always reported its captures in const traps = ["f3", "f6", "c3", "c6"]; export interface IMoveState extends IIndividualState { @@ -128,10 +136,12 @@ interface ILegendObj { [key: string]: Glyph|[Glyph, ...Glyph[]]; } -function isLower(character: string): boolean { - return character === character.toLowerCase() && character !== character.toUpperCase(); +/** `inputMode` is the mode a click was made in, as `handleClick` returns it in its result's `opts`. */ +interface IArimaaRenderOpts extends IRenderOpts { + inputMode?: string; } + export class ArimaaGame extends GameBase { public static readonly gameinfo: APGamesInformation = { name: "Arimaa", @@ -140,7 +150,7 @@ export class ArimaaGame extends GameBase { version: "20251223", dateAdded: "2026-01-23", description: "The pieces are animals of various strengths jockeying for position, trying to get one of their rabbits to the far row. But watch out for traps!", - notes: "Made available under section 3 of the [Arimaa public license](https://arimaa.com/arimaa/license/).\n\nDuring standard setup, you only need to place your eight non-rabbits. Once they are down, Complete Move fills the rest of your setup area with rabbits. You can still place any or all of the rabbits yourself first if you want them somewhere in particular.\n\nTo enter a move, click a piece and then the square it should end your turn on. The engine finds the shortest legal way to get it there, pushes and pulls included, and draws one arrow per piece from where it started to where it ends up. You can point at enemy pieces too. Click an arrow's head to extend it, or its tail to remove it. Clicking a selected piece a second time keeps it where it stands, which is how you stop the engine moving it aside. A few rarer turns need one more click; the wiki page for this game lists them all.\n\nMoves are recorded in Lightvector notation, which names each piece and where it ends up rather than listing every step. You can type it into the move box, and the older step-by-step notation is still accepted. The wiki page explains the notation in full.\n\nHarlog is an accepted method for determining material advantage. Positive scores favour Gold, negative Silver. The hard range is ±112, but in practice ±20 is a very strong advantage.\n\nIn Dicey Moves, a player whose die allows a single step has no move, and loses, when only pushes and pulls remain.\n\nBecause we can't generate comprehensive lists of moves, the system cannot detect the rare cases where your only available moves are illegal due to position repetition. The system won't let you make those illegal repetitions, and you'll have to resign manually.", + notes: "Made available under section 3 of the [Arimaa public license](https://arimaa.com/arimaa/license/).\n\nControl Inputs: Click on an empty square to mark the move complete. Click on an opposing piece to undo the last move token.\n\nBasic Input Mode (default): Click on pieces and where you want to move them in the order they must move as per the rules. This mode is intended to be in line with other AP games in terms of intuitiveness and ease of use. See the AP Wiki for more details.\n\nAdvanced Input Mode: Click on pieces and where you want them to end up at the end of the turn. For sending a piece to a trap square, a filled triangle means to capture the piece if possible, an empty triangle means to avoid capturing the piece if possible, and clicking elsewhere on the trap square tries the other/default, which is almost always what you want. Click on certain empty squares to expedite certain sets of steps (cf, AP Wiki: Target Clicks). The system heavily infers steps necessary to make your input legal. This mode is intended to strive for click-efficiency without being too unintuitive once you're used to it. See the AP Wiki for more details (highly recommended).\n\nMoves are recorded in Lightvector notation, which is modeled after algebraic chess notation, albeit more flexible (and using lowercase letters to denote silver pieces). It's backwards-compatible with the Arimaa Gameroom Notation, and the legacy AP notation is still accepted. See the AP Wiki for more details.\n\nHarlog is a method for estimating material advantage. The color of the icon indicates who it favors. The hard range for standard setup is ±112, but in practice ±20 is a very strong advantage.\n\nIn Dicey Moves, a player whose die allows a single step has no move (and loses), if only pushes and pulls remain.\n\nBecause we can't generate comprehensive lists of moves, the system cannot detect the rare cases where your only available moves are illegal due to position repetition. The system won't let you make those illegal repetitions, and you'll have to resign manually.", urls: [ "https://arimaa.com/arimaa/", "https://arimaa.com/arimaa/learn/rulesIntro.html", @@ -176,7 +186,7 @@ export class ArimaaGame extends GameBase { ], }, { uid: "free", group: "setup", unrated: true }, - { uid: "dicey", experimental: true }, + { uid: "dicey", experimental: false }, ], customizations: [ { @@ -216,6 +226,10 @@ export class ArimaaGame extends GameBase { explanation: "Traps are the `fill` colour at 50% opacity" }, ], + inputModes: [ + {uid: "basic", group: "entry"}, + {uid: "advanced", group: "entry"}, + ], categories: ["goal>breakthrough", "goal>cripple", "goal>immobilize", "mechanic>capture", "mechanic>move", "mechanic>coopt", "mechanic>random>setup", "board>shape>rect", "board>connect>rect", "components>chess"], flags: ["perspective", "no-moves", "custom-buttons", "random-start", "custom-colours"] }; @@ -235,102 +249,10 @@ export class ArimaaGame extends GameBase { return GameBase.algebraic2coords(cell, 8); } public static strength(piece: Piece): number { - const str = "EMHDCR"; - return str.length - str.indexOf(piece); - } - // the two ranks a player sets up on, in the order they get auto-filled - private static homeCells(player: playerid): string[] { - const cells: string[] = []; - for (const row of (player === 1 ? [6,7] : [0,1])) { - for (let col = 0; col < 8; col++) { - cells.push(ArimaaGame.coords2algebraic(col, row)); - } - } - return cells; + return STRENGTH[piece]; } public static EEE(): {gold: [Piece, string][], silver: [Piece, string][]} { - const getRanks = (ranks: number[]): string[] => { - const cells: string[] = []; - for (const row of ranks) { - for (let col = 0; col < 8; col++) { - cells.push(ArimaaGame.coords2algebraic(col, row)); - } - } - return cells; - } - - let gold: Piece[]; - do { - gold = ["E"]; - // camels - let limit = randomInt(1, 0); - for (let i = 0; i < limit; i++) { - gold.push("M"); - } - // horses, dogs, cats - for (const pc of ["H","D","C"] as const) { - limit = randomInt(2, 0); - for (let i = 0; i < limit; i++) { - gold.push(pc); - } - } - // rabbits - limit = randomInt(8, 1); - for (let i = 0; i < limit; i++) { - gold.push("R"); - } - } while (gold.length < 4 || gold.length > 12); - const cellsGold = shuffle(getRanks([6,7])); - const combinedGold: [Piece, string][] = []; - for (let i = 0; i < gold.length; i++) { - combinedGold.push([gold[i], cellsGold[i]]); - } - const flip = randomInt(1, 0); - const combinedSilver: [Piece, string][] = []; - combinedGold.forEach(([pc, cell]) => { - const [col, row] = ArimaaGame.algebraic2coords(cell); - // rows reverse no matter what - let newRow: number; - if (row === 6) { - newRow = 1; - } else { - newRow = 0; - } - // reverse columns only if flip is 1 - let newCol = col; - if (flip === 1) { - newCol = 7 - col; - } - combinedSilver.push([pc, ArimaaGame.coords2algebraic(newCol, newRow)]); - }); - return {gold: combinedGold, silver: combinedSilver}; - } - - // strip any parentheticals and just return the base move - private static baseMove(mv: string): [Piece, playerid, string?, string?] { - mv = mv.replace(/\s+/g, ""); - const idx = mv.indexOf("("); - let base = mv; - if (idx >= 0) { - base = mv.slice(0, idx); - } - const pcStr = base[0]; - let player: playerid; - if (isLower(pcStr)) { - player = 2; - } else { - player = 1; - } - const pc = pcStr.toUpperCase() as Piece; - let from: string|undefined; - if (base.length > 1) { - from = base.substring(1,3); - } - let to: string|undefined; - if (base.length > 3) { - to = base.substring(3); - } - return [pc, player, from, to]; + return endlessEndgame(); } public numplayers = 2; @@ -346,10 +268,11 @@ export class ArimaaGame extends GameBase { public stack!: Array; public results: Array = []; private _selected: string|undefined; + private _selections: string[]|undefined; + private _entryMove: string|undefined; // the player's arrows, kept for drawing when they do not yet resolve to a move private _arrows: Array<[string, string]>|undefined; - // the squares of the player's holds and capture marks, drawn whether or not the move resolves - private _holds: string[]|undefined; + // the squares of the player's capture marks, drawn whether or not the move resolves private _marks: string[]|undefined; constructor(state?: IArimaaState | string, variants?: string[]) { @@ -426,20 +349,16 @@ export class ArimaaGame extends GameBase { // what a turn did is drawn from its results; anything left over from a // partial move belongs to the entry being typed, not to this state this._selected = undefined; + this._selections = undefined; + this._entryMove = undefined; this._arrows = undefined; - this._holds = undefined; this._marks = undefined; return this; } - // the standard 16-piece setup, which the setup variants replace - private standardSetup(): boolean { - return !this.variants.includes("eee") && !this.variants.includes("free"); - } - public getButtons(): ICustomButton[] { // base game, gold setup - if (this.standardSetup() && this.stack.length === 1) { + if (standardSetup(this.variants) && this.stack.length === 1) { return [ { label: "apgames:buttons.arimaa.gold99", @@ -448,7 +367,7 @@ export class ArimaaGame extends GameBase { ]; } // base game, silver setup - else if (this.standardSetup() && this.stack.length === 2) { + else if (standardSetup(this.variants) && this.stack.length === 2) { return [ { label: "apgames:buttons.arimaa.silver99e7", @@ -463,135 +382,9 @@ export class ArimaaGame extends GameBase { return []; } - // In standard setup, a player only needs to place their eight non-rabbits. - // Once they have, the rest of their setup area gets filled with rabbits. - // Returns the move untouched in every other circumstance. - private fillRabbits(m: string): string { - if (!this.standardSetup() || this.hands === undefined || this.hands[this.currplayer - 1].length === 0) { - return m; - } - const mvs = m.split(",").filter(Boolean); - const steps = mvs.map(mv => ArimaaGame.baseMove(mv)); - const myhand = [...this.hands[this.currplayer - 1]]; - for (const [pc, , cell] of steps) { - // a dangling piece selection or anything the validator will reject - if (cell === undefined || !myhand.includes(pc)) { - return m; - } - myhand.splice(myhand.indexOf(pc), 1); - } - // everything but the rabbits has to be placed already - if (myhand.length === 0 || myhand.some(pc => pc !== "R")) { - return m; - } - const placedCells = new Set(steps.map(([,,cell,]) => cell!)); - const empty = ArimaaGame.homeCells(this.currplayer).filter(cell => !this.board.has(cell) && !placedCells.has(cell)); - if (empty.length !== myhand.length) { - return m; - } - return [...mvs, ...empty.map(cell => `${this.currplayer === 1 ? "R" : "r"}${cell}`)].join(","); - } - - // A very niche helper function to fix the "can't push pull at same time" issue - // Looks at each move in a chain and determines the nature of each. - // Naive. Just looks at the notation and sequence, not board context. - public static classify(player: playerid, moves: string[]): ("placement"|"pusher"|"puller"|"pushee"|"pullee"|"mover"|undefined)[] { - const classifications: ("placement"|"pusher"|"puller"|"pushee"|"pullee"|"mover"|undefined)[] = []; - - for (let i = 0; i < moves.length; i++) { - const [, owner, from, to] = ArimaaGame.baseMove(moves[i]); - // if mine: - // - placement if to is undefined - // - pusher if previous was pushed - // - puller if next is enemy and moves into vacated space - // - mover otherwise - if (owner === player) { - if (to === undefined) { - classifications.push("placement"); - } else if (i > 0 && classifications[i - 1] === "pushee") { - classifications.push("pusher"); - } else { - if (i < moves.length - 1) { - const [, nextOwner, , nextTo] = ArimaaGame.baseMove(moves[i + 1]); - if (nextOwner !== player && nextTo === from) { - classifications.push("puller"); - } else { - classifications.push("mover"); - } - } else { - classifications.push("mover"); - } - } - } - // if other: - // - pullee if previous is puller - // - pushee if previous is not puller and next is mine moving into space - // - undefined otherwise - else { - if (i > 0 && classifications[i - 1] === "puller") { - classifications.push("pullee"); - } else { - if (i < moves.length - 1) { - const [, nextOwner, , nextTo] = ArimaaGame.baseMove(moves[i + 1]); - if (nextOwner === player && nextTo === from) { - classifications.push("pushee"); - } else { - classifications.push(undefined); - } - } else { - classifications.push(undefined); - } - } - } - } - - return classifications; - } - - private isFrozen(cell: string): boolean { - const g = new SquareOrthGraph(8, 8); - if (!this.board.has(cell)) { - throw new Error("You can't check the frozen status of a nonexistent piece."); - } - const [pc, owner] = this.board.get(cell)!; - const friendlies: Piece[] = []; - const enemies: Piece[] = []; - for (const n of g.neighbours(cell)) { - if (this.board.has(n)) { - const [nPc, nOwner] = this.board.get(n)!; - if (nOwner === owner) { - friendlies.push(nPc); - } else { - enemies.push(nPc); - } - } - } - // only ever frozen if no friendlies and at least one stronger enemy - if (friendlies.length === 0) { - for (const enemy of enemies) { - if (ArimaaGame.strength(enemy) > ArimaaGame.strength(pc)) { - return true; - } - } - } - // otherwise free - return false; - } - - private isAlone(cell: string): boolean { - if (this.board.has(cell)) { - const [, owner] = this.board.get(cell)!; - const g = new SquareOrthGraph(8, 8); - for (const n of g.neighbours(cell)) { - if (this.board.has(n)) { - const [, nOwner] = this.board.get(n)!; - if (nOwner === owner) { - return false; - } - } - } - } - return true; + // what each step of a legacy step list is (see arimaa/legacy.ts) + public static classify(player: playerid, moves: string[]): StepKind[] { + return classify(player, moves); } // chains together a random series of moves @@ -601,14 +394,43 @@ export class ArimaaGame extends GameBase { // return moves[Math.floor(Math.random() * moves.length)]; // } - public handleClick(move: string, row: number, col: number, piece?: string): IClickResult { + public handleClick(move: string, row: number, col: number, piece?: string, ui?: IHandleClickUi): IClickResult { try { // placing pieces: // - either still pieces in hand // - or we're in standard setup and ply 1 or 2, no matter the hands - const placing = (this.hands !== undefined && this.hands[this.currplayer - 1].length > 0) || - (this.standardSetup() && this.stack.length <= 2); - const newmove = placing ? this.setupClick(move, row, col, piece) : this.moveClick(move, row, col); + const setup = placing(this.hands, this.currplayer) || + (standardSetup(this.variants) && this.stack.length <= 2); + const advanced = this.resolveActiveInputMode(ui?.inputMode) === "advanced"; + // The custom SVG triangle is an ordinary clickable renderer + // piece. Its reserved keys (one per way it is drawn) distinguish + // its click from a click on the trap square itself, without + // affecting actual board pieces. + const square = row >= 0 && row < 8 && col >= 0 && col < 8 ? + ArimaaGame.coords2algebraic(col, row) : undefined; + const isCaptureChoice = piece === ARIMAA_CAPTURE_CHOICE || piece === ARIMAA_SPARE_CHOICE; + const alternativeCapture = !setup && isCaptureChoice && + advanced && square !== undefined && + captureAlternatives(this.board, this.currplayer, this.maxSteps(), move).includes(square); + // render() is not told the input mode and runs on a fresh game + // object, but clients hand a click's `opts` on to it: that is how + // the preview of an Advanced entry gets its trap controls. + const withMode = (r: IClickResult): IClickResult => { + if (advanced && !setup && r.move.length > 0) { + const opts: IArimaaRenderOpts = {inputMode: "advanced"}; + r.opts = opts; + } + return r; + }; + // a control that is not on offer does nothing, and neither does + // a click off the board once the pieces are down + if ((isCaptureChoice && !alternativeCapture) || (!setup && square === undefined)) { + return withMode({...this.validateMove(move), move}); + } + const input: InputClick = setup ? setupClick(this, move, row, col, piece) : + inputClick(this.board, this.currplayer, this.maxSteps(), move, square!, + advanced ? "advanced" : "basic", alternativeCapture); + const newmove = input.move; let result = this.validateMove(newmove) as IClickResult; if (! result.valid) { result.move = move; @@ -620,8 +442,14 @@ export class ArimaaGame extends GameBase { } else { result.move = newmove; } + if (input.complete && result.valid && result.complete === 0) { + result.complete = 1; + } else if (input.oneOf !== undefined && result.valid && result.complete === 0) { + // the click had more than one equally good way to go + result.message = `${result.message} ${i18next.t("apgames:validation.arimaa.AMBIGUOUS", {count: input.oneOf})}`; + } } - return result; + return withMode(result); } catch (e) { // console.log(e); return { @@ -632,213 +460,9 @@ export class ArimaaGame extends GameBase { } } - // Setup clicks work on the comma-separated placement list. - private setupClick(move: string, row: number, col: number, piece?: string): string { - let newmove = ""; - const steps = move.split(",").filter(Boolean).map(mv => ArimaaGame.baseMove(mv)); - let lastPc: Piece|undefined; - let lastPlayer: playerid|undefined; - let lastFrom: string|undefined; - let lastTo: string|undefined; - if (steps.length > 0) { - [lastPc,lastPlayer,lastFrom,lastTo] = steps[steps.length - 1]; - } - let lastmove = ""; - let stub = move; - if (steps.length > 0) { - // set lastmove and stub if move is incomplete - // placement - if (this.hands !== undefined && this.hands[this.currplayer - 1].length > 0 && lastFrom === undefined) { - lastmove = this.currplayer === 1 ? lastPc! : lastPc!.toLowerCase(); - stub = move.substring(0, move.lastIndexOf(",")); - } - // movement - else if ((this.hands === undefined || this.hands[this.currplayer - 1].length === 0) && (lastFrom !== undefined && lastTo === undefined) ) { - lastmove = `${lastPlayer === 1 ? lastPc : lastPc!.toLowerCase()}${lastFrom}`; - stub = move.substring(0, move.lastIndexOf(",")); - } - } - // console.log(JSON.stringify({move, lastPc, lastFrom, lastTo, lastmove, stub})); - // make the moves in the stub - const cloned = this.clone(); - cloned.move(stub, {partial: true}); - - // clicking off the board resets - if (row === -1 || col === -1) { - const [,pc, pstr] = piece!.split(""); - const p = parseInt(pstr, 10); - newmove = `${stub}${stub.length > 0 ? "," : ""}${p === 1 ? pc : pc.toLowerCase()}`; - } else { - const cell = ArimaaGame.coords2algebraic(col, row); - // clicking a placed cell unplaces it - if (cloned.board.has(cell)) { - // clicking an occupied cell after selecting a piece to place - if (lastmove.length === 0) { - // the click may land on the piece glyph or on the empty part of - // the square (then `piece` is empty), so go by what's on the board - const [occupant,] = cloned.board.get(cell)!; - const idx = steps.findIndex(([pc,,f,]) => pc === occupant && f === cell); - if (idx >= 0) { - steps.splice(idx, 1); - newmove = steps.map(([pc, p, f,]) => `${p === 1 ? pc : pc.toLowerCase()}${f}`).join(","); - } else { - newmove = stub; - } - } else { - newmove = stub; - } - } else { - // if just clicking directly on the board, choose a piece for them: - // in free setup the hand never empties, so default to a rabbit; - // otherwise take the strongest piece still in hand - if (lastmove === undefined || lastmove === "") { - let dflt: Piece; - if (this.variants.includes("free")) { - dflt = "R"; - } else { - dflt = [...cloned.hands![cloned.currplayer - 1]].sort((a,b) => ArimaaGame.strength(b) - ArimaaGame.strength(a))[0]; - } - lastmove = cloned.currplayer === 1 ? dflt : dflt.toLowerCase(); - } - newmove = `${stub}${stub.length > 0 ? "," : ""}${lastmove}${cell}`; - } - } - - return newmove; - } - - // Movement clicks work on the drawn tokens; the rules are in the branch - // comments below. The move string holds destination tokens (arrows, and - // holds: a piece sent to its own square), capture marks (a hold on a trap, - // clicked once more), anything typed, and at most two trailing bare - // squares: the selected piece awaiting a destination and, before it, the - // selection that a second click on the current one completes an arrow from. - private moveClick(move: string, row: number, col: number): string { - let parsed: ParsedMove; - try { - parsed = parseMove(move, true); - } catch { - // unreadable typed input: start over from this click - parsed = {tokens: []}; - } - const clicked = ArimaaGame.coords2algebraic(col, row); - const drawn = parsed.tokens.filter(t => isArrow(t) || isHold(t) || isMark(t)); - const others = parsed.tokens.filter(t => !drawn.includes(t)); - let pending = parsed.pending; - let previous = parsed.previous; - const tailOf = (sq: string): number => drawn.findIndex(t => isArrow(t) && t.spec.square === sq); - const headOf = (sq: string): number => drawn.findIndex(t => isArrow(t) && (t.prop as {square: string}).square === sq); - // every arrow ending on this square, latest first: more than one piece - // can finish on a trap, the ones that died there and at most one alive - const headsOf = (sq: string): Token[] => drawn.filter(t => isArrow(t) && (t.prop as {square: string}).square === sq).reverse(); - const holdOf = (sq: string): number => drawn.findIndex(t => isHold(t) && t.spec.square === sq); - const markOf = (sq: string): number => drawn.findIndex(t => isMark(t) && t.spec.square === sq); - // occupancy is judged at the start of the turn; a square whose piece - // already has an arrow away from it counts as vacated - const unvacatedPiece = (sq: string): boolean => this.board.has(sq) && tailOf(sq) < 0; - const mkArrow = (from: string, to: string): Token => { - const [pc, owner] = this.board.get(from)!; - return arrowToken(pc, owner, from, to); - }; - // a capture asserted of an arrow's piece rides with that arrow: it says - // the piece dies where the arrow sends it, so it goes when the arrow does - const dropMark = (origin: string): void => { - const m = markOf(origin); - if (m >= 0) { - drawn.splice(m, 1); - } - }; - // send what is selected at `from` to `to`: a new arrow from a piece's - // square, or the extension of the arrow whose head was re-opened - const complete = (from: string, to: string): void => { - if (unvacatedPiece(from)) { - drawn.push(mkArrow(from, to)); - return; - } - const h = headOf(from); - if (h >= 0) { - const tail = drawn[h].spec.square!; - dropMark(tail); - if (tail === to) { - drawn.splice(headOf(from), 1); - } else { - drawn[headOf(from)] = mkArrow(tail, to); - } - } - }; - - if (pending !== undefined) { - if (clicked === pending) { - if (previous !== undefined) { - // the second click on an occupied square sends the - // selection before it there; its occupant will have to move - complete(previous, clicked); - } else if (traps.includes(clicked) && headOf(clicked) >= 0) { - // the second click on an arrow's head, when that head is a - // trap, says the piece dies there rather than surviving on - // it; the arrow stays, because it says which trap. This - // comes before holding, because whatever still stands on - // the trap cannot survive alongside what is arriving. The - // claim falls on the last arrow drawn to that trap that - // does not carry one yet, and once they all do, clicking - // again takes them all back. - const heads = headsOf(clicked); - const next = heads.find(t => markOf(t.spec.square!) < 0); - if (next === undefined) { - for (const t of heads) { - dropMark(t.spec.square!); - } - } else { - const [pc, owner] = this.board.get(next.spec.square!)!; - drawn.push(captureToken(pc, owner, next.spec.square!)); - } - } else if (unvacatedPiece(clicked) && holdOf(clicked) < 0 && markOf(clicked) < 0) { - // the second click on a selected piece holds it where it stands - const [pc, owner] = this.board.get(clicked)!; - drawn.push(holdToken(pc, owner, clicked)); - } - // a re-opened arrow head is simply released - pending = undefined; - previous = undefined; - } else if (unvacatedPiece(clicked)) { - // re-selection rather than a destination; the selection it - // replaces is kept in case the next click confirms this square - previous = unvacatedPiece(pending) || headOf(pending) >= 0 ? pending : undefined; - pending = clicked; - } else { - complete(pending, clicked); - pending = undefined; - previous = undefined; - } - } else { - const t = tailOf(clicked); - const p = holdOf(clicked); - if (t >= 0) { - // grabbing an arrow's tail removes it and starts a new one - dropMark(clicked); - drawn.splice(tailOf(clicked), 1); - pending = clicked; - } else if (p >= 0 && traps.includes(clicked)) { - // on a trap a hold cannot tell survival from capture, so a - // click on it turns the hold into a capture mark - const [pc, owner] = this.board.get(clicked)!; - drawn[p] = captureToken(pc, owner, clicked); - } else if (p >= 0 || markOf(clicked) >= 0) { - // a hold or a capture mark is lifted like an arrow's tail - drawn.splice(p >= 0 ? p : markOf(clicked), 1); - pending = clicked; - } else if (this.board.has(clicked) || headOf(clicked) >= 0) { - pending = clicked; - } else { - return move; - } - } - return joinMove([...others, ...drawn], pending, previous); - } - public validateMove(m: string): IValidationResult { const result: IValidationResult = {valid: false, message: i18next.t("apgames:validation._general.DEFAULT_HANDLER")}; - const setup = this.hands !== undefined && this.hands[this.currplayer - 1].length > 0; + const setup = placing(this.hands, this.currplayer); // placement and legacy step lists ignore whitespace; the notation is space-delimited if (setup || isLegacy(m)) { m = m.replace(/\s+/g, ""); @@ -855,7 +479,7 @@ export class ArimaaGame extends GameBase { result.canrender = true; } result.canrender = true; - result.message = i18next.t("apgames:validation.arimaa.INITIAL_INSTRUCTIONS", {context: (this.hands !== undefined && this.hands[this.currplayer - 1].length > 0) ? "place" : "play"}); + result.message = i18next.t("apgames:validation.arimaa.INITIAL_INSTRUCTIONS", {context: placing(this.hands, this.currplayer) ? "place" : "play"}); // Dicey Moves: lead with what the die allows if (this.die !== undefined) { result.message = [i18next.t("apgames:validation.arimaa.DIE", {count: this.die.steps}), result.message].join(" "); @@ -864,375 +488,14 @@ export class ArimaaGame extends GameBase { } if (setup) { - return this.validateSetup(m); + return validateSetup(this.board, this.hands![this.currplayer - 1], this.currplayer, this.variants, m); } if (isLegacy(m)) { - return this.validateLegacyMovement(m); + return validateLegacyMovement(this, m, this.maxSteps()); } return this.validateNotation(m); } - private validateSetup(m: string): IValidationResult { - const result: IValidationResult = {valid: false, message: i18next.t("apgames:validation._general.DEFAULT_HANDLER")}; - const g = new SquareOrthGraph(8, 8); - // capture tokens written at the end of free setup carry no instruction - const steps = m.split(",").filter(Boolean).filter(mv => !mv.startsWith("x")).map(mv => ArimaaGame.baseMove(mv)); - const cloned = this.clone(); - const myhand = [...cloned.hands![cloned.currplayer - 1]]; - for (const [pc, , cell] of steps) { - // must have pc in hand - if (!myhand.includes(pc)) { - result.valid = false; - result.message = i18next.t("apgames:validation.arimaa.NOPIECE", {piece: pc2name.get(pc)}); - return result; - } - if (cell !== undefined) { - // cell must be valid - try { - ArimaaGame.algebraic2coords(cell); - } catch { - result.valid = false; - result.message = i18next.t("apgames:validation._general.INVALIDCELL", {cell}); - return result; - } - // cell must be empty, including of anything placed earlier in this move - if (cloned.board.has(cell)) { - result.valid = false; - result.message = i18next.t("apgames:validation._general.OCCUPIED", {where: cell}); - return result; - } - // in normal play, must be on home ranks - if (!this.variants.includes("free")) { - const homeRows = this.currplayer === 1 ? [6,7] : [0,1]; - const [,y] = ArimaaGame.algebraic2coords(cell); - if (!homeRows.includes(y)) { - result.valid = false; - result.message = i18next.t("apgames:validation.arimaa.HOME_ROW"); - return result; - } - } - // fake place the piece - cloned.board.set(cell, [pc, cloned.currplayer]); - // remove the piece from the hand unless in free mode - if (!this.variants.includes("free")) { - myhand.splice(myhand.indexOf(pc), 1); - } - } - // if it's just a piece number, we need a cell - else { - result.valid = true; - result.complete = -1; - result.message = i18next.t("apgames:validation.arimaa.PARTIAL_PLACE"); - return result; - } - } - - // if we've gotten this far, everything is valid - // now we just have to check completeness and return - let complete: -1|0|1; - let message: string; - // in free mode: - // - usually 0 with specific message - // - but must have 1 rabbit and none on the goal row - if (this.variants.includes("free")) { - const rabbits = [...cloned.board.entries()].filter(e => e[1][1] === cloned.currplayer && e[1][0] === "R").map(e => e[0]); - const goal = cloned.currplayer === 1 ? "8" : "1"; - if (rabbits.length === 0 || rabbits.filter(cell => cell.endsWith(goal)).length > 0) { - complete = -1; - message = i18next.t("apgames:validation.arimaa.PARTIAL_FREE_NO") - } else { - complete = 0; - message = i18next.t("apgames:validation.arimaa.PARTIAL_FREE") - } - } - // otherwise, you have to place all your pieces, - // though the rabbits can be filled in for you - else { - const emptyHome = ArimaaGame.homeCells(cloned.currplayer).filter(c => !cloned.board.has(c)); - const autoRabbits = myhand.length > 0 && myhand.every(pc => pc === "R") && emptyHome.length === myhand.length; - if (myhand.length > 0 && !autoRabbits) { - complete = -1; - message = i18next.t("apgames:validation.arimaa.PARTIAL_PLAY") - } else { - // fake place the rabbits so the advice below sees the real setup - if (autoRabbits) { - for (const cell of emptyHome) { - cloned.board.set(cell, ["R", cloned.currplayer]); - } - } - // warnings go here - const warnings: string[] = []; - // same file (only silver) - if (this.currplayer === 2) { - const [e1, e2] = [...cloned.board.entries()].filter(e => e[1][0] === "E").map(e => e[0][0]); - if (e1 === e2) { - warnings.push(i18next.t("apgames:validation.arimaa.WARN_FILE") || "WARN"); - } - } - // unbalanced (gold and silver) - const majors = [...cloned.board.entries()].filter(e => e[1][1] === this.currplayer && ["E", "M", "H"].includes(e[1][0])).map(e => ArimaaGame.algebraic2coords(e[0])[0]); - const oneSide = majors.filter(n => n < 5).length; - if (oneSide === 0 || oneSide === 4) { - warnings.push(i18next.t("apgames:validation.arimaa.WARN_BALANCE") || "WARN"); - } - // hiding (gold and silver) - const frontRow = this.currplayer === 1 ? 6 : 1; - const backRow = this.currplayer === 1 ? 7 : 0; - for (let col = 0; col < 8; col++) { - const frontCell = g.coords2algebraic(col, frontRow); - const backCell = g.coords2algebraic(col, backRow); - const front = cloned.board.get(frontCell)![0]; - const back = cloned.board.get(backCell)![0]; - if (ArimaaGame.strength(front) < ArimaaGame.strength(back)) { - if (front !== "R" && back !== "C") { - warnings.push(i18next.t("apgames:validation.arimaa.WARN_HIDE") || "WARN"); - break; - } - } - } - if (warnings.length > 0) { - complete = 0; - message = [i18next.t("apgames:validation.arimaa.WARNINGS"), ...warnings].join(" "); - } else { - // complete is never 1 for setup - complete = 0; - message = i18next.t("apgames:validation._general.VALID_MOVE") - } - if (autoRabbits) { - message = [i18next.t("apgames:validation.arimaa.PARTIAL_RABBITS"), message].join(" "); - } - } - } - - result.valid = true; - result.canrender = true; - result.complete = complete; - result.message = message; - return result; - - } - - // The pre-notation movement grammar: comma-separated `` - // steps with optional capture parentheticals. Kept verbatim so every - // historical move string still validates exactly as it did. - private validateLegacyMovement(m: string): IValidationResult { - const result: IValidationResult = {valid: false, message: i18next.t("apgames:validation._general.DEFAULT_HANDLER")}; - const g = new SquareOrthGraph(8, 8); - // This validator once had two lapses: a push completed by a piece of - // equal strength when a stronger one was also adjacent, and a pull that - // moved the pulled piece somewhere other than the square the puller - // vacated. Both are rejected here, so no new move can use them. A few - // recorded games contain such a move; they replay through `trusted`, - // which skips validation entirely, so no saved game is disturbed. - const classifications = ArimaaGame.classify(this.currplayer, m.split(",").filter(Boolean)); - const steps = m.split(",").filter(Boolean).map(mv => ArimaaGame.baseMove(mv)); - // can't make too many moves - const maxMoves = this.maxSteps(); - if (steps.length > maxMoves) { - result.valid = false; - result.message = i18next.t("apgames:validation.arimaa.TOO_MANY", {num: maxMoves}); - return result; - } - const cloned = this.clone(); - // pushPending is used to make sure pushes are completed - let pushPending = false; - // validate each step - for (let i = 0; i < steps.length; i++) { - const [pc, owner, from, to] = steps[i]; - // console.log(JSON.stringify({pc, owner, from, to})); - // validate from first - if (from === undefined) { - throw new Error("From should never be undefined at this point."); - } - // valid cell - try { - ArimaaGame.algebraic2coords(from); - } catch { - result.valid = false; - result.message = i18next.t("apgames:validation._general.INVALIDCELL", {cell: from}); - return result; - } - // from contents match - if (!cloned.board.has(from) || cloned.board.get(from)![0] !== pc || cloned.board.get(from)![1] !== owner) { - result.valid = false; - result.message = i18next.t("apgames:validation._general.NONEXISTENT"); - return result; - } - // if it's your piece, it can't be frozen - if (owner === cloned.currplayer && cloned.isFrozen(from)) { - result.valid = false; - result.message = i18next.t("apgames:validation.arimaa.FROZEN", {where: from}); - return result; - } - // if a push is pending, then this move *must* be completing the push - if (pushPending) { - const [lastPc, lastPlayer, lastFrom] = steps[i - 1]; - // lastPlayer must be the enemy - // from must be adjacent to lastFrom - // to must equal lastFrom - // pc must be stronger than lastPc - if (lastPlayer === cloned.currplayer || !g.neighbours(lastFrom!).includes(from) || (to !== undefined && to !== lastFrom) || ArimaaGame.strength(pc) <= ArimaaGame.strength(lastPc)) { - result.valid = false; - result.message = i18next.t("apgames:validation.arimaa.INVALID_PUSH", {where: from}); - return result; - } - pushPending = false; - // if this is the last step, suggest an autocomplete - if (i === steps.length - 1 && to === undefined) { - result.autocomplete = m + lastFrom; - } - } - // if it's an enemy piece, it must be a push or pull - if (owner !== cloned.currplayer) { - // check for pulls first - let validPull = false; - if (i > 0 && classifications[i - 1] !== "pusher") { - const [lastPc, lastPlayer, lastFrom] = steps[i - 1]; - const ns = g.neighbours(from); - if (lastPlayer === cloned.currplayer && ns.includes(lastFrom!) && ArimaaGame.strength(lastPc) > ArimaaGame.strength(pc) && (to === undefined || to === lastFrom)) { - validPull = true; - // check if push is possible - let canPush = false; - if (i < maxMoves - 1) { - for (const n of g.neighbours(from)) { - if (cloned.board.has(n)) { - const [nPc, nOwner] = cloned.board.get(n)!; - if (nOwner === cloned.currplayer && ArimaaGame.strength(nPc) > ArimaaGame.strength(pc) && !cloned.isFrozen(n)) { - canPush = true; - break; - } - } - } - } - // if this is the last step, suggest an autocomplete - if (i === steps.length - 1 && to === undefined) { - if (i === maxMoves - 1 || !canPush) { - result.autocomplete = m + lastFrom; - } - } - } - } - // if there is no valid pull, then it must be a push and be completed - // on the next step - if (!validPull) { - pushPending = true; - // for it to be a valid pending push, the current player must have - // an unfrozen, stronger piece adjacent - let validPush = false; - for (const n of g.neighbours(from)) { - if (cloned.board.has(n)) { - const [nPc, nOwner] = cloned.board.get(n)!; - if (nOwner === cloned.currplayer && ArimaaGame.strength(nPc) > ArimaaGame.strength(pc) && !cloned.isFrozen(n)) { - validPush = true; - } - } - } - if (!validPush) { - result.valid = false; - result.message = i18next.t("apgames:validation.arimaa.INVALID_PUSHPULL", {where: from}); - return result; - } - } - } - - // partial move at the end of the chain - if (from !== undefined && to === undefined && i === steps.length - 1) { - result.valid = true; - result.complete = -1; - result.message = i18next.t("apgames:validation.arimaa.PARTIAL_MOVE"); - result.canrender = true; - return result; - } - // otherwise from and to must be defined - else if (from === undefined || to === undefined) { - throw new Error("From and to should never be undefined at this point."); - } - - // to is a valid cell - try { - ArimaaGame.algebraic2coords(to); - } catch { - result.valid = false; - result.message = i18next.t("apgames:validation._general.INVALIDCELL", {cell: to}); - return result; - } - // to is empty - if (cloned.board.has(to)) { - result.valid = false; - result.message = i18next.t("apgames:validation._general.OCCUPIED", {where: to}); - return result; - } - // to is orthogonally adjacent - if (!g.neighbours(from).includes(to)) { - result.valid = false; - result.message = i18next.t("apgames:validation.arimaa.NOT_ADJ"); - return result; - } - // you can't move your own rabbits backwards - const forbidden = cloned.currplayer === 1 ? "S" : "N"; - if (pc === "R" && owner === cloned.currplayer) { - const [fx, fy] = ArimaaGame.algebraic2coords(from); - const [tx, ty] = ArimaaGame.algebraic2coords(to); - const bearing = RectGrid.bearing(fx, fy, tx, ty)!; - if (bearing.startsWith(forbidden)) { - result.valid = false; - result.message = i18next.t("apgames:validation.arimaa.BACKWARDS", {where: from}); - return result; - } - } - - // fake execute the step - const moved = cloned.board.get(from)!; - cloned.board.set(to, moved); - cloned.board.delete(from); - // check traps - for (const trap of traps) { - if (cloned.board.has(trap) && cloned.isAlone(trap)) { - cloned.board.delete(trap); - } - } - } - - // At this point, everything is valid. - // Verify completeness and board state repetition and return. - // Because partial moves that are invalid can become valid with further steps, - // we can't return `valid: false`; return `complete: -1` instead. - let complete: -1|0|1; - let message: string; - // if the board position hasn't changed, then -1 - if (cloned.signature() === this.signature()) { - complete = -1; - message = i18next.t("apgames:validation.arimaa.NOPASS"); - } - // if third occurrence of position, then -1 - else if (cloned.numRepeats() >= 2) { - complete = -1; - message = i18next.t("apgames:validation.arimaa.REPEAT"); - } - // if a push is pending, then -1 - else if (pushPending) { - complete = -1; - message = i18next.t("apgames:validation.arimaa.PARTIAL_PUSH"); - } - // if the number of moves are < max moves, then 0 - else if (steps.length < maxMoves) { - const remaining = maxMoves - steps.length; - complete = 0; - message = i18next.t("apgames:validation.arimaa.PARTIAL", {count: remaining}); - } - // otherwise we're good - else { - complete = 1; - message = i18next.t("apgames:validation._general.VALID_MOVE"); - } - - result.valid = true; - result.canrender = true; - result.complete = complete; - result.message = message; - return result; - } - // Steps the mover may take this turn: what the die says in Dicey Moves, // two for the opening move of Endless endgame, otherwise four. private maxSteps(): number { @@ -1284,9 +547,10 @@ export class ArimaaGame extends GameBase { return `${pc}${sqName(tr.start)}${sqName(tr.final)}`; } - // Lightvector notation: resolve the tokens leniently and report: invalid for - // unreadable or unsatisfiable input, -1 while ambiguous, selecting or - // repeating, 1 only for a full turn with nothing inferred, otherwise 0. + // Lightvector notation: find the turn the tokens are shown as and report: + // invalid for unreadable or unsatisfiable input; -1 while nothing moves + // yet, a piece is only selected, or the position would repeat; otherwise + // 0, so that the move stays open to editing until the player completes it. private validateNotation(m: string): IValidationResult { const result: IValidationResult = {valid: false, message: i18next.t("apgames:validation._general.DEFAULT_HANDLER")}; let parsed: ParsedMove; @@ -1301,52 +565,60 @@ export class ArimaaGame extends GameBase { result.message = i18next.t("apgames:validation.arimaa.TOO_LONG", {num: maxMoves}); return result; } + // a push entered step by step waits for the piece that pushes + const awaitsPusher = (shown: Map): boolean => + pendingPush(shown, this.currplayer, parsed.selections ?? []) !== undefined; // only a selected piece so far if (parsed.tokens.length === 0) { result.valid = true; result.complete = -1; result.canrender = true; - result.message = i18next.t("apgames:validation.arimaa.PARTIAL_MOVE"); + result.message = i18next.t(awaitsPusher(this.board) ? "apgames:validation.arimaa.PARTIAL_PUSH" : "apgames:validation.arimaa.PARTIAL_MOVE"); return result; } - const r = resolve(this.board, this.currplayer, maxMoves, parsed.tokens, true); - if (r.status === "unsatisfiable") { + const d = display(this.board, this.currplayer, maxMoves, parsed.tokens); + if (d.status === "unsatisfiable") { result.message = this.explainUnsatisfiable(parsed.tokens, maxMoves); return result; } result.valid = true; result.canrender = true; - if (r.status === "ambiguous") { - result.complete = -1; - result.message = i18next.t("apgames:validation.arimaa.AMBIGUOUS", {count: r.positions}); - return result; - } - // the move is known; repetition is checked only now - const cloned = this.clone(); - cloned.applyTurn(r.turn); - if (cloned.numRepeats() >= 2) { - result.complete = -1; - result.message = i18next.t("apgames:validation.arimaa.REPEAT"); - return result; - } - const extra = inferred(r.turn, parsed.tokens); - const used = r.turn.steps.length; const messages: string[] = []; - if (used === maxMoves) { - // auto-completion only when the player has seen every piece that moves - result.complete = extra.length === 0 ? 1 : 0; - messages.push(i18next.t("apgames:validation._general.VALID_MOVE")); + let shown = this.board; + if (d.status === "idle") { + // pieces are only held where they stand: there is no move to submit yet + result.complete = -1; + messages.push(i18next.t("apgames:validation.arimaa.IDLE")); } else { + // the move is known; repetition is checked only now + const cloned = this.clone(); + cloned.applyTurn(d.turn); + shown = cloned.board; + if (cloned.numRepeats() >= 2) { + result.complete = -1; + result.message = i18next.t("apgames:validation.arimaa.REPEAT"); + return result; + } result.complete = 0; - messages.push(i18next.t("apgames:validation.arimaa.PARTIAL", {count: maxMoves - used})); - } - if (extra.length > 0) { - messages.push(i18next.t("apgames:validation.arimaa.INFERRED", {pieces: extra.map(tr => this.describeTrajectory(tr)).join(", ")})); + const used = d.turn.steps.length; + if (used === maxMoves) { + messages.push(i18next.t("apgames:validation._general.VALID_MOVE")); + } else { + messages.push(i18next.t("apgames:validation.arimaa.PARTIAL", {count: maxMoves - used})); + } + // an entry that ends with the steps of its turn names every piece in them: what else it says is what was asked for + const extra = inferred(d.turn, declared(parsed.tokens, d.turn)); + if (extra.length > 0) { + messages.push(i18next.t("apgames:validation.arimaa.INFERRED", {pieces: extra.map(tr => this.describeTrajectory(tr)).join(", ")})); + } + if (d.by === "choice") { + // what is shown is one of several moves the entry fits, and it is the one a submission plays + messages.push(i18next.t("apgames:validation.arimaa.AMBIGUOUS", {count: d.positions})); + } } if (parsed.pending !== undefined) { - // a selected piece never submits on its own; the hint says what a click does - result.complete = 0; - messages.push(i18next.t("apgames:validation.arimaa.INCOMPLETE")); + // a selection is dropped on submission; the hint says what a click does + messages.push(i18next.t(awaitsPusher(shown) ? "apgames:validation.arimaa.PARTIAL_PUSH" : "apgames:validation.arimaa.INCOMPLETE")); } result.message = messages.join(" "); return result; @@ -1386,7 +658,7 @@ export class ArimaaGame extends GameBase { if (to !== undefined && to !== from && occupant[0] === "R" && (this.currplayer === 1 ? to[1] < from[1] : to[1] > from[1])) { return i18next.t("apgames:validation.arimaa.BACKWARDS"); } - if (this.isFrozen(from)) { + if (isFrozen(this.board, from)) { return i18next.t("apgames:validation.arimaa.NO_MOVE_FROZEN", {from}); } if (to !== undefined && to !== from) { @@ -1400,7 +672,7 @@ export class ArimaaGame extends GameBase { throw new UserFacingError("MOVES_GAMEOVER", i18next.t("apgames:validation._general.MOVES_GAMEOVER")); } - const setup = this.hands !== undefined && this.hands[this.currplayer - 1].length > 0; + const setup = placing(this.hands, this.currplayer); if (setup || isLegacy(m)) { m = m.replace(/\s+/g, ""); } else { @@ -1415,7 +687,7 @@ export class ArimaaGame extends GameBase { // top up a standard setup with the rabbits the player didn't place // (a no-op on a setup that's already complete, so replays are unaffected) if (!partial) { - m = this.fillRabbits(m); + m = fillRabbits(this.board, this.hands, this.currplayer, this.variants, m); } const initial = this.clone(); // used to triple check that the board state changes @@ -1427,8 +699,9 @@ export class ArimaaGame extends GameBase { this.results.push({type: "roll", values: [this.die.steps]}); } this._selected = undefined; + this._selections = undefined; + this._entryMove = undefined; this._arrows = undefined; - this._holds = undefined; this._marks = undefined; if (m.length > 0) { if (setup) { @@ -1442,7 +715,7 @@ export class ArimaaGame extends GameBase { } else { const turn = this.applyNotation(m, partial); if (turn !== undefined && !partial) { - lastmove.push(serializeTurn(initial.board, this.currplayer, this.maxSteps(), turn) ?? m); + lastmove.push(serializeTurn(initial.board, this.currplayer, this.maxSteps(), turn) ?? turn.steps.map(st => `${pieceChar(st.piece, st.owner)}${sqName(st.from)}${st.dir}`).join(" ")); } } } @@ -1454,7 +727,7 @@ export class ArimaaGame extends GameBase { // failsafe checks // except for "free" variant, nobody should have pieces in hand at the end of the turn if (!this.variants.includes("free")) { - if (this.hands !== undefined && this.hands[this.currplayer - 1].length > 0) { + if (placing(this.hands, this.currplayer)) { throw new Error("Players should only have empty hands at the end of the turn."); } } @@ -1482,7 +755,7 @@ export class ArimaaGame extends GameBase { // After free setup, activate all traps if (this.variants.includes("free") && this.stack.length === 2) { for (const trap of traps) { - if (this.board.has(trap) && this.isAlone(trap)) { + if (this.board.has(trap) && isAlone(this.board, trap)) { const [trapPc, trapOwner] = this.board.get(trap)!; this.board.delete(trap); this.results.push({type: "destroy", what: trapOwner === 1 ? trapPc : trapPc.toLowerCase(), where: trap}); @@ -1534,7 +807,7 @@ export class ArimaaGame extends GameBase { this.board.delete(from); this.results.push({type: "move", from, to}); for (const trap of traps) { - if (this.board.has(trap) && this.isAlone(trap)) { + if (this.board.has(trap) && isAlone(this.board, trap)) { const [trapPc, trapOwner] = this.board.get(trap)!; this.board.delete(trap); this.results.push({type: "destroy", what: trapOwner === 1 ? trapPc : trapPc.toLowerCase(), where: trap}); @@ -1552,7 +825,7 @@ export class ArimaaGame extends GameBase { // Placement: returns the notation for each piece placed. private applySetup(m: string): string[] { const parts: string[] = []; - const steps = m.split(",").filter(Boolean).filter(mv => !mv.startsWith("x")).map(mv => ArimaaGame.baseMove(mv)); + const steps = m.split(",").filter(Boolean).filter(mv => !mv.startsWith("x")).map(mv => baseMove(mv)); for (let i = 0; i < steps.length; i++) { const [pc, , from] = steps[i]; if (from !== undefined) { @@ -1575,7 +848,7 @@ export class ArimaaGame extends GameBase { private applyLegacy(m: string): {steps: Array<{from: string; to: string}>; legacy: string[]} { const taken: Array<{from: string; to: string}> = []; const legacy: string[] = []; - const steps = m.split(",").filter(Boolean).map(mv => ArimaaGame.baseMove(mv)); + const steps = m.split(",").filter(Boolean).map(mv => baseMove(mv)); for (let i = 0; i < steps.length; i++) { const [pc, owner, from, to] = steps[i]; if (from !== undefined && to !== undefined) { @@ -1593,34 +866,46 @@ export class ArimaaGame extends GameBase { return {steps: taken, legacy}; } - // Lightvector notation: resolve and play the turn. Returns nothing when a - // partial move does not (yet) denote one; the arrows are kept for drawing. + // Lightvector notation: play the turn the tokens are shown as. Returns + // nothing when a partial move does not (yet) denote one; the arrows are + // kept for drawing. private applyNotation(m: string, partial: boolean): Turn|undefined { // a selection never blocks a submission: it is simply dropped const parsed = parseMove(m, true); this._selected = parsed.pending; + this._selections = parsed.selections; + this._entryMove = m; if (parsed.tokens.length === 0) { + this.drawPendingPush(parsed); return undefined; } - const r = resolve(this.board, this.currplayer, this.maxSteps(), parsed.tokens, true); - if (r.status !== "resolved") { + const d = display(this.board, this.currplayer, this.maxSteps(), parsed.tokens); + if (d.status !== "turn") { if (!partial) { - throw new UserFacingError("VALIDATION_GENERAL", i18next.t(r.status === "ambiguous" ? "apgames:validation.arimaa.AMBIGUOUS" : "apgames:validation.arimaa.NO_MOVE", {count: r.status === "ambiguous" ? r.positions : 0})); + throw new UserFacingError("VALIDATION_GENERAL", i18next.t(d.status === "idle" ? "apgames:validation.arimaa.NOPASS" : "apgames:validation.arimaa.NO_MOVE")); } // the move does not yet denote a turn, so draw what was entered this._arrows = parsed.tokens.filter(isArrow).map(t => [t.spec.square!, (t.prop as {square: string}).square]); - this._holds = parsed.tokens.filter(isHold).map(t => t.spec.square!); this._marks = parsed.tokens.filter(isMark).map(t => t.spec.square!); + if (d.status === "idle") { + this.drawPendingPush(parsed); + } return undefined; } - this.applyTurn(r.turn); + this.applyTurn(d.turn); if (partial) { - // the turn's own results draw its arrows and captures, but a held - // piece leaves no trace in them, and the player needs to see that - // the hold is there (a click on it lifts it) - this._holds = parsed.tokens.filter(isHold).map(t => t.spec.square!); + this.drawPendingPush(parsed); + } + return d.turn; + } + + // The enemy piece's step of a push entered step by step is drawn as an + // arrow while the pusher's step is still to come. + private drawPendingPush(parsed: ParsedMove): void { + const push = pendingPush(this.board, this.currplayer, parsed.selections ?? []); + if (push !== undefined) { + this._arrows = [...(this._arrows ?? []), [push.from, push.to]]; } - return r.turn; } protected checkEOG(): ArimaaGame { @@ -1709,7 +994,7 @@ export class ArimaaGame extends GameBase { }; } - public render(): APRenderRep { + public render(opts: IArimaaRenderOpts = {}): APRenderRep { // Build piece string const plst: string[] = []; for (let row = 0; row < 8; row++) { @@ -1718,7 +1003,7 @@ export class ArimaaGame extends GameBase { const cell = ArimaaGame.coords2algebraic(col, row); if (this.board.has(cell)) { const [pc, owner] = this.board.get(cell)!; - pieces.push(`${pc}${owner}${this.isFrozen(cell) ? "x" : ""}`); + pieces.push(`${pc}${owner}${isFrozen(this.board, cell) ? "x" : ""}`); } else { pieces.push("-"); } @@ -1792,7 +1077,7 @@ export class ArimaaGame extends GameBase { // add an area if the current player has pieces to place let areas: AreaPieces[]|undefined; - if (this.hands !== undefined && this.hands[this.currplayer - 1].length > 0) { + if (placing(this.hands, this.currplayer)) { // add pieces to legend with wider click boxes to the legend for (const [key, pc] of [...Object.entries(legend)]) { if (key !== "T" && !Array.isArray(pc)) { @@ -1885,6 +1170,46 @@ export class ArimaaGame extends GameBase { }); } + // Advanced trap capture control: one custom SVG triangle is both the + // visible control and its hit shape. Unlike an ordinary shading + // marker, the renderer gives board pieces a click handler. The + // triangle is filled where clicking it has the piece captured, and + // a thick outline where it keeps the piece alive; the outline's + // interior is painted fully transparent so that it is still hit. + if (opts.inputMode === "advanced" && this._entryMove !== undefined && this._selected !== undefined) { + const original = this.stack[this.stack.length - 1].board; + const choices = captureChoices(original, this.currplayer, this.maxSteps(), this._entryMove); + if (choices.size > 0) { + rep.glyphDefs = {}; + // Board pieces normally have a 0.85 placement inset. Cancel it + // to align the polygon exactly to the grid: x=[0.5,1], y=[0,0.5] + // of the trap cell. + const paint = {func: "flatten", fg: "_context_fill", bg: "_context_board", opacity: 0.5} as const; + if ([...choices.values()].includes(true)) { + rep.glyphDefs["arimaa-trap-choice"] = { + viewBox: [0, 0, 100, 100], + markup: '', + }; + legend[ARIMAA_CAPTURE_CHOICE] = {def: "arimaa-trap-choice", scale: 1 / 0.85, paint: {fill: paint}}; + } + if ([...choices.values()].includes(false)) { + rep.glyphDefs["arimaa-trap-spare"] = { + viewBox: [0, 0, 100, 100], + markup: '', + }; + legend[ARIMAA_SPARE_CHOICE] = {def: "arimaa-trap-spare", scale: 1 / 0.85, paint: {fill: paint}}; + } + // This is a render-only extra layer. The actual game board, + // saved moves and the mode-independent pieces stay unchanged. + const layers = plst.map(line => line.split(",").map(key => key === "-" ? [] : [key])); + for (const [trap, captured] of choices) { + const [x, y] = ArimaaGame.algebraic2coords(trap); + layers[y][x].push(captured ? ARIMAA_CAPTURE_CHOICE : ARIMAA_SPARE_CHOICE); + } + rep.pieces = [layers[0], ...layers.slice(1)]; + } + } + // Add annotations: one arrow per piece from where it started the turn // to where it ended up, the enter glyph for a piece back where it began, // and the exit glyph on a trap that claimed a piece @@ -1893,7 +1218,6 @@ export class ArimaaGame extends GameBase { const [x, y] = ArimaaGame.algebraic2coords(cell); return {row: y, col: x}; }; - const entered = new Set(); const exited = new Set(); for (const tr of ArimaaGame.trajectoriesFromResults(this.results)) { if (tr.start !== tr.final) { @@ -1904,7 +1228,6 @@ export class ArimaaGame extends GameBase { exited.add(tr.final); } else if (tr.start === tr.final) { rep.annotations.push({type: "enter", targets: [point(tr.start)]}); - entered.add(tr.start); } } for (const r of this.results) { @@ -1918,15 +1241,7 @@ export class ArimaaGame extends GameBase { rep.annotations.push({type: "move", targets: [point(from), point(to)]}); } } - // holds are drawn as the piece entering its own square, capture marks as it leaving - if (this._holds !== undefined) { - for (const sq of this._holds) { - if (!entered.has(sq) && !exited.has(sq)) { - rep.annotations.push({type: "enter", targets: [point(sq)]}); - entered.add(sq); - } - } - } + // capture marks are drawn as the piece leaving if (this._marks !== undefined) { for (const sq of this._marks) { if (!exited.has(sq)) { @@ -1935,16 +1250,16 @@ export class ArimaaGame extends GameBase { } } } - // show selected piece if present - if (this._selected !== undefined) { - const [x, y] = ArimaaGame.algebraic2coords(this._selected); + // A chain can have several selected pieces. Highlight each square, + // including an enemy which is about to be pushed or pulled. + for (const square of this._selections ?? (this._selected === undefined ? [] : [this._selected])) { + const [x, y] = ArimaaGame.algebraic2coords(square); (rep.board as BoardBasic).markers!.push({ type: "flood", colour: this.getPlayerColour(this.currplayer), opacity: 0.25, points: [{row: y, col: x}], }); - // rep.annotations.push({type: "enter", targets: [{row: y, col: x}]}); } if (rep.annotations.length === 0) { delete rep.annotations; diff --git a/src/games/arimaa/input.ts b/src/games/arimaa/input.ts new file mode 100644 index 000000000..24094330e --- /dev/null +++ b/src/games/arimaa/input.ts @@ -0,0 +1,919 @@ +/** + * Click entry for Arimaa: what a click on the board does to the move being + * entered, in each of the two input modes. + * + * The entry is a move string: tokens, then the squares of the selected pieces, + * oldest first. Clicks name squares of the board as it is drawn, which is the + * board after the turn the tokens are shown as (`display`). + * + * Basic plays what it is told and nothing else. A destination click adds the + * steps of the selected pieces, written as step tokens, after the steps + * already entered, so that steps happen in the order they were entered. + * + * Advanced says where pieces end up and leaves the rest to the engine. Its + * tokens name a piece by the square it started the turn on, and sending a + * piece somewhere else replaces what was said of it. What is left open it + * settles by preferences of its own (`choose`), which are not the notation's: + * above all it moves no piece it was not told to if it can help it, even at + * the cost of steps. An entry is read by the notation wherever it goes next, + * so when the notation would read what was said as some other turn, the entry + * ends with the steps of the turn meant, and those it can read no other way. + */ +import { + arrowToken, captureToken, joinSelections, parseMove, stepsToken, surviveToken, + type Dir, type ParsedMove, type Piece, type Token, type playerid, +} from "./notation.js"; +import { + NEIGHBOURS, STRENGTH, TRAP_SQUARES as TRAPS, boardSignature, canMoveWithin, choose, dirBetween, display, fewestDisplaced, manhattan, + preferences, resolve, serializeTurn, sqIndex, sqName, standing, + type CellContents, type Displayed, type Found, type Turn, type TurnStep, +} from "./turns.js"; + +export type ArimaaInputMode = "basic" | "advanced"; +export interface InputClick { + move: string; + complete?: boolean; + /** Advanced: how many moves what was said fits, when the one shown is no better than another of them */ + oneOf?: number; +} + +/** + * Reserved renderer-only legend key for the Advanced alternative trap outcome. + * + * This is not a real board occupant. It is a single custom SVG triangle in + * the render representation, and the renderer forwards its identifier with + * ordinary board-piece clicks. + */ +export const ARIMAA_CAPTURE_CHOICE = "ARIMAA_CAPTURE_CHOICE"; + +/** The same control drawn as an outline, where clicking it keeps the piece alive. */ +export const ARIMAA_SPARE_CHOICE = "ARIMAA_SPARE_CHOICE"; + + +type Board = Map; + +/** A piece as drawn, with the square it started the turn on. */ +interface Shown { + piece: Piece; + owner: playerid; + origin: string; +} + +/** What the player is looking at: the turn the tokens are shown as and the board after it. */ +interface View { + /** the position the turn starts from: the board, whose turn it is, and the steps it may take */ + board: Board; + player: playerid; + limit: number; + tokens: Token[]; + /** whether the tokens end with the list of the steps of the turn shown, as an Advanced entry may */ + listed: boolean; + /** what Advanced takes the tokens to say of the turn */ + said: Token[]; + /** false when no turn fits the tokens */ + fits: boolean; + turn?: Turn; + /** whether the tokens denote `turn` on their own, with no preference applied */ + settled: boolean; + shown: Map; + after: Board; + /** steps not yet spent */ + left: number; +} + +const text = (tokens: Token[]): string => tokens.map(t => t.text).join(" "); + +function look(board: Board, player: playerid, limit: number, tokens: Token[]): View { + const shown = new Map(); + for (const [cell, [piece, owner]] of board) { + shown.set(cell, {piece, owner, origin: cell}); + } + const d = display(board, player, limit, tokens); + const turn = d.status === "turn" ? d.turn : undefined; + if (turn !== undefined) { + let next = 0; + turn.steps.forEach((st, i) => { + const from = sqName(st.from); + shown.set(sqName(st.to), shown.get(from)!); + shown.delete(from); + for (; next < turn.captures.length && turn.captures[next].afterStep === i; next++) { + shown.delete(sqName(turn.captures[next].square)); + } + }); + } + const after: Board = new Map([...shown].map(([cell, p]): [string, CellContents] => [cell, [p.piece, p.owner]])); + const stated = declared(tokens, turn); + return { + board, player, limit, tokens, turn, shown, after, + listed: stated.length < tokens.length, + said: turn === undefined ? stated : endings(stated, turn), + fits: d.status !== "unsatisfiable", + settled: d.status === "turn" && d.by === "notation", + left: limit - (turn?.steps.length ?? 0), + }; +} + +/** The same position with other tokens entered. */ +const lookAgain = (v: View, tokens: Token[]): View => look(v.board, v.player, v.limit, tokens); + +/** One step token for each run of consecutive steps by one piece. */ +function runs(steps: TurnStep[]): Token[] { + const out: Token[] = []; + for (let i = 0; i < steps.length;) { + const first = steps[i]; + const dirs: Dir[] = []; + for (; i < steps.length && steps[i].pid === first.pid; i++) { + dirs.push(steps[i].dir); + } + out.push(stepsToken(first.piece, first.owner, sqName(first.from), dirs)); + } + return out; +} + +/** + * The tokens of an entry less the list of the steps of the turn it is shown + * as, when it ends with one after saying something else. That list is how an + * Advanced entry makes the notation read it as the turn meant; it is not + * something the player said. + */ +export function declared(tokens: Token[], turn: Turn | undefined): Token[] { + const listed = turn === undefined ? [] : runs(turn.steps); + const at = tokens.length - listed.length; + if (listed.length > 0 && at > 0 && listed.every((t, i) => tokens[at + i].text === t.text)) { + return tokens.slice(0, at); + } + return tokens; +} + +// What tokens say of where pieces end up. Advanced goes by nothing else, and +// a step token, typed or entered in Basic, says only that a piece took a +// step: left at that, the piece would be walked back to where it started. +// So in place of step tokens, every piece the turn shown displaces or +// captures is said to end as it does there. +function endings(tokens: Token[], turn: Turn): Token[] { + if (!tokens.some(t => t.prop.kind === "steps")) { + return tokens; + } + const out = tokens.filter(t => t.prop.kind !== "steps"); + for (const tr of turn.trajectories) { + const start = sqName(tr.start); + const t = tr.captured ? captureToken(tr.type, tr.owner, start) : + tr.final !== tr.start ? arrowToken(tr.type, tr.owner, start, sqName(tr.final)) : undefined; + if (t !== undefined && !out.some(o => o.text === t.text)) { + out.push(t); + } + } + return out; +} + +// What an explicit completion submits: the entry itself where it needs no +// preference to be read and holds nothing that is only for input, otherwise +// the turn shown, written so that it does. +function committed(v: View): string { + if (v.settled && !v.listed && !v.tokens.some(t => t.prop.kind === "survive")) { + return text(v.tokens); + } + return serializeTurn(v.board, v.player, v.limit, v.turn!) ?? text(v.tokens); +} + +// --------------------------------------------------------------------------- +// Basic + +/** Whether the entry is a step list that is played exactly as it is written. */ +function literal(v: View): boolean { + let steps = 0; + for (const t of v.tokens) { + if (t.prop.kind !== "steps" || t.spec.piece === undefined || t.spec.square === undefined) { + return false; + } + steps += t.prop.dirs.length; + } + return v.turn !== undefined && v.turn.steps.length === steps; +} + +/** The entry as the steps it is shown as. */ +function sofar(v: View): Token[] { + return literal(v) ? v.tokens : v.turn === undefined ? [] : runs(v.turn.steps); +} + +// The click result for a step list `tokens` played as `turn`. Steps that only +// bring back the position the turn started from are no entry. +function entered(v: View, tokens: Token[], turn: Turn): InputClick { + return turn.signature === boardSignature(v.board) ? {move: ""} : {move: text(tokens)}; +} + +const neighbours = (sq: string): string[] => NEIGHBOURS[sqIndex(sq)].map(sqName); +/** The squares a piece on `start` passes through taking steps `dirs`, `start` first. */ +const routeOf = (start: string, dirs: Dir[]): string[] => { + const out = [start]; + for (const d of dirs) { + const i = sqIndex(out[out.length - 1]); + out.push(sqName(i + (d === "n" ? 8 : d === "s" ? -8 : d === "e" ? 1 : -1))); + } + return out; +}; +const beside = (a: string, b: string): boolean => manhattan(sqIndex(a), sqIndex(b)) === 1; + +/** One step on the board as drawn, from a square to the one beside it. */ +type Hop = [from: string, to: string]; + +// Step tokens for `hops` taken one after another on `board`, a run of steps +// by one piece being one token, as runs() writes it. Nothing if a hop starts +// from an empty square. +function hopTokens(board: Board, hops: Hop[]): Token[] | undefined { + const at = new Map(board); + const out: Array<{piece: Piece; owner: playerid; from: string; dirs: Dir[]}> = []; + let end: string | undefined; + for (const [from, to] of hops) { + const here = at.get(from); + if (here === undefined) { + return undefined; + } + at.delete(from); + at.set(to, here); + const dir = dirBetween(sqIndex(from), sqIndex(to)); + if (from === end) { + out[out.length - 1].dirs.push(dir); + } else { + out.push({piece: here[0], owner: here[1], from, dirs: [dir]}); + } + end = to; + } + return out.map(r => stepsToken(r.piece, r.owner, r.from, r.dirs)); +} + +// The entry with `hops` added one by one, if they are played as entered: +// each the next step of the turn, and nothing else moving. +function stepped(v: View, hops: Hop[]): View | undefined { + const added = hopTokens(v.after, hops); + if (added === undefined) { + return undefined; + } + const next = lookAgain(v, [...sofar(v), ...added]); + const played = next.turn?.steps.slice(-hops.length) ?? []; + if (!literal(next) || played.length !== hops.length || + played.some((st, i) => sqName(st.from) !== hops[i][0] || sqName(st.to) !== hops[i][1])) { + return undefined; + } + return next; +} + +// The entry as it was entered and, if its last arrow is a piece of the +// player's taking several steps, as it would be had that piece gone by +// another route as long between the same squares, ending in the same +// position. The player said only where the piece went, and a later step +// may need it to have come by one way rather than another. +function routes(v: View): View[] { + const out = [v]; + const all = sofar(v); + const last = all[all.length - 1]; + if (v.turn === undefined || last === undefined || last.prop.kind !== "steps" || last.prop.dirs.length < 2 || + last.spec.owner !== v.player || last.spec.square === undefined) { + return out; + } + const taken = routeOf(last.spec.square, last.prop.dirs); + const length = last.prop.dirs.length; + const end = sqIndex(taken[length]); + const before = lookAgain(v, all.slice(0, -1)); + const walk = (path: string[]): void => { + const at = path[path.length - 1]; + if (path.length === length + 1) { + if (sqIndex(at) === end && path.join() !== taken.join()) { + const other = stepped(before, path.slice(1).map((sq, i): Hop => [path[i], sq])); + if (other !== undefined && other.turn!.signature === v.turn!.signature) { + out.push(other); + } + } + return; + } + for (const next of neighbours(at)) { + if (!path.includes(next) && manhattan(sqIndex(next), end) <= length - path.length) { + walk([...path, next]); + } + } + }; + walk([taken[0]]); + return out; +} + +// The second half of a pull: the enemy piece on `cell` follows the player's +// piece that has just stepped away from beside it, into the square that +// piece left, by the route entered or another that ends the same way. A +// piece that has just pushed cannot also pull. +function pulls(v: View, cell: string): Array<{into: string; base: View}> { + const enemy = v.shown.get(cell); + if (enemy === undefined || enemy.owner === v.player || v.left < 1) { + return []; + } + const out: Array<{into: string; base: View}> = []; + for (const base of routes(v)) { + const steps = base.turn?.steps ?? []; + const last = steps[steps.length - 1]; + const prev = steps[steps.length - 2]; + if (last !== undefined && last.owner === v.player && STRENGTH[last.piece] > STRENGTH[enemy.piece] && + beside(cell, sqName(last.from)) && !(prev !== undefined && prev.owner !== v.player && prev.from === last.to) && + !out.some(o => o.into === sqName(last.from))) { + out.push({into: sqName(last.from), base}); + } + } + return out; +} + +// The first half of a push entered on its own: whether some piece of the +// player's can follow the enemy piece on `from` once it has stepped to the +// empty square `to`. +function pushable(v: View, from: string, to: string): boolean { + const enemy = v.shown.get(from); + return enemy !== undefined && enemy.owner !== v.player && v.left >= 2 && !v.after.has(to) && beside(from, to) && + [...v.shown].some(([at, p]) => p.owner === v.player && beside(at, from) && STRENGTH[p.piece] > STRENGTH[enemy.piece] && + stepped(v, [[from, to], [at, from]]) !== undefined); +} + +/** + * A push being entered one step at a time in Basic: the enemy piece on + * `from` has been sent to the empty square `to`, which it can only reach by + * being pushed. The selections hold it until a click on the piece that + * pushes it enters both steps. + */ +export function pendingPush(after: Board, player: playerid, selections: string[]): {from: string; to: string} | undefined { + if (selections.length !== 2) { + return undefined; + } + const [from, to] = selections; + const enemy = after.get(from); + if (enemy === undefined || enemy[1] === player || after.has(to) || !beside(from, to)) { + return undefined; + } + return {from, to}; +} + +// The steps that take each selected piece to the square the next one stands +// on, and the last to `target`, moving nothing else: the fewest there are, +// provided every way of taking that few ends in one position. +function basicChain(v: View, squares: string[], target: string): Turn | undefined { + const starts = squares.map(sqIndex); + const ends = squares.map((_, i) => sqIndex(i === squares.length - 1 ? target : squares[i + 1])); + const tokens = squares.map((s, i) => { + const p = v.shown.get(s)!; + return arrowToken(p.piece, p.owner, s, sqName(ends[i])); + }); + const r = resolve(v.after, v.player, v.left, tokens, false, true, turn => { + const moved = turn.trajectories.filter(tr => tr.visited.length > 1); + return moved.every(tr => starts.includes(tr.start)) && + starts.every((s, i) => moved.some(tr => tr.start === s && tr.final === ends[i])); + }); + return r.status === "resolved" ? r.turn : undefined; +} + +// Whether the newest selection could move onto the clicked piece's square as +// part of the chain: the pieces selected so far follow one another, the +// clicked piece makes way, and whatever else moves does so because a link of +// the chain takes its place (it can be selected next). +function basicChainable(v: View, squares: string[], clicked: string): boolean { + const starts = squares.map(sqIndex); + const there = sqIndex(clicked); + const ends = [...starts.slice(1), there]; + const tokens = squares.map((s, i) => { + const p = v.shown.get(s)!; + return arrowToken(p.piece, p.owner, s, sqName(ends[i])); + }); + const r = resolve(v.after, v.player, v.left, tokens, false, true, turn => { + const moved = turn.trajectories.filter(tr => tr.visited.length > 1); + const taken = new Set(moved.map(tr => tr.final)); + return moved.some(tr => tr.start === there) && + moved.every(tr => starts.includes(tr.start) || taken.has(tr.start)) && + starts.every((s, i) => moved.some(tr => tr.start === s && tr.final === ends[i])); + }); + return r.status !== "unsatisfiable"; +} + +function basicClick(v: View, selections: string[], square: string): InputClick { + const player = v.player; + const clicked = v.shown.get(square); + const stay: InputClick = {move: text(v.tokens)}; + const select = (squares: string[]): InputClick => ({move: joinSelections(v.tokens, squares)}); + const movable = (cell: string): boolean => canMoveWithin(v.after, player, v.left, cell) || pulls(v, cell).length > 0; + + if (selections.length === 0) { + if (clicked === undefined) { + return v.turn === undefined ? stay : {move: committed(v), complete: true}; + } + if (movable(square)) { + return select([square]); + } + if (clicked.owner === player) { + return stay; + } + // undo one token, and with it whatever of a push or pull it leaves unplayable + let rest = v.tokens.slice(0, -1); + if (literal(v)) { + while (rest.length > 0 && !literal(lookAgain(v, rest))) { + rest = rest.slice(0, -1); + } + } + return {move: text(rest)}; + } + + // A push entered as two steps: the enemy piece's, then a click on the + // piece that pushes it, which can only follow it into the square it left. + const push = pendingPush(v.after, player, selections); + if (push !== undefined) { + if (clicked !== undefined && clicked.owner === player) { + const pushed = stepped(v, [[push.from, push.to], [square, push.from]]); + if (pushed !== undefined) { + return entered(v, pushed.tokens, pushed.turn!); + } + } + if (clicked === undefined || selections.includes(square)) { + return stay; + } + return movable(square) ? select([square]) : stay; + } + + if (selections.some(s => !v.shown.has(s))) { + return stay; + } + // A click on the first selection closes a loop: three pieces rotating. + // Two pieces trading places is left to Advanced; in Basic that click + // deselects them, as a click on any selected piece does. + if (clicked === undefined || (square === selections[0] && selections.length > 2)) { + const turn = basicChain(v, selections, square); + if (turn !== undefined) { + // the entry as the steps it is shown as, followed by the new ones + return entered(v, [...sofar(v), ...runs(turn.steps)], turn); + } + } + if (clicked === undefined && selections.length === 1) { + // An enemy piece's steps, entered after the puller's or before the + // pusher's: following the piece that has just stepped away from beside + // it, then perhaps on to the start of a push, which waits for its + // pusher. It can take no more steps in a row than that. + const [from] = selections; + const pulled = pulls(v, from).map(({into, base}) => ({into, after: stepped(base, [[from, into]])})); + for (const {into, after} of pulled) { + if (after !== undefined && into === square) { + return entered(v, after.tokens, after.turn!); + } + } + for (const {into, after} of pulled) { + if (after !== undefined && pushable(after, into, square)) { + return {move: joinSelections(after.tokens, [into, square])}; + } + } + if (pushable(v, from, square)) { + return select([from, square]); + } + } + if (clicked === undefined || selections.includes(square)) { + return stay; + } + if (basicChainable(v, selections, square)) { + return select([...selections, square]); + } + return movable(square) ? select([square]) : stay; +} + +// --------------------------------------------------------------------------- +// Advanced + +/** Where a piece ends up in a turn, and by way of which squares. */ +interface Fate { + final: number; + captured: boolean; + visited: number[]; +} + +function fate(turn: Turn | undefined, origin: string): Fate { + const start = sqIndex(origin); + const tr = turn?.trajectories.find(t => t.start === start); + return tr === undefined ? {final: start, captured: false, visited: [start]} : tr; +} + +// Whether, in the turn shown, token `t` is said of `piece`. A token that +// names no square is taken to be only if it names where the piece ends up. +function describes(t: Token, piece: Shown, f: Fate): boolean { + if (t.spec.piece !== undefined && (t.spec.piece !== piece.piece || t.spec.owner !== piece.owner)) { + return false; + } + if (t.spec.square === undefined) { + return t.prop.kind === "dest" && f.final === sqIndex(t.prop.square); + } + if (!f.visited.includes(sqIndex(t.spec.square))) { + return false; + } + switch (t.prop.kind) { + case "dest": return f.final === sqIndex(t.prop.square); + case "capture": return f.captured; + case "survive": return !f.captured; + // no step token is among what Advanced takes to be said + default: return false; + } +} + +/** A selected piece, the square it is drawn on, and the square it is being sent to. */ +interface Link { + piece: Shown; + at: string; + to: string; +} + +function links(v: View, squares: string[], target: string): Link[] | undefined { + const out: Link[] = []; + for (let i = 0; i < squares.length; i++) { + const piece = v.shown.get(squares[i]); + if (piece === undefined) { + return undefined; + } + out.push({piece, at: squares[i], to: i === squares.length - 1 ? target : squares[i + 1]}); + } + return out; +} + +// What was said with what it said of each link replaced by an arrow to where +// the link is now sent, newest selection first. +function sent(v: View, chain: Link[], tokens = v.said): Token[] { + const fates = chain.map(l => fate(v.turn, l.piece.origin)); + return [ + ...tokens.filter(t => !chain.some((l, i) => describes(t, l.piece, fates[i]))), + ...chain.map(l => arrowToken(l.piece.piece, l.piece.owner, l.piece.origin, l.to)).reverse(), + ]; +} + +/** Whether the player put the link's piece on the square it is drawn on, rather than the resolver. */ +function placed(v: View, l: Link): boolean { + if (l.at === l.piece.origin) { + return true; + } + const f = fate(v.turn, l.piece.origin); + const at = sqIndex(l.at); + return v.said.some(t => t.prop.kind === "dest" && sqIndex(t.prop.square) === at && describes(t, l.piece, f)); +} + +// What a turn must do to be the chain: every link ends where it was sent, and +// a link whose square another link moves into has stood on that square if the +// player put it there (a piece the resolver put there is simply planned anew). +function obeys(v: View, chain: Link[]): (turn: Turn) => boolean { + const via = chain.map((l, i) => i > 0 && placed(v, l)); + return turn => chain.every((l, i) => { + const f = fate(turn, l.piece.origin); + return f.final === sqIndex(l.to) && (!via[i] || f.visited.includes(sqIndex(l.at))); + }); +} + +// The entry for `said` when it is to be shown, and played, as `turn`, which +// fits it: the tokens alone if the notation reads them as that turn, and +// otherwise the steps of the turn after them. +function entry(v: View, said: Token[], turn: Turn): string { + const r = resolve(v.board, v.player, v.limit, said, false); + if (r.status === "resolved" && r.turn.signature === turn.signature) { + return text(said); + } + return text([...said, ...runs(turn.steps)]); +} + +// The click result for `said` shown as the turn chosen for it, which is one +// of several where nothing but the order positions sort in chose it. +function chosen(v: View, said: Token[], c: Extract): InputClick { + return {move: entry(v, said, c.turn), oneOf: c.by === "choice" ? c.positions : undefined}; +} + +// The entry for what is now said, shown as the turn Advanced takes it to mean. +function restated(v: View, said: Token[]): InputClick { + const c = choose(v.board, v.player, v.limit, said); + return c.status === "turn" ? chosen(v, said, c) : {move: text(said)}; +} + +// The entry after a chain is sent on its way: what is now said, shown as the +// turn Advanced prefers of those in which the chain happens. `captured` is +// what a trap's triangle asks of the newest selection, which is then said +// too. It is asked of that very piece: the token alone would be met by +// another piece of its kind that crossed the square it started on. +function advancedChain(v: View, chain: Link[], captured?: boolean): InputClick | undefined { + const {board, player, limit} = v; + const last = chain[chain.length - 1].piece; + const tokens = sent(v, chain); + if (captured !== undefined) { + tokens.push((captured ? captureToken : surviveToken)(last.piece, last.owner, last.origin)); + } + if (standing(board, tokens)) { + return {move: text(tokens)}; + } + const follows = obeys(v, chain); + const want = choose(board, player, limit, tokens, captured === undefined ? follows : + turn => follows(turn) && fate(turn, last.origin).captured === captured); + if (want.status !== "turn") { + return undefined; + } + // A link sent on from a square the player had put it on is said to have + // been there, if the arrows alone would be taken some other way. + const through = chain.filter((l, i) => i > 0 && l.at !== l.piece.origin && placed(v, l)) + .map(l => arrowToken(l.piece.piece, l.piece.owner, l.at, l.to)); + let said = tokens; + if (through.length > 0) { + const plain = choose(board, player, limit, tokens); + if (plain.status !== "turn" || plain.turn.signature !== want.turn.signature) { + said = [...tokens, ...through]; + } + } + return chosen(v, said, want); +} + +// Whether the chain could go on through the clicked piece: the newest +// selection ends on its square and it ends somewhere else. +function advancedChainable(v: View, squares: string[], clicked: string): boolean { + const chain = links(v, squares, clicked); + const x = v.shown.get(clicked); + if (chain === undefined || x === undefined) { + return false; + } + const f = fate(v.turn, x.origin); + const tokens = sent(v, chain, v.said.filter(t => !describes(t, x, f))); + const follows = obeys(v, chain); + const there = sqIndex(clicked); + return display(v.board, v.player, v.limit, tokens, turn => fate(turn, x.origin).final !== there && follows(turn)).status === "turn"; +} + +/** A turn that brings a piece to the square a target click names, and the arrow that says so. */ +interface Aim { + found: Found; + arrow: Token; +} + +// The move a click on an empty square asks for by itself. Of the turns that +// fit what was said and end with a piece on (or captured on) `target`: those +// taking a rabbit of the player's to goal there if any do, otherwise those +// moving an enemy piece there if any do; then the fewest pieces displaced, +// the fewest steps, and then by the `preferences` Normal Move goes by too. If +// that still leaves more than one position, the one that sorts first where a +// rabbit goes to goal, and otherwise nothing. +function targetSelection(v: View, target: string): InputClick | undefined { + const {board, player, limit, said} = v; + const there = sqIndex(target); + const prefer = preferences(player); + const goal = target[1] === (player === 1 ? "8" : "1"); + // the pieces within reach, by which of those preferences their coming meets + const classes: Array> = [[], [], []]; + for (const [origin, contents] of board) { + const [piece, owner] = contents; + // an enemy piece takes two steps a square + if (manhattan(sqIndex(origin), there) * (owner === player ? 1 : 2) <= limit) { + classes[owner !== player ? 1 : goal && piece === "R" ? 0 : 2].push([origin, contents]); + } + } + for (const [kind, pieces] of classes.entries()) { + let aims: Aim[] = []; + for (const [origin, [piece, owner]] of pieces) { + const start = sqIndex(origin); + const arrow = arrowToken(piece, owner, origin, target); + const found = fewestDisplaced(board, player, limit, [...said, arrow], turn => + turn.trajectories.some(tr => tr.start === start && tr.final === there && (tr.visited.length > 1 || tr.captured))); + if (found.length === 0) { + continue; + } + const sooner = aims.length === 0 ? -1 : + found[0].turn.displaced - aims[0].found.turn.displaced || found[0].turn.steps.length - aims[0].found.turn.steps.length; + if (sooner < 0) { + aims = []; + } + if (sooner <= 0) { + aims.push(...found.map(f => ({found: f, arrow}))); + } + } + if (aims.length === 0) { + continue; + } + const order = (a: Aim, b: Aim): number => prefer(a.found, b.found); + aims.sort(order); + const best = aims.filter(a => order(a, aims[0]) === 0); + const tied = best.some(a => a.found.turn.signature !== best[0].found.turn.signature); + // only a tie between rabbits going to goal (the first class) is broken + if (tied && kind !== 0) { + return undefined; + } + const pick = best.reduce((a, b) => b.found.turn.signature < a.found.turn.signature ? b : a); + return { + move: entry(v, [...said, pick.arrow], pick.found.turn), + oneOf: tied ? new Set(aims.map(a => a.found.turn.signature)).size : undefined, + }; + } + return undefined; +} + +/** + * The piece sitting on a trap: the one drawn there, or the one the turn shown + * captures there without its having moved. + */ +function onTrap(v: View, square: string): Shown | undefined { + if (!TRAPS.includes(square)) { + return undefined; + } + const drawn = v.shown.get(square); + if (drawn !== undefined) { + return drawn; + } + const at = sqIndex(square); + const tr = v.turn?.trajectories.find(t => t.captured && t.start === at && t.final === at); + return tr === undefined ? undefined : {piece: tr.type, owner: tr.owner, origin: square}; +} + +/** What was said, less whatever it said of whether `p` is captured. */ +function unfated(v: View, p: Shown): Token[] { + return v.said.filter(t => !((t.prop.kind === "capture" || t.prop.kind === "survive") && t.spec.square === p.origin && + t.spec.piece === p.piece && t.spec.owner === p.owner)); +} + +// A trap's triangle does the opposite of what a plain click would show: it +// has the piece captured where it would survive, and survive where it would +// be captured. These say which, or nothing where the opposite cannot happen. + +// For the chain sent to the trap it ends on. +function sendChoice(v: View, chain: Link[]): boolean | undefined { + const {board, player, limit} = v; + const last = chain[chain.length - 1].piece; + const tokens = sent(v, chain); + const follows = obeys(v, chain); + const shown = choose(board, player, limit, tokens, follows); + if (shown.status !== "turn") { + return undefined; + } + const captured = !fate(shown.turn, last.origin).captured; + return display(board, player, limit, tokens, turn => + follows(turn) && fate(turn, last.origin).captured === captured).status === "turn" ? captured : undefined; +} + +// For a piece sitting on its trap. +function sitChoice(v: View, p: Shown): boolean | undefined { + if (!fateOpen(v, p)) { + return undefined; + } + return !(v.turn !== undefined && fate(v.turn, p.origin).captured); +} + +// Whether what was said leaves it open if `p` is captured: some turn that +// fits it captures the piece, and some other leaves it alive. The turn shown +// answers one of the two; a capture token lets the search for a capture +// skip what cannot lead to one. +function fateOpen(v: View, p: Shown): boolean { + const said = unfated(v, p); + const can = (captured: boolean): boolean => display(v.board, v.player, v.limit, + captured ? [...said, captureToken(p.piece, p.owner, p.origin)] : said, + turn => fate(turn, p.origin).captured === captured).status === "turn"; + const shown = v.turn === undefined ? undefined : fate(v.turn, p.origin).captured; + return (shown === true || can(true)) && (shown === false || can(false)); +} + +// The entry once it says that `p` is captured, or that it is not. +function fated(v: View, p: Shown, captured: boolean): InputClick | undefined { + const said = [...unfated(v, p), (captured ? captureToken : surviveToken)(p.piece, p.owner, p.origin)]; + if (standing(v.board, said)) { + return {move: text(said)}; + } + const c = choose(v.board, v.player, v.limit, said, turn => fate(turn, p.origin).captured === captured); + return c.status === "turn" ? chosen(v, said, c) : undefined; +} + +/** + * The trap squares that get the advanced-mode triangle while pieces are + * selected, and for each whether clicking it has the newest selection + * captured (true) or keeps it alive (false): the opposite of what a click on + * the square would show. The traps are those the newest selection can be sent + * to, and the trap it sits on, where it can end up either way. + */ +export function captureChoices(board: Board, player: playerid, limit: number, move: string): Map { + const out = new Map(); + let parsed: ParsedMove; + try { + parsed = parseMove(move, true); + } catch { + return out; + } + const squares = parsed.selections ?? []; + const v = look(board, player, limit, parsed.tokens); + if (squares.length === 0 || !v.fits) { + return out; + } + const sitting = squares.length === 1 ? onTrap(v, squares[0]) : undefined; + const own = sitting === undefined ? undefined : sitChoice(v, sitting); + if (own !== undefined) { + out.set(squares[0], own); + } + for (const trap of TRAPS) { + const chain = v.shown.has(trap) ? undefined : links(v, squares, trap); + const captured = chain === undefined ? undefined : sendChoice(v, chain); + if (captured !== undefined) { + out.set(trap, captured); + } + } + return out; +} + +/** The trap squares of `captureChoices`. */ +export function captureAlternatives(board: Board, player: playerid, limit: number, move: string): string[] { + return [...captureChoices(board, player, limit, move).keys()]; +} + +function advancedClick(v: View, selections: string[], square: string, triangle: boolean): InputClick { + const {board, player, limit} = v; + const clicked = v.shown.get(square); + const stay: InputClick = {move: text(v.tokens)}; + const select = (squares: string[]): InputClick => ({move: joinSelections(v.tokens, squares)}); + // A piece can be selected if it can still move once the turn shown has + // been played, if it moves in that turn (it can be sent elsewhere), or + // if what was said leaves room for it to move in place of what was inferred. + const movable = (cell: string): boolean => { + const p = v.shown.get(cell); + if (p === undefined) { + return false; + } + if (canMoveWithin(v.after, player, v.left, cell)) { + return true; + } + const f = fate(v.turn, p.origin); + if (f.visited.length > 1) { + return true; + } + return v.turn !== undefined && canMoveWithin(board, player, limit, p.origin, v.said.filter(t => !describes(t, p, f))); + }; + // A piece on a trap can also be selected if whether it is captured is + // still open, so that its triangle can settle that. + const open = (cell: string): boolean => { + const p = onTrap(v, cell); + return p !== undefined && fateOpen(v, p); + }; + // A piece is selected where it stands, as in Basic, so a square a piece + // has left is free for a target click. A piece captured on the trap it + // stood on is not drawn, but it is still there to be selected. + const capturedHere = (cell: string): InputClick | undefined => open(cell) ? select([cell]) : undefined; + const aimed = (): InputClick | undefined => targetSelection(v, square); + + if (selections.length === 0) { + if (clicked === undefined) { + return capturedHere(square) ?? aimed() ?? + (v.turn === undefined ? stay : {move: committed(v), complete: true}); + } + if (movable(square) || open(square)) { + return select([square]); + } + // undo: one thing less is said + return clicked.owner === player ? stay : restated(v, v.said.slice(0, -1)); + } + + // A piece on a trap: its triangle settles whether it is captured, the + // other way from the turn shown, and a click on its square deselects it. + // A piece captured there is not drawn, so it cannot be sent anywhere. + const sitting = selections.length === 1 ? onTrap(v, selections[0]) : undefined; + if (sitting !== undefined && square === selections[0]) { + const captured = triangle ? sitChoice(v, sitting) : undefined; + return (captured === undefined ? undefined : fated(v, sitting, captured)) ?? stay; + } + if (sitting !== undefined && !v.shown.has(selections[0])) { + if (clicked !== undefined) { + return movable(square) || open(square) ? select([square]) : stay; + } + return capturedHere(square) ?? aimed() ?? stay; + } + + const chain = links(v, selections, square); + if (chain === undefined) { + return stay; + } + if (clicked === undefined) { + // a trap's triangle: the opposite of what a click on the square shows + const captured = triangle && TRAPS.includes(square) ? sendChoice(v, chain) : undefined; + return advancedChain(v, chain, captured) ?? capturedHere(square) ?? aimed() ?? stay; + } + if (square === selections[0]) { + if (selections.length === 1) { + // a second click on the selected piece deselects it + return stay; + } + const looped = advancedChain(v, chain); + if (looped !== undefined) { + return looped; + } + } + if (!selections.includes(square) && advancedChainable(v, selections, square)) { + return select([...selections, square]); + } + return movable(square) || open(square) ? select([square]) : stay; +} + +export function inputClick( + board: Board, player: playerid, limit: number, + move: string, square: string, mode: ArimaaInputMode, alternativeCapture = false, +): InputClick { + let parsed: ParsedMove; + try { + parsed = parseMove(move, true); + } catch { + parsed = {tokens: [], selections: []}; + } + const v = look(board, player, limit, parsed.tokens); + const selections = parsed.selections ?? []; + if (!v.fits) { + // nothing can be added to an entry no turn fits; an enemy click still takes its last token back + const clicked = v.shown.get(square); + return {move: text(clicked !== undefined && clicked.owner !== player ? v.tokens.slice(0, -1) : v.tokens)}; + } + return mode === "advanced" ? advancedClick(v, selections, square, alternativeCapture) : basicClick(v, selections, square); +} diff --git a/src/games/arimaa/legacy.ts b/src/games/arimaa/legacy.ts new file mode 100644 index 000000000..2ff8eaa95 --- /dev/null +++ b/src/games/arimaa/legacy.ts @@ -0,0 +1,317 @@ +/** + * The pre-notation step lists: comma-separated `` steps with + * optional capture parentheticals, which recorded games hold and which can + * still be typed. Placements during setup use the same tokens without the + * destination. + */ +import i18next from "i18next"; +import { GameBase, type IValidationResult } from "../_base.js"; +import { RectGrid, SquareOrthGraph } from "../../common/index.js"; +import type { ArimaaGame } from "../arimaa.js"; +import { isLower, type Piece, type playerid } from "./notation.js"; +import { STRENGTH, TRAP_SQUARES, isAlone, isFrozen } from "./turns.js"; + +export type StepKind = "placement" | "pusher" | "puller" | "pushee" | "pullee" | "mover" | undefined; + +// strip any parentheticals and just return the base move +export function baseMove(mv: string): [Piece, playerid, string?, string?] { + mv = mv.replace(/\s+/g, ""); + const idx = mv.indexOf("("); + let base = mv; + if (idx >= 0) { + base = mv.slice(0, idx); + } + const pcStr = base[0]; + let player: playerid; + if (isLower(pcStr)) { + player = 2; + } else { + player = 1; + } + const pc = pcStr.toUpperCase() as Piece; + let from: string|undefined; + if (base.length > 1) { + from = base.substring(1,3); + } + let to: string|undefined; + if (base.length > 3) { + to = base.substring(3); + } + return [pc, player, from, to]; +} + +// A very niche helper function to fix the "can't push pull at same time" issue +// Looks at each move in a chain and determines the nature of each. +// Naive. Just looks at the notation and sequence, not board context. +export function classify(player: playerid, moves: string[]): StepKind[] { + const classifications: StepKind[] = []; + + for (let i = 0; i < moves.length; i++) { + const [, owner, from, to] = baseMove(moves[i]); + // if mine: + // - placement if to is undefined + // - pusher if previous was pushed + // - puller if next is enemy and moves into vacated space + // - mover otherwise + if (owner === player) { + if (to === undefined) { + classifications.push("placement"); + } else if (i > 0 && classifications[i - 1] === "pushee") { + classifications.push("pusher"); + } else { + if (i < moves.length - 1) { + const [, nextOwner, , nextTo] = baseMove(moves[i + 1]); + if (nextOwner !== player && nextTo === from) { + classifications.push("puller"); + } else { + classifications.push("mover"); + } + } else { + classifications.push("mover"); + } + } + } + // if other: + // - pullee if previous is puller + // - pushee if previous is not puller and next is mine moving into space + // - undefined otherwise + else { + if (i > 0 && classifications[i - 1] === "puller") { + classifications.push("pullee"); + } else { + if (i < moves.length - 1) { + const [, nextOwner, , nextTo] = baseMove(moves[i + 1]); + if (nextOwner === player && nextTo === from) { + classifications.push("pushee"); + } else { + classifications.push(undefined); + } + } else { + classifications.push(undefined); + } + } + } + } + + return classifications; +} + +// The pre-notation movement grammar, validated as it always was, so that every +// historical move string still validates exactly as it did. `maxMoves` is the +// steps the mover may take this turn. +export function validateLegacyMovement(game: ArimaaGame, m: string, maxMoves: number): IValidationResult { + const result: IValidationResult = {valid: false, message: i18next.t("apgames:validation._general.DEFAULT_HANDLER")}; + const g = new SquareOrthGraph(8, 8); + // This validator once had two lapses: a push completed by a piece of + // equal strength when a stronger one was also adjacent, and a pull that + // moved the pulled piece somewhere other than the square the puller + // vacated. Both are rejected here, so no new move can use them. A few + // recorded games contain such a move; they replay through `trusted`, + // which skips validation entirely, so no saved game is disturbed. + const classifications = classify(game.currplayer, m.split(",").filter(Boolean)); + const steps = m.split(",").filter(Boolean).map(mv => baseMove(mv)); + // can't make too many moves + if (steps.length > maxMoves) { + result.valid = false; + result.message = i18next.t("apgames:validation.arimaa.TOO_MANY", {num: maxMoves}); + return result; + } + const cloned = game.clone(); + // pushPending is used to make sure pushes are completed + let pushPending = false; + // validate each step + for (let i = 0; i < steps.length; i++) { + const [pc, owner, from, to] = steps[i]; + // console.log(JSON.stringify({pc, owner, from, to})); + // validate from first + if (from === undefined) { + throw new Error("From should never be undefined at this point."); + } + // valid cell + try { + GameBase.algebraic2coords(from, 8); + } catch { + result.valid = false; + result.message = i18next.t("apgames:validation._general.INVALIDCELL", {cell: from}); + return result; + } + // from contents match + if (!cloned.board.has(from) || cloned.board.get(from)![0] !== pc || cloned.board.get(from)![1] !== owner) { + result.valid = false; + result.message = i18next.t("apgames:validation._general.NONEXISTENT"); + return result; + } + // if it's your piece, it can't be frozen + if (owner === cloned.currplayer && isFrozen(cloned.board, from)) { + result.valid = false; + result.message = i18next.t("apgames:validation.arimaa.FROZEN", {where: from}); + return result; + } + // if a push is pending, then this move *must* be completing the push + if (pushPending) { + const [lastPc, lastPlayer, lastFrom] = steps[i - 1]; + // lastPlayer must be the enemy + // from must be adjacent to lastFrom + // to must equal lastFrom + // pc must be stronger than lastPc + if (lastPlayer === cloned.currplayer || !g.neighbours(lastFrom!).includes(from) || (to !== undefined && to !== lastFrom) || STRENGTH[pc] <= STRENGTH[lastPc]) { + result.valid = false; + result.message = i18next.t("apgames:validation.arimaa.INVALID_PUSH", {where: from}); + return result; + } + pushPending = false; + // if this is the last step, suggest an autocomplete + if (i === steps.length - 1 && to === undefined) { + result.autocomplete = m + lastFrom; + } + } + // if it's an enemy piece, it must be a push or pull + if (owner !== cloned.currplayer) { + // check for pulls first + let validPull = false; + if (i > 0 && classifications[i - 1] !== "pusher") { + const [lastPc, lastPlayer, lastFrom] = steps[i - 1]; + const ns = g.neighbours(from); + if (lastPlayer === cloned.currplayer && ns.includes(lastFrom!) && STRENGTH[lastPc] > STRENGTH[pc] && (to === undefined || to === lastFrom)) { + validPull = true; + // check if push is possible + let canPush = false; + if (i < maxMoves - 1) { + for (const n of g.neighbours(from)) { + if (cloned.board.has(n)) { + const [nPc, nOwner] = cloned.board.get(n)!; + if (nOwner === cloned.currplayer && STRENGTH[nPc] > STRENGTH[pc] && !isFrozen(cloned.board, n)) { + canPush = true; + break; + } + } + } + } + // if this is the last step, suggest an autocomplete + if (i === steps.length - 1 && to === undefined) { + if (i === maxMoves - 1 || !canPush) { + result.autocomplete = m + lastFrom; + } + } + } + } + // if there is no valid pull, then it must be a push and be completed + // on the next step + if (!validPull) { + pushPending = true; + // for it to be a valid pending push, the current player must have + // an unfrozen, stronger piece adjacent + let validPush = false; + for (const n of g.neighbours(from)) { + if (cloned.board.has(n)) { + const [nPc, nOwner] = cloned.board.get(n)!; + if (nOwner === cloned.currplayer && STRENGTH[nPc] > STRENGTH[pc] && !isFrozen(cloned.board, n)) { + validPush = true; + } + } + } + if (!validPush) { + result.valid = false; + result.message = i18next.t("apgames:validation.arimaa.INVALID_PUSHPULL", {where: from}); + return result; + } + } + } + + // partial move at the end of the chain + if (from !== undefined && to === undefined && i === steps.length - 1) { + result.valid = true; + result.complete = -1; + result.message = i18next.t("apgames:validation.arimaa.PARTIAL_MOVE"); + result.canrender = true; + return result; + } + // otherwise from and to must be defined + else if (from === undefined || to === undefined) { + throw new Error("From and to should never be undefined at this point."); + } + + // to is a valid cell + try { + GameBase.algebraic2coords(to, 8); + } catch { + result.valid = false; + result.message = i18next.t("apgames:validation._general.INVALIDCELL", {cell: to}); + return result; + } + // to is empty + if (cloned.board.has(to)) { + result.valid = false; + result.message = i18next.t("apgames:validation._general.OCCUPIED", {where: to}); + return result; + } + // to is orthogonally adjacent + if (!g.neighbours(from).includes(to)) { + result.valid = false; + result.message = i18next.t("apgames:validation.arimaa.NOT_ADJ"); + return result; + } + // you can't move your own rabbits backwards + const forbidden = cloned.currplayer === 1 ? "S" : "N"; + if (pc === "R" && owner === cloned.currplayer) { + const [fx, fy] = GameBase.algebraic2coords(from, 8); + const [tx, ty] = GameBase.algebraic2coords(to, 8); + const bearing = RectGrid.bearing(fx, fy, tx, ty)!; + if (bearing.startsWith(forbidden)) { + result.valid = false; + result.message = i18next.t("apgames:validation.arimaa.BACKWARDS", {where: from}); + return result; + } + } + + // fake execute the step + const moved = cloned.board.get(from)!; + cloned.board.set(to, moved); + cloned.board.delete(from); + // check traps + for (const trap of TRAP_SQUARES) { + if (cloned.board.has(trap) && isAlone(cloned.board, trap)) { + cloned.board.delete(trap); + } + } + } + + // At this point, everything is valid. + // Verify completeness and board state repetition and return. + // Because partial moves that are invalid can become valid with further steps, + // we can't return `valid: false`; return `complete: -1` instead. + let complete: -1|0|1; + let message: string; + // if the board position hasn't changed, then -1 + if (cloned.signature() === game.signature()) { + complete = -1; + message = i18next.t("apgames:validation.arimaa.NOPASS"); + } + // if third occurrence of position, then -1 + else if (cloned.numRepeats() >= 2) { + complete = -1; + message = i18next.t("apgames:validation.arimaa.REPEAT"); + } + // if a push is pending, then -1 + else if (pushPending) { + complete = -1; + message = i18next.t("apgames:validation.arimaa.PARTIAL_PUSH"); + } + // if the number of moves are < max moves, then 0 + else if (steps.length < maxMoves) { + const remaining = maxMoves - steps.length; + complete = 0; + message = i18next.t("apgames:validation.arimaa.PARTIAL", {count: remaining}); + } + // otherwise we're good, but only the player completes a move + else { + complete = 0; + message = i18next.t("apgames:validation._general.VALID_MOVE"); + } + + result.valid = true; + result.canrender = true; + result.complete = complete; + result.message = message; + return result; +} diff --git a/src/games/arimaa/notation.ts b/src/games/arimaa/notation.ts index 345be71b1..edb727f30 100644 --- a/src/games/arimaa/notation.ts +++ b/src/games/arimaa/notation.ts @@ -11,12 +11,29 @@ * captured. The move meant is found in the first (steps, displaced pieces) * bucket holding a satisfying turn, provided every satisfying turn there * reaches the same position. + * + * Click entry also writes the property `o`, the opposite of `x`: the piece is + * not captured. It is understood wherever a move is read but never stored. */ export type Piece = "E" | "M" | "H" | "D" | "C" | "R"; export type playerid = 1 | 2; export type Dir = "n" | "s" | "e" | "w"; +export const pc2name = new Map([ + ["E", "Elephant"], + ["M", "Camel"], + ["H", "Horse"], + ["D", "Dog"], + ["C", "Cat"], + ["R", "Rabbit"], +]); + +/** Whether a piece letter is lower-case, which is to say Silver's. */ +export function isLower(character: string): boolean { + return character === character.toLowerCase() && character !== character.toUpperCase(); +} + const pieceRe = /^[EMHDCRemhdcr]$/; const squareRe = /^[a-h][1-8]$/; @@ -29,7 +46,9 @@ export interface Specifier { export type Property = | { kind: "dest"; square: string } | { kind: "steps"; dirs: Dir[] } - | { kind: "capture" }; + | { kind: "capture" } + /** Input-only assertion: the named piece must survive the turn. */ + | { kind: "survive" }; export interface Token { spec: Specifier; @@ -41,8 +60,8 @@ export interface ParsedMove { tokens: Token[]; /** A trailing bare square: the selected piece awaiting a destination. Input only. */ pending?: string; - /** The selection before `pending`, kept while a second click on `pending` could complete an arrow from it. Input only. */ - previous?: string; + /** All trailing square selections, oldest first. */ + selections?: string[]; } export class NotationError extends Error { @@ -54,10 +73,6 @@ export class NotationError extends Error { } } -export function isSquare(s: string): boolean { - return squareRe.test(s); -} - /** Trim and collapse runs of whitespace to single spaces. */ export function normalize(m: string): string { return m.trim().replace(/\s+/g, " "); @@ -100,9 +115,10 @@ export function parseSpecifier(s: string): Specifier | undefined { /** * Properties are self-delimiting, so one pass from the right splits a token: - * a trailing `x` is a capture; a trailing digit ends a square; otherwise the - * maximal trailing run of `[nsew]` is the step list, backing off one character - * if that would leave no specifier (`ee` is the Silver elephant stepping east). + * a trailing `x` is a capture and a trailing `o` its opposite; a trailing + * digit ends a square; otherwise the maximal trailing run of `[nsew]` is the + * step list, backing off one character if that would leave no specifier + * (`ee` is the Silver elephant stepping east). */ export function parseToken(text: string): Token { if (text.length < 2) { @@ -111,8 +127,8 @@ export function parseToken(text: string): Token { const last = text[text.length - 1]; let specText: string; let prop: Property; - if (last === "x") { - prop = { kind: "capture" }; + if (last === "x" || last === "o") { + prop = { kind: last === "x" ? "capture" : "survive" }; specText = text.slice(0, -1); } else if (/[1-8]/.test(last)) { const square = text.slice(-2); @@ -142,25 +158,21 @@ export function parseToken(text: string): Token { } /** - * Parse a whole move. With `allowPending`, up to two final bare squares are - * returned separately, as the pending selection and the selection before it, - * instead of being rejected. + * Parse a whole move. With `allowPending`, the bare squares it ends with are + * returned separately, as the selections (oldest first, so the last of them + * is the pending one), instead of being rejected. */ export function parseMove(m: string, allowPending = false): ParsedMove { const parts = tokenize(m); let end = parts.length; - let pending: string | undefined; - let previous: string | undefined; - if (allowPending && end > 0 && squareRe.test(parts[end - 1])) { - pending = parts[end - 1]; - end--; - if (end > 0 && squareRe.test(parts[end - 1])) { - previous = parts[end - 1]; - end--; + const selections: string[] = []; + if (allowPending) { + while (end > 0 && squareRe.test(parts[end - 1])) { + selections.unshift(parts[--end]); } } const tokens = parts.slice(0, end).map(parseToken); - return { tokens, pending, previous }; + return { tokens, pending: selections[selections.length - 1], selections }; } export function pieceChar(piece: Piece, owner: playerid): string { @@ -171,16 +183,9 @@ export function tokenText(t: Token): string { return t.text; } -/** Rebuild a move string from tokens, keeping the selections last (the pending square at the very end). */ -export function joinMove(tokens: Token[], pending?: string, previous?: string): string { - const parts = tokens.map(tokenText); - if (pending !== undefined) { - if (previous !== undefined) { - parts.push(previous); - } - parts.push(pending); - } - return parts.join(" "); +/** Keep any number of pending selections at the end of the move. */ +export function joinSelections(tokens: Token[], selections: string[]): string { + return [...tokens.map(tokenText), ...selections].join(" "); } /** Build a destination token for `piece` on `from` ending on `to`. */ @@ -189,9 +194,10 @@ export function arrowToken(piece: Piece, owner: playerid, from: string, to: stri return { spec: { piece, owner, square: from }, prop: { kind: "dest", square: to }, text }; } -/** A hold: `piece` on `square` ends the turn where it stands (a zero-length arrow). */ -export function holdToken(piece: Piece, owner: playerid, square: string): Token { - return arrowToken(piece, owner, square, square); +/** Build a step token for `piece` on `from` taking the steps `dirs`. */ +export function stepsToken(piece: Piece, owner: playerid, from: string, dirs: Dir[]): Token { + const text = `${pieceChar(piece, owner)}${from}${dirs.join("")}`; + return { spec: { piece, owner, square: from }, prop: { kind: "steps", dirs }, text }; } /** A destination token drawn from a piece's square to another square. */ @@ -199,16 +205,16 @@ export function isArrow(t: Token): boolean { return t.prop.kind === "dest" && t.spec.square !== undefined && t.spec.square !== t.prop.square; } -/** A destination token that keeps a piece on its own square. */ -export function isHold(t: Token): boolean { - return t.prop.kind === "dest" && t.spec.square !== undefined && t.spec.square === t.prop.square; -} - /** A capture token for the piece on `square`: it is captured during the turn. */ export function captureToken(piece: Piece, owner: playerid, square: string): Token { return { spec: { piece, owner, square }, prop: { kind: "capture" }, text: `${pieceChar(piece, owner)}${square}x` }; } +/** An input-only assertion that the piece is not captured; serialization drops it. */ +export function surviveToken(piece: Piece, owner: playerid, square: string): Token { + return { spec: { piece, owner, square }, prop: { kind: "survive" }, text: `${pieceChar(piece, owner)}${square}o` }; +} + /** A capture token naming a square: a mark on the piece standing there. */ export function isMark(t: Token): boolean { return t.prop.kind === "capture" && t.spec.square !== undefined; diff --git a/src/games/arimaa/setup.ts b/src/games/arimaa/setup.ts new file mode 100644 index 000000000..0304e51a1 --- /dev/null +++ b/src/games/arimaa/setup.ts @@ -0,0 +1,354 @@ +/** + * Setting up: the standard 16-piece setup, Free placement, and the random + * start of Endless endgame. A setup is entered as comma-separated placements + * (`Ee2,Md2`), and a trailing piece letter on its own is the piece selected + * from the hand. + */ +import i18next from "i18next"; +import { GameBase, type IValidationResult } from "../_base.js"; +import { randomInt, shuffle, SquareOrthGraph } from "../../common/index.js"; +import type { ArimaaGame } from "../arimaa.js"; +import type { InputClick } from "./input.js"; +import { baseMove } from "./legacy.js"; +import { pc2name, type Piece, type playerid } from "./notation.js"; +import { STRENGTH, type CellContents } from "./turns.js"; + +const coords2algebraic = (x: number, y: number): string => GameBase.coords2algebraic(x, y, 8); +const algebraic2coords = (cell: string): [number, number] => GameBase.algebraic2coords(cell, 8); + +/** Whether `player` still has pieces in hand to place. */ +export function placing(hands: [Piece[], Piece[]] | undefined, player: playerid): hands is [Piece[], Piece[]] { + return hands !== undefined && hands[player - 1].length > 0; +} + +// the standard 16-piece setup, which the setup variants replace +export function standardSetup(variants: string[]): boolean { + return !variants.includes("eee") && !variants.includes("free"); +} + +// the two ranks a player sets up on, in the order they get auto-filled +export function homeCells(player: playerid): string[] { + const cells: string[] = []; + for (const row of (player === 1 ? [6,7] : [0,1])) { + for (let col = 0; col < 8; col++) { + cells.push(coords2algebraic(col, row)); + } + } + return cells; +} + +// Endless endgame's random start: a random army for Gold on its two ranks, +// and its mirror image for Silver +export function endlessEndgame(): {gold: [Piece, string][], silver: [Piece, string][]} { + const getRanks = (ranks: number[]): string[] => { + const cells: string[] = []; + for (const row of ranks) { + for (let col = 0; col < 8; col++) { + cells.push(coords2algebraic(col, row)); + } + } + return cells; + } + + let gold: Piece[]; + do { + gold = ["E"]; + // camels + let limit = randomInt(1, 0); + for (let i = 0; i < limit; i++) { + gold.push("M"); + } + // horses, dogs, cats + for (const pc of ["H","D","C"] as const) { + limit = randomInt(2, 0); + for (let i = 0; i < limit; i++) { + gold.push(pc); + } + } + // rabbits + limit = randomInt(8, 1); + for (let i = 0; i < limit; i++) { + gold.push("R"); + } + } while (gold.length < 4 || gold.length > 12); + const cellsGold = shuffle(getRanks([6,7])); + const combinedGold: [Piece, string][] = []; + for (let i = 0; i < gold.length; i++) { + combinedGold.push([gold[i], cellsGold[i]]); + } + const flip = randomInt(1, 0); + const combinedSilver: [Piece, string][] = []; + combinedGold.forEach(([pc, cell]) => { + const [col, row] = algebraic2coords(cell); + // rows reverse no matter what + let newRow: number; + if (row === 6) { + newRow = 1; + } else { + newRow = 0; + } + // reverse columns only if flip is 1 + let newCol = col; + if (flip === 1) { + newCol = 7 - col; + } + combinedSilver.push([pc, coords2algebraic(newCol, newRow)]); + }); + return {gold: combinedGold, silver: combinedSilver}; +} + +// In standard setup, a player only needs to place their eight non-rabbits. +// Once they have, the rest of their setup area gets filled with rabbits. +// Returns the move untouched in every other circumstance. +export function fillRabbits(board: Map, hands: [Piece[], Piece[]] | undefined, player: playerid, variants: string[], m: string): string { + if (!standardSetup(variants) || !placing(hands, player)) { + return m; + } + const mvs = m.split(",").filter(Boolean); + const steps = mvs.map(mv => baseMove(mv)); + const myhand = [...hands[player - 1]]; + for (const [pc, , cell] of steps) { + // a dangling piece selection or anything the validator will reject + if (cell === undefined || !myhand.includes(pc)) { + return m; + } + myhand.splice(myhand.indexOf(pc), 1); + } + // everything but the rabbits has to be placed already + if (myhand.length === 0 || myhand.some(pc => pc !== "R")) { + return m; + } + const placedCells = new Set(steps.map(([,,cell,]) => cell!)); + const empty = homeCells(player).filter(cell => !board.has(cell) && !placedCells.has(cell)); + if (empty.length !== myhand.length) { + return m; + } + return [...mvs, ...empty.map(cell => `${player === 1 ? "R" : "r"}${cell}`)].join(","); +} + +// A placement list, for `player` placing from `hand` onto `board`. +export function validateSetup(board: Map, hand: Piece[], player: playerid, variants: string[], m: string): IValidationResult { + const result: IValidationResult = {valid: false, message: i18next.t("apgames:validation._general.DEFAULT_HANDLER")}; + const g = new SquareOrthGraph(8, 8); + // capture tokens written at the end of free setup carry no instruction + const steps = m.split(",").filter(Boolean).filter(mv => !mv.startsWith("x")).map(mv => baseMove(mv)); + const placed = new Map(board); + const myhand = [...hand]; + for (const [pc, , cell] of steps) { + // must have pc in hand + if (!myhand.includes(pc)) { + result.valid = false; + result.message = i18next.t("apgames:validation.arimaa.NOPIECE", {piece: pc2name.get(pc)}); + return result; + } + if (cell !== undefined) { + // cell must be valid + try { + algebraic2coords(cell); + } catch { + result.valid = false; + result.message = i18next.t("apgames:validation._general.INVALIDCELL", {cell}); + return result; + } + // cell must be empty, including of anything placed earlier in this move + if (placed.has(cell)) { + result.valid = false; + result.message = i18next.t("apgames:validation._general.OCCUPIED", {where: cell}); + return result; + } + // in normal play, must be on home ranks + if (!variants.includes("free")) { + const homeRows = player === 1 ? [6,7] : [0,1]; + const [,y] = algebraic2coords(cell); + if (!homeRows.includes(y)) { + result.valid = false; + result.message = i18next.t("apgames:validation.arimaa.HOME_ROW"); + return result; + } + } + // fake place the piece + placed.set(cell, [pc, player]); + // remove the piece from the hand unless in free mode + if (!variants.includes("free")) { + myhand.splice(myhand.indexOf(pc), 1); + } + } + // if it's just a piece number, we need a cell + else { + result.valid = true; + result.complete = -1; + result.message = i18next.t("apgames:validation.arimaa.PARTIAL_PLACE"); + result.canrender = true; + return result; + } + } + + // if we've gotten this far, everything is valid + // now we just have to check completeness and return + let complete: -1|0|1; + let message: string; + // in free mode: + // - usually 0 with specific message + // - but must have 1 rabbit and none on the goal row + if (variants.includes("free")) { + const rabbits = [...placed.entries()].filter(e => e[1][1] === player && e[1][0] === "R").map(e => e[0]); + const goal = player === 1 ? "8" : "1"; + if (rabbits.length === 0 || rabbits.filter(cell => cell.endsWith(goal)).length > 0) { + complete = -1; + message = i18next.t("apgames:validation.arimaa.PARTIAL_FREE_NO") + } else { + complete = 0; + message = i18next.t("apgames:validation.arimaa.PARTIAL_FREE") + } + } + // otherwise, you have to place all your pieces, + // though the rabbits can be filled in for you + else { + const emptyHome = homeCells(player).filter(c => !placed.has(c)); + const autoRabbits = myhand.length > 0 && myhand.every(pc => pc === "R") && emptyHome.length === myhand.length; + if (myhand.length > 0 && !autoRabbits) { + complete = -1; + message = i18next.t("apgames:validation.arimaa.PARTIAL_PLAY") + } else { + // fake place the rabbits so the advice below sees the real setup + if (autoRabbits) { + for (const cell of emptyHome) { + placed.set(cell, ["R", player]); + } + } + // warnings go here + const warnings: string[] = []; + // same file (only silver) + if (player === 2) { + const [e1, e2] = [...placed.entries()].filter(e => e[1][0] === "E").map(e => e[0][0]); + if (e1 === e2) { + warnings.push(i18next.t("apgames:validation.arimaa.WARN_FILE") || "WARN"); + } + } + // unbalanced (gold and silver) + const majors = [...placed.entries()].filter(e => e[1][1] === player && ["E", "M", "H"].includes(e[1][0])).map(e => algebraic2coords(e[0])[0]); + const oneSide = majors.filter(n => n < 5).length; + if (oneSide === 0 || oneSide === 4) { + warnings.push(i18next.t("apgames:validation.arimaa.WARN_BALANCE") || "WARN"); + } + // hiding (gold and silver): a piece other than a cat on the back + // rank behind a weaker piece, a rabbit included + const frontRow = player === 1 ? 6 : 1; + const backRow = player === 1 ? 7 : 0; + for (let col = 0; col < 8; col++) { + const frontCell = g.coords2algebraic(col, frontRow); + const backCell = g.coords2algebraic(col, backRow); + const front = placed.get(frontCell)![0]; + const back = placed.get(backCell)![0]; + if (back !== "C" && STRENGTH[front] < STRENGTH[back]) { + warnings.push(i18next.t("apgames:validation.arimaa.WARN_HIDE") || "WARN"); + break; + } + } + if (warnings.length > 0) { + complete = 0; + message = [i18next.t("apgames:validation.arimaa.WARNINGS"), ...warnings].join(" "); + } else { + // complete is never 1 for setup + complete = 0; + message = i18next.t("apgames:validation._general.VALID_MOVE") + } + if (autoRabbits) { + message = [i18next.t("apgames:validation.arimaa.PARTIAL_RABBITS"), message].join(" "); + } + } + } + + result.valid = true; + result.canrender = true; + result.complete = complete; + result.message = message; + return result; +} + +// Setup clicks work on the comma-separated placement list. As in +// movement, a click that means nothing is a control: an empty square +// nothing can be placed on finishes the setup if it can be submitted, or +// else drops the piece selected from the hand, and an opponent's piece +// drops that selection, or else takes back the last piece placed. +export function setupClick(game: ArimaaGame, move: string, row: number, col: number, piece?: string): InputClick { + let newmove = ""; + const steps = move.split(",").filter(Boolean).map(mv => baseMove(mv)); + let lastPc: Piece|undefined; + let lastPlayer: playerid|undefined; + let lastFrom: string|undefined; + let lastTo: string|undefined; + if (steps.length > 0) { + [lastPc,lastPlayer,lastFrom,lastTo] = steps[steps.length - 1]; + } + let lastmove = ""; + let stub = move; + if (steps.length > 0) { + // set lastmove and stub if move is incomplete + // placement + if (placing(game.hands, game.currplayer) && lastFrom === undefined) { + lastmove = game.currplayer === 1 ? lastPc! : lastPc!.toLowerCase(); + stub = move.substring(0, move.lastIndexOf(",")); + } + // movement + else if (!placing(game.hands, game.currplayer) && (lastFrom !== undefined && lastTo === undefined) ) { + lastmove = `${lastPlayer === 1 ? lastPc : lastPc!.toLowerCase()}${lastFrom}`; + stub = move.substring(0, move.lastIndexOf(",")); + } + } + // console.log(JSON.stringify({move, lastPc, lastFrom, lastTo, lastmove, stub})); + // make the moves in the stub + const cloned = game.clone(); + cloned.move(stub, {partial: true}); + + // clicking off the board resets + if (row === -1 || col === -1) { + const [,pc, pstr] = piece!.split(""); + const p = parseInt(pstr, 10); + newmove = `${stub}${stub.length > 0 ? "," : ""}${p === 1 ? pc : pc.toLowerCase()}`; + } else { + const cell = coords2algebraic(col, row); + // clicking a placed cell unplaces it + if (cloned.board.has(cell)) { + // clicking an occupied cell after selecting a piece to place + if (lastmove.length === 0) { + // the click may land on the piece glyph or on the empty part of + // the square (then `piece` is empty), so go by what's on the board + const [occupant, owner] = cloned.board.get(cell)!; + const idx = steps.findIndex(([pc,,f,]) => pc === occupant && f === cell); + if (owner !== game.currplayer) { + newmove = move.split(",").filter(Boolean).slice(0, -1).join(","); + } else if (idx >= 0) { + steps.splice(idx, 1); + newmove = steps.map(([pc, p, f,]) => `${p === 1 ? pc : pc.toLowerCase()}${f}`).join(","); + } else { + newmove = stub; + } + } else { + newmove = stub; + } + } else if (!game.variants.includes("free") && !homeCells(game.currplayer).includes(cell)) { + if (lastmove.length > 0) { + return {move: stub}; + } + const v = game.validateMove(move); + return v.valid && (v.complete ?? -1) >= 0 ? {move, complete: true} : {move}; + } else { + // if just clicking directly on the board, choose a piece for them: + // in free setup the hand never empties, so default to a rabbit; + // otherwise take the strongest piece still in hand + if (lastmove === undefined || lastmove === "") { + let dflt: Piece; + if (game.variants.includes("free")) { + dflt = "R"; + } else { + dflt = [...cloned.hands![cloned.currplayer - 1]].sort((a,b) => STRENGTH[b] - STRENGTH[a])[0]; + } + lastmove = cloned.currplayer === 1 ? dflt : dflt.toLowerCase(); + } + newmove = `${stub}${stub.length > 0 ? "," : ""}${lastmove}${cell}`; + } + } + + return {move: newmove}; +} diff --git a/src/games/arimaa/turns.ts b/src/games/arimaa/turns.ts index cc1d669ff..855c12e58 100644 --- a/src/games/arimaa/turns.ts +++ b/src/games/arimaa/turns.ts @@ -5,7 +5,7 @@ * Squares are indexed `rank * 8 + file` with rank 0 being rank "1", so `n` is * +8, `s` is -8, `e` is +1 and `w` is -1. */ -import { arrowToken, captureToken, pieceChar, tokenText, type Dir, type Piece, type playerid, type Token } from "./notation.js"; +import { arrowToken, captureToken, pieceChar, stepsToken, tokenText, type Dir, type Piece, type playerid, type Token } from "./notation.js"; export type CellContents = [Piece, playerid]; @@ -30,7 +30,7 @@ function stepTo(i: number, d: number): number { } } -const NEIGHBOURS: number[][] = []; +export const NEIGHBOURS: number[][] = []; for (let i = 0; i < 64; i++) { const ns: number[] = []; for (const [, d] of DIRS) { @@ -42,7 +42,8 @@ for (let i = 0; i < 64; i++) { NEIGHBOURS.push(ns); } -export const TRAPS: number[] = ["c3", "f3", "c6", "f6"].map(sqIndex); +export const TRAP_SQUARES: readonly string[] = ["c3", "f3", "c6", "f6"]; +export const TRAPS: number[] = TRAP_SQUARES.map(sqIndex); export function manhattan(a: number, b: number): number { return Math.abs((a % 8) - (b % 8)) + Math.abs(Math.floor(a / 8) - Math.floor(b / 8)); @@ -56,12 +57,56 @@ for (let a = 0; a < 64; a++) { } } -function dirBetween(from: number, to: number): Dir { +export function dirBetween(from: number, to: number): Dir { const d = to - from; return d === 8 ? "n" : d === -8 ? "s" : d === 1 ? "e" : "w"; } -const STRENGTH: Record = { R: 1, C: 2, D: 3, H: 4, M: 5, E: 6 }; +export const STRENGTH: Record = { R: 1, C: 2, D: 3, H: 4, M: 5, E: 6 }; + +/** Whether the piece on `cell` is frozen: no piece of its own is beside it, and a stronger enemy piece is. */ +export function isFrozen(board: Map, cell: string): boolean { + const here = board.get(cell); + if (here === undefined) { + throw new Error("You can't check the frozen status of a nonexistent piece."); + } + let stronger = false; + for (const n of NEIGHBOURS[sqIndex(cell)]) { + const there = board.get(sqName(n)); + if (there === undefined) { + continue; + } + if (there[1] === here[1]) { + return false; + } + if (STRENGTH[there[0]] > STRENGTH[here[0]]) { + stronger = true; + } + } + return stronger; +} + +/** Whether no piece of its own is beside the piece on `cell`, as on a trap that captures it. An empty square counts as alone. */ +export function isAlone(board: Map, cell: string): boolean { + const here = board.get(cell); + return here === undefined || NEIGHBOURS[sqIndex(cell)].every(n => board.get(sqName(n))?.[1] !== here[1]); +} + +// Whether strength `strong` is exactly one rank above `weak` among the pieces +// on a board, `held[s]` being how many of either colour have strength `s`. A +// strength nobody holds is no rank: with no dog left, a horse is one rank +// above a cat. +function oneRankAbove(held: Int8Array, strong: number, weak: number): boolean { + if (strong <= weak) { + return false; + } + for (let s = weak + 1; s < strong; s++) { + if (held[s] > 0) { + return false; + } + } + return true; +} interface PieceState { id: number; @@ -130,6 +175,8 @@ class Search { public readonly pieces: PieceState[] = []; public readonly steps: TurnStep[] = []; public readonly captures: CaptureRec[] = []; + /** how many pieces of each strength, of either colour, are on the board */ + public readonly held = new Int8Array(7); public readonly startSig: string; constructor(board: Map, public readonly player: playerid) { @@ -139,6 +186,7 @@ class Search { this.pieces.push({ id, type, owner, strength: STRENGTH[type], start: i, cur: i, capturedAt: -1, visited: [i] }); this.cells[i] = owner === 1 ? STRENGTH[type] : -STRENGTH[type]; this.ids[i] = id; + this.held[STRENGTH[type]]++; } this.startSig = this.signature(); } @@ -265,6 +313,7 @@ class Search { this.ids[t] = -1; qp.cur = -1; qp.capturedAt = t; + this.held[qp.strength]--; this.captures.push({ pid: q, piece: qp.type, owner: qp.owner, square: t, afterStep: this.steps.length - 1 }); undo.caps.push({ pid: q, square: t, code: c }); } @@ -278,6 +327,7 @@ class Search { this.ids[square] = pid; this.pieces[pid].cur = square; this.pieces[pid].capturedAt = -1; + this.held[this.pieces[pid].strength]++; this.captures.pop(); } const p = this.pieces[u.st.pid]; @@ -303,6 +353,48 @@ class Search { return n; } + // The fewest pieces that can still be displaced `remaining` steps from + // now. A piece off its square needs a step for every square of the way + // back; one captured away from home stays away, and so does a rabbit of + // the mover's that has gone forward. + public leastDisplaced(remaining: number): number { + let n = 0; + const back: number[] = []; + for (const p of this.pieces) { + if (p.visited.length === 1) { + continue; + } + if (p.cur < 0) { + if (p.capturedAt !== p.start) { + n++; + } + } else if (p.cur !== p.start) { + n++; + if (p.type !== "R" || p.owner !== this.player || (p.cur >> 3) === (p.start >> 3)) { + back.push(DIST[p.cur * 64 + p.start]); + } + } + } + back.sort((a, b) => a - b); + for (const d of back) { + if (d > remaining) { + break; + } + remaining -= d; + n--; + } + return n; + } + + /** Whether a push or pull is made by a piece exactly one rank above the piece it moves, as the board stands. */ + public rightSized(atom: TurnStep[]): boolean { + if (atom.length !== 2) { + return false; + } + const [own, other] = atom[0].owner === this.player ? atom : [atom[1], atom[0]]; + return oneRankAbove(this.held, STRENGTH[own.piece], STRENGTH[other.piece]); + } + public snapshot(displaced: number, signature: string): Turn { const trajectories: Trajectory[] = []; let ownCaptured = 0; @@ -338,7 +430,7 @@ interface PTok { owner?: playerid; /** specifier square index, or -1 */ sq: number; - kind: "dest" | "steps" | "capture"; + kind: "dest" | "steps" | "capture" | "survive"; dest: number; dirs: Dir[]; } @@ -360,17 +452,44 @@ export type Resolution = | { status: "resolved"; bucket: [number, number]; turn: Turn; positions: number; lenient: boolean }; /** - * Find the move a token list denotes from `board` with `player` to move. - * Strict resolution is the notation's meaning; lenient resolution breaks a - * tie in the first bucket by fewest own captures, then most enemy captures. - * `prune` disables the search heuristic; it exists so tests can check that - * pruning never changes an answer. + * A turn a search found for a position, and the most pushes and pulls made by + * a piece exactly one rank above the piece it moves that any way of playing + * that position has, in as many steps and displacing as few pieces. Only a + * search that puts displaced pieces first counts them. */ -export function resolve(board: Map, player: playerid, maxSteps: number, tokens: Token[], lenient: boolean, prune = true): Resolution { +export interface Found { + turn: Turn; + rightSized: number; +} + +/** What `firstBucket` looks for. `prune` and `accept` are described at `resolve`. */ +interface Wanted { + prune: boolean; + accept?: (turn: Turn) => boolean; + /** order buckets by displaced pieces and then by steps */ + displacedFirst?: boolean; + /** the square of a piece that has to take a step, or be pushed or pulled, during the turn */ + mover?: number; + /** stop at the first turn found */ + any?: boolean; +} + +// Every position that a turn fitting the tokens reaches, with a turn for each, +// from the first bucket holding any. The notation orders buckets by steps and +// then by displaced pieces. With `displacedFirst` they are ordered by +// displaced pieces and then by steps, as click entry in Advanced mode asks, +// which can put a longer turn before a shorter one. +function firstBucket(board: Map, player: playerid, maxSteps: number, tokens: Token[], wanted: Wanted): Found[] { + const { prune, accept, displacedFirst = false, mover, any = false } = wanted; const s = new Search(board, player); + const moving = mover === undefined ? undefined : s.pieces[s.ids[mover]]; + if (mover !== undefined && moving === undefined) { + return []; + } const toks = prepare(tokens); const destGroups = new Map(); const captureToks: PTok[] = []; + const surviveToks: PTok[] = []; const stepToks: PTok[] = []; for (const t of toks) { if (t.kind === "dest") { @@ -382,6 +501,8 @@ export function resolve(board: Map, player: playerid, maxS } } else if (t.kind === "capture") { captureToks.push(t); + } else if (t.kind === "survive") { + surviveToks.push(t); } else { stepToks.push(t); } @@ -391,16 +512,19 @@ export function resolve(board: Map, player: playerid, maxS const visitedOk = (p: PieceState, t: PTok): boolean => t.sq < 0 || p.visited.includes(t.sq); const finalOf = (p: PieceState): number => p.cur < 0 ? p.capturedAt : p.cur; - // Longest prefix of a step token some piece has taken so far, ignoring the - // ordering between tokens (a lower bound on what remains). - const bestPrefix = (t: PTok): number => { - let best = 0; + // How far the steps taken after index `after` go towards a step token: + // the index at which some piece first completes it, or failing that the + // longest prefix of it any piece has taken. + const witness = (t: PTok, after: number): { end: number; prefix: number } => { + let end = Infinity; + let prefix = 0; for (const p of s.pieces) { if (!typeMatch(p, t)) { continue; } let j = 0; - for (const st of s.steps) { + for (let i = after + 1; i < s.steps.length; i++) { + const st = s.steps[i]; if (st.pid !== p.id) { continue; } @@ -410,15 +534,18 @@ export function resolve(board: Map, player: playerid, maxS if (st.dir === t.dirs[j]) { j++; if (j === t.dirs.length) { + if (i < end) { + end = i; + } break; } } } - if (j > best) { - best = j; + if (j > prefix) { + prefix = j; } } - return best; + return { end, prefix }; }; // Pieces a token could be witnessed by, and for a destination group the @@ -501,16 +628,43 @@ export function resolve(board: Map, player: playerid, maxS // priced: enough to skip a witness that cannot beat the best so far. const atLeast = (p: PieceState, d: number): number => p.owner === s.player ? d : 2 * d; + // Steps still needed before `moving` has moved: none once it has. An + // enemy piece needs its own step and its pusher's or puller's, once a + // stronger piece of the mover's is next to it. A piece of the mover's + // needs its own step, and before it a step by another piece if it is + // frozen and another if every square it could step to is taken. One step + // cannot do both: what frees it is a friend arriving next to it, which + // empties no square there since no friend stood there to leave, or a push + // or pull, which is two steps. + const movingPrice = (): number => { + const p = moving!; + if (p.visited.length > 1) { + return 0; + } + if (p.cur < 0) { + return Infinity; + } + if (p.owner !== s.player) { + return enemyPrice(p, 1); + } + const open = NEIGHBOURS[p.cur].some(n => s.cells[n] === 0 && !(ownRabbit(p) && behind(p.cur, n))); + return 1 + (s.frozen(p.cur) ? 1 : 0) + (open ? 0 : 1); + }; + // An admissible lower bound on the steps still needed, or any value above // `limit` as soon as the bound is known to exceed it. Two bounds are // combined by max: (1) one step per square for every witness, summed over // distinct destinations, which need distinct witnesses; (2) per token, the // full price of its cheapest witness, including an enemy's partner and - // approach steps, a frozen piece's release, and clearing the destination. + // approach steps, a frozen piece's release, and clearing the destination, + // and likewise what it takes for the piece that has to move to move. const heuristic = (limit: number): number => { stamp++; let sum = 0; - let max = 0; + let max = moving === undefined ? 0 : movingPrice(); + if (max > limit) { + return max; + } for (const [dest, group] of destGroups) { let groupCost = 0; let groupFull = 0; @@ -679,16 +833,30 @@ export function resolve(board: Map, player: playerid, maxS return max; } } + // Step tokens are witnessed in the order written, each by steps taken + // after the one before it was completed, so what they still lack adds + // up: the rest of the first one not yet completed and every step of + // those after it. + let after = -1; + let lacking = 0; + let open = false; for (const t of stepToks) { if (t.type === "R" && t.owner === s.player && t.dirs.includes(backwardDir)) { return Infinity; } - const left = t.dirs.length - bestPrefix(t); - if (left > max) { - max = left; + if (open) { + lacking += t.dirs.length; + continue; + } + const w = witness(t, after); + if (w.end === Infinity) { + open = true; + lacking += t.dirs.length - w.prefix; + } else { + after = w.end; } } - return Math.max(sum, max); + return Math.max(sum, max, lacking); }; const satisfies = (): boolean => { @@ -704,41 +872,19 @@ export function resolve(board: Map, player: playerid, maxS return false; } } + for (const t of surviveToks) { + if (!s.pieces.some(p => typeMatch(p, t) && visitedOk(p, t) && p.cur >= 0)) { + return false; + } + } // step tokens must be witnessed in the order written; the earliest // completion of each leaves the most room for the next let after = -1; for (const t of stepToks) { - let bestEnd = Infinity; - for (const p of s.pieces) { - if (!typeMatch(p, t)) { - continue; - } - let j = 0; - let end = -1; - for (let i = after + 1; i < s.steps.length; i++) { - const st = s.steps[i]; - if (st.pid !== p.id) { - continue; - } - if (j === 0 && t.sq >= 0 && st.from !== t.sq) { - continue; - } - if (st.dir === t.dirs[j]) { - j++; - end = i; - if (j === t.dirs.length) { - break; - } - } - } - if (j === t.dirs.length && end < bestEnd) { - bestEnd = end; - } - } - if (bestEnd === Infinity) { + after = witness(t, after).end; + if (after === Infinity) { return false; } - after = bestEnd; } return true; }; @@ -746,6 +892,7 @@ export function resolve(board: Map, player: playerid, maxS // Everything the search asks of a state, except the order of the steps // that led to it, is in the board and each moved piece's visited squares. // Step tokens are the exception, so the memo is off while any is present. + // `accept` is held to the same rule. const stateKey = (): string => { let key = s.signature(); for (const p of s.pieces) { @@ -757,49 +904,91 @@ export function resolve(board: Map, player: playerid, maxS }; const memo = stepToks.length === 0; + // No turn that fits displaces fewer pieces than this: a destination that + // the piece standing on it does not answer for takes a piece from + // elsewhere, and distinct destinations take distinct pieces. + let floor = 0; + for (const [dest, group] of destGroups) { + const there = s.ids[dest]; + if (there < 0 || !group.every(t => typeMatch(s.pieces[there], t))) { + floor++; + } + } + + let best: Found[] = []; + // displaced pieces a turn has to stay under to be worth its extra steps + let under = Infinity; + let rightSized = 0; + // set once a turn is found when any will do + let done = false; for (let k = 1; k <= maxSteps; k++) { - const found = new Map(); - // States already searched with at least as many steps left. Every - // shallower iteration came up empty, so reaching a state again with - // fewer steps left can only lead to ends found there or ends that - // would have satisfied a shallower iteration. + const found = new Map(); + // States already searched with at least as many steps left, and as + // many right-sized pushes and pulls behind them. Whatever a state + // leads to with fewer steps left was within reach of a shallower + // iteration, which either came up empty or found it in fewer steps. const seen = new Map(); const dfs = (remaining: number): void => { + if (done) { + return; + } if (remaining === 0) { + if (moving !== undefined && moving.visited.length === 1) { + return; + } const sig = s.signature(); if (sig === s.startSig || !satisfies()) { return; } const displaced = s.displaced(); + if (displaced >= under) { + return; + } + const candidate = s.snapshot(displaced, sig); + if (accept !== undefined && !accept(candidate)) { + return; + } const existing = found.get(sig); - if (existing === undefined || displaced < existing.displaced) { - found.set(sig, s.snapshot(displaced, sig)); + if (existing === undefined || displaced < existing.turn.displaced || + (displaced === existing.turn.displaced && rightSized > existing.rightSized)) { + found.set(sig, { turn: candidate, rightSized }); } + done = any; return; } if (prune && heuristic(remaining) > remaining) { return; } + if (prune && under !== Infinity && s.leastDisplaced(remaining) >= under) { + return; + } if (prune && memo && remaining < k) { const key = stateKey(); - const best = seen.get(key); - if (best !== undefined && best >= remaining) { + const reached = remaining * (maxSteps + 1) + rightSized; + const before = seen.get(key); + if (before !== undefined && before >= reached) { return; } - seen.set(key, remaining); + seen.set(key, reached); } for (const atom of s.atoms(remaining)) { if (atom.length > remaining) { continue; } + const counts = displacedFirst && s.rightSized(atom) ? 1 : 0; const undos: Undo[] = []; for (const st of atom) { undos.push(s.apply(st)); } + rightSized += counts; dfs(remaining - atom.length); + rightSized -= counts; while (undos.length > 0) { s.undo(undos.pop()!); } + if (done) { + return; + } } }; dfs(k); @@ -807,35 +996,238 @@ export function resolve(board: Map, player: playerid, maxS continue; } let minDisplaced = Infinity; - for (const t of found.values()) { - if (t.displaced < minDisplaced) { - minDisplaced = t.displaced; + for (const f of found.values()) { + if (f.turn.displaced < minDisplaced) { + minDisplaced = f.turn.displaced; } } - const candidates = [...found.values()].filter(t => t.displaced === minDisplaced); - const bucket: [number, number] = [k, minDisplaced]; - if (candidates.length === 1) { - return { status: "resolved", bucket, turn: candidates[0], positions: 1, lenient: false }; - } - if (lenient) { - const score = (t: Turn): number => t.ownCaptured * 100 - t.enemyCaptured; - let best = candidates[0]; - let tie = false; - for (const t of candidates.slice(1)) { - if (score(t) < score(best)) { - best = t; - tie = false; - } else if (score(t) === score(best)) { - tie = true; - } + best = [...found.values()].filter(f => f.turn.displaced === minDisplaced); + if (!displacedFirst || minDisplaced <= floor) { + break; + } + under = minDisplaced; + } + return best; +} + +/** + * Find the move a token list denotes from `board` with `player` to move. + * Strict resolution is the notation's meaning; lenient resolution breaks a + * tie in the first bucket by fewest own captures, then most enemy captures. + * `prune` disables the search heuristic; it exists so tests can check that + * pruning never changes an answer. `accept` narrows the turns considered to + * those it returns true for; click entry uses it to ask for more than tokens + * can say. It may look only at where each piece starts, passes and ends, not + * at the order of the steps: the search does not try every order that reaches + * a state. + */ +export function resolve(board: Map, player: playerid, maxSteps: number, tokens: Token[], lenient: boolean, prune = true, accept?: (turn: Turn) => boolean): Resolution { + const candidates = firstBucket(board, player, maxSteps, tokens, {prune, accept}).map(f => f.turn); + if (candidates.length === 0) { + return { status: "unsatisfiable" }; + } + const bucket: [number, number] = [candidates[0].steps.length, candidates[0].displaced]; + if (candidates.length === 1) { + return { status: "resolved", bucket, turn: candidates[0], positions: 1, lenient: false }; + } + if (lenient) { + let best = candidates[0]; + let tie = false; + for (const t of candidates.slice(1)) { + const c = byCaptures(t, best); + if (c < 0) { + best = t; + tie = false; + } else if (c === 0) { + tie = true; } - if (!tie) { - return { status: "resolved", bucket, turn: best, positions: candidates.length, lenient: true }; + } + if (!tie) { + return { status: "resolved", bucket, turn: best, positions: candidates.length, lenient: true }; + } + } + return { status: "ambiguous", bucket, positions: candidates.length, candidates }; +} + +/** + * The turns that fit a token list when what is asked of a turn is, before + * anything else, to displace as few pieces as it can, and only then to take as + * few steps: one for each position in the first such bucket, and none if no + * turn fits. This is how click entry in Advanced mode reads what a player has + * said so far. It is not what the notation means: `resolve` is. + */ +export function fewestDisplaced(board: Map, player: playerid, maxSteps: number, tokens: Token[], accept?: (turn: Turn) => boolean, prune = true): Found[] { + return firstBucket(board, player, maxSteps, tokens, {prune, accept, displacedFirst: true}); +} + +/** + * Whether every token already holds of the position as it stands: holds and + * survival assertions about pieces that are where the tokens say. + */ +export function standing(board: Map, tokens: Token[]): boolean { + return tokens.every(t => { + if (t.prop.kind !== "dest" && t.prop.kind !== "survive") { + return false; + } + const matches = ([piece, owner]: CellContents): boolean => t.spec.piece === undefined || (t.spec.piece === piece && t.spec.owner === owner); + const at = t.prop.kind === "dest" ? t.prop.square : t.spec.square; + if (at === undefined) { + return [...board.values()].some(matches); + } + if (t.spec.square !== undefined && t.spec.square !== at) { + return false; + } + const there = board.get(at); + return there !== undefined && matches(there); + }); +} + +export type Displayed = + | { status: "unsatisfiable" } + /** every token already holds of the position as it stands: nothing moves yet */ + | { status: "idle" } + /** + * `by` says what settled on the turn: the notation's own meaning, a + * preference for some captures over others, the whole of Advanced click + * entry's preferences (`choose`), or, with "choice", nothing but the + * order positions sort in. `positions` is how many the first bucket holds. + */ + | { status: "turn"; turn: Turn; by: "notation" | "captures" | "preference" | "choice"; positions: number }; + +/** + * What a token list is shown as and, once the player completes it, played as: + * the notation's own meaning where it has one, and otherwise, of the turns in + * its first bucket, the one capturing the fewest own pieces, then the most + * enemy pieces, then (so that there is always an answer) the one whose + * position sorts first. What is stored for a turn is always written by + * `serializeTurn`, which needs none of these preferences to be read back. + */ +export function display(board: Map, player: playerid, maxSteps: number, tokens: Token[], accept?: (turn: Turn) => boolean): Displayed { + if (accept === undefined && standing(board, tokens)) { + return { status: "idle" }; + } + const r = resolve(board, player, maxSteps, tokens, true, true, accept); + if (r.status === "unsatisfiable") { + return r; + } + if (r.status === "resolved") { + return { status: "turn", turn: r.turn, by: r.lenient ? "captures" : "notation", positions: r.positions }; + } + let best = r.candidates[0]; + for (const t of r.candidates) { + const c = byCaptures(t, best); + if (c < 0 || (c === 0 && t.signature < best.signature)) { + best = t; + } + } + return { status: "turn", turn: best, by: "choice", positions: r.positions }; +} + +/** Turns that capture fewer own pieces first, then those capturing more enemy pieces. */ +export function byCaptures(a: Turn, b: Turn): number { + return a.ownCaptured - b.ownCaptured || b.enemyCaptured - a.enemyCaptured; +} + +/** + * How Advanced click entry orders the turns of a first bucket, which already + * displace the fewest pieces in the fewest steps: the fewest own pieces + * captured, the most enemy pieces captured, the most pushes and pulls of a + * piece exactly one rank weaker, then the most enemy pieces less own pieces + * left beside an opposing piece exactly one rank stronger (`wrongPieces`). + * Normal Move (`choose`) and Target Selection both order by this. + */ +export function preferences(player: playerid): (a: Found, b: Found) => number { + const enemy: playerid = player === 1 ? 2 : 1; + const wrongs = new Map(); + const wrong = ({turn: {signature}}: Found): number => { + let n = wrongs.get(signature); + if (n === undefined) { + n = wrongPieces(signature, enemy) - wrongPieces(signature, player); + wrongs.set(signature, n); + } + return n; + }; + return (a, b) => byCaptures(a.turn, b.turn) || b.rightSized - a.rightSized || wrong(b) - wrong(a); +} + +/** + * What click entry in Advanced mode takes a token list to mean, which is not + * what the notation means by it (`display`). Beyond what the tokens say it + * asks for as little as it can: of every turn that fits, the fewest pieces + * displaced, then the fewest steps, then by `preferences`, and then (so that + * there is always an answer) the position that sorts first. An entry that is + * to be played as this turn has to say so in terms the notation reads the + * same way. + */ +export function choose(board: Map, player: playerid, maxSteps: number, tokens: Token[], accept?: (turn: Turn) => boolean): Displayed { + if (accept === undefined && standing(board, tokens)) { + return { status: "idle" }; + } + const found = fewestDisplaced(board, player, maxSteps, tokens, accept); + if (found.length === 0) { + return { status: "unsatisfiable" }; + } + const preference = preferences(player); + let best = found[0]; + let tied = false; + for (const f of found.slice(1)) { + const c = preference(f, best); + if (c < 0) { + best = f; + tied = false; + } else if (c === 0) { + tied = true; + if (f.turn.signature < best.turn.signature) { + best = f; } } - return { status: "ambiguous", bucket, positions: candidates.length, candidates }; } - return { status: "unsatisfiable" }; + return { status: "turn", turn: best.turn, by: tied ? "choice" : "preference", positions: found.length }; +} + +/** + * How many of `side`'s pieces, in the position a signature describes, stand + * next to an enemy piece exactly one rank stronger. Ranks are counted over + * the pieces on the board, as for a right-sized push. + */ +export function wrongPieces(signature: string, side: playerid): number { + const cells = new Int8Array(64); + const held = new Int8Array(7); + for (let i = 0; i < 64; i++) { + const ch = signature[i]; + if (ch !== "-") { + const strength = STRENGTH[ch.toUpperCase() as Piece]; + cells[i] = ch === ch.toUpperCase() ? strength : -strength; + held[strength]++; + } + } + let n = 0; + for (let i = 0; i < 64; i++) { + const c = cells[i]; + if (c === 0 || (c > 0) !== (side === 1)) { + continue; + } + if (NEIGHBOURS[i].some(j => cells[j] !== 0 && (cells[j] > 0) !== (c > 0) && oneRankAbove(held, Math.abs(cells[j]), Math.abs(c)))) { + n++; + } + } + return n; +} + +/** The position signature turns are compared by. */ +export function boardSignature(board: Map): string { + return new Search(board, 1).signature(); +} + +/** + * Whether the piece on `origin` can take a step, or be pushed or pulled, in + * some turn of at most `maxSteps` steps that fits `tokens`. + */ +export function canMoveWithin(board: Map, player: playerid, maxSteps: number, origin: string, tokens: Token[] = []): boolean { + if (maxSteps <= 0 || !board.has(origin)) { + return false; + } + return firstBucket(board, player, maxSteps, tokens, {prune: true, mover: sqIndex(origin), any: true}).length > 0; } /** @@ -874,8 +1266,7 @@ export function inferred(turn: Turn, tokens: Token[]): Trajectory[] { // Serialization function stepToken(st: TurnStep): Token { - const from = sqName(st.from); - return { spec: { piece: st.piece, owner: st.owner, square: from }, prop: { kind: "steps", dirs: [st.dir] }, text: `${pieceChar(st.piece, st.owner)}${from}${st.dir}` }; + return stepsToken(st.piece, st.owner, sqName(st.from), [st.dir]); } function bareToken(t: Token): Token { @@ -885,8 +1276,10 @@ function bareToken(t: Token): Token { text = `${piece}${t.prop.square}`; } else if (t.prop.kind === "capture") { text = `${piece}x`; - } else { + } else if (t.prop.kind === "steps") { text = `${piece}${t.prop.dirs.join("")}`; + } else { + text = `${piece}o`; } return { spec: { piece: t.spec.piece, owner: t.spec.owner }, prop: t.prop, text }; } diff --git a/test/fixtures/arimaa/coverage.ts b/test/fixtures/arimaa/coverage.ts index bfe273f61..0703a63d0 100644 --- a/test/fixtures/arimaa/coverage.ts +++ b/test/fixtures/arimaa/coverage.ts @@ -1,7 +1,8 @@ // An independent enumerator of every legal Arimaa turn from a position, used to -// check that each reachable position can be entered with clicks alone. It -// deliberately re-implements the rules rather than calling the engine's own -// search, so a mistake in one is not mirrored in the other. +// check that each reachable position can be entered with clicks alone, and +// that click entry prefers the turns it is meant to. It deliberately +// re-implements the rules rather than calling the engine's own search, so a +// mistake in one is not mirrored in the other. export type Owner = 1 | 2; export type Board = Map; @@ -147,3 +148,104 @@ export const allTurns = (b: Board, player: Owner, maxSteps: number): Map; + /** pushes and pulls made by a piece exactly one rank above the piece it moved */ + rightSized: number; +} + +/** + * Whether `strong` is exactly one rank above `weak` on a board. A rank that + * no piece of either colour holds does not count: with no dog on the board, a + * horse is one rank above a cat. + */ +export const oneRankAbove = (b: Board, strong: string, weak: string): boolean => { + if (STRENGTH[strong] <= STRENGTH[weak]) { + return false; + } + for (const [pc] of b.values()) { + if (STRENGTH[pc] > STRENGTH[weak] && STRENGTH[pc] < STRENGTH[strong]) { + return false; + } + } + return true; +}; + +/** + * Every way of playing every legal turn of at most `maxSteps` steps, with each + * piece followed from the square it started on. A push or pull is judged on + * the board as it stands when it is made. + */ +export const allPlays = (b: Board, player: Owner, maxSteps: number): Play[] => { + const start = signature(b); + const out: Play[] = []; + // `origin` maps the square a moved piece stands on to the one it started on + const dfs = (cur: Board, origin: Map, paths: Map, steps: number, rightSized: number): void => { + if (steps > 0 && signature(cur) !== start) { + out.push({ steps, board: cur, paths, rightSized }); + } + const left = maxSteps - steps; + for (const atom of left === 0 ? [] : atoms(cur, player, left)) { + if (atom.length > left) { + continue; + } + let fits = 0; + if (atom.length === 2) { + const first = cur.get(atom[0][0])!; + const second = cur.get(atom[1][0])!; + const [mine, theirs] = first[1] === player ? [first, second] : [second, first]; + fits = oneRankAbove(cur, mine[0], theirs[0]) ? 1 : 0; + } + let nb = cur; + const no = new Map(origin); + const np = new Map([...paths].map(([from, p]): [string, Path] => [from, { ...p, visited: p.visited.slice() }])); + const pathOf = (from: string, pc: [string, Owner]): Path => { + let p = np.get(from); + if (p === undefined) { + p = { type: pc[0], owner: pc[1], visited: [from], final: from, captured: false }; + np.set(from, p); + } + return p; + }; + for (const [f, t] of atom) { + const pc = nb.get(f)!; + const from = no.get(f) ?? f; + no.delete(f); + no.set(t, from); + const moved = pathOf(from, pc); + moved.visited.push(t); + moved.final = t; + const standing: Board = new Map(nb); + standing.set(t, pc); + standing.delete(f); + nb = step(nb, f, t); + for (const trap of TRAPS) { + const gone = standing.get(trap); + if (gone !== undefined && !nb.has(trap)) { + const died = pathOf(no.get(trap) ?? trap, gone); + no.delete(trap); + died.captured = true; + died.final = trap; + } + } + } + dfs(nb, no, np, steps + atom.length, rightSized + fits); + } + }; + dfs(b, new Map(), new Map(), 0, 0); + return out; +}; diff --git a/test/games/arimaa-input-modes.test.ts b/test/games/arimaa-input-modes.test.ts new file mode 100644 index 000000000..ad0d97aec --- /dev/null +++ b/test/games/arimaa-input-modes.test.ts @@ -0,0 +1,1268 @@ +import "mocha"; +import { expect } from "chai"; +import i18next from "i18next"; +import { addResource } from "../../src"; +import { ArimaaGame } from "../../src/games/arimaa"; +import { parseMove } from "../../src/games/arimaa/notation"; +import { ARIMAA_CAPTURE_CHOICE, ARIMAA_SPARE_CHOICE, captureAlternatives, captureChoices } from "../../src/games/arimaa/input"; +import { resolve } from "../../src/games/arimaa/turns"; +import { allPlays, allTurns, boardOf, neighbours, oneRankAbove, signature, type Board, type Owner, type Path, type Play } from "../fixtures/arimaa/coverage"; + +type Mode = "basic" | "advanced"; +const MODES: Mode[] = ["basic", "advanced"]; + +const at = (cell: string): [number, number] => { + const [col, row] = ArimaaGame.algebraic2coords(cell); + return [row, col]; +}; +const click = (game: ArimaaGame, move: string, cell: string, mode: Mode = "basic", piece?: string) => + game.handleClick(move, ...at(cell), piece, {inputMode: mode}); + +const position = (gold: string, silver: string): ArimaaGame => { + const game = new ArimaaGame(undefined, ["free"]); + game.move(gold); + game.move(silver); + return game; +}; +/** Click squares in order, each of which must be accepted; a leading `^` clicks the trap's capture triangle. */ +const enter = (game: ArimaaGame, mode: Mode, squares: string[], start = ""): string => { + let move = start; + for (const sq of squares) { + const r = click(game, move, sq.replace("^", ""), mode, sq.startsWith("^") ? ARIMAA_CAPTURE_CHOICE : undefined); + expect(r.valid, `${mode} click ${sq} after "${move}": ${r.message}`).to.equal(true); + move = r.move; + } + return move; +}; +/** The game after `move`, which has to be one a player could submit. */ +const played = (game: ArimaaGame, move: string): ArimaaGame => { + const v = game.validateMove(move); + expect(v.valid, `${move}: ${v.message}`).to.equal(true); + expect(v.complete, `${move}: ${v.message}`).to.be.at.least(0); + return game.clone().move(move); +}; +/** What is drawn for an entry while it is being made, as `type:square>square`. */ +const marks = (game: ArimaaGame, move: string): string[] => + ((game.clone().move(move, {partial: true}).render().annotations ?? []) as Array<{type: string; targets: Array<{row: number; col: number}>}>) + .map(a => `${a.type}:${a.targets.map(t => ArimaaGame.coords2algebraic(t.col, t.row)).join(">")}`); + +/** What an Advanced entry says, apart from the steps of the move shown that it may list after that. */ +const said = (move: string): string[] => parseMove(move, true).tokens.filter(t => t.prop.kind !== "steps").map(t => t.text); +const listed = (move: string): string[] => parseMove(move, true).tokens.filter(t => t.prop.kind === "steps").map(t => t.text); +const ambiguous = (count: number): string => i18next.t("apgames:validation.arimaa.AMBIGUOUS", {count}); +const withDie = (game: ArimaaGame, steps: number): ArimaaGame => { + game.die = {steps, square: "a4"}; + return game; +}; +/** A position to click on, with no hands and the given player to move. */ +const ready = (board: Board, player: Owner): ArimaaGame => { + const g = new ArimaaGame(undefined, ["free"]); + g.stack[0].board = new Map(board) as ArimaaGame["board"]; + g.stack.push({...g.stack[0], _results: [], _timestamp: new Date(), currplayer: player, board: new Map(board) as ArimaaGame["board"], hands: undefined, lastmove: "x"}); + g.load(); + g.hands = undefined; + return g; +}; + +describe("Arimaa input modes", () => { + before(() => addResource("en")); + + it("defaults to Basic, with Advanced on request", () => { + const g = position("Ed4,Ra1", "ra8,ee8"); + expect(g.resolveActiveInputMode(undefined)).to.equal("basic"); + expect(g.resolveActiveInputMode("advanced")).to.equal("advanced"); + }); + + describe("Basic", () => { + it("selects and moves an ordinary piece without automatic submission", () => { + const g = position("Ed4,Ra1", "ra8,ee8"); + const selected = click(g, "", "d4"); + expect(selected.move).to.equal("d4"); + expect(selected.complete).to.equal(-1); + const moved = click(g, selected.move, "e4"); + expect(moved.move).to.equal("Ed4e"); + expect(moved.valid).to.equal(true); + expect(moved.complete).to.equal(0); + expect(g.validateMove(moved.move).complete).to.equal(0); + expect(click(g, moved.move, "h2").complete).to.equal(1); + }); + + it("writes each destination click as the steps the selected piece takes", () => { + const g = position("Ed4,Ra1", "ra8,ee8"); + let move = enter(g, "basic", ["d4", "d6"]); + expect(move).to.equal("Ed4nn"); + move = enter(g, "basic", ["a1", "a2"], move); + expect(move).to.equal("Ed4nn Ra1n"); + // a piece that has moved is named by the square it now stands on + move = enter(g, "basic", ["d6", "e6"], move); + expect(move).to.equal("Ed4nn Ra1n Ed6e"); + const after = played(g, move); + expect(after.board.get("e6")).to.deep.equal(["E", 1]); + expect(after.board.get("a2")).to.deep.equal(["R", 1]); + // what is stored is the usual notation, not the step list + expect(after.lastmove).to.equal("Ee6 Ra2"); + }); + + it("never infers an unselected pusher, though Advanced does", () => { + const g = position("Hg3,Cf2,Ra2,Ee1", "dh3,ra7,ee8"); + const basicSelected = click(g, "", "h3"); + expect(basicSelected.move).to.equal("h3"); + const basicMoved = click(g, basicSelected.move, "f3"); + expect(basicMoved.move).to.equal(""); + const advancedSelected = click(g, "", "h3", "advanced"); + expect(advancedSelected.move).to.equal("h3"); + const advancedMoved = click(g, advancedSelected.move, "f3", "advanced"); + expect(advancedMoved.valid).to.equal(true); + expect(advancedMoved.move).to.equal("dh3f3"); + expect(advancedMoved.complete).to.equal(0); + }); + + it("enters an explicitly selected push and pull as ordered chains", () => { + const g = position("Ed4,Hf4,Ra1,Cc1", "re4,ra8,ee8"); + let p = click(g, "", "d4"); + p = click(g, p.move, "e4"); + expect(p.move).to.equal("d4 e4"); + p = click(g, p.move, "e5"); + expect(p.valid).to.equal(true); + expect(p.move).to.equal("re4n Ed4e"); + expect(p.complete).to.equal(0); + expect(played(g, p.move).lastmove).to.equal("re5 Ee4"); + + let pull = click(g, "", "e4"); + pull = click(g, pull.move, "d4"); + expect(pull.move).to.equal("e4 d4"); + pull = click(g, pull.move, "c4"); + expect(pull.valid).to.equal(true); + expect(pull.move).to.equal("Ed4w re4w"); + expect(pull.complete).to.equal(0); + expect(played(g, pull.move).lastmove).to.equal("Ec4 rd4"); + }); + + it("takes a push or pull as its two steps, one after the other, as well as all at once", () => { + const g = position("Ed4,Hf4,Ra1,Cc1", "re4,ra8,ee8"); + const push = enter(g, "basic", ["d4", "e4", "e5"]); + // the pushed piece first: it waits, drawn as an arrow, for the piece that pushes it + const waiting = enter(g, "basic", ["e4", "e5"]); + expect(waiting).to.equal("e4 e5"); + const v = g.validateMove(waiting); + expect(v.complete).to.equal(-1); + expect(v.message).to.equal(i18next.t("apgames:validation.arimaa.PARTIAL_PUSH")); + expect(marks(g, waiting)).to.deep.equal(["move:e4>e5"]); + // a click on the pusher is enough: it can only follow into the square the pushed piece left + expect(enter(g, "basic", ["d4"], waiting)).to.equal(push); + // either piece strong enough can be the one that pushes + const byHorse = played(g, enter(g, "basic", ["f4"], waiting)); + expect(byHorse.board.get("e4")).to.deep.equal(["H", 1]); + expect(byHorse.board.get("e5")).to.deep.equal(["R", 2]); + // the puller first, then the pulled piece into the square it left + const pull = enter(g, "basic", ["e4", "d4", "c4"]); + expect(enter(g, "basic", ["d4", "c4", "e4", "d4"])).to.equal(pull); + // with a two-step die, the pull's second step is the last + const dicey = withDie(position("Ed4,Hf4,Ra1,Cc1", "re4,ra8,ee8"), 2); + expect(played(dicey, enter(dicey, "basic", ["d4", "c4", "e4", "d4"])).board.get("d4")).to.deep.equal(["R", 2]); + }); + + it("sends an enemy piece two squares in one arrow, pulled then pushed, as in a flip", () => { + // the horse steps away, the dog follows it and is pushed on onto the + // trap, and the horse steps back: the dog dies and nothing else changes + const g = position("Hg3,Cf2,Ra2,Ee1", "dh3,ra7,ee8"); + const away = enter(g, "basic", ["g3", "g4"]); + const arrow = enter(g, "basic", ["h3", "f3"], away); + expect(arrow).to.equal("Hg3n dh3w g3 f3"); + expect(g.validateMove(arrow).message).to.contain(i18next.t("apgames:validation.arimaa.PARTIAL_PUSH")); + const flipped = enter(g, "basic", ["g4"], arrow); + expect(flipped).to.equal("Hg3n dh3w dg3w Hg4s"); + const after = played(g, flipped); + expect(after.lastmove).to.equal("dx"); + expect(after.board.get("g3")).to.deep.equal(["H", 1]); + // the dog's steps one at a time come to the same thing + expect(enter(g, "basic", ["h3", "g3", "g3", "f3", "g4"], away)).to.equal(flipped); + // an enemy piece cannot take a third step in a row + const three = position("Hg3,Ra2,Ee1", "dh3,ra7,ee8"); + expect(enter(three, "basic", ["h3", "e3"], enter(three, "basic", ["g3", "g4"]))).to.equal("Hg3n"); + }); + + it("takes the route that lets an enemy piece follow, of those as short to the same square", () => { + // the elephant can reach e5 by d5 or by e4: whichever rabbit is + // to follow it, it comes by the square beside that rabbit + const g = position("Ed4,Ra1", "rf4,rc5,ra8,ee8"); + const walked = enter(g, "basic", ["d4", "e5"]); + for (const [rabbit, into] of [["f4", "e4"], ["c5", "d5"]]) { + const selected = click(g, walked, rabbit, "basic"); + expect(selected.move, rabbit).to.equal(`${walked} ${rabbit}`); + const after = played(g, click(g, selected.move, into, "basic").move); + expect(after.board.get("e5"), rabbit).to.deep.equal(["E", 1]); + expect(after.board.get(into), rabbit).to.deep.equal(["R", 2]); + expect(after.board.has(rabbit), rabbit).to.equal(false); + } + }); + + it("does not let a piece that has just pushed pull as well", () => { + const g = position("Ed4,Ra1", "re4,rd5,ra8,ee8"); + const pushed = enter(g, "basic", ["d4", "e4", "e5"]); + expect(pushed).to.equal("re4n Ed4e"); + // the rabbit beside the square the elephant left cannot follow it + const after = click(g, `${pushed} d5`, "d4", "basic"); + expect(after.move).not.to.contain("rd5s"); + expect(click(g, pushed, "d5", "basic").move).not.to.equal(`${pushed} d5`); + }); + + it("plays steps in the order they were entered", () => { + // the cat is safe on the trap only if the rabbit is beside it first + const g = position("Re2,Cf2", "rb7,mc7"); + const catFirst = played(g, enter(g, "basic", ["f2", "f3", "e2", "e3"])); + expect(catFirst.board.has("f3")).to.equal(false); + expect(catFirst.board.get("e3")).to.deep.equal(["R", 1]); + const rabbitFirst = played(g, enter(g, "basic", ["e2", "e3", "f2", "f3"])); + expect(rabbitFirst.board.get("f3")).to.deep.equal(["C", 1]); + expect(rabbitFirst.board.get("e3")).to.deep.equal(["R", 1]); + }); + + it("can sacrifice a piece by stepping it onto a trap before its support arrives", () => { + const g = position("Rb4,Ec2,Ra1", "rc4,ee8"); + const sacrificed = played(g, enter(g, "basic", ["c2", "c3", "a1", "b3"])); + expect(sacrificed.board.has("c3")).to.equal(false); + expect(sacrificed.board.get("b3")).to.deep.equal(["R", 1]); + const supported = played(g, enter(g, "basic", ["a1", "b3", "c2", "c3"])); + expect(supported.board.get("c3")).to.deep.equal(["E", 1]); + expect(supported.board.get("b3")).to.deep.equal(["R", 1]); + }); + + it("goes round a piece that was not selected rather than move it", () => { + const g = position("Ed4,Rd5,Cc5,Ra1", "ra8,ee8"); + const move = enter(g, "basic", ["d4", "d6"]); + const after = played(g, move); + expect(after.board.get("d5")).to.deep.equal(["R", 1]); + expect(after.board.get("d6")).to.deep.equal(["E", 1]); + expect(g.validateMove(move).message).not.to.contain("Rd5"); + }); + + it("does not sacrifice an unselected cat to shorten a rabbit's walk (archive 4711e615, ply 73)", () => { + const g = position("Ha3,Ra6,Rb4,Ed4,Re2,Cg3,Rh1", + "ra2,ra4,da7,rb6,rc7,ed3,dd5,cf7,rf8,rg5,cg6,rh5,rh6"); + const recorded = g.clone().move("Re2f2, Rf2f3, Rf3f4, Rf4e4"); + const after = played(g, enter(g, "basic", ["e2", "e4"])); + expect(after.board.get("g3")).to.deep.equal(["C", 1]); + expect(after.signature()).to.equal(recorded.signature()); + }); + + it("keeps a trap occupant supported when its supporters move in turn (archive 21f8a821, ply 57)", () => { + const g = position("Ra1,Ha6,Rb1,Cc1,Dd2,Ed6,Re2,Rf2,Cf3,Rg2,Hg6,Rh5", + "ha2,ra7,ra8,eb6,cb7,rc7,df4,rf5,rf6,df7,hg5,rg7,rg8,rh7"); + const recorded = g.clone().move("Rg2h2, Re2e3, Rf2g2, Dd2e2"); + const after = played(g, enter(g, "basic", ["g2", "h2", "e2", "e3", "f2", "g2", "d2", "e2"])); + expect(after.board.get("f3")).to.deep.equal(["C", 1]); + expect(after.signature()).to.equal(recorded.signature()); + }); + + it("stays open to further steps after any earlier ones", () => { + const g = position("Re2,Cf2,Ra1", "rb7,mc7"); + const after = played(g, enter(g, "basic", ["e2", "e3", "f2", "f3", "a1", "a2"])); + expect(after.board.get("e3")).to.deep.equal(["R", 1]); + expect(after.board.get("f3")).to.deep.equal(["C", 1]); + expect(after.board.get("a2")).to.deep.equal(["R", 1]); + }); + + it("undoes a push whole, and never leaves an enemy piece moving alone", () => { + const g = position("Ed4,Hf4,Ra1,Cc1", "re4,ra8,ee8"); + const push = enter(g, "basic", ["d4", "e4", "e5"]); + expect(click(g, push, "a8").move).to.equal(""); + const pull = enter(g, "basic", ["e4", "d4", "c4"]); + const half = click(g, pull, "a8"); + expect(half.move).to.equal("Ed4w"); + expect(click(g, half.move, "a8").move).to.equal(""); + }); + + it("treats steps that only restore the starting position as no entry", () => { + const g = position("Ed4,Ra1", "ra8,ee8"); + const out = enter(g, "basic", ["d4", "d5"]); + expect(enter(g, "basic", ["d5", "d4"], out)).to.equal(""); + }); + + it("turns a typed entry into the steps shown before adding to it", () => { + const g = position("Ed4,Rd5,Ra1", "ra8,ee8"); + // the rabbit can make way to either side: the preview shows one + const preview = g.clone().move("Ed4d6", {partial: true}); + const move = enter(g, "basic", ["a1", "a2"], "Ed4d6"); + expect(parseMove(move).tokens.every(t => t.prop.kind === "steps")).to.equal(true); + const after = played(g, move); + expect(after.board.get("a2")).to.deep.equal(["R", 1]); + for (const [cell, piece] of preview.board) { + if (cell !== "a1") { + expect(after.board.get(cell), cell).to.deep.equal(piece); + } + } + }); + + it("selects a frozen piece after preparatory support and a blocked piece after clearing space", () => { + const frozen = position("Rc4,Eb3,Ra1", "ec5,ra8"); + expect(click(frozen, "", "c4").move).to.equal("c4"); + let support = click(frozen, "", "b3"); + support = click(frozen, support.move, "c3"); + expect(support.move).to.equal("Eb3e"); + let rabbit = click(frozen, support.move, "c4"); + expect(rabbit.move).to.equal("Eb3e c4"); + rabbit = click(frozen, rabbit.move, "d4"); + expect(rabbit.valid).to.equal(true); + expect(frozen.clone().move(rabbit.move).board.get("d4")).to.deep.equal(["R", 1]); + + const blocked = position("Rb1,Rb2,Ra1,Rc1,Ee2", "ra8,ee8"); + expect(click(blocked, "", "b1").move).to.equal("b1"); + const oneStep = position("Rc4,Eb3,Ra1", "ec5,ra8"); + oneStep.die = {steps: 1, square: "a4"}; + expect(click(oneStep, "", "c4").move).to.equal(""); + }); + + it("rotates three pieces in a loop, but leaves two trading places to single steps", () => { + // the dog steps aside, the horse and elephant move up, and the dog comes round to d4 + const g = position("Ed4,He4,De5,Ra1", "ra8,ee8"); + const rotated = played(g, enter(g, "basic", ["d4", "e4", "e5", "d4"])); + expect(rotated.board.get("e4")).to.deep.equal(["E", 1]); + expect(rotated.board.get("e5")).to.deep.equal(["H", 1]); + expect(rotated.board.get("d4")).to.deep.equal(["D", 1]); + // a click on the first of two selected pieces deselects them, as on any selected piece + const two = position("Ed4,He4,Ra1", "ra8,ee8"); + for (const sequence of [["d4", "e4", "d4"], ["e4", "d4", "e4"]]) { + const r = click(two, enter(two, "basic", sequence.slice(0, 2)), sequence[2], "basic"); + expect(r.move, sequence.join(" ")).to.equal(""); + expect(r.complete, sequence.join(" ")).to.equal(-1); + } + // the same exchange entered step by step + const swapped = played(two, enter(two, "basic", ["d4", "d5", "e4", "d4", "d5", "e4"])); + expect(swapped.board.get("e4")).to.deep.equal(["E", 1]); + expect(swapped.board.get("d4")).to.deep.equal(["H", 1]); + }); + + it("ignores a click on an empty square while nothing is selected or entered", () => { + const g = position("Ed4,Ra1", "ra8,ee8"); + const r = click(g, "", "d6"); + expect(r.move).to.equal(""); + expect(r.complete).to.equal(-1); + }); + }); + + describe("selection in both modes", () => { + it("uses immovable enemy clicks to undo the last token", () => { + const g = position("Ed4,Ra1", "ra8,ee8"); + for (const mode of MODES) { + const result = click(g, "Ed4e4", "a8", mode); + expect(result.move, mode).to.equal(""); + expect(result.valid, mode).to.equal(true); + expect(result.complete, mode).to.equal(-1); + // During a selection, undo cancels selections, not a move token. + const cancel = click(g, "Ed4e4 e4", "a8", mode); + expect(cancel.move, mode).to.equal("Ed4e4"); + } + }); + + it("still selects a pushable enemy when a legal push is available", () => { + const g = position("Ed4,Ra1", "re4,ra8,ee8"); + for (const mode of MODES) { + const r = click(g, "", "e4", mode); + expect(r.valid, mode).to.equal(true); + expect(r.move, mode).to.equal("e4"); + } + }); + + it("does not select an enemy when the only remaining die step cannot complete a push", () => { + const g = position("Ed4,Ra1", "re5,ra8,ee8"); + g.die = {steps: 2, square: "b5"}; + for (const mode of MODES) { + const r = click(g, "Ed4e4", "e5", mode); + expect(r.move, mode).to.equal(""); + } + }); + + it("adds a piece to the chain only if the newest selection can reach its square", () => { + const g = position("Ed4,Rd5,Ra1,Rh1", "ra8,ee8"); + for (const mode of MODES) { + // the elephant cannot get to a1 this turn: the rabbit there is simply selected instead + expect(enter(g, mode, ["d4", "a1"]), mode).to.equal("a1"); + const after = played(g, enter(g, mode, ["d4", "a1", "a2"])); + expect(after.board.get("a2"), mode).to.deep.equal(["R", 1]); + expect(after.board.get("d4"), mode).to.deep.equal(["E", 1]); + // the rabbit in front of it can make way, so it joins the chain + expect(enter(g, mode, ["d4", "d5"]), mode).to.equal("d4 d5"); + const chained = played(g, enter(g, mode, ["d4", "d5", "e5"])); + expect(chained.board.get("e5"), mode).to.deep.equal(["R", 1]); + expect(chained.board.get("d5"), mode).to.deep.equal(["E", 1]); + } + }); + + it("closes a loop of two or three pieces, in either selection direction", () => { + // Advanced only: Basic rotates three pieces but does not swap two. + // The square to close onto is occupied at the outset. The elephant + // must take a detour so the horse can take its original square. + const game = position("Ed4,He4,Ra1", "ra8,ee8"); + for (const sequence of [["d4", "e4", "d4"], ["e4", "d4", "e4"]]) { + const label = sequence.join(" "); + expect(enter(game, "advanced", sequence.slice(0, 2)), label).to.equal(sequence.slice(0, 2).join(" ")); + const after = played(game, enter(game, "advanced", sequence)); + expect(after.board.get("e4"), label).to.deep.equal(["E", 1]); + expect(after.board.get("d4"), label).to.deep.equal(["H", 1]); + expect(after.board.get("a1"), label).to.deep.equal(["R", 1]); + } + const three = position("Ed4,He4,De5,Ra1", "ra8,ee8"); + const rotated = played(three, enter(three, "advanced", ["d4", "e4", "e5", "d4"])); + expect(rotated.board.get("d4")).to.deep.equal(["D", 1]); + expect(rotated.board.get("e5")).to.deep.equal(["H", 1]); + }); + + it("accepts either mode with a one-step Dicey Moves limit", () => { + const g = position("Ed4,Ra1", "ra8,ee8"); + g.die = {steps: 1, square: "c4"}; + for (const mode of MODES) { + const entered = click(g, enter(g, mode, ["d4"]), "e4", mode); + expect(entered.valid, mode).to.equal(true); + expect(entered.complete, mode).to.equal(0); + expect(played(g, entered.move).board.get("e4"), mode).to.deep.equal(["E", 1]); + // nothing further can be selected once the die is spent + expect(click(g, entered.move, "a1", mode).move, mode).to.equal(entered.move); + } + }); + + it("pulls with the piece the player moved up, not with one that could push instead (archive 8c4b586f, ply 11)", () => { + const g = position("Da1,Ra2,Cb1,Rc1,Rc2,Rd1,Hd4,Ed6,Re1,Re2,Rf1,Cg1,Dh1,Rh2", + "ha7,ra8,mb6,cb8,dc6,rc7,rc8,rd8,de8,ef5,rf7,rf8,hg6,rg8,ch6,rh8"); + const recorded = g.clone().move("Hd4d5, Hd5c5, Hc5c4, dc6c5"); + for (const mode of MODES) { + // horse to c5, then the dog and the horse as a chain to c4 + const after = played(g, enter(g, mode, ["d4", "c5", "c6", "c5", "c4"])); + expect(after.board.get("d6"), mode).to.deep.equal(["E", 1]); + expect(after.signature(), mode).to.equal(recorded.signature()); + } + }); + + it("ignores a click off the board once the pieces are down", () => { + const g = position("Ed4,Ra1", "ra8,ee8"); + for (const mode of MODES) { + const r = g.handleClick("Ed4e4", -1, -1, undefined, {inputMode: mode}); + expect(r.move, mode).to.equal("Ed4e4"); + expect(r.complete, mode).to.equal(0); + } + }); + }); + + describe("Advanced", () => { + it("deselects a piece that is clicked again, leaving the entry as it was", () => { + const g = position("Ed4,Rd5,Ra1", "ra8,ee8"); + for (const mode of MODES) { + const none = click(g, enter(g, mode, ["d5"]), "d5", mode); + expect(none.move, mode).to.equal(""); + expect(none.complete, mode).to.equal(-1); + const entry = enter(g, mode, ["a1", "a2"]); + expect(enter(g, mode, ["d4", "d4"], entry), mode).to.equal(entry); + } + }); + + it("selects a piece only where it stands, so the square it left is free for a target click", () => { + // nothing can come to the square the elephant left: as in Basic, the click completes the move + const g = position("Ed4,Ra1", "ra8,ee8"); + const sent = enter(g, "advanced", ["d4", "d6"]); + const done = click(g, sent, "d4", "advanced"); + expect(done.move).to.equal(sent); + expect(done.complete).to.equal(1); + // the elephant is selected where it now stands + expect(click(g, sent, "d6", "advanced").move).to.equal(`${sent} d6`); + // the rabbit beside the square can come to it + const h = position("Ed4,Rc4,Ra1", "ra8,ee8"); + const filled = click(h, enter(h, "advanced", ["d4", "d6"]), "d4", "advanced"); + expect(said(filled.move)).to.deep.equal(["Ed4d6", "Rc4d4"]); + }); + + it("chooses the piece that pushes by sending it, with no need to keep it anywhere", () => { + const g = position("Ed4,Hf4,Ra1", "re4,ra8,ee8"); + // the horse pushes, being one rank above a rabbit here, and steps back + const pushed = enter(g, "advanced", ["e4", "e5"]); + const shown = g.clone().move(pushed, {partial: true}); + expect(shown.board.has("e4")).to.equal(false); + expect(shown.board.get("f4")).to.deep.equal(["H", 1]); + // sending either piece onto the rabbit's square has it push and stay + for (const [from, piece] of [["d4", "E"], ["f4", "H"]]) { + const move = enter(g, "advanced", [from, "e4"], pushed); + expect(move, from).to.equal(`re4e5 ${piece}${from}e4`); + expect(played(g, move).board.get("e4"), from).to.deep.equal([piece, 1]); + } + }); + + it("takes a typed same-square token as saying where the piece ends, and draws nothing for it", () => { + const g = position("Ed4,Rd5,Ra1", "ra8,ee8"); + // with the rabbit kept on d5, the elephant has to walk round it + const after = played(g, "Rd5d5 Ed4d6"); + expect(after.board.get("d5")).to.deep.equal(["R", 1]); + expect(after.board.get("d6")).to.deep.equal(["E", 1]); + // the enter glyph is for a piece that moved and came back, not for one said to stay + expect(marks(g, "Rd5d5")).to.deep.equal([]); + expect(marks(g, "Rd5d5 Ed4d6")).to.deep.equal(["move:d4>d6"]); + }); + + it("shows one of the moves an entry fits when none is better, and lets the player complete it", () => { + // three steps are too few to walk round the rabbit, so it has to make way, to either side + const g = withDie(position("Ed4,Rd5,Ra1", "ra8,ee8"), 3); + const entered = click(g, enter(g, "advanced", ["d4"]), "d6", "advanced"); + expect(said(entered.move)).to.deep.equal(["Ed4d6"]); + expect(entered.complete).to.equal(0); + expect(entered.message).to.contain(ambiguous(2)); + expect(entered.message).to.contain(i18next.t("apgames:validation.arimaa.INFERRED", {pieces: ""}).split(":")[0]); + const preview = g.clone().move(entered.move, {partial: true}); + expect(preview.board.get("d6")).to.deep.equal(["E", 1]); + expect(preview.board.has("d5")).to.equal(false); + // submitted as it is, it plays what was shown and is stored unambiguously + const submitted = g.clone().move(entered.move); + expect(submitted.signature()).to.equal(preview.signature()); + expect(resolve(g.board, 1, 3, parseMove(submitted.lastmove!).tokens, false).status).to.equal("resolved"); + // and so does completing it with a click on an empty square + const done = click(g, entered.move, "h8", "advanced"); + expect(done.complete).to.equal(1); + expect(resolve(g.board, 1, 3, parseMove(done.move).tokens, false).status).to.equal("resolved"); + expect(g.clone().move(done.move).signature()).to.equal(preview.signature()); + }); + + it("sends a piece the engine moved somewhere else instead", () => { + const g = position("Ed4,Rd5,Ra1", "ra8,ee8"); + const preview = g.clone().move("Ed4d6", {partial: true}); + const [shown, other] = preview.board.has("e5") ? ["e5", "c5"] : ["c5", "e5"]; + const move = enter(g, "advanced", [shown, other], "Ed4d6"); + expect(move).to.equal(`Ed4d6 Rd5${other}`); + const after = played(g, move); + expect(after.board.get(other)).to.deep.equal(["R", 1]); + expect(after.board.get("d6")).to.deep.equal(["E", 1]); + }); + + it("completes the supplied partially ambiguous horse-and-rabbit move on an empty square", () => { + const game = position("Ha2,Hh2,Dd2,De1,Cg2,Rc2,Ra1,Rf1,Rg1,Rh1,Cb2,Rb1,Rc1,Re2,Ee5", "hg7,ra7,ra8,rb8,rf8,rg8,rh8,rh7,dd8,cc7,cf7,rc8,md6,eb5,de4,hb6"); + const move = "Hh2f3 Re2f2"; + expect(game.validateMove(move).valid).to.equal(true); + const completed = click(game, move, "a6", "advanced"); + expect(completed.valid).to.equal(true); + expect(completed.complete).to.equal(1); + expect(completed.move).not.to.equal(""); + const before = game.clone(); + game.move(completed.move); + expect(game.board.get("f3")).to.deep.equal(["H", 1]); + expect(game.board.get("f2")).to.deep.equal(["R", 1]); + expect(before.validateMove(completed.move).valid).to.equal(true); + }); + + it("honours every explicitly selected link of the horse-over-elephant push chain", () => { + const game = position("Ha2,Dd2,De1,Cg2,Rc2,Ra1,Rf1,Rg1,Rh1,Cb2,Rb1,Rc1,Ee5,Rf2,Hf3", "hg7,ra7,ra8,rb8,rf8,rg8,rh8,cc7,cf7,rc8,md6,eb5,de4,hb6,rh4,dd7"); + let result = click(game, "", "f3", "advanced"); + expect(result.move).to.equal("f3"); + result = click(game, result.move, "e4", "advanced"); + expect(result.move).to.equal("f3 e4"); + result = click(game, result.move, "d4", "advanced"); + expect(result.valid).to.equal(true); + expect(result.move).to.contain("Hf3e4"); + expect(result.move).to.contain("de4d4"); + const after = game.clone().move(result.move); + expect(after.board.get("e4")).to.deep.equal(["H", 1]); + expect(after.board.get("d4")).to.deep.equal(["D", 2]); + expect(after.board.get("e5")).to.deep.equal(["E", 1]); + }); + + it("allows a different explicitly selected pusher after an inferred dog flip", () => { + const game = position("Ha2,Dd2,De1,Cg2,Rc2,Ra1,Rf1,Rg1,Rh1,Cb2,Rb1,Rc1,Ee5,Rf2,He3", "hg7,ra7,ra8,rb8,rf8,rg8,rh8,cc7,cf7,md6,eb5,de4,hb6,rh4,dd7,rd8"); + let result = click(game, "", "e4", "advanced"); + result = click(game, result.move, "f3", "advanced"); + expect(result.valid).to.equal(true); + const dogMove = result.move; + for (const pusher of ["e5", "e3"]) { + const selected = click(game, dogMove, pusher, "advanced"); + expect(selected.valid, pusher).to.equal(true); + expect(selected.move, pusher).to.equal(`${dogMove} ${pusher}`); + const directed = click(game, selected.move, "f4", "advanced"); + expect(directed.valid, pusher).to.equal(true); + expect(directed.move, pusher).to.contain( + pusher === "e5" ? "Ee5f4" : "He3f4" + ); + const after = game.clone().move(directed.move); + // f3 is a trap without adjacent silver support: the pushed dog + // is captured, not left standing on f3. + expect(after.board.has("f3"), pusher).to.equal(false); + expect(after.results.some(r => + r.type === "destroy" && r.where === "f3" && r.what === "d" + ), pusher).to.equal(true); + expect(after.board.get("f4"), pusher).to.deep.equal([ + pusher === "e5" ? "E" : "H", 1 + ]); + } + }); + + it("frees a frozen piece with one that steps out and comes back (archive 10441479, ply 29)", () => { + const g = position("Ra2,Ra5,Rb1,Cb2,Mb4,Rc2,Hd3,Ed5,De2,De4,Rf1,Rf2,Cg1,Hg3,Rh1,Rh2", + "ra6,rb7,ec4,hc6,cc7,rc8,dd4,rd7,re7,cf7,rf8,hg6,rg8,dh6,rh8"); + const recorded = g.clone().move("Ra5b5, Mb4b3, Mb3a3, Rb5a5"); + // Sending the camel is all it takes. Whichever piece frees it + // comes back, because that leaves every other piece where it was, + // and it is the same move whichever piece that is. + expect(played(g, enter(g, "advanced", ["b4", "a3"])).signature()).to.equal(recorded.signature()); + // Basic simply plays the steps + expect(played(g, enter(g, "basic", ["a5", "b5", "b4", "a3", "b5", "a5"])).signature()).to.equal(recorded.signature()); + }); + }); + + describe("Advanced preferences", () => { + const moves = (g: ArimaaGame): number => g.results.filter(r => r.type === "move").length; + + it("brings a pusher back unless it is sent somewhere too", () => { + const g = position("Cd4,Ra1", "re4,ra8,ee8"); + const back = played(g, enter(g, "advanced", ["e4", "e5"])); + expect(back.board.get("e5")).to.deep.equal(["R", 2]); + expect(back.board.get("d4")).to.deep.equal(["C", 1]); + expect(back.board.has("e4")).to.equal(false); + expect(moves(back)).to.equal(3); + // sent after the rabbit, or selected before it as a chain, the cat stays on the rabbit's square + for (const clicks of [["e4", "e5", "d4", "e4"], ["d4", "e4", "e5"]]) { + const move = enter(g, "advanced", clicks); + expect(move, clicks.join(" ")).to.equal("re4e5 Cd4e4"); + const after = played(g, move); + expect(after.board.get("e4"), clicks.join(" ")).to.deep.equal(["C", 1]); + expect(moves(after), clicks.join(" ")).to.equal(2); + } + }); + + it("pushes with the piece exactly one rank stronger, counting only the ranks on the board", () => { + // two steps, so whichever piece pushes cannot come back + const cat = withDie(position("Cd4,Df4,Ra1", "re4,ra8,ee8"), 2); + const byCat = click(cat, "e4", "e5", "advanced"); + expect(played(cat, byCat.move).board.get("e4")).to.deep.equal(["C", 1]); + expect(byCat.message).not.to.contain(ambiguous(2)); + // with no cat on the board, a dog is one rank above a rabbit + const dog = withDie(position("Hd4,Df4,Ra1", "re4,ra8,ee8"), 2); + const byDog = click(dog, "e4", "e5", "advanced"); + expect(played(dog, byDog.move).board.get("e4")).to.deep.equal(["D", 1]); + expect(byDog.message).not.to.contain(ambiguous(2)); + // a cat anywhere, of either colour, and neither the dog nor the horse is one rank above it + const gap = withDie(position("Hd4,Df4,Ra1", "re4,ra8,ee8,cb8"), 2); + const either = click(gap, "e4", "e5", "advanced"); + expect(either.complete).to.equal(0); + expect(either.message).to.contain(ambiguous(2)); + }); + + it("prefers a right-sized push before leaving enemy pieces, and not its own, beside a piece one rank stronger", () => { + // two steps: the cat's push is the right-sized one, though it + // leaves the cat beside the enemy dog, while the dog's push would + // leave the rabbit on d5 beside the cat + const g = withDie(position("Cd4,Df4,Ra1", "re4,rd5,de3,ra8,ee8"), 2); + const pushed = click(g, "e4", "e5", "advanced"); + expect(played(g, pushed.move).board.get("e4")).to.deep.equal(["C", 1]); + expect(pushed.message).not.to.contain(ambiguous(2)); + // between two right-sized pushes, the cat that stays put is better + // not left beside the enemy dog (the rabbit on f5 keeps it unfrozen) + const twins = withDie(position("Cd4,Cf4,Rf5,Ra1", "re4,dg4,ra8,ee8"), 2); + const either = click(twins, "e4", "e5", "advanced"); + const after = played(twins, either.move); + expect(after.board.get("e4")).to.deep.equal(["C", 1]); + expect(after.board.has("f4")).to.equal(false); + expect(either.message).not.to.contain(ambiguous(2)); + }); + + it("lists the steps of the move shown where the notation alone reads otherwise", () => { + const g = position("Ed4,Rd5,Ra1", "ra8,ee8"); + const move = enter(g, "advanced", ["d4", "d6"]); + // by themselves the tokens mean the shorter move, in which the rabbit makes way + expect(g.clone().move("Ed4d6", {partial: true}).board.has("d5")).to.equal(false); + expect(said(move)).to.deep.equal(["Ed4d6"]); + expect(listed(move).length).to.be.greaterThan(0); + expect(move.split(" ").slice(1)).to.deep.equal(listed(move)); + // with the steps, it is notation that reads one way only + expect(resolve(g.board, 1, 4, parseMove(move).tokens, false).status).to.equal("resolved"); + expect(g.validateMove(move).message).not.to.contain(ambiguous(2)); + // what is stored is the usual notation, and it reads back the same + const after = played(g, move); + expect(after.lastmove).to.equal("Ed6 Rd5"); + expect(resolve(g.board, 1, 4, parseMove(after.lastmove!).tokens, false).status).to.equal("resolved"); + expect(g.clone().move(after.lastmove!).signature()).to.equal(after.signature()); + // so is a completion by click + const done = click(g, move, "h8", "advanced"); + expect(done.complete).to.equal(1); + expect(done.move).to.equal("Ed6 Rd5"); + // an entry the notation reads the same way lists nothing + expect(enter(g, "advanced", ["a1", "a2"])).to.equal("Ra1a2"); + }); + + it("goes by what was said, not by the steps it listed", () => { + const g = position("Ed4,Rd5,Ra1", "ra8,ee8"); + const round = enter(g, "advanced", ["d4", "d6"]); + // a fifth step is too many: now the rabbit in the way makes room + const both = click(g, enter(g, "advanced", ["a1"], round), "a2", "advanced"); + expect(said(both.move)).to.deep.equal(["Ed4d6", "Ra1a2"]); + expect(both.message).to.contain("Rd5"); + const after = played(g, both.move); + expect(after.board.get("d6")).to.deep.equal(["E", 1]); + expect(after.board.get("a2")).to.deep.equal(["R", 1]); + expect(after.board.has("d5")).to.equal(false); + // undo takes back what was said last, and the elephant walks round again + expect(click(g, both.move, "a8", "advanced").move).to.equal(round); + expect(click(g, round, "a8", "advanced").move).to.equal(""); + }); + + it("takes steps that were typed or entered in Basic as saying where the pieces end up", () => { + const g = position("Ed4,Rd5,Ra1", "ra8,ee8"); + const basic = enter(g, "basic", ["d5", "e5", "d4", "d6"]); + expect(basic).to.equal("Rd5e Ed4nn"); + // neither piece is walked back to where it started + const move = enter(g, "advanced", ["a1", "a2"], basic); + expect(said(move)).to.have.members(["Rd5e5", "Ed4d6", "Ra1a2"]); + const after = played(g, move); + expect(after.board.get("d6")).to.deep.equal(["E", 1]); + expect(after.board.get("e5")).to.deep.equal(["R", 1]); + expect(after.board.get("a2")).to.deep.equal(["R", 1]); + }); + }); + + describe("Advanced target clicks", () => { + it("take a rabbit to goal before pushing an enemy piece there", () => { + const g = position("Re7,Dd7,Ra1", "cd8,ra8,ee5"); + const goal = click(g, "", "e8", "advanced"); + expect(goal.move).to.equal("Re7e8"); + expect(played(g, goal.move).winner).to.deep.equal([1]); + // one rank short of goal, the enemy piece is preferred as before + const lower = position("Re6,Dd6,Ra1", "cd7,ra8,ee4"); + const pushed = click(lower, "", "e7", "advanced"); + expect(said(pushed.move)).to.deep.equal(["cd7e7"]); + const after = played(lower, pushed.move); + expect(after.board.get("e7")).to.deep.equal(["C", 2]); + expect(after.board.get("e6")).to.deep.equal(["R", 1]); + // and the dog that pushed is back where it started + expect(after.board.get("d6")).to.deep.equal(["D", 1]); + }); + + it("take one of two rabbits to goal where nothing else separates them, though short of goal such a tie chooses neither", () => { + // either rabbit reaches e8 in two steps, and the two moves are alike in everything else + const g = position("Rd7,Rf7,Ra1", "ra8,eh8"); + const goal = click(g, "", "e8", "advanced"); + expect(said(goal.move)).to.have.length(1); + expect(["Rd7e8", "Rf7e8"]).to.include(said(goal.move)[0]); + expect(goal.message).to.contain(ambiguous(2)); + expect(click(g, "", "e8", "advanced").move).to.equal(goal.move); + expect(played(g, goal.move).winner).to.deep.equal([1]); + // a row lower the same tie is no win, and the click chooses neither + const lower = position("Rd5,Rf5,Ra1", "ra8,eh8"); + const none = click(lower, "", "e6", "advanced"); + expect(none.move).to.equal(""); + expect(none.complete).to.equal(-1); + }); + + it("prefer to leave enemy pieces, and not their own, beside a piece one rank stronger", () => { + // one step: the cat or the dog can step between them, and nothing else separates the two moves + const rabbit = withDie(position("Cd4,Df4,Ra1", "re5,ra8,ee8"), 1); + expect(click(rabbit, "", "e4", "advanced").move).to.equal("Cd4e4"); + const cat = withDie(position("Cd4,Df4,Ra1", "ce5,ra8,ee8"), 1); + expect(click(cat, "", "e4", "advanced").move).to.equal("Df4e4"); + // the cat would stand beside a dog; the rabbit is two ranks below it + const dog = withDie(position("Cd4,Rf4,Ra1", "de5,ra8,ee8"), 1); + expect(click(dog, "", "e4", "advanced").move).to.equal("Rf4e4"); + // where nothing separates them, the click chooses neither + const same = withDie(position("Cd4,Cf4,Ra1", "re5,ra8,ee8"), 1); + const none = click(same, "", "e4", "advanced"); + expect(none.move).to.equal(""); + expect(none.complete).to.equal(-1); + }); + }); + + describe("Advanced follows its two priority lists", () => { + // What each list measures, worked out from every way of playing every + // legal turn rather than by the engine's search. + const displaced = (p: Play): number => [...p.paths].filter(([from, path]) => path.final !== from).length; + const captured = (p: Play, owner: Owner): number => [...p.paths.values()].filter(path => path.captured && path.owner === owner).length; + const wrong = (b: Board, side: Owner): number => [...b].filter(([cell, [pc, owner]]) => owner === side && + neighbours(cell).some(n => { + const o = b.get(n); + return o !== undefined && o[1] !== side && oneRankAbove(b, o[0], pc); + })).length; + const other = (player: Owner): Owner => player === 1 ? 2 : 1; + // "prefer": keep the candidates with the best value + const prefer = (plays: Play[], cost: (p: Play) => number): Play[] => { + const best = Math.min(...plays.map(cost)); + return plays.filter(p => cost(p) === best); + }; + const normalMove = (plays: Play[], player: Owner): Play[] => [ + displaced, + (p: Play) => p.steps, + (p: Play) => captured(p, player), + (p: Play) => -captured(p, other(player)), + (p: Play) => -p.rightSized, + (p: Play) => wrong(p.board, player) - wrong(p.board, other(player)), + ].reduce(prefer, plays); + // also whether a rabbit of the player's goes to goal, which lets a tie be broken + const targetSelection = (plays: Play[], player: Owner, target: string): {best: Play[]; goal: boolean} => { + const brings = (p: Play, which: (path: Path) => boolean): boolean => + [...p.paths.values()].some(path => path.final === target && which(path)); + let left = plays.filter(p => brings(p, () => true)); + let goal = false; + if (target[1] === (player === 1 ? "8" : "1")) { + const rabbits = left.filter(p => brings(p, path => path.type === "R" && path.owner === player)); + goal = rabbits.length > 0; + left = goal ? rabbits : left; + } + const enemy = left.filter(p => brings(p, path => path.owner !== player)); + left = enemy.length > 0 ? enemy : left; + const best = [ + displaced, + (p: Play) => p.steps, + (p: Play) => captured(p, player), + (p: Play) => -captured(p, other(player)), + (p: Play) => -p.rightSized, + (p: Play) => wrong(p.board, player) - wrong(p.board, other(player)), + ].reduce(prefer, left); + return {best, goal}; + }; + const positions = (plays: Play[]): Set => new Set(plays.map(p => signature(p.board))); + // whether a click's message says the move shown is one of several, whatever number it gives + const hinted = (message: string): boolean => new RegExp(ambiguous(0).replace("0", "\\d+")).test(message); + const squares = "abcdefgh".split("").flatMap(f => "12345678".split("").map(r => `${f}${r}`)); + // triangles clicked over all the positions together + let offers = 0; + after(() => expect(offers).to.be.greaterThan(3)); + const shown = (g: ArimaaGame, move: string): string => signature(g.clone().move(move, {partial: true}).board as Board); + + for (const [name, spec, player, steps] of [ + ["pushers of three ranks around a rabbit", "Cd4 Df4 He3 Ra1 re4 rd5 ee8", 1, 4], + ["a rabbit and an enemy cat one step from goal", "Re7 Dd7 Cf7 cd8 rg8 de6", 1, 3], + ["pieces beside two traps", "Rb3 Cc2 Ed3 Hf2 rc4 db4 ce3 rf4", 1, 3], + ["no cats or dogs on the board", "Hd5 Me4 Rd3 rd4 re5 hc5 ef5", 1, 4], + ["Silver to move, beside a trap", "Rc5 Cb6 Dd6 rc7 hb5 ed5 rc6", 2, 3], + ["Silver's rabbit near goal", "Ee3 Rd1 Cf2 rd2 re2 hc2 df1", 2, 3], + ["two rabbits a step from goal", "Rd7 Rf7 Me6 Ra1 cg8 rb8 dh6", 1, 3], + ] as Array<[string, string, Owner, number]>) { + it(name, function () { + this.timeout(120000); + const board = boardOf(spec); + const plays = allPlays(board, player, steps); + const g = ready(board, player); + if (steps < 4) { + withDie(g, steps); + } + let sends = 0; + let aimed = 0; + // a piece is selected and sent to an empty square: the Normal Move list + for (const [origin, [pc, owner]] of board) { + const selected = click(g, "", origin, "advanced").move; + expect(selected === origin, `selecting ${origin}`).to.equal(plays.some(p => (p.paths.get(origin)?.visited.length ?? 1) > 1)); + for (const dest of selected === origin ? squares : []) { + const fit = plays.filter(p => p.paths.get(origin)?.final === dest); + if (board.has(dest) || fit.length === 0) { + continue; + } + const label = `${origin} to ${dest}`; + const r = click(g, selected, dest, "advanced"); + expect(said(r.move), label).to.deep.equal([`${owner === 1 ? pc : pc.toLowerCase()}${origin}${dest}`]); + const wanted = positions(normalMove(fit, player)); + expect([...wanted], `${label}: ${r.move}`).to.include(shown(g, r.move)); + // the player is told when the list leaves more than one move and the one shown is only the first of them + expect(hinted(r.message), label).to.equal(wanted.size > 1); + // what is shown is what is played, and what is stored reads back as it + const after = g.clone().move(r.move); + expect(signature(after.board as Board), label).to.equal(shown(g, r.move)); + expect(signature(g.clone().move(after.lastmove!).board as Board), `${label}: ${after.lastmove}`).to.equal(shown(g, r.move)); + sends++; + } + } + // a trap's triangle is offered where the selected piece can end there both ways, and plays + // the way a click on the square does not + let triangles = 0; + for (const [origin, [pc, owner]] of board) { + if (click(g, "", origin, "advanced").move !== origin) { + continue; + } + const offered = captureChoices(g.board, player, steps, origin); + for (const trap of ["c3", "f3", "c6", "f6"].filter(sq => !board.has(sq))) { + const ends = plays.filter(p => p.paths.get(origin)?.final === trap); + const dies = ends.filter(p => p.paths.get(origin)!.captured); + const lives = ends.filter(p => !p.paths.get(origin)!.captured); + const label = `${origin} to ${trap}`; + expect(offered.has(trap), label).to.equal(dies.length > 0 && lives.length > 0); + if (offered.has(trap)) { + const plain = click(g, origin, trap, "advanced"); + const dying = positions(dies).has(shown(g, plain.move)); + expect(offered.get(trap), label).to.equal(!dying); + const r = click(g, origin, trap, "advanced", dying ? ARIMAA_SPARE_CHOICE : ARIMAA_CAPTURE_CHOICE); + const letter = owner === 1 ? pc : pc.toLowerCase(); + expect(said(r.move), label).to.deep.equal([`${letter}${origin}${trap}`, `${letter}${origin}${dying ? "o" : "x"}`]); + expect([...positions(normalMove(dying ? lives : dies, player))], `${label}: ${r.move}`).to.include(shown(g, r.move)); + triangles++; + } + } + } + // an empty square is clicked with nothing selected: the Target Selection list + for (const target of squares.filter(sq => !board.has(sq))) { + const {best, goal} = targetSelection(plays, player, target); + const wanted = positions(best); + const r = click(g, "", target, "advanced"); + // a tie is broken only where a rabbit goes to goal, and the player is told of it + if (wanted.size === 1 || (wanted.size > 1 && goal)) { + expect(r.move, target).not.to.equal(""); + expect([...wanted], `${target}: ${r.move}`).to.include(shown(g, r.move)); + expect(hinted(r.message), target).to.equal(wanted.size > 1); + aimed++; + } else { + expect(r.move, target).to.equal(""); + } + } + expect(sends).to.be.greaterThan(10); + expect(aimed).to.be.greaterThan(5); + offers += triangles; + }); + } + }); + + describe("Advanced trap capture control", () => { + const fresh = (g: ArimaaGame): ArimaaGame => new ArimaaGame(g.serialize()); + + it("is one custom-glyph polygon, shown only for an Advanced selection that has both outcomes", () => { + const g = position("Rf2,Cg2,Ra1", "ra8,ee8"); + expect(captureAlternatives(g.board, g.currplayer, 4, "g2")).to.deep.equal(["f3"]); + const before = g.serialize(); + const preview = g.clone().move("g2", {partial: true}); + const advanced = preview.render({inputMode: "advanced"}); + expect(advanced.legend?.[ARIMAA_CAPTURE_CHOICE]).not.to.equal(undefined); + const layers = advanced.pieces as string[][][]; + expect(layers).to.have.length(8); + expect(layers[5][5]).to.deep.equal([ARIMAA_CAPTURE_CHOICE]); // f3 + expect(layers.flat(2).filter(key => key === ARIMAA_CAPTURE_CHOICE)).to.have.length(1); + expect(g.serialize()).to.equal(before); // No virtual board occupant. + + // The control is absent from Basic and from idle Advanced previews. + const basic = preview.render({inputMode: "basic"}); + expect(basic.glyphDefs).to.equal(undefined); + expect(typeof basic.pieces).to.equal("string"); + expect(basic.legend?.[ARIMAA_CAPTURE_CHOICE]).to.equal(undefined); + expect(preview.render().legend?.[ARIMAA_CAPTURE_CHOICE]).to.equal(undefined); + const idle = g.render({inputMode: "advanced"}); + expect(idle.glyphDefs).to.equal(undefined); + expect(typeof idle.pieces).to.equal("string"); + }); + + it("is drawn as the other glyph where clicking it keeps the piece alive", () => { + const g = position("Cg2,Rf1,Ra1", "ra8,ee8"); + const rep = g.clone().move("g2", {partial: true}).render({inputMode: "advanced"}); + expect(rep.legend?.[ARIMAA_SPARE_CHOICE]).not.to.equal(undefined); + expect(rep.legend?.[ARIMAA_CAPTURE_CHOICE]).to.equal(undefined); + expect((rep.pieces as string[][][])[5][5]).to.deep.equal([ARIMAA_SPARE_CHOICE]); // f3 + // either key is the triangle's click + expect(click(g, "g2", "f3", "advanced", ARIMAA_SPARE_CHOICE).move).to.equal(click(g, "g2", "f3", "advanced", ARIMAA_CAPTURE_CHOICE).move); + }); + + it("reaches render() through the click result, on a game object that never saw the click", () => { + const g = position("Rf2,Cg2,Ra1", "ra8,ee8"); + const selected = click(g, "", "g2", "advanced"); + expect(selected.opts).to.deep.equal({inputMode: "advanced"}); + const shown = fresh(g).move(selected.move, {partial: true}).render(selected.opts); + expect(shown.legend?.[ARIMAA_CAPTURE_CHOICE]).not.to.equal(undefined); + // a Basic click carries no mode, so its preview has no control + const basic = click(g, "", "g2", "basic"); + expect(basic.opts).to.equal(undefined); + const plain = fresh(g).move(basic.move, {partial: true}).render(basic.opts); + expect(plain.legend?.[ARIMAA_CAPTURE_CHOICE]).to.equal(undefined); + }); + + it("captures an own piece on the trap, where the square itself keeps it alive", () => { + const g = position("Rf2,Cg2,Ra1", "ra8,ee8"); + const ordinary = click(g, "g2", "f3", "advanced"); + expect(ordinary.move).to.equal("Cg2f3"); + expect(played(g, ordinary.move).board.get("f3")).to.deep.equal(["C", 1]); + + // The renderer reports (row,col,legendKey) for a custom board + // piece, exactly as for stock sheet pieces. + const special = click(g, "g2", "f3", "advanced", ARIMAA_CAPTURE_CHOICE); + expect(special.valid).to.equal(true); + expect(said(special.move)).to.deep.equal(["Cg2f3", "Cg2x"]); + // The rabbit beside the trap has to leave for the cat to die, + // and then comes back: nothing was said of it. + expect(special.complete).to.equal(0); + const captured = played(g, special.move); + expect(captured.board.has("f3")).to.equal(false); + expect(captured.board.get("f2")).to.deep.equal(["R", 1]); + expect(captured.results.some(r => r.type === "destroy" && r.where === "f3" && r.what === "C")).to.equal(true); + expect(captured.lastmove).not.to.contain("o"); + // sent somewhere, it stays there + const withRabbit = enter(g, "advanced", ["f2", "e2"], special.move); + expect(said(withRabbit)).to.deep.equal(["Cg2f3", "Cg2x", "Rf2e2"]); + const away = played(g, withRabbit); + expect(away.board.get("e2")).to.deep.equal(["R", 1]); + expect(away.board.has("f3")).to.equal(false); + + // Forged or out-of-mode custom-piece clicks must do nothing. + expect(click(g, "g2", "f3", "basic", ARIMAA_CAPTURE_CHOICE).move).to.equal("g2"); + expect(click(g, "g2", "c3", "advanced", ARIMAA_CAPTURE_CHOICE).move).to.equal("g2"); + }); + + it("is not offered because some other piece of the same kind could meet it", () => { + // The rabbit on d3 dies on f3 whatever else happens. The other + // rabbit could cross d3 after it and live, which is another matter. + const g = ready(boardOf("Hb5 Re5 dc3 ed6 me7 rd3 rd5"), 2); + expect(click(g, "", "d3", "advanced").move).to.equal("d3"); + expect(captureAlternatives(g.board, 2, 4, "d3")).to.deep.equal([]); + const sent = click(g, "d3", "f3", "advanced"); + expect(said(sent.move)).to.deep.equal(["rd3f3"]); + expect(played(g, sent.move).board.has("f3")).to.equal(false); + // a forged click on the triangle does nothing + expect(click(g, "d3", "f3", "advanced", ARIMAA_CAPTURE_CHOICE).move).to.equal("d3"); + }); + + it("keeps an enemy piece alive on the trap, where the square itself captures it", () => { + // The dog pushed onto f3 dies unless its rabbit comes up beside + // the trap, which takes a second push. + const g = position("Ef5,Hg5,Ra1", "df4,rg4,ra8,ee8"); + const squares = ["f5", "f4"]; + const selection = enter(g, "advanced", squares); + expect(captureAlternatives(g.board, 1, 4, selection)).to.deep.equal(["f3"]); + const captured = played(g, enter(g, "advanced", [...squares, "f3"])); + expect(captured.board.has("f3")).to.equal(false); + const spared = enter(g, "advanced", [...squares, "^f3"]); + expect(spared).to.contain("df4o"); + const after = played(g, spared); + expect(after.board.get("f3")).to.deep.equal(["D", 2]); + expect(after.lastmove).not.to.contain("o"); + // the stored notation replays to the same position + expect(g.clone().move(after.lastmove!).signature()).to.equal(after.signature()); + }); + }); + + describe("Advanced trap control for a piece already on a trap", () => { + // the dog can walk round the rabbit, or push it aside and pull it + // back, which leaves the elephant on c3 alone long enough to die + const elephant = (): ArimaaGame => ready(boardOf("Ha3 Rd3 Ec3 dd2 Rh1 rh8"), 2); + const walkRound = (g: ArimaaGame): string => g.clone().move("dd2e2, de2e3, de3e4, de4d4", {trusted: true}).signature(); + + it("selects an enemy piece the move shown captures, and its triangle keeps it alive", () => { + const g = elephant(); + const sent = enter(g, "advanced", ["d2", "d4"]); + expect(g.clone().move(sent, {partial: true}).board.has("c3")).to.equal(false); + // the elephant is not drawn, but its square selects it + const selected = click(g, sent, "c3", "advanced"); + expect(selected.move).to.equal(`${sent} c3`); + expect(captureAlternatives(g.board, 2, 4, selected.move)).to.deep.equal(["c3"]); + const spared = click(g, selected.move, "c3", "advanced", ARIMAA_CAPTURE_CHOICE); + expect(said(spared.move)).to.deep.equal(["dd2d4", "Ec3o"]); + const after = played(g, spared.move); + expect(after.signature()).to.equal(walkRound(g)); + expect(after.lastmove).not.to.match(/o( |$)/); + // a click on the square itself just deselects it + expect(click(g, selected.move, "c3", "advanced").move).to.equal(sent); + }); + + it("goes the other way from the move shown each time, moving nothing where that is how things stand", () => { + const g = elephant(); + // nothing entered: the elephant stands, so its triangle captures it + expect([...captureChoices(g.board, 2, 4, "c3")]).to.deep.equal([["c3", true]]); + const doomed = enter(g, "advanced", ["c3", "^c3"]); + expect(said(doomed)).to.deep.equal(["Ec3x"]); + expect(g.clone().move(doomed, {partial: true}).board.has("c3")).to.equal(false); + // now that it dies, the triangle keeps it alive, which is how things stood + expect([...captureChoices(g.board, 2, 4, `${doomed} c3`)]).to.deep.equal([["c3", false]]); + const spared = enter(g, "advanced", ["c3", "^c3"], doomed); + expect(spared).to.equal("Ec3o"); + expect(g.validateMove(spared).complete).to.equal(-1); + expect(played(g, enter(g, "advanced", ["d2", "d4"], spared)).signature()).to.equal(walkRound(g)); + }); + + it("keeps an own piece alive where it would die, and has an enemy piece die where it would live", () => { + // the cat sent alone onto f3 dies there; its triangle brings the rabbit up beside it + const cat = position("Cg2,Rf1,Ra1", "ra8,ee8"); + expect(played(cat, enter(cat, "advanced", ["g2", "f3"])).board.has("f3")).to.equal(false); + expect([...captureChoices(cat.board, 1, 4, "g2")]).to.deep.equal([["f3", false]]); + const kept = enter(cat, "advanced", ["g2", "^f3"]); + expect(said(kept)).to.deep.equal(["Cg2f3", "Cg2o"]); + const alive = played(cat, kept); + expect(alive.board.get("f3")).to.deep.equal(["C", 1]); + expect(alive.lastmove).not.to.match(/o( |$)/); + // the dog pushed onto f3 lives beside its rabbit; the triangle has the horse pull the rabbit away + const dog = position("Ef5,Hh3,Ra1", "df4,rg3,ra8,ee8"); + expect(played(dog, enter(dog, "advanced", ["f5", "f4", "f3"])).board.get("f3")).to.deep.equal(["D", 2]); + expect([...captureChoices(dog.board, 1, 4, "f5 f4")]).to.deep.equal([["f3", true]]); + const killed = played(dog, enter(dog, "advanced", ["f5", "f4", "^f3"])); + expect(killed.board.has("f3")).to.equal(false); + expect(killed.board.get("f4")).to.deep.equal(["E", 1]); + }); + + it("has an own piece captured where it stands", () => { + const g = position("Cf3,Rf2,Ra1", "ra8,ee8"); + const move = enter(g, "advanced", ["a1", "a2", "f3", "^f3"]); + expect(said(move)).to.deep.equal(["Ra1a2", "Cf3x"]); + const after = played(g, move); + expect(after.board.has("f3")).to.equal(false); + expect(after.board.get("a2")).to.deep.equal(["R", 1]); + // its friend steps away and back: nothing was said of it + expect(after.board.get("f2")).to.deep.equal(["R", 1]); + }); + + it("offers nothing for a piece on a trap whose fate is settled", () => { + // no gold piece can reach the silver dog's only friend + const g = position("Ra1,Rh1", "dc6,rc7,ee8"); + expect(click(g, "", "c6", "advanced").move).to.equal(""); + expect(captureAlternatives(g.board, 1, 4, "c6")).to.deep.equal([]); + }); + }); + + describe("notation", () => { + it("keeps the cat alive when the rabbit reaches e3 before the cat reaches f3", () => { + const g = position("Rf2,Cg2,Ra1", "ra8,ee8"); + g.move("Cg2f3 Rf2e3"); + expect(g.board.get("f3")).to.deep.equal(["C", 1]); + expect(g.board.get("e3")).to.deep.equal(["R", 1]); + }); + + it("treats a same-square token as an assertion, not an obligatory round-trip", () => { + const g = position("Ed4,Ra1", "ra8,ee8"); + const result = g.validateMove("Ed4d4 Ra1a2"); + expect(result.valid).to.equal(true); + const before = g.clone(); + g.move("Ed4d4 Ra1a2"); + expect(g.board.get("d4")).to.deep.equal(["E", 1]); + expect(g.board.get("a2")).to.deep.equal(["R", 1]); + const replay = before.clone(); + replay.move(g.lastmove!); + expect(replay.signature()).to.equal(g.signature()); + }); + + it("compares a move entered in either mode, or typed, as the same move", () => { + // what premoves rely on: the stored move matches however it was entered + const g = position("Ed4,Hf4,Ra1,Cc1", "re4,ra8,ee8"); + const basic = enter(g, "basic", ["d4", "e4", "e5", "a1", "a2"]); + const advanced = enter(g, "advanced", ["d4", "e4", "e5", "a1", "a2"]); + expect(basic).not.to.equal(advanced); + const after = played(g, basic); + for (const other of [advanced, "re5 Ee4 Ra2", "re4e5, Ed4e4, Ra1a2", after.lastmove!]) { + expect(after.sameMove(basic, other), other).to.equal(true); + expect(played(g, other).signature(), other).to.equal(after.signature()); + } + expect(after.sameMove(basic, "re5 Ee4")).to.equal(false); + }); + }); + + describe("every legal turn can be entered", () => { + const TRAPS = ["c3", "f3", "c6", "f6"]; + const legacy = (g: ArimaaGame, steps: Array<[string, string]>): string => { + const board = new Map(g.board); + return steps.map(([from, to]) => { + const [pc, owner] = board.get(from)!; + board.set(to, board.get(from)!); + board.delete(from); + return `${owner === 1 ? pc : pc.toLowerCase()}${from}${to}`; + }).join(", "); + }; + // The clicks for a step list: a piece and where its run of steps + // ends; pusher, pushed piece and where that goes; pulled piece, + // puller and where that goes. + // How a push or pull is clicked. As a "chain": pusher, pushed piece + // and where that goes; pulled piece, puller and where that goes. As + // "steps", its two steps in the order they happen: the pushed piece + // and where it goes, then a click on the pusher; the puller and where + // it goes, then the pulled piece and the square the puller left. + // "Merged" is "steps" with arrows as long as they can be: a puller's + // walk up to the pull is one arrow, whose route Basic picks for itself, + // and a pull and the push of the same piece that follows it are one + // arrow for that piece, as in a flip. + type Form = "chain" | "steps" | "merged"; + const clicksFor = (g: ArimaaGame, steps: Array<[string, string]>, form: Form = "chain"): string[][] => { + const owner = new Map([...g.board].map(([cell, [, o]]): [string, number] => [cell, o])); + const mine = (sq: string): boolean => owner.get(sq) === g.currplayer; + const go = (from: string, to: string): void => { + owner.set(to, owner.get(from)!); + owner.delete(from); + }; + const out: string[][] = []; + // the groups that are one piece's walk + const walks = new Set(); + // where the piece pulled by the last group now stands + let pulledTo: string | undefined; + for (let i = 0; i < steps.length; i++) { + const [from, to] = steps[i]; + const next = steps[i + 1]; + if (next !== undefined && next[1] === from && owner.has(next[0]) && mine(next[0]) !== mine(from)) { + const pull = mine(from); + const last = out[out.length - 1]; + if (form === "chain") { + out.push([next[0], from, to]); + } else if (pull && form === "merged" && last !== undefined && walks.has(last) && last[1] === from) { + // the puller's walk goes on to its last step + last[1] = to; + walks.delete(last); + out.push([next[0], from]); + } else if (pull) { + out.push([from, to, next[0], from]); + } else if (form === "merged" && pulledTo === from && last !== undefined) { + // the pulled piece's arrow goes on to where it is pushed + last[last.length - 1] = to; + last.push(next[0]); + } else { + out.push([from, to, next[0]]); + } + pulledTo = pull ? from : undefined; + go(from, to); + go(next[0], next[1]); + i++; + continue; + } + pulledTo = undefined; + const last = out[out.length - 1]; + if (last !== undefined && walks.has(last) && last[1] === from) { + last[1] = to; + } else { + const walk = [from, to]; + walks.add(walk); + out.push(walk); + } + go(from, to); + } + return out; + }; + // plain clicks, and in Advanced each variant that clicks one trap + // destination's triangle instead, or that ends by selecting the piece + // on that trap and clicking its triangle there + const sequences = (clicks: string[][], mode: Mode): string[][] => { + const seqs = [clicks.flat()]; + if (mode === "advanced") { + clicks.forEach((group, i) => { + const trap = group[group.length - 1]; + if (TRAPS.includes(trap)) { + seqs.push(clicks.map((c, j) => j === i ? [...c.slice(0, -1), `^${trap}`] : c).flat()); + seqs.push([...clicks.flat(), trap, `^${trap}`]); + } + }); + } + return seqs; + }; + for (const [name, spec, player] of [ + ["a frozen-piece tangle", "Ed5,Mf5,Rd3,Ra1,me5,rd4,rf4,ee8,ra8", 2], + ["a rabbit near goal", "Eb2,Hc4,Rh1,Ra1,rb1,rc2,ed8,ra8", 2], + ["pieces dying on a trap", "Rb4,Ec2,rc4,ee8,Ra1", 1], + ["pushes and pulls in the open", "Dd4,Ra1,re4,cd5,ra8,ee8", 1], + ["Silver pushing and pulling beside a trap", "ed5,ra8,Re5,Cd4,Ra1,Ee1", 2], + ] as Array<[string, string, Owner]>) { + for (const mode of MODES) { + it(`${mode}: ${name}`, function () { + this.timeout(120000); + const reachable = allTurns(boardOf(spec.replace(/,/g, " ")), player, 4); + expect(reachable.size).to.be.greaterThan(20); + const missed: string[] = []; + // Basic also takes every push and pull as its steps in turn + for (const form of mode === "basic" ? ["chain", "steps", "merged"] as const : ["chain"] as const) { + for (const stepLists of reachable.values()) { + const g = ready(boardOf(spec.replace(/,/g, " ")), player); + const target = g.clone().move(legacy(g, stepLists[0]), {trusted: true, partial: true}).signature(); + const entered = stepLists.some(steps => sequences(clicksFor(g, steps, form), mode).some(seq => { + let move = ""; + for (const sq of seq) { + const r = click(g, move, sq.replace("^", ""), mode, sq.startsWith("^") ? ARIMAA_CAPTURE_CHOICE : undefined); + if (r.valid) { + move = r.move; + } + } + const v = g.validateMove(move); + return v.valid && (v.complete ?? -1) >= 0 && + g.clone().move(move).signature() === target; + })); + if (!entered) { + missed.push(`${form}: ${legacy(g, stepLists[0])}`); + } + } + } + expect(missed, missed.slice(0, 5).join("; ")).to.deep.equal([]); + }); + } + } + }); +}); diff --git a/test/games/arimaa.test.ts b/test/games/arimaa.test.ts index d087b080f..f6a48d3a5 100644 --- a/test/games/arimaa.test.ts +++ b/test/games/arimaa.test.ts @@ -91,6 +91,15 @@ describe("Arimaa", () => { expect(result.message).to.equal(i18next.t("apgames:validation._general.VALID_MOVE")); result = g.validateMove("ed7,hb7,hg7,ra7,ra8,rb8,rc8,rf8,rg8,rh8,rh7,cf7,ce7,dc7,dd8,me8"); expect(result.message).to.include(i18next.t("apgames:validation.arimaa.WARN_HIDE")); + // a rabbit in front hides a stronger piece too, unless it is a cat + result = g.validateMove("ed7,me7,hb7,hg7,ra7,ra8,rb8,rc8,rg8,rh8,rh7,df8,rf7,cd8,ce8,dc7"); + expect(result.message).to.include(i18next.t("apgames:validation.arimaa.WARN_HIDE")); + // and so is any non-cat on the back rank with a weaker piece in front, for Gold as well + const gold = new ArimaaGame(); + expect(gold.validateMove("Ed2,Me2,Hb2,Hg2,Ra2,Ra1,Rb1,Rc1,Rg1,Rh1,Rh2,Df1,Rf2,Cd1,Ce1,Dc2").message) + .to.include(i18next.t("apgames:validation.arimaa.WARN_HIDE")); + expect(gold.validateMove("Ed2,Me2,Hb2,Hg2,Ra2,Ra1,Rb1,Rc1,Rg1,Rh1,Rh2,Cf1,Rf2,Dd1,De1,Cc2").message) + .to.equal(i18next.t("apgames:validation._general.VALID_MOVE")); }); it ("Rabbit autofill in standard setup", () => { @@ -179,6 +188,51 @@ describe("Arimaa", () => { expect(result.move).to.equal("Ee2,Md2"); }); + it ("Setup clicks that mean nothing are controls", () => { + const nonrabbits = "Ee2,Md2,Hb2,Hg2,Cf2,Cc2,Dd1,De1"; + // standard setup: an empty square outside the setup area (d4) finishes + // a setup that can be submitted, and otherwise drops the selection + let g = new ArimaaGame(); + let result = g.handleClick(nonrabbits, 4, 3); + expect(result.valid).to.be.true; + expect(result.move).to.equal(nonrabbits); + expect(result.complete).to.equal(1); + result = g.handleClick(`${nonrabbits},R`, 4, 3); + expect(result.move).to.equal(nonrabbits); + expect(result.complete).to.equal(0); + result = g.handleClick("Ee2,Md2,Hb2,Hg2,Cf2,Cc2,Dd1", 4, 3); + expect(result.move).to.equal("Ee2,Md2,Hb2,Hg2,Cf2,Cc2,Dd1"); + expect(result.complete).to.equal(-1); + result = g.handleClick("E", 4, 3); + expect(result.move).to.equal(""); + result = g.handleClick("", 4, 3); + expect(result.valid).to.be.true; + expect(result.move).to.equal(""); + expect(result.complete).to.equal(-1); + // an opponent's piece (Gold's on e2) drops the selection, or else the last piece placed + g.move(nonrabbits); + result = g.handleClick("ee7,md7,m", 6, 4); + expect(result.move).to.equal("ee7,md7"); + result = g.handleClick("ee7,md7", 6, 4); + expect(result.valid).to.be.true; + expect(result.move).to.equal("ee7"); + result = g.handleClick("", 6, 4); + expect(result.move).to.equal(""); + result = g.handleClick("ee7,md7,hb7,hg7,cf7,cc7,dd8,de8", 4, 3); + expect(result.complete).to.equal(1); + + // free placement: every empty square takes a piece, but an opponent's piece is a control + g = new ArimaaGame(undefined, ["free"]); + g.move("Ec3,Rd4"); + result = g.handleClick("ed5,rd6,m", 5, 2); + expect(result.move).to.equal("ed5,rd6"); + result = g.handleClick("ed5,rd6", 5, 2); + expect(result.valid).to.be.true; + expect(result.move).to.equal("ed5"); + result = g.handleClick("ed5", 4, 4); + expect(result.move).to.equal("ed5,re4"); + }); + it ("Can't place two pieces on one cell", () => { // only reachable by typing; the click handler refuses to drop onto an // occupied cell. Used to throw an unhandled TypeError in standard setup @@ -221,7 +275,7 @@ describe("Arimaa", () => { g.move("rd5,rd3"); result = g.validateMove("Hd6d7,rd5d6,Ed4d5,rd3d4"); expect(result.valid).to.be.true; - expect(result.complete).to.equal(1); + expect(result.complete).to.equal(0); }); it ("Harlog status shows the leader's colour instead of a sign", () => { @@ -280,15 +334,10 @@ describe("Arimaa", () => { // Lightvector notation and arrow entry import { isLegacy, parseMove, parseToken, NotationError } from "../../src/games/arimaa/notation"; -import { resolve, serializeTurn, sqName, turnFromSteps, type CellContents } from "../../src/games/arimaa/turns"; +import { canMoveWithin, fewestDisplaced, resolve, serializeTurn, sqIndex, sqName, turnFromSteps, type CellContents, type Found, type Turn } from "../../src/games/arimaa/turns"; import { arimaaRecords } from "../fixtures/arimaa/records"; -import { allTurns, boardOf as coverageBoard, unsupportedOnTrap, type Owner } from "../fixtures/arimaa/coverage"; +import { allPlays, unsupportedOnTrap } from "../fixtures/arimaa/coverage"; -const rc = (cell: string): [number, number] => { - const [x, y] = ArimaaGame.algebraic2coords(cell); - return [y, x]; -}; -const click = (g: ArimaaGame, move: string, cell: string) => g.handleClick(move, ...rc(cell)); const annotations = (g: ArimaaGame): string[] => { const rep = g.render(); const name = (t: {row: number; col: number}): string => ArimaaGame.coords2algebraic(t.col, t.row); @@ -353,10 +402,10 @@ describe("Arimaa notation parser", () => { expect(p.pending).to.equal("e4"); expect(() => parseMove("Ed4e4 e4")).to.throw(NotationError); expect(() => parseMove("e4 Ed4e4", true)).to.throw(NotationError); - // two trailing squares: the selection before the current one is kept too + // two trailing squares: both are kept, oldest first const q = parseMove("Ed4e4 d4 e4", true); expect(q.tokens.map(t => t.text)).to.deep.equal(["Ed4e4"]); - expect(q.previous).to.equal("d4"); + expect(q.selections).to.deep.equal(["d4", "e4"]); expect(q.pending).to.equal("e4"); expect(() => parseMove("d4 e4 Ed4e4", true)).to.throw(NotationError); }); @@ -441,6 +490,77 @@ describe("Arimaa resolution", () => { const r2 = resolve(c, 2, 4, parseMove("rb6x mb5x Ra5b5").tokens, false); expect(r2.status).to.equal("resolved"); }); + it("counts a right-sized pull even where the position is first reached without one", () => { + // The cat steps north and the rabbit follows it; then the dog takes + // the rabbit's square. Those same three steps are also the cat + // stepping away and the dog pushing the rabbit, which the search + // comes to first, and a dog is not one rank above a rabbit while + // there is a cat on the board. + const b = boardOf("Ce5 Dd4 Ra1 re4 ra8 ee8"); + const tokens = parseMove("re4e5 Ce5e6 Dd4f4").tokens; + for (const prune of [true, false]) { + const found = fewestDisplaced(b, 1, 4, tokens, undefined, prune); + expect(found, `prune ${prune}`).to.have.length(1); + expect(found[0].turn.steps, `prune ${prune}`).to.have.length(4); + expect(found[0].rightSized, `prune ${prune}`).to.equal(1); + } + }); + it("knows which pieces can move this turn, alone and alongside what an entry says", function () { + this.timeout(120000); + // crowded random positions, so that pieces block, freeze and push one another + let seed = 777; + const rnd = (n: 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) % n; + }; + const types = ["E", "M", "H", "D", "C", "R", "R", "C", "D", "H"]; + let blocked = 0; + let withTokens = 0; + for (let trial = 0; trial < 40; trial++) { + const b = new Map(); + const [cx, cy] = [1 + rnd(6), 1 + rnd(6)]; + for (let i = 0; i < 24 && b.size < 5 + rnd(5); i++) { + const cell = ArimaaGame.coords2algebraic(Math.min(7, Math.max(0, cx + rnd(5) - 2)), Math.min(7, Math.max(0, cy + rnd(5) - 2))); + if (!b.has(cell)) { + b.set(cell, [types[rnd(types.length)] as CellContents[0], (1 + rnd(2)) as 1 | 2]); + } + } + let trap: string | undefined; + while ((trap = unsupportedOnTrap(b as unknown as Parameters[0])) !== undefined) { + b.delete(trap); + } + const player = (1 + rnd(2)) as 1 | 2; + const label = `${[...b.entries()].map(([c, [pc, o]]) => (o === 1 ? pc : pc.toLowerCase()) + c).join(" ")} / player ${player}`; + // every way of playing every turn, enumerated independently of the engine + const plays = allPlays(b as unknown as Parameters[0], player, 4); + for (const cell of b.keys()) { + for (let limit = 1; limit <= 4; limit++) { + const can = plays.some(p => p.steps <= limit && (p.paths.get(cell)?.visited.length ?? 1) > 1); + expect(canMoveWithin(b, player, limit, cell), `${label} / ${cell} in ${limit}`).to.equal(can); + blocked += can ? 0 : 1; + } + } + // and with an entry, against a search that prunes nothing + const play = plays[rnd(plays.length)]; + const moved = play === undefined ? undefined : [...play.paths].find(([from, path]) => path.final !== from); + if (moved !== undefined) { + const [from, path] = moved; + const letter = path.owner === 1 ? path.type : path.type.toLowerCase(); + const tokens = parseMove(path.captured ? `${letter}${from}x` : `${letter}${from}${path.final}`).tokens; + for (const cell of b.keys()) { + const start = sqIndex(cell); + const full = resolve(b, player, 4, tokens, false, false, turn => turn.trajectories.some(tr => tr.start === start && tr.visited.length > 1)); + expect(canMoveWithin(b, player, 4, cell, tokens), `${label} / ${tokens.map(t => t.text).join(" ")} / ${cell}`) + .to.equal(full.status !== "unsatisfiable"); + withTokens++; + } + } + } + expect(blocked).to.be.greaterThan(100); + expect(withTokens).to.be.greaterThan(100); + }); it("pruning never changes an answer", function () { this.timeout(120000); // deterministic pseudo-random positions and token sets: sparse boards @@ -509,7 +629,27 @@ describe("Arimaa resolution", () => { const parsed = parseMove(tokens.join(" ")).tokens; const pruned = resolve(b, player, maxSteps, parsed, false, true); const full = resolve(b, player, maxSteps, parsed, false, false); - expect(key(pruned), `${[...b.entries()].map(([c, [p, o]]) => (o === 1 ? p : p.toLowerCase()) + c).join(" ")} / ${tokens.join(" ")} / player ${player} / ${maxSteps} steps`).to.equal(key(full)); + const label = `${[...b.entries()].map(([c, [p, o]]) => (o === 1 ? p : p.toLowerCase()) + c).join(" ")} / ${tokens.join(" ")} / player ${player} / ${maxSteps} steps`; + expect(key(pruned), label).to.equal(key(full)); + // nor when displaced pieces are counted before steps, as click + // entry in Advanced mode counts them: then a longer turn can beat + // a shorter one, and the count of right-sized pushes matters + const bucket = (found: Found[]): string => found.map(f => `${f.turn.signature}:${f.turn.displaced}:${f.turn.steps.length}:${f.rightSized}`).sort().join(" "); + expect(bucket(fewestDisplaced(b, player, maxSteps, parsed)), `${label} / displaced first`) + .to.equal(bucket(fewestDisplaced(b, player, maxSteps, parsed, undefined, false))); + // nor with a filter of the kinds click entry passes, which read + // only where pieces start, pass and end: one piece has to move, + // or nothing else may + if (cells.length > 0) { + const chosen = sqIndex(cells[tokens.length % cells.length]); + for (const [name, accept] of [ + ["moves", (turn: Turn): boolean => turn.trajectories.some(tr => tr.start === chosen && tr.visited.length > 1)], + ["alone", (turn: Turn): boolean => turn.trajectories.every(tr => tr.start === chosen || tr.visited.length === 1)], + ] as Array<[string, (turn: Turn) => boolean]>) { + expect(key(resolve(b, player, maxSteps, parsed, false, true, accept)), `${label} / ${name}`) + .to.equal(key(resolve(b, player, maxSteps, parsed, false, false, accept))); + } + } }; for (let trial = 0; trial < 150; trial++) { check(4 + rnd(4), 4); @@ -521,19 +661,15 @@ describe("Arimaa resolution", () => { }); describe("Arimaa arrow entry", () => { - it("enters a flip in two clicks and records it as dx", () => { + it("reads an enemy arrow onto a trap as a flip and records it as dx", () => { const g = position("Hg3,Cf2,Ra2,Ee1", "dh3,ra7,ee8"); - let r = click(g, "", "h3"); - expect(r.move).to.equal("h3"); - expect(r.complete).to.equal(-1); - r = click(g, r.move, "f3"); - expect(r.move).to.equal("dh3f3"); + const r = g.validateMove("dh3f3"); expect(r.valid).to.be.true; - expect(r.complete).to.equal(1); + expect(r.complete).to.equal(0); const preview = g.clone(); - preview.move(r.move, {partial: true}); + preview.move("dh3f3", {partial: true}); expect(annotations(preview)).to.have.members(["enter:g3", "move:h3>f3", "exit:f3"]); - g.move(r.move); + g.move("dh3f3"); expect(g.lastmove).to.equal("dx"); expect(g.board.has("h3")).to.be.false; expect(g.board.get("g3")).to.deep.equal(["H", 1]); @@ -541,74 +677,29 @@ describe("Arimaa arrow entry", () => { expect(g.results.filter(x => x.type === "move").length).to.equal(4); expect(g.results.filter(x => x.type === "destroy").length).to.equal(1); }); - it("holds an ambiguous push by arrowing the pusher onto the vacated square", () => { + it("settles an ambiguous push with an arrow of the pusher onto the vacated square", () => { const g = position("Ed4,Hf4,Ra1,Cc1", "re4,ra8,ee8"); - let r = click(g, "", "e4"); - r = click(g, r.move, "e5"); - expect(r.move).to.equal("re4e5"); - expect(r.complete).to.equal(-1); - r = click(g, r.move, "d4"); - expect(r.move).to.equal("re4e5 d4"); - r = click(g, r.move, "e4"); - expect(r.move).to.equal("re4e5 Ed4e4"); + // either pusher fits: one is shown, and the message says so + const r = g.validateMove("re4e5"); expect(r.complete).to.equal(0); - g.move(r.move); + expect(r.message).to.contain(i18next.t("apgames:validation.arimaa.AMBIGUOUS", {count: 2})); + expect(g.validateMove("re4e5 Ed4e4").complete).to.equal(0); + g.move("re4e5 Ed4e4"); expect(g.lastmove).to.equal("re5 Ee4"); }); - it("enters a pull in four clicks", () => { + it("reads a pull from the arrows of the puller and the pulled piece", () => { const g = position("Ed4,Hf4,Ra1,Cc1", "re4,ra8,ee8"); - let r = click(g, "", "d4"); - r = click(g, r.move, "c4"); - r = click(g, r.move, "e4"); - expect(r.move).to.equal("Ed4c4 e4"); - // the arrows already form a move; the selection only adds a hint - expect(r.complete).to.equal(0); - expect(r.message).to.contain(i18next.t("apgames:validation.arimaa.INCOMPLETE")); - r = click(g, r.move, "d4"); - expect(r.move).to.equal("Ed4c4 re4d4"); - g.move(r.move); + expect(g.validateMove("Ed4c4 re4d4").complete).to.equal(0); + g.move("Ed4c4 re4d4"); expect(g.lastmove).to.equal("Ec4 rd4"); expect(annotations(g)).to.have.members(["move:d4>c4", "move:e4>d4"]); }); - it("re-selects, holds, extends from an arrow head and deletes from its tail", () => { + it("lets an arrow end on an occupied square, leaving open where the occupant goes", () => { const g = position("Ed4,Hf4,Ra1,Cc1", "re4,ra8,ee8"); - let r = click(g, "", "d4"); - r = click(g, r.move, "f4"); - // another piece re-selects, remembering the first for a second click - expect(r.move).to.equal("d4 f4"); - r = click(g, r.move, "f4"); - // which sends the first onto this square; the horse has to make way, - // and where it goes is still open - expect(r.move).to.equal("Ed4f4"); - expect(r.valid).to.be.true; - expect(r.complete).to.equal(-1); - r = click(g, "d4", "d6"); - expect(r.move).to.equal("Ed4d6"); - r = click(g, r.move, "d6"); - expect(r.move).to.equal("Ed4d6 d6"); - r = click(g, r.move, "e6"); - expect(r.move).to.equal("Ed4e6"); - r = click(g, r.move, "d4"); - expect(r.move).to.equal("d4"); - // a second click on a selected piece holds it; a click on the hold lifts it - r = click(g, r.move, "d4"); - expect(r.move).to.equal("Ed4d4"); - expect(r.valid).to.be.true; - r = click(g, r.move, "d4"); - expect(r.move).to.equal("d4"); - // an empty square with nothing selected is a no-op - r = click(g, "", "b5"); - expect(r.move).to.equal(""); - }); - it("rejects a click that no legal move can satisfy and keeps the previous move", () => { - const g = position("Ed4,Ra1", "ee5,ra8"); - let r = click(g, "d4", "h8"); - expect(r.move).to.equal("d4"); - expect(r.valid).to.be.false; - // an occupied, unvacated square is a re-selection, never a destination - r = click(g, "d4", "e5"); - expect(r.move).to.equal("d4 e5"); + const r = g.validateMove("Ed4f4"); expect(r.valid).to.be.true; + expect(r.complete).to.equal(0); + expect(r.message).to.contain(i18next.t("apgames:validation.arimaa.AMBIGUOUS", {count: 6})); }); it("rejects arrows no turn can satisfy on a full board, and says why", () => { const g = new ArimaaGame(); @@ -626,8 +717,7 @@ describe("Arimaa arrow entry", () => { // a boxed-in piece, and one on the back rank with the front rank in the way expect(rejected("Rh1h4")).to.equal(i18next.t("apgames:validation.arimaa.NO_MOVE_REACH", {from: "h1", to: "h4", num: 4})); expect(rejected("De1d3")).to.equal(i18next.t("apgames:validation.arimaa.NO_MOVE_REACH", {from: "e1", to: "d3", num: 4})); - // an enemy piece nothing can push or pull, which is also what a click - // on the wrong side's piece produces + // an enemy piece nothing can push or pull expect(rejected("ra7a6")).to.equal(i18next.t("apgames:validation.arimaa.NO_MOVE_ENEMY", {from: "a7", num: 4})); // the old step list typed with spaces reads as two elephants expect(rejected("Ee2e3 Ee3e4")).to.equal(i18next.t("apgames:validation.arimaa.NO_MOVE_CHAIN", {first: "Ee2e3", second: "Ee3e4", combined: "Ee2e4"})); @@ -657,138 +747,85 @@ describe("Arimaa arrow entry", () => { expect(r.valid).to.be.false; expect(r.message).to.equal(i18next.t("apgames:validation.arimaa.TOO_LONG", {num: 4})); }); - it("keeps a hold visible once the move resolves", () => { - const g = position("Ed4,Cc4,Ra1", "ee8,ra8"); - let r = click(g, "", "d4"); - r = click(g, r.move, "e4"); - r = click(g, r.move, "c4"); - r = click(g, r.move, "c4"); - expect(r.move).to.equal("Ed4e4 Cc4c4"); - expect(r.valid).to.be.true; - g.move(r.move, {partial: true}); - expect(annotations(g)).to.include("move:d4>e4"); - expect(annotations(g)).to.include("enter:c4"); - }); - it("holds a piece that steps out and back with a second click on it", () => { + it("keeps a piece that steps out and back on its square with a hold", () => { // the elephant pushes the dog into the trap and returns; without the hold // the arrows read as the three-step turn that leaves it on d6 const g = position("Ee6,Cg2,Ra1", "dd6,ra8,ee8"); - let r = click(g, "", "d6"); - r = click(g, r.move, "c6"); - r = click(g, r.move, "g2"); - r = click(g, r.move, "g3"); - expect(r.move).to.equal("dd6c6 Cg2g3"); + const unheld = g.validateMove("dd6c6 Cg2g3"); + expect(unheld.valid).to.be.true; + expect(unheld.message).to.contain("Ee6d6"); + const r = g.validateMove("dd6c6 Cg2g3 Ee6e6"); expect(r.valid).to.be.true; - expect(r.message).to.contain("Ee6d6"); - r = click(g, r.move, "e6"); - r = click(g, r.move, "e6"); - expect(r.move).to.equal("dd6c6 Cg2g3 Ee6e6"); - expect(r.valid).to.be.true; - expect(r.complete).to.equal(1); + expect(r.complete).to.equal(0); const preview = g.clone(); - preview.move(r.move, {partial: true}); + preview.move("dd6c6 Cg2g3 Ee6e6", {partial: true}); expect(annotations(preview)).to.include.members(["enter:e6", "move:d6>c6", "exit:c6", "move:g2>g3"]); - g.move(r.move); + g.move("dd6c6 Cg2g3 Ee6e6"); expect(g.lastmove).to.equal("Cg3 dx Ee6"); expect(g.board.get("e6")).to.deep.equal(["E", 1]); expect(g.board.has("c6")).to.be.false; }); - it("completes an arrow onto an occupied square with a second click on it", () => { - // a rotation: the elephant pulls one rabbit and pushes the other, - // ending where the second one stood + it("reads a rotation from arrows onto occupied squares", () => { + // the elephant pulls one rabbit and pushes the other, ending where the + // second one stood const g = position("Eh5,Ra1", "rh6,rg6,ra8,ee8"); - let r = click(g, "", "h5"); - r = click(g, r.move, "g6"); - expect(r.move).to.equal("h5 g6"); - r = click(g, r.move, "g6"); - expect(r.move).to.equal("Eh5g6"); + expect(g.validateMove("Eh5g6").valid).to.be.true; + const r = g.validateMove("Eh5g6 rg6h6 rh6h5"); expect(r.valid).to.be.true; - r = click(g, r.move, "g6"); - expect(r.move).to.equal("Eh5g6 g6"); - r = click(g, r.move, "h6"); - r = click(g, r.move, "h6"); - expect(r.move).to.equal("Eh5g6 rg6h6"); - r = click(g, r.move, "h6"); - r = click(g, r.move, "h5"); - expect(r.move).to.equal("Eh5g6 rg6h6 rh6h5"); - expect(r.valid).to.be.true; - expect(r.complete).to.equal(1); - g.move(r.move); + expect(r.complete).to.equal(0); + g.move("Eh5g6 rg6h6 rh6h5"); expect(g.board.get("g6")).to.deep.equal(["E", 1]); expect(g.board.get("h6")).to.deep.equal(["R", 2]); expect(g.board.get("h5")).to.deep.equal(["R", 2]); }); it("holds a blocker so that a piece walks around it", () => { const g = position("Re2,De3,Ra1", "ra8,ee8"); - let r = click(g, "", "e2"); - r = click(g, r.move, "e4"); - expect(r.move).to.equal("Re2e4"); // the shorter reading moves the dog aside (to d3 rather than the trap) - expect(r.complete).to.equal(0); - expect(r.message).to.contain("De3d3"); - r = click(g, r.move, "e3"); - r = click(g, r.move, "e3"); - expect(r.move).to.equal("Re2e4 De3e3"); + const unheld = g.validateMove("Re2e4"); + expect(unheld.complete).to.equal(0); + expect(unheld.message).to.contain("De3d3"); + const r = g.validateMove("Re2e4 De3e3"); expect(r.valid).to.be.true; - expect(r.complete).to.equal(1); - g.move(r.move); + expect(r.complete).to.equal(0); + g.move("Re2e4 De3e3"); expect(g.board.get("e4")).to.deep.equal(["R", 1]); expect(g.board.get("e3")).to.deep.equal(["D", 1]); expect(g.lastmove).to.equal("Re4 De3"); }); - it("marks a piece on a trap captured with a third click on it", () => { + it("marks a piece on a trap captured", () => { // from a recorded game, mirrored: the horse leaves its rabbit on the // trap unsupported; read without the mark, the rabbit's own move comes // first and keeps it alive const g = position("Ra1,Rg1,Rh1,Rh2,Ce1,Ca2,Hb3,Dh3,Rg2,Rb2,Ef2,Rd2,Hf3,Dc5,Rc3,Mb4", "ra7,ra8,rb8,rc8,rf8,rg8,rh8,rh7,cc7,df7,ce8,dd7,mf4,hg3,he3,ec4"); - let r = click(g, "", "b3"); - r = click(g, r.move, "a4"); - r = click(g, r.move, "b4"); - r = click(g, r.move, "b3"); - r = click(g, r.move, "b2"); - r = click(g, r.move, "c2"); - expect(r.move).to.equal("Hb3a4 Mb4b3 Rb2c2"); - expect(r.valid).to.be.true; + const arrows = "Hb3a4 Mb4b3 Rb2c2"; + expect(g.validateMove(arrows).valid).to.be.true; const reading = g.clone(); - reading.move(r.move, {partial: true}); + reading.move(arrows, {partial: true}); expect(reading.board.has("c3")).to.be.true; - r = click(g, r.move, "c3"); - r = click(g, r.move, "c3"); - // the second click holds it, which changes nothing here... - expect(r.move).to.equal("Hb3a4 Mb4b3 Rb2c2 Rc3c3"); - expect(r.valid).to.be.true; - // ...and on a trap a third click turns the hold into a capture mark - r = click(g, r.move, "c3"); - expect(r.move).to.equal("Hb3a4 Mb4b3 Rb2c2 Rc3x"); + // a hold changes nothing here... + expect(g.validateMove(`${arrows} Rc3c3`).valid).to.be.true; + // ...and a capture mark has the rabbit die + const r = g.validateMove(`${arrows} Rc3x`); expect(r.valid).to.be.true; - expect(r.complete).to.equal(1); + expect(r.complete).to.equal(0); const preview = g.clone(); - preview.move(r.move, {partial: true}); + preview.move(`${arrows} Rc3x`, {partial: true}); expect(preview.board.has("c3")).to.be.false; expect(annotations(preview)).to.include("exit:c3"); - // a click on the mark lifts it - r = click(g, r.move, "c3"); - expect(r.move).to.equal("Hb3a4 Mb4b3 Rb2c2 c3"); - g.move("Hb3a4 Mb4b3 Rb2c2 Rc3x"); + g.move(`${arrows} Rc3x`); expect(g.board.has("c3")).to.be.false; }); it("marks an enemy piece captured by pieces that step out and back", () => { // from a recorded game, mirrored: the elephant steps aside, pulls the // camel off the rabbit's trap and pushes it back; nothing is displaced const g = position("Rh3,Re3,Rf3,Rh2,Re2,Rd2,Rg3,Rg2,Re1,Rg1,Ra3,Rd3,Ra2,Hb5,Cb2,Eb4", "rg8,cb8,hf7,rh5,ef2,rd7,cb6,ra4,rf5,rd4,rc3,mb3"); - let r = click(g, "", "c3"); - r = click(g, r.move, "c3"); - expect(r.move).to.equal("rc3c3"); - r = click(g, r.move, "c3"); - expect(r.move).to.equal("rc3x"); + let r = g.validateMove("rc3x"); expect(r.valid).to.be.true; expect(r.complete).to.equal(0); - r = click(g, r.move, "b4"); - r = click(g, r.move, "b4"); - expect(r.move).to.equal("rc3x Eb4b4"); + r = g.validateMove("rc3x Eb4b4"); expect(r.valid).to.be.true; - expect(r.complete).to.equal(1); - g.move(r.move); + expect(r.complete).to.equal(0); + g.move("rc3x Eb4b4"); expect(g.board.has("c3")).to.be.false; expect(g.board.get("b4")).to.deep.equal(["E", 1]); expect(g.board.get("b3")).to.deep.equal(["M", 2]); @@ -824,19 +861,12 @@ describe("Arimaa arrow entry", () => { const g = position("Ed4,Ra1,Cc1", "re4,ra8,ee8"); const r = g.validateMove("re4e6 Ed4e5"); expect(r.valid).to.be.true; - expect(r.complete).to.equal(1); + expect(r.complete).to.equal(0); g.move("re4e6 Ed4e5"); expect(g.board.get("e6")).to.deep.equal(["R", 2]); expect(g.board.get("e5")).to.deep.equal(["E", 1]); expect(g.lastmove).to.equal("re6 Ee5"); }); - it("names the pieces it inferred", () => { - const g = position("Ed4,Ra1,Cc1", "re4,ra8,ee8"); - const r = g.validateMove("re4e5"); - expect(r.valid).to.be.true; - expect(r.complete).to.equal(0); - expect(r.message).to.contain("Ed4e4"); - }); it("applies the two-step ceiling on the first ply of an endless endgame", () => { const g = new ArimaaGame(undefined, ["eee"]); const e = [...g.board.entries()].find(([, [pc, owner]]) => pc === "E" && owner === 1)![0]; @@ -849,19 +879,6 @@ describe("Arimaa arrow entry", () => { }); describe("Arimaa notation compatibility", () => { - it("reads the old step notation and writes the new one", () => { - const g = position("Hg3,Cf2,Ra2,Ee1", "dh3,ra7,ee8"); - g.move("Hg3g4,dh3g3,dg3f3(xdf3),Hg4g3"); - expect(g.lastmove).to.equal("dx"); - expect(g.board.has("f3")).to.be.false; - }); - it("compares moves by the position they reach", () => { - const g = position("Hg3,Cf2,Ra2,Ee1", "dh3,ra7,ee8"); - g.move("dh3f3"); - expect(g.sameMove("dx", "Hg3g2, dh3g3, dg3f3, Hg2g3")).to.be.true; - expect(g.sameMove("dx", "df3")).to.be.true; - expect(g.sameMove("dx", "Hg3g4")).to.be.false; - }); it("stored notation replays to the same position", () => { const g = position("Ed4,Hf4,Ra1,Cc1,Db4", "re4,ra8,ee8,md7"); for (const m of ["Db4b5 Ed4c4", "md7d6 ra8b8", "Hf4e4 re4e5 Ec4c5", "ee8e7", "Hf4 Db5b4"]) { @@ -980,124 +997,6 @@ describe("Arimaa recorded games", () => { }); -describe("Arimaa click coverage", () => { - // a position to click on, with no hands and the given player to move - const ready = (spec: string, player: Owner, eee: boolean): ArimaaGame => { - const board = boardOf(spec.replace(/,/g, " ")); - const g = new ArimaaGame(undefined, eee ? ["eee"] : ["free"]); - g.stack[0].board = new Map(board); - if (!eee) { - g.stack.push({...g.stack[0], _results: [], _timestamp: new Date(), currplayer: player, board: new Map(board), hands: undefined, lastmove: "x"}); - } - g.load(); - g.hands = undefined; - return g; - }; - const perms = (xs: T[]): T[][] => xs.length <= 1 ? [xs] : xs.flatMap((x, i) => perms([...xs.slice(0, i), ...xs.slice(i + 1)]).map(r => [x, ...r])); - // every arrow first: naming every displaced piece is what usually works - const subsets = (xs: T[]): T[][] => xs.reduce((acc, x) => [...acc, ...acc.map(a => [...a, x])], [[]]).sort((a, b) => b.length - a.length); - - // every legal turn from a position must be reachable with clicks alone - for (const [name, spec, player, eee] of [ - ["a frozen-piece tangle", "Ed5,Mf5,Rd3,Ra1,me5,rd4,rf4,ee8,ra8", 2, false], - ["a rabbit near goal", "Eb2,Hc4,Rh1,Ra1,rb1,rc2,ed8,ra8", 2, false], - ["pieces dying on a trap", "Rb4,Ec2,rc4,ee8,Ra1", 1, false], - ] as Array<[string, string, Owner, boolean]>) { - it(`enters every legal turn in ${name}`, function () { - this.timeout(120000); - const board = coverageBoard(spec.replace(/,/g, " ")); - expect(unsupportedOnTrap(board), "the position itself must be legal").to.be.undefined; - const maxSteps = eee ? 2 : 4; - const reachable = allTurns(board, player, maxSteps); - expect(reachable.size).to.be.greaterThan(20); - const missed: string[] = []; - for (const [target, stepLists] of reachable.entries()) { - const g = ready(spec, player, eee); - let entered = false; - for (const steps of stepLists) { - if (entered) { - break; - } - const turn = turnFromSteps(board as Map, player, steps.map(([from, to]) => ({from, to}))); - const arrows = turn.trajectories.filter(t => t.final !== t.start) - .map(t => ({letter: t.owner === 1 ? t.type : t.type.toLowerCase(), from: sqName(t.start), to: sqName(t.final), dies: t.captured})); - const extras = turn.trajectories.filter(t => (t.captured && t.visited.length === 1) || (!t.captured && t.final === t.start && t.visited.length > 1)) - .map(t => ({sq: sqName(t.start), mark: t.captured})); - const draw = (order: typeof arrows, holds: typeof extras): string | undefined => { - let m = ""; - for (const a of order) { - let r = click(g, m, a.from); - if (!r.valid || !r.move!.endsWith(a.from)) { return undefined; } - m = r.move!; - r = click(g, m, a.to); - if (!r.valid) { return undefined; } - m = r.move!; - if (!m.endsWith(`${a.letter}${a.from}${a.to}`)) { - r = click(g, m, a.to); - if (!r.valid) { return undefined; } - m = r.move!; - } - if (!m.endsWith(`${a.letter}${a.from}${a.to}`)) { return undefined; } - if (a.dies) { - r = click(g, m, a.to); - if (!r.valid) { return undefined; } - m = r.move!; - r = click(g, m, a.to); - if (!r.valid || !r.move!.endsWith(`${a.letter}${a.from}x`)) { return undefined; } - m = r.move!; - } - } - for (const {sq, mark} of holds) { - let r = click(g, m, sq); - if (!r.valid) { return undefined; } - m = r.move!; - r = click(g, m, sq); - if (!r.valid || !r.move!.endsWith(`${sq}${sq}`)) { return undefined; } - m = r.move!; - if (mark) { - r = click(g, m, sq); - if (!r.valid || !r.move!.endsWith(`${sq}x`)) { return undefined; } - m = r.move!; - } - } - return m; - }; - for (const subset of subsets(arrows)) { - if (entered) { - break; - } - for (const order of (subset.length <= 4 ? perms(subset) : [subset])) { - for (const holds of [[], extras]) { - const m = draw(order, holds as typeof extras); - if (m === undefined || m.length === 0) { - continue; - } - const v = g.validateMove(m); - if (!v.valid || v.complete === -1) { - continue; - } - const preview = g.clone(); - preview.move(m, {partial: true}); - if (preview.signature() === target) { - entered = true; - break; - } - } - if (entered) { - break; - } - } - } - } - if (!entered) { - missed.push(stepLists[0].map(([f, t]) => f + t).join(" ")); - } - } - expect(missed, `${missed.length} of ${reachable.size} turns could not be entered`).to.be.empty; - }); - } -}); - describe("Arimaa Dicey Moves", () => { before(() => { addResource("en"); @@ -1172,29 +1071,31 @@ describe("Arimaa Dicey Moves", () => { expect(withRandom(0.34, () => freeStart().move("ee7, ra7").die!.steps)).to.equal(3); expect(withRandom(0.5, () => freeStart().move("ee7, ra7").die!.steps)).to.equal(4); expect(withRandom(0.99, () => freeStart().move("ee7, ra7").die!.steps)).to.equal(4); - const seen = new Set(); - for (let i = 0; i < 120; i++) { - seen.add(freeStart().move("ee7, ra7").die!.steps); - } - expect([...seen].sort()).to.deep.equal([1, 2, 3, 4]); + expect(withRandom(0.2, () => freeStart().move("ee7, ra7").die!.steps)).to.equal(2); }); it("gives the opening move of Endless endgame one step or two", () => { + // seeded (mulberry32), as the random setup draws on Math.random too + 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 seen = new Set(); - for (let i = 0; i < 60; i++) { - const g = new ArimaaGame(undefined, ["eee", "dicey"]); - expect(g.die).to.not.be.undefined; - expect([1, 2]).to.include(g.die!.steps); - expect(g.board.has(g.die!.square)).to.be.false; - seen.add(g.die!.steps); + const original = Math.random; + try { + for (let seed = 1; seed <= 20; seed++) { + Math.random = seeded(seed); + const g = new ArimaaGame(undefined, ["eee", "dicey"]); + expect([1, 2]).to.include(g.die!.steps); + expect(g.board.has(g.die!.square)).to.be.false; + seen.add(g.die!.steps); + } + } finally { + Math.random = original; } - expect(seen.size).to.equal(2); - // without the die, the opening move is still capped at two steps (EEE randomizes layout) - const g = new ArimaaGame(undefined, ["eee"]); - const e = [...g.board.entries()].find(([, [pc, owner]]) => pc === "E" && owner === 1)![0]; - const [x, y] = ArimaaGame.algebraic2coords(e); - const far = ArimaaGame.coords2algebraic(x, y < 4 ? y + 3 : y - 3); - expect(g.validateMove(`E${e}${far}`).valid).to.be.false; + expect([...seen].sort()).to.deep.equal([1, 2]); }); it("limits the turn to the die in both notations", () => { @@ -1202,7 +1103,7 @@ describe("Arimaa Dicey Moves", () => { g.die = {steps: 1, square: g.die!.square}; let result = g.validateMove("Ed3"); expect(result.valid).to.be.true; - expect(result.complete).to.equal(1); + expect(result.complete).to.equal(0); result = g.validateMove("Ed4"); expect(result.valid).to.be.false; result = g.validateMove("Ed2d4"); @@ -1210,7 +1111,7 @@ describe("Arimaa Dicey Moves", () => { expect(result.message).to.equal(i18next.t("apgames:validation.arimaa.TOO_LONG", {num: 1})); result = g.validateMove("Ed2d3"); expect(result.valid).to.be.true; - expect(result.complete).to.equal(1); + expect(result.complete).to.equal(0); result = g.validateMove("Ed2d3,Ed3d4"); expect(result.valid).to.be.false; expect(result.message).to.equal(i18next.t("apgames:validation.arimaa.TOO_MANY", {num: 1})); @@ -1402,10 +1303,6 @@ describe("Arimaa Dicey Moves", () => { expect(g.results.some(r => r.type === "roll")).to.be.false; expect(g.render().legend).to.not.have.property("DIE"); expect(g.validateMove("").message).to.equal(i18next.t("apgames:validation.arimaa.INITIAL_INSTRUCTIONS", {context: "play"})); - const variants = g.allvariants()!; - expect(variants.find(v => v.uid === "eee")!.fans).to.equal(true); - expect(variants.find(v => v.uid === "dicey")!.fans).to.not.equal(true); - expect(ArimaaGame.gameinfo.variants!.find(v => v.uid === "eee")!.people![0].name).to.equal("clyring"); }); }); @@ -1427,4 +1324,16 @@ describe("Arimaa setup clicks", () => { result = g.handleClick("Ee2,Md2", 6, 3, "M1"); expect(result.move).to.equal("Ee2"); }); + + it("preserves placed pieces when another piece is selected from either setup tray", () => { + for (const variants of [[], ["free"]]) { + const game = new ArimaaGame(undefined, variants); + const selected = game.handleClick("Ee2", -1, -1, "pC1"); + expect(selected.move).to.equal("Ee2,C"); + expect(selected.canrender).to.equal(true); + const preview = game.clone().move(selected.move, {partial: true}); + expect(preview.board.get("e2")).to.deep.equal(["E", 1]); + expect(preview.render().pieces).to.be.a("string").and.include("E1"); + } + }); });