From 486262dc4aa9add79978a70bf96e414101e9395a Mon Sep 17 00:00:00 2001 From: Mark Steere <80453551+MarkSteere@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:16:18 +0800 Subject: [PATCH] Add Counterflow (experimental) Counterflow is a two-player checker race game by Mark Steere (November 2026, designed in collaboration with Claude). It is played on an odd-sided square board: 5x5, 7x7 (default), 9x9 or 11x11. Blue checkers fill the rows above the empty middle row and red checkers the rows below it, and the two armies flow through each other in opposite directions. Checkers move like non-capturing chess queens, directly forward, diagonally forward or sideways. A move must not complete a wall (a row filled with one colour) except in the mover's far row, in the next row behind another wall of that colour, or to win, and a sideways move must shorten the shortest distance of any checker to an opening, or win. You win when all of your groups have at least one checker in your far row. At least one player always has a legal move and no position can repeat. A player with no legal move has the turn skipped (`autopass` flag, with a move-log line of its own). The render follows the designer's own app: one felt colour, a green dot on every checker that has a legal move, green squares for the destinations of the selected checker, a white ring on the checker moved last, and a gold outline around the winner's groups at the end. The tests are built from the figures of the rule sheet. The rule helpers reproduce the position counts of the designer's programs on six small boards, and the game class agrees with the engine of the designer's app on every legal move, skipped turn, checker distance and winner in 5,220 random games (492,661 positions) on the four board sizes. Rules: https://www.marksteeregames.com/Counterflow_rules.pdf Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GoHk3oWRd5GQy4KKJ1TryQ --- CHANGELOG.md | 2 +- locale-src/de/apgames.json | 4 + .../en/apresults/apresults-path-map.json | 22 +- locale-src/es-US/apgames.json | 4 + locale-src/fr/apgames.json | 4 + locale-src/it/apgames.json | 4 + locales/de/apgames.json | 1 + locales/en/apgames.json | 28 + locales/en/apresults.json | 8 + locales/es-US/apgames.json | 1 + locales/fr/apgames.json | 1 + locales/it/apgames.json | 1 + src/games/counterflow.ts | 999 ++++++++++++++++++ test/games/counterflow.test.ts | 656 ++++++++++++ 14 files changed, 1733 insertions(+), 2 deletions(-) create mode 100644 src/games/counterflow.ts create mode 100644 test/games/counterflow.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index fb1e245a..a60f7533 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ Since the `1.0.0-beta` release, the version in `package.json` has stayed at `1.0 ### Added -- **New games (dev / experimental only):** Agents of MARS, Bagh Chal, Bashni, Bricka, Croda, Dama, Ice Palace, Neutron, Outbound, QBF, Squares, Thricewise. +- **New games (dev / experimental only):** Agents of MARS, Bagh Chal, Bashni, Bricka, Counterflow, Croda, Dama, Ice Palace, Neutron, Outbound, QBF, Squares, Thricewise. ## [1.0.0-ci] - 2026-11-11 diff --git a/locale-src/de/apgames.json b/locale-src/de/apgames.json index 1a729d6e..ced71845 100644 --- a/locale-src/de/apgames.json +++ b/locale-src/de/apgames.json @@ -3763,6 +3763,10 @@ "src": "Control", "out": "Control" }, + "names.counterflow": { + "src": "Counterflow", + "out": "Counterflow" + }, "names.court": { "src": "Court", "out": "Court" diff --git a/locale-src/en/apresults/apresults-path-map.json b/locale-src/en/apresults/apresults-path-map.json index 6679be1a..598442d2 100644 --- a/locale-src/en/apresults/apresults-path-map.json +++ b/locale-src/en/apresults/apresults-path-map.json @@ -1,5 +1,5 @@ { - "generatedAt": "2026-11-06", + "generatedAt": "2026-11-13", "schemaVersion": 1, "entries": [ { @@ -2552,6 +2552,26 @@ "newFullKey": "apresults:connections.EOG.path", "english": "The game has ended because a player connected their dots." }, + { + "oldPath": "EOG.counterflow_groups", + "oldFullKey": "apresults:EOG.counterflow_groups", + "uid": "counterflow", + "resultType": "EOG", + "newLeaf": "groups", + "newPath": "counterflow.EOG.groups", + "newFullKey": "apresults:counterflow.EOG.groups", + "english": "All of {{player}}'s groups have at least one checker in the far row." + }, + { + "oldPath": "PASS.counterflow_skipped", + "oldFullKey": "apresults:PASS.counterflow_skipped", + "uid": "counterflow", + "resultType": "PASS", + "newLeaf": "skipped", + "newPath": "counterflow.PASS.skipped", + "newFullKey": "apresults:counterflow.PASS.skipped", + "english": "{{player}} had no available move, so the turn was skipped." + }, { "oldPath": "PLACE.court", "oldFullKey": "apresults:PLACE.court", diff --git a/locale-src/es-US/apgames.json b/locale-src/es-US/apgames.json index 51d9ab2b..f3ebcfc7 100644 --- a/locale-src/es-US/apgames.json +++ b/locale-src/es-US/apgames.json @@ -3763,6 +3763,10 @@ "src": "Control", "out": "Control" }, + "names.counterflow": { + "src": "Counterflow", + "out": "Counterflow" + }, "names.court": { "src": "Court", "out": "Court" diff --git a/locale-src/fr/apgames.json b/locale-src/fr/apgames.json index 386ee91f..ab0eb354 100644 --- a/locale-src/fr/apgames.json +++ b/locale-src/fr/apgames.json @@ -3763,6 +3763,10 @@ "src": "Control", "out": "Control" }, + "names.counterflow": { + "src": "Counterflow", + "out": "Counterflow" + }, "names.court": { "src": "Court", "out": "Court" diff --git a/locale-src/it/apgames.json b/locale-src/it/apgames.json index 359da2ba..720a30ab 100644 --- a/locale-src/it/apgames.json +++ b/locale-src/it/apgames.json @@ -3763,6 +3763,10 @@ "src": "Control", "out": "Control" }, + "names.counterflow": { + "src": "Counterflow", + "out": "Counterflow" + }, "names.court": { "src": "Court", "out": "Court" diff --git a/locales/de/apgames.json b/locales/de/apgames.json index 45b2df6b..09250958 100644 --- a/locales/de/apgames.json +++ b/locales/de/apgames.json @@ -4616,6 +4616,7 @@ "connections": "Connections", "conspirateurs": "Conspirateurs", "control": "Control", + "counterflow": "Counterflow", "court": "Court", "courtesan": "King & Courtesan", "croda": "Croda", diff --git a/locales/en/apgames.json b/locales/en/apgames.json index ea0906ce..d17c2c76 100644 --- a/locales/en/apgames.json +++ b/locales/en/apgames.json @@ -1632,6 +1632,17 @@ "INSUFFICIENT_CONTROL": "You do not control {{cell}}.", "OPPONENT_CONTROL": "Your opponent controls {{cell}}." }, + "counterflow": { + "INITIAL_INSTRUCTIONS": "Select one of your checkers. A green dot marks every checker that has a legal move. The squares the selected checker may move to are then marked in green.", + "PARTIAL": "Select the square to move the checker to, or select another of your checkers instead.", + "DIRECTION": "The checker on {{from}} cannot move to {{to}}. A checker moves like a non-capturing Chess queen, directly forward, diagonally forward, or sideways.", + "BLOCKED": "The checker on {{from}} cannot reach {{to}}. A checker moves over consecutive unoccupied squares only.", + "WALL": "The checker on {{from}} may not move to {{to}}, because the move would complete a wall. You must not complete a wall except when your move wins the game, the wall is in your far row, or there is another wall of your colour in the next row ahead of the wall.", + "SIDEWAYS": "The checker on {{from}} may not move sideways to {{to}}. A sideways move is legal only if the shortest distance after the move is shorter than the shortest distance before the move, or the move wins the game.", + "SIDEWAYS_ZERO": "The checker on {{from}} may not move sideways to {{to}}. The shortest distance is 0, so no sideways move is legal, except for a winning sideways move.", + "NO_PASS": "You may not pass while you have an available move.", + "MUST_PASS": "You have no available move. Your turn is skipped." + }, "court": { "INITIAL_INSTRUCTIONS": "Select one of your pieces to move, or promote a Pawn (if officials are still available) by clicking on it multiple times. Pawns, Knights, Bishops and Rooks move as in Chess. (Pawns do not have an initial double move and don't need to reach the final rank to promote.)", "NOT_FRIENDLY_PIECE": "Select a friendly piece to move or promote.", @@ -4313,6 +4324,7 @@ "connections": "Draw lines between dots of your colour to connect the sides of the board, or surround your opponent's dots to win.", "conspirateurs": "A traditional French game where you try to get all your pieces to safety before your opponent can do the same.", "control": "Control is a finite, drawless territory game of elegant simplicity. Add pieces where your opponent doesn't have more influence or remove pieces from where you have more influence. Last to move wins.", + "counterflow": "A checker race game. Two armies of checkers flow through each other in opposite directions. Checkers move like non-capturing Chess queens, directly forward, diagonally forward, or sideways, with restrictions on completing walls and on sideways moves. You win if all of your groups have at least one checker in your far row. Cycles and deadlocks cannot occur.", "court": "A set of pawns that can be promoted anytime to a limited set of officials. However, without pawns one loses the game. A stalemated player also loses the game.", "courtesan": "Get your king to the other side of the board while safely \"hiding\" it among your other pieces.", "croda": "Croda on an 8×8 board: men step one square forward orthogonally or diagonally; they capture orthogonally in any direction. Kings slide and capture along ranks and files. Maximal capture is compulsory; you win by immobilizing the opponent.", @@ -4616,6 +4628,7 @@ "connections": "Connections", "conspirateurs": "Conspirateurs", "control": "Control", + "counterflow": "Counterflow", "court": "Court", "courtesan": "King & Courtesan", "croda": "Croda", @@ -4864,6 +4877,7 @@ "circleOfLife": "Species are numbered 0–11 counterclockwise on the ring, starting with the single-hex species at the top. Species 0 eats 11; each other species eats the one numbered directly below it. Predation only occurs when you place a stone that forms a species adjacent to prey. Groups may not exceed four stones. The first player to capture 20 opponent stones wins, or the player who cannot place on their turn wins (having filled the ecosystem).", "clearpath": "Clear Path was designed by Mark Steere in September 2026, in collaboration with Claude Fable 5.1, an AI model made by Anthropic.\n\nThe dots mark the points where the player to move may not place. Each dotted point is vital to the opponent (every possible connection of the opponent passes through it), not vital to the player to move, and not a winning placement. A point vital to both players is not dotted, since either player may take it, and neither is a point where the player to move completes a winning path. The dots are drawn in the opponent's colour. A player who no longer has any possible connection has no vital points.\n\nA placement that leaves the opponent without any possible connecting path ends the game at once, and the player who placed wins: the opponent can never connect and can never take the winner's vital points, so the winner's connection can no longer be stopped. The chain of stones that cuts the opponent off is drawn on the board, as is a completed winning path.\n\nPassing is not allowed, but a player with no legal placement has their turn skipped. The pass is submitted automatically.", "conspirateurs": "In the base game, pieces may move through sanctuaries as part of a multistep jump. They're not frozen until they end their move in a sanctuary. In the strict variant, pieces are frozen as soon as they enter a sanctuary.\n\nIn four-player games, players 1 and 2 are partnered, as are players 3 and 4.", + "counterflow": "Counterflow was designed by Mark Steere in November 2026, in collaboration with Claude, an AI model made by Anthropic.\n\nCounterflow is played on an odd-sided, square board. At the start the middle row is empty. Blue checkers fill the area above the middle row, and red checkers fill the area below it. Red and Blue take turns moving checkers of their own colour, one checker per turn, starting with Red. If you have an available move, you must make one. If not, your turn is skipped. At least one player will always have an available move. A skipped turn is entered automatically and is recorded as a pass.\n\nA group is an orthogonally interconnected group of one or more same-coloured checkers. You win if all of your groups have at least one checker in your far row.\n\nCheckers move like non-capturing Chess queens, directly forward, diagonally forward, or sideways, over any number of consecutive unoccupied squares. Sideways moves are subject to a restriction described below.\n\nA wall is a row filled with same-coloured checkers. You must not complete a wall except when: 1) your move wins the game, 2) the wall is in your far row, or 3) there is another wall of your colour in the next row ahead of the wall.\n\nAn opening of a checker is an unoccupied square in the next row ahead of it, with one exception. A square is not an opening of a checker if all three of the following are true: 1) a checker of that colour on the square would complete a wall, 2) the wall would not be in that colour's far row, and 3) there would not be a wall of the wall's colour in the next row ahead of the wall. An opening doesn't have to be in front of a square that the checker can move to.\n\nThe distance of a checker is the number of columns from the checker's column to the column of its nearest opening. An opening straight ahead of the checker is at a distance of 0. A checker with no opening has no distance.\n\nThe shortest distance is the shortest distance of all checkers of both colours on the board. A sideways move is legal only if 1) the shortest distance after the move is shorter than the shortest distance before the move, or 2) the move wins the game. If the shortest distance is 0, no sideways move is legal, except for a winning sideways move.\n\nA green dot marks every checker that has a legal move. Select a checker and the squares it may move to are marked in green. The checker moved last carries a white ring, and a white dot marks the square it came from. When the game is over, a gold outline surrounds every group of the winner's checkers.", "deckfish": "More information on the Decktet system can be found on the [official Decktet website](https://www.decktet.com).\n\nThe suit powers (token movement abilities) are:\n* Moons: Jump orthogonally over gaps. \n* Suns: Move one or two cards diagonally. \n* Waves: Move orthogonally until the last unobstructed card. \n* Leaves: Move orthogonally onto any card with no neighboring obstacles.\n* Wyrms: Move orthogonally onto the first occupied card, bumping that piece to the next card.\n* Knots: Make three orthogonal one-card moves, without backtracking.\n\nIn the rules, the \"first\" player is the player who places second in the placement phase but moves first in the movement phase, but here the first player is the one who places first but moves second. This is implemented using an automatic pass for the appropriate player.\n\nThe rule is enforced that, even when the last player is already winning, he must continue playing until he is out of moves.", "domineering": "Domineering, aka, Stop-Gate, is a partisan combinatorial game. The game was designed by Göran Andersson, c.1973, and was presented in the seminal CGT book *Winning Ways for Your Mathematical Plays*. There is an impartial version, called Cram, where players can both place horizontal or vertical dominoes. The variant \"Quelhas\" was proposed by Carlos P. Santos and Alfie Davies in 2025, being a misère version (the player without options wins the game) and using longer domino-like polyominoes.", "druid": "A lintel must be supported at both ends (not on bare ground) and rest on exactly two of your stones (which need not both be at the ends). Lintels must lie flat: both ends must rest on stacks of equal height. Lintels may cross one another, but you may not thread a new lintel through the gap beneath an existing lintel's centre. Only the topmost stone on each cell counts toward connections.\n\nWith the Druid's Walk variant on the rectangular board, your Druid appears the first time you place a stone on either of your edges (west or east for player 2, north or south for player 1). To win, the druid must be borne off the board on the opposite edge. Each turn you either place a stone or move your Druid — not both. Druids move onto orthogonally adjacent stones of their colour and always stand on the topmost stone; they cannot step into bare gaps under lintels. Stones cannot be placed on a Druid. The first player to bear their Druid off wins. Druid's Walk does not apply to Druid's Y or Druid's Hex boards.", @@ -6508,6 +6522,20 @@ "name": "Large board (Size 9)" } }, + "counterflow": { + "#board": { + "name": "7x7 board" + }, + "size-5": { + "name": "5x5 board" + }, + "size-9": { + "name": "9x9 board" + }, + "size-11": { + "name": "11x11 board" + } + }, "court": { "#board": { "name": "8x8 board, 2 officials of each type" diff --git a/locales/en/apresults.json b/locales/en/apresults.json index 2b1d449e..52f57c88 100644 --- a/locales/en/apresults.json +++ b/locales/en/apresults.json @@ -574,6 +574,14 @@ "path": "The game has ended because a player connected their dots." } }, + "counterflow": { + "PASS": { + "skipped": "{{player}} had no available move, so the turn was skipped." + }, + "EOG": { + "groups": "All of {{player}}'s groups have at least one checker in the far row." + } + }, "court": { "PLACE": { "default": "{{player}} promoted {{where}} to a {{what}}." diff --git a/locales/es-US/apgames.json b/locales/es-US/apgames.json index c4d3efc0..803179bf 100644 --- a/locales/es-US/apgames.json +++ b/locales/es-US/apgames.json @@ -4616,6 +4616,7 @@ "connections": "Connections", "conspirateurs": "Conspirateurs", "control": "Control", + "counterflow": "Counterflow", "court": "Court", "courtesan": "King & Courtesan", "croda": "Croda", diff --git a/locales/fr/apgames.json b/locales/fr/apgames.json index b72a99be..96e9ac68 100644 --- a/locales/fr/apgames.json +++ b/locales/fr/apgames.json @@ -4616,6 +4616,7 @@ "connections": "Connections", "conspirateurs": "Conspirateurs", "control": "Control", + "counterflow": "Counterflow", "court": "Court", "courtesan": "King & Courtesan", "croda": "Croda", diff --git a/locales/it/apgames.json b/locales/it/apgames.json index 6a4626b7..1d7c0782 100644 --- a/locales/it/apgames.json +++ b/locales/it/apgames.json @@ -4616,6 +4616,7 @@ "connections": "Connections", "conspirateurs": "Conspirateurs", "control": "Control", + "counterflow": "Counterflow", "court": "Court", "courtesan": "King & Courtesan", "croda": "Croda", diff --git a/src/games/counterflow.ts b/src/games/counterflow.ts new file mode 100644 index 00000000..c96e1192 --- /dev/null +++ b/src/games/counterflow.ts @@ -0,0 +1,999 @@ +import { GameBase, IAPGameState, IClickResult, IIndividualState, IValidationResult, type ChatLogCollectContext, type ChatLogLine } from "./_base.js"; +import { APGamesInformation } from "../schemas/gameinfo.js"; +import { APRenderRep, AnnotationBasic, BoardBasic, Colourfuncs, Glyph, MarkerFenceData, RowCol } from "@abstractplay/renderer/build/schemas/schema"; +import { APMoveResult } from "../schemas/moveresults.js"; +import { reviver, UserFacingError } from "../common/index.js"; +import i18next from "i18next"; + +export const gameApgamesEn = { + validation: { + INITIAL_INSTRUCTIONS: "Select one of your checkers. A green dot marks every checker that has a legal move. The squares the selected checker may move to are then marked in green.", + PARTIAL: "Select the square to move the checker to, or select another of your checkers instead.", + DIRECTION: "The checker on {{from}} cannot move to {{to}}. A checker moves like a non-capturing Chess queen, directly forward, diagonally forward, or sideways.", + BLOCKED: "The checker on {{from}} cannot reach {{to}}. A checker moves over consecutive unoccupied squares only.", + WALL: "The checker on {{from}} may not move to {{to}}, because the move would complete a wall. You must not complete a wall except when your move wins the game, the wall is in your far row, or there is another wall of your colour in the next row ahead of the wall.", + SIDEWAYS: "The checker on {{from}} may not move sideways to {{to}}. A sideways move is legal only if the shortest distance after the move is shorter than the shortest distance before the move, or the move wins the game.", + SIDEWAYS_ZERO: "The checker on {{from}} may not move sideways to {{to}}. The shortest distance is 0, so no sideways move is legal, except for a winning sideways move.", + NO_PASS: "You may not pass while you have an available move.", + MUST_PASS: "You have no available move. Your turn is skipped.", + }, + variants: { + "#board": { + name: "7x7 board", + }, + "size-5": { + name: "5x5 board", + }, + "size-9": { + name: "9x9 board", + }, + "size-11": { + name: "11x11 board", + }, + }, +}; + +export const gameApresultsEn = { + PASS: { + skipped: "{{player}} had no available move, so the turn was skipped.", + }, + EOG: { + groups: "All of {{player}}'s groups have at least one checker in the far row.", + }, +}; + +export type playerid = 1|2; + +export interface IMoveState extends IIndividualState { + currplayer: playerid; + board: Map; + lastmove?: string; +} + +export interface ICounterflowState extends IAPGameState { + winner: playerid[]; + stack: Array; +} + +/* + * Rule helpers. + * + * The helpers work on a board of `width` columns and `height` rows with the + * squares indexed row by row from the top left, index = row * width + col. + * Red (player 1) starts in the bottom rows and moves up the board, so Red's + * far row is the top row. Blue (player 2) starts in the top rows and moves + * down, so Blue's far row is the bottom row. The game itself is played on + * odd-sided square boards; the helpers take any width so that the rules can + * be checked exhaustively on small boards. + * + * A checker moves like a non-capturing chess queen, directly forward, + * diagonally forward, or sideways, over any number of consecutive unoccupied + * squares. Two rules restrict the moves: + * + * Walls. A wall is a row filled with same-coloured checkers. A move must + * not complete a wall except when 1) the move wins the game, 2) the wall is + * in the mover's far row, or 3) there is another wall of the mover's colour + * in the next row ahead of the wall. + * + * Sideways moves. An opening of a checker is an unoccupied square in the + * next row ahead of it, except a square on which a checker of that colour + * would complete a wall that meets neither exception 2 nor exception 3. The + * distance of a checker is the number of columns from its column to the + * column of its nearest opening. A sideways move is legal only if the + * shortest distance of all checkers of both colours is shorter after the + * move than before it, or the move wins the game. + * + * A player wins when all of that player's groups (orthogonally connected + * same-coloured checkers) have at least one checker in the player's far row. + * Under these rules at least one player always has a legal move and no + * position can repeat. + */ + +/** A board with one entry per square, undefined for an unoccupied square. */ +export type CfBoard = (playerid | undefined)[]; + +export interface ICfMove { + from: number; + to: number; + /** A move along the row; all other moves are forward moves. */ + sideways: boolean; + /** The move wins the game for the mover. */ + wins: boolean; +} + +/** The far row of a player: the top row for Red, the bottom row for Blue. */ +export function cfFarRow(player: playerid, height: number): number { + return player === 1 ? 0 : height - 1; +} + +/** The change in row index of one step forward. */ +function cfForward(player: playerid): number { + return player === 1 ? -1 : 1; +} + +/** + * The starting position. The middle row is empty (the two middle rows when + * the height is even), blue checkers fill the rows above it and red checkers + * the rows below it. + */ +export function cfStart(width: number, height: number): CfBoard { + const filled = Math.floor((height - 1) / 2); + const board: CfBoard = new Array(width * height).fill(undefined); + for (let row = 0; row < filled; row++) { + for (let col = 0; col < width; col++) { + board[row * width + col] = 2; + board[(height - 1 - row) * width + col] = 1; + } + } + return board; +} + +function cfNeighbours(sq: number, width: number, height: number): number[] { + const row = Math.floor(sq / width); + const col = sq % width; + const out: number[] = []; + if (row > 0) { out.push(sq - width); } + if (row < height - 1) { out.push(sq + width); } + if (col > 0) { out.push(sq - 1); } + if (col < width - 1) { out.push(sq + 1); } + return out; +} + +/** The groups of a player: the sets of that player's checkers that are orthogonally interconnected. */ +export function cfGroups(board: CfBoard, player: playerid, width: number, height: number): number[][] { + const seen = new Array(board.length).fill(false); + const groups: number[][] = []; + for (let start = 0; start < board.length; start++) { + if (board[start] !== player || seen[start]) { + continue; + } + const group = [start]; + seen[start] = true; + for (let i = 0; i < group.length; i++) { + for (const n of cfNeighbours(group[i], width, height)) { + if (board[n] === player && !seen[n]) { + seen[n] = true; + group.push(n); + } + } + } + groups.push(group); + } + return groups; +} + +/** True when all of the player's groups have at least one checker in the player's far row. */ +export function cfHasWon(board: CfBoard, player: playerid, width: number, height: number): boolean { + // every checker must be reachable from a checker of its colour in the far row + const far = cfFarRow(player, height); + const seen = new Array(board.length).fill(false); + const todo: number[] = []; + for (let col = 0; col < width; col++) { + const sq = far * width + col; + if (board[sq] === player) { + seen[sq] = true; + todo.push(sq); + } + } + let reached = todo.length; + while (todo.length > 0) { + for (const n of cfNeighbours(todo.pop()!, width, height)) { + if (board[n] === player && !seen[n]) { + seen[n] = true; + reached++; + todo.push(n); + } + } + } + let total = 0; + for (const who of board) { + if (who === player) { + total++; + } + } + return reached === total; +} + +/** For every row, the number of unoccupied squares [0], red checkers [1] and blue checkers [2]. */ +function cfRowCounts(board: CfBoard, width: number, height: number): [number, number, number][] { + const counts: [number, number, number][] = []; + for (let row = 0; row < height; row++) { + const c: [number, number, number] = [0, 0, 0]; + for (let col = 0; col < width; col++) { + c[board[row * width + col] ?? 0]++; + } + counts.push(c); + } + return counts; +} + +/** True when the row is a wall of the player: every square of it holds one of the player's checkers. */ +export function cfIsWall(board: CfBoard, player: playerid, row: number, width: number): boolean { + for (let col = 0; col < width; col++) { + if (board[row * width + col] !== player) { + return false; + } + } + return true; +} + +/** + * True when the row is closed to the player: one more checker of the player + * in the row would complete a wall, the row is not the player's far row, and + * the next row ahead of it is not a wall of the player. The player may not + * move into a closed row unless the move wins the game, and the unoccupied + * square of a closed row is not an opening of any of the player's checkers. + */ +function cfRowClosed(counts: [number, number, number][], player: playerid, row: number, width: number, height: number): boolean { + if (counts[row][0] !== 1 || counts[row][player] !== width - 1) { + return false; + } + if (row === cfFarRow(player, height)) { + return false; + } + return counts[row + cfForward(player)][player] !== width; +} + +/** + * The distance of every checker: the number of columns from the checker's + * column to the column of its nearest opening. The entry is undefined for a + * checker with no opening, and for an unoccupied square. + */ +export function cfDistances(board: CfBoard, width: number, height: number): (number | undefined)[] { + const counts = cfRowCounts(board, width, height); + const out = new Array(board.length).fill(undefined); + for (let sq = 0; sq < board.length; sq++) { + const player = board[sq]; + if (player === undefined) { + continue; + } + const col = sq % width; + const ahead = Math.floor(sq / width) + cfForward(player); + if (ahead < 0 || ahead >= height || cfRowClosed(counts, player, ahead, width, height)) { + continue; + } + let best: number | undefined; + for (let c = 0; c < width; c++) { + if (board[ahead * width + c] === undefined) { + const d = Math.abs(c - col); + if (best === undefined || d < best) { + best = d; + } + } + } + out[sq] = best; + } + return out; +} + +/** The shortest distance of all checkers of both colours, or undefined when no checker has an opening. */ +export function cfShortestDistance(board: CfBoard, width: number, height: number): number | undefined { + let best: number | undefined; + for (const d of cfDistances(board, width, height)) { + if (d !== undefined && (best === undefined || d < best)) { + best = d; + } + } + return best; +} + +/** The legal moves of a player. */ +export function cfMoves(board: CfBoard, player: playerid, width: number, height: number): ICfMove[] { + const counts = cfRowCounts(board, width, height); + const before = cfShortestDistance(board, width, height); + const dir = cfForward(player); + const trial = [...board]; + const moves: ICfMove[] = []; + for (let from = 0; from < board.length; from++) { + if (board[from] !== player) { + continue; + } + const row = Math.floor(from / width); + const col = from % width; + // directly forward and diagonally forward + for (const dc of [-1, 0, 1]) { + let r = row + dir; + let c = col + dc; + while (r >= 0 && r < height && c >= 0 && c < width && board[r * width + c] === undefined) { + const to = r * width + c; + trial[from] = undefined; + trial[to] = player; + const wins = cfHasWon(trial, player, width, height); + trial[to] = undefined; + trial[from] = player; + // the wall rule + if (wins || !cfRowClosed(counts, player, r, width, height)) { + moves.push({from, to, sideways: false, wins}); + } + r += dir; + c += dc; + } + } + // sideways + for (const dc of [-1, 1]) { + let c = col + dc; + while (c >= 0 && c < width && board[row * width + c] === undefined) { + const to = row * width + c; + trial[from] = undefined; + trial[to] = player; + const wins = cfHasWon(trial, player, width, height); + let legal = wins; + if (!legal && before !== undefined && before > 0) { + // the sideways move restriction + const after = cfShortestDistance(trial, width, height); + legal = after !== undefined && after < before; + } + trial[to] = undefined; + trial[from] = player; + if (legal) { + moves.push({from, to, sideways: true, wins}); + } + c += dc; + } + } + } + return moves; +} + +const LEGAL_GREEN = "#28b446"; +const LEGAL_OPACITY = 0.45; +const LEGAL_SCALE = 0.94; // a little smaller than the square, so that the grid lines stay visible +const LEGAL_COLOUR: Colourfuncs = {func: "custom", default: LEGAL_GREEN, palette: 5}; +const LAST_WHITE = "#ffffff"; +const LAST_COLOUR: Colourfuncs = {func: "custom", default: LAST_WHITE, palette: 6}; +const GOLD = "#f5c542"; +const GOLD_COLOUR: Colourfuncs = {func: "custom", default: GOLD, palette: 7}; +// the outline around the winner's groups: gold fences over slightly wider dark ones, in multiples of the grid's stroke +const OUTLINE_WIDTH = 2.8; +const OUTLINE_EDGE_WIDTH = 4; +const OUTLINE_EDGE = "#2e1c08"; + +// the board of the designer's own app: one tan felt, grid lines in a darker tan, an oak frame +const FELT = "#e8d6b2"; +const GRID = "#b08e60"; +const OAK = "#c48f4f"; +const FELT_COLOUR: Colourfuncs = {func: "custom", default: FELT, palette: 3}; +const GRID_COLOUR: Colourfuncs = {func: "custom", default: GRID, palette: 4}; + +// The rings drawn over a checker by a glyph annotation. The ring glyph is +// 0.65 of a cell across at scale 1. A nudge is measured in 1/500 of a cell +// and is applied before the layer's scale, and the face of the marbled +// checker sits 2% of a cell above the centre of the cell. +const FACE_DY = -10; +const LAST_SCALE = 0.62; +const SELECTED_SCALE = 0.7; + +function ringGlyph(colour: Colourfuncs, scale: number, opacity: number): Glyph { + return { + name: "ring-02", + paint: {fill: {colour: LAST_WHITE, opacity: 0}, border: colour}, + opacity, + scale, + nudge: {dx: 0, dy: FACE_DY / scale}, + }; +} + +export class CounterflowGame extends GameBase { + public static readonly gameinfo: APGamesInformation = { + name: "Counterflow", + uid: "counterflow", + playercounts: [2], + version: "20261113", + dateAdded: "2026-11-13", + description: "A checker race game. Two armies of checkers flow through each other in opposite directions. Checkers move like non-capturing Chess queens, directly forward, diagonally forward, or sideways, with restrictions on completing walls and on sideways moves. You win if all of your groups have at least one checker in your far row. Cycles and deadlocks cannot occur.", + notes: "Counterflow was designed by Mark Steere in November 2026, in collaboration with Claude, an AI model made by Anthropic.\n\nCounterflow is played on an odd-sided, square board. At the start the middle row is empty. Blue checkers fill the area above the middle row, and red checkers fill the area below it. Red and Blue take turns moving checkers of their own colour, one checker per turn, starting with Red. If you have an available move, you must make one. If not, your turn is skipped. At least one player will always have an available move. A skipped turn is entered automatically and is recorded as a pass.\n\nA group is an orthogonally interconnected group of one or more same-coloured checkers. You win if all of your groups have at least one checker in your far row.\n\nCheckers move like non-capturing Chess queens, directly forward, diagonally forward, or sideways, over any number of consecutive unoccupied squares. Sideways moves are subject to a restriction described below.\n\nA wall is a row filled with same-coloured checkers. You must not complete a wall except when: 1) your move wins the game, 2) the wall is in your far row, or 3) there is another wall of your colour in the next row ahead of the wall.\n\nAn opening of a checker is an unoccupied square in the next row ahead of it, with one exception. A square is not an opening of a checker if all three of the following are true: 1) a checker of that colour on the square would complete a wall, 2) the wall would not be in that colour's far row, and 3) there would not be a wall of the wall's colour in the next row ahead of the wall. An opening doesn't have to be in front of a square that the checker can move to.\n\nThe distance of a checker is the number of columns from the checker's column to the column of its nearest opening. An opening straight ahead of the checker is at a distance of 0. A checker with no opening has no distance.\n\nThe shortest distance is the shortest distance of all checkers of both colours on the board. A sideways move is legal only if 1) the shortest distance after the move is shorter than the shortest distance before the move, or 2) the move wins the game. If the shortest distance is 0, no sideways move is legal, except for a winning sideways move.\n\nA green dot marks every checker that has a legal move. Select a checker and the squares it may move to are marked in green. The checker moved last carries a white ring, and a white dot marks the square it came from. When the game is over, a gold outline surrounds every group of the winner's checkers.", + urls: [ + "https://www.marksteeregames.com/Counterflow_rules.pdf", + "https://www.marksteeregames.com", + ], + people: [ + { + type: "designer", + name: "Mark Steere", + urls: ["https://www.marksteeregames.com"], + apid: "e7a3ebf6-5b05-4548-ae95-299f75527b3f", + }, + { + type: "coder", + name: "Claude Fable 5.2 (Anthropic)", + }, + ], + variants: [ + { uid: "size-5", group: "board" }, + { uid: "#board" }, + { uid: "size-9", group: "board" }, + { uid: "size-11", group: "board" }, + ], + categories: ["goal>breakthrough", "mechanic>move", "mechanic>block", "board>shape>rect", "board>connect>rect", "components>simple>1per"], + flags: ["experimental", "autopass"], + customizations: [ + { + num: 1, + default: 1, + explanation: "Colour of Red's checkers (player 1)", + player: 1, + }, + { + num: 2, + default: 2, + explanation: "Colour of Blue's checkers (player 2)", + player: 2, + }, + { + num: 3, + default: FELT, + explanation: "Colour of the felt squares", + }, + { + num: 4, + default: GRID, + explanation: "Colour of the grid lines", + }, + { + num: 5, + default: LEGAL_GREEN, + explanation: "Colour of the dots on the checkers that have a legal move and of the squares a selected checker may move to", + }, + { + num: 6, + default: LAST_WHITE, + explanation: "Colour of the ring on the checker moved last and of the dot on the square it came from", + }, + { + num: 7, + default: GOLD, + explanation: "Colour of the ring on the selected checker and of the outline around the winner's groups", + }, + ], + }; + + public numplayers = 2; + public currplayer: playerid = 1; + public board!: Map; + public boardsize = 7; + public gameover = false; + public winner: playerid[] = []; + public variants: string[] = []; + public stack!: Array; + public results: Array = []; + // the destinations of a selected checker, shown while a move is being entered; not part of the state + private highlights: string[] = []; + private selected?: string; + // true while a complete move that has not been submitted yet is being shown + private pending = false; + + constructor(state?: ICounterflowState | string, variants?: string[]) { + super(); + if (state === undefined) { + if (variants !== undefined) { + this.variants = this.applyVariantConstraints(variants); + } + const size = this.getBoardSize(); + this.boardsize = size; + const board = new Map(); + cfStart(size, size).forEach((who, sq) => { + if (who !== undefined) { + board.set(this.coords2algebraic(sq % size, Math.floor(sq / size)), who); + } + }); + const fresh: IMoveState = { + _version: CounterflowGame.gameinfo.version, + _results: [], + _timestamp: new Date(), + currplayer: 1, + board, + }; + this.stack = [fresh]; + } else { + if (typeof state === "string") { + state = JSON.parse(state, reviver) as ICounterflowState; + } + if (state.game !== CounterflowGame.gameinfo.uid) { + throw new Error(`The Counterflow engine cannot process a game of '${state.game}'.`); + } + this.gameover = state.gameover; + this.winner = [...state.winner]; + this.variants = state.variants; + this.stack = [...state.stack]; + } + this.load(); + } + + public load(idx = -1): CounterflowGame { + if (idx < 0) { + idx += this.stack.length; + } + if ( (idx < 0) || (idx >= this.stack.length) ) { + throw new Error("Could not load the requested state from the stack."); + } + + const state = this.stack[idx]; + this.currplayer = state.currplayer; + this.board = new Map(state.board); + this.lastmove = state.lastmove; + this.results = [...state._results]; + this.boardsize = this.getBoardSize(); + this.highlights = []; + this.selected = undefined; + this.pending = false; + return this; + } + + private getBoardSize(): number { + for (const size of [5, 9, 11]) { + if (this.variants.includes(`size-${size}`)) { + return size; + } + } + return 7; + } + + // x is the column, y the row counted from the top (as the renderer counts rows) + public coords2algebraic(x: number, y: number): string { + return GameBase.coords2algebraic(x, y, this.boardsize); + } + public algebraic2coords(cell: string): [number, number] { + return GameBase.algebraic2coords(cell, this.boardsize); + } + private cell2sq(cell: string): number { + const [x, y] = this.algebraic2coords(cell); + return y * this.boardsize + x; + } + private sq2cell(sq: number): string { + return this.coords2algebraic(sq % this.boardsize, Math.floor(sq / this.boardsize)); + } + + /** The position as the rule helpers take it. */ + private squares(): CfBoard { + const out: CfBoard = new Array(this.boardsize * this.boardsize).fill(undefined); + for (const [cell, who] of this.board.entries()) { + out[this.cell2sq(cell)] = who; + } + return out; + } + + /** The checkers of a player, row by row from the top. */ + public checkers(player: playerid): string[] { + const out: string[] = []; + this.squares().forEach((who, sq) => { + if (who === player) { + out.push(this.sq2cell(sq)); + } + }); + return out; + } + + /** The groups of a player's checkers, each as a list of squares. */ + public groups(player: playerid): string[][] { + return cfGroups(this.squares(), player, this.boardsize, this.boardsize).map(g => g.map(sq => this.sq2cell(sq))); + } + + /** The distance of the checker on `cell`, or undefined when it has no opening. */ + public distance(cell: string): number | undefined { + return cfDistances(this.squares(), this.boardsize, this.boardsize)[this.cell2sq(cell)]; + } + + /** The shortest distance of all checkers of both colours on the board. */ + public shortestDistance(): number | undefined { + return cfShortestDistance(this.squares(), this.boardsize, this.boardsize); + } + + private legalMoves(player: playerid): {from: string; to: string}[] { + return cfMoves(this.squares(), player, this.boardsize, this.boardsize).map(m => ({from: this.sq2cell(m.from), to: this.sq2cell(m.to)})); + } + + /** The squares the checker on `cell` may move to. */ + public destinations(cell: string, player?: playerid): string[] { + if (player === undefined) { + player = this.currplayer; + } + return this.legalMoves(player).filter(m => m.from === cell).map(m => m.to); + } + + public moves(player?: playerid): string[] { + if (this.gameover) { return []; } + if (player === undefined) { + player = this.currplayer; + } + const moves = this.legalMoves(player).map(m => `${m.from}-${m.to}`); + if (moves.length === 0) { + // A player with no available move has their turn skipped. The + // `autopass` flag makes the front end submit this pass + // automatically. + return ["pass"]; + } + return moves; + } + + public handleClick(move: string, row: number, col: number, piece?: string): IClickResult { + try { + let newmove = ""; + const cell = this.coords2algebraic(col, row); + const mine = this.board.has(cell) && this.board.get(cell) === this.currplayer; + if (move.length === 0) { + // nothing selected yet: only a click on one of your own checkers does anything + if (mine) { + newmove = cell; + } else { + return {move: "", valid: false, message: i18next.t("apgames:validation.counterflow.INITIAL_INSTRUCTIONS")}; + } + } else { + const [from, to] = move.split("-"); + if (to === undefined && cell === from) { + // clicking the selected checker again deselects it + return {move: "", valid: true, complete: -1, message: i18next.t("apgames:validation.counterflow.INITIAL_INSTRUCTIONS")}; + } else if (mine) { + // switching to another checker + newmove = cell; + } else { + newmove = `${from}-${cell}`; + } + } + const result = this.validateMove(newmove) as IClickResult; + if (! result.valid) { + // keep the selection so that the player can try another square + result.move = move.includes("-") ? "" : move; + } else { + result.move = newmove; + } + return result; + } catch (e) { + return { + move, + valid: false, + message: i18next.t("apgames:validation._general.GENERIC", {move, row, col, piece, emessage: (e as Error).message}) + } + } + } + + public validateMove(m: string): IValidationResult { + const result: IValidationResult = {valid: false, message: i18next.t("apgames:validation._general.DEFAULT_HANDLER")}; + + if (m.length === 0) { + result.valid = true; + result.complete = -1; + result.message = i18next.t("apgames:validation.counterflow.INITIAL_INSTRUCTIONS"); + return result; + } + + const legal = this.legalMoves(this.currplayer); + if (m === "pass") { + if (legal.length > 0) { + result.valid = false; + result.message = i18next.t("apgames:validation.counterflow.NO_PASS"); + return result; + } + result.valid = true; + result.complete = 1; + result.message = i18next.t("apgames:validation.counterflow.MUST_PASS"); + return result; + } + + const [from, to, extra] = m.split("-"); + if (extra !== undefined) { + result.valid = false; + result.message = i18next.t("apgames:validation._general.INVALID_MOVE", {move: m}); + return result; + } + for (const cell of [from, to]) { + if (cell !== undefined) { + try { + this.algebraic2coords(cell); + } catch { + result.valid = false; + result.message = i18next.t("apgames:validation._general.INVALIDCELL", {cell}); + return result; + } + } + } + if (! this.board.has(from)) { + result.valid = false; + result.message = i18next.t("apgames:validation._general.NONEXISTENT", {where: from}); + return result; + } + if (this.board.get(from) !== this.currplayer) { + result.valid = false; + result.message = i18next.t("apgames:validation._general.UNCONTROLLED"); + return result; + } + const dests = legal.filter(mv => mv.from === from).map(mv => mv.to); + if (to === undefined) { + if (dests.length === 0) { + result.valid = false; + result.message = i18next.t("apgames:validation._general.NO_MOVES", {where: from}); + return result; + } + result.valid = true; + result.complete = -1; + result.canrender = true; + result.message = i18next.t("apgames:validation.counterflow.PARTIAL"); + return result; + } + if (! dests.includes(to)) { + result.valid = false; + result.message = this.explain(from, to); + return result; + } + + result.valid = true; + result.complete = 1; + result.message = i18next.t("apgames:validation._general.VALID_MOVE"); + return result; + } + + /** Why the current player's checker on `from` may not move to `to`. */ + private explain(from: string, to: string): string { + const [fx, fy] = this.algebraic2coords(from); + const [tx, ty] = this.algebraic2coords(to); + const dx = tx - fx; + const dy = ty - fy; + const sideways = dy === 0 && dx !== 0; + // Red moves up the board, toward smaller y + const forward = (this.currplayer === 1 ? dy < 0 : dy > 0) && (dx === 0 || Math.abs(dx) === Math.abs(dy)); + if (!sideways && !forward) { + return i18next.t("apgames:validation.counterflow.DIRECTION", {from, to}); + } + if (this.board.has(to)) { + return i18next.t("apgames:validation._general.OCCUPIED", {where: to}); + } + const steps = Math.max(Math.abs(dx), Math.abs(dy)); + for (let k = 1; k < steps; k++) { + if (this.board.has(this.coords2algebraic(fx + k * Math.sign(dx), fy + k * Math.sign(dy)))) { + return i18next.t("apgames:validation.counterflow.BLOCKED", {from, to}); + } + } + if (forward) { + return i18next.t("apgames:validation.counterflow.WALL", {from, to}); + } + if (this.shortestDistance() === 0) { + return i18next.t("apgames:validation.counterflow.SIDEWAYS_ZERO", {from, to}); + } + return i18next.t("apgames:validation.counterflow.SIDEWAYS", {from, to}); + } + + public move(m: string, {partial = false, trusted = false} = {}): CounterflowGame { + if (this.gameover) { + throw new UserFacingError("MOVES_GAMEOVER", i18next.t("apgames:validation._general.MOVES_GAMEOVER")); + } + + m = m.toLowerCase(); + m = m.replace(/\s+/g, ""); + if (! trusted) { + const result = this.validateMove(m); + if (! result.valid) { + throw new UserFacingError("VALIDATION_GENERAL", result.message) + } + if ( (! partial) && (! this.moves().includes(m)) ) { + throw new UserFacingError("VALIDATION_FAILSAFE", i18next.t("apgames:validation._general.FAILSAFE", {move: m})) + } + } + + this.highlights = []; + this.selected = undefined; + this.pending = false; + const [from, to] = m.split("-"); + if (m !== "pass" && to === undefined) { + // a checker has been selected: show where it may go and wait for the destination + if (partial) { + this.selected = from; + this.highlights = this.destinations(from); + return this; + } + throw new UserFacingError("VALIDATION_GENERAL", i18next.t("apgames:validation.counterflow.PARTIAL")); + } + + this.results = []; + if (m === "pass") { + this.results.push({type: "pass"}); + } else { + this.board.delete(from); + this.board.set(to, this.currplayer); + this.results.push({type: "move", from, to}); + } + + if (partial) { + this.pending = true; + return this; + } + + // update currplayer + this.lastmove = m; + let newplayer = (this.currplayer as number) + 1; + if (newplayer > this.numplayers) { + newplayer = 1; + } + this.currplayer = newplayer as playerid; + + this.checkEOG(); + this.saveState(); + return this; + } + + protected checkEOG(): CounterflowGame { + // the player who just moved + const prev: playerid = this.currplayer === 1 ? 2 : 1; + if (cfHasWon(this.squares(), prev, this.boardsize, this.boardsize)) { + this.gameover = true; + this.winner = [prev]; + this.results.push({type: "eog", reason: "groups"}); + } else if (this.legalMoves(this.currplayer).length === 0 && this.legalMoves(prev).length === 0) { + // Under the rules this cannot happen: at least one player always + // has an available move. The game must still be able to finish + // if it ever did, so it ends without a winner. + this.gameover = true; + this.winner = [1, 2]; + this.results.push({type: "eog"}); + } + if (this.gameover) { + this.results.push({type: "winners", players: [...this.winner]}); + } + return this; + } + + public collectChatLogLine(lines: ChatLogLine[], r: APMoveResult, ctx: ChatLogCollectContext): boolean { + if (r.type === "pass") { + this.pushSeatChatLine(lines, ctx.defaultSeat, "apresults:counterflow.PASS.skipped"); + return true; + } + return super.collectChatLogLine(lines, r, ctx); + } + + protected eogChatLineOverride(r: Extract, ctx: ChatLogCollectContext): ChatLogLine | undefined { + if (r.reason === "groups") { + const winner = this.resolveChatPlayerName(this.winner[0], ctx.players); + return { + actor: { kind: "none" }, + textKey: "apresults:counterflow.EOG.groups", + textParams: { player: winner }, + }; + } + return undefined; + } + + public state(): ICounterflowState { + return { + game: CounterflowGame.gameinfo.uid, + numplayers: this.numplayers, + variants: this.variants, + gameover: this.gameover, + winner: [...this.winner], + stack: [...this.stack] + }; + } + + public moveState(): IMoveState { + return { + _version: CounterflowGame.gameinfo.version, + _results: [...this.results], + _timestamp: new Date(), + currplayer: this.currplayer, + lastmove: this.lastmove, + board: new Map(this.board), + }; + } + + private rowCol(cell: string): RowCol { + const [x, y] = this.algebraic2coords(cell); + return {row: y, col: x}; + } + + /** + * The outline around the winner's groups: one fence on every side of a + * winner's checker that does not face another of the winner's checkers. + */ + private outline(player: playerid, colour: MarkerFenceData["colour"], width: number): MarkerFenceData[] { + const size = this.boardsize; + const squares = this.squares(); + const own = (row: number, col: number): boolean => row >= 0 && row < size && col >= 0 && col < size && squares[row * size + col] === player; + const sides: MarkerFenceData[] = []; + for (let row = 0; row < size; row++) { + for (let col = 0; col < size; col++) { + if (!own(row, col)) { + continue; + } + const edges: [MarkerFenceData["side"], number, number][] = [["N", row - 1, col], ["E", row, col + 1], ["S", row + 1, col], ["W", row, col - 1]]; + for (const [side, r, c] of edges) { + if (!own(r, c)) { + sides.push({cell: {row, col}, side, colour, width}); + } + } + } + } + return sides; + } + + public render(): APRenderRep { + const size = this.boardsize; + + // Build piece string + let pstr = ""; + for (let row = 0; row < size; row++) { + if (pstr.length > 0) { + pstr += "\n"; + } + for (let col = 0; col < size; col++) { + const cell = this.coords2algebraic(col, row); + if (this.board.has(cell)) { + pstr += this.board.get(cell) === 1 ? "A" : "B"; + } else { + pstr += "-"; + } + } + } + pstr = pstr.replace(new RegExp(`-{${size}}`, "g"), "_"); + + const board: BoardBasic = { + // one felt colour on both kinds of square, as in the designer's app + style: "squares-checkered", + width: size, + height: size, + checkeredLight: FELT_COLOUR, + checkeredDark: FELT_COLOUR, + strokeColour: GRID_COLOUR, + strokeOpacity: 0.9, + strokeWeight: 1.25, + backFill: { + type: "full", + colour: {func: "custom", default: OAK, palette: "_context_background"}, + }, + }; + const rep: APRenderRep = { + board, + legend: { + A: {name: "piece-marbled", paint: {fill: 1}}, + B: {name: "piece-marbled", paint: {fill: 2}}, + H: {name: "piece-square-borderless", paint: {fill: LEGAL_COLOUR}, opacity: LEGAL_OPACITY, scale: LEGAL_SCALE}, + L: ringGlyph(LAST_COLOUR, LAST_SCALE, 0.9), + S: ringGlyph(GOLD_COLOUR, SELECTED_SCALE, 1), + }, + pieces: pstr, + }; + + // A position in which a player has reached the goal: the gold outline + // around every group of that player's checkers, and no other marks. + // A game that ended in any other way (resignation, timeout) shows none. + const squares = this.squares(); + const finisher = ([1, 2] as playerid[]).find(p => cfHasWon(squares, p, size, size)); + if (finisher !== undefined) { + board.markers = [ + {type: "fences", sides: this.outline(finisher, OUTLINE_EDGE, OUTLINE_EDGE_WIDTH) as [MarkerFenceData, ...MarkerFenceData[]]}, + {type: "fences", sides: this.outline(finisher, GOLD_COLOUR, OUTLINE_WIDTH) as [MarkerFenceData, ...MarkerFenceData[]]}, + ]; + return rep; + } + + // Add annotations + const annotations: AnnotationBasic[] = []; + // the checker moved last: a white dot where it came from and a white ring on the checker + for (const r of this.results) { + if (r.type === "move") { + annotations.push({type: "dots", targets: [this.rowCol(r.from)], colour: LAST_COLOUR, opacity: 0.8, size: 0.14}); + annotations.push({type: "glyph", glyph: "L", targets: [this.rowCol(r.to)]}); + } + } + if (this.selected !== undefined) { + // a gold ring on the selected checker, and the squares it may move to in green + annotations.push({type: "glyph", glyph: "S", targets: [this.rowCol(this.selected)]}); + if (this.highlights.length > 0) { + annotations.push({type: "glyph", glyph: "H", targets: this.highlights.map(cell => this.rowCol(cell)) as [RowCol, ...RowCol[]]}); + } + } else if (!this.pending && !this.gameover) { + // a green dot on every checker that has a legal move + const movable = [...new Set(this.legalMoves(this.currplayer).map(mv => mv.from))]; + if (movable.length > 0) { + const targets = movable.map(cell => this.rowCol(cell)) as [RowCol, ...RowCol[]]; + annotations.push({type: "dots", targets, colour: LAST_COLOUR, opacity: 0.9, size: 0.21}); + annotations.push({type: "dots", targets, colour: LEGAL_COLOUR, size: 0.17}); + } + } + if (annotations.length > 0) { + rep.annotations = annotations; + } + + return rep; + } + + public clone(): CounterflowGame { + return new CounterflowGame(this.serialize()); + } +} diff --git a/test/games/counterflow.test.ts b/test/games/counterflow.test.ts new file mode 100644 index 00000000..337b728d --- /dev/null +++ b/test/games/counterflow.test.ts @@ -0,0 +1,656 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions */ +import "mocha"; +import { expect } from "chai"; +import i18next from "i18next"; +import { + CounterflowGame, cfDistances, cfFarRow, cfGroups, cfHasWon, cfIsWall, cfMoves, cfShortestDistance, cfStart, + type CfBoard, type playerid, +} from "../../src/games/counterflow"; +import { assertChatLogParity } from "../fixtures/chat/helpers"; +import { addResource } from "../../src"; + +// Board notation: columns a, b, c... left to right, rows 1, 2, 3... bottom to +// top. Red (player 1) starts below the empty middle row and moves up, so +// Red's far row is the top row. Blue (player 2) starts above the middle row +// and moves down. Red moves first. A move is written from-to, e.g. "a2-a3". +// Positions are written as the rows of the board from the top, separated by +// "/", with R for a red checker, B for a blue checker and "." for an +// unoccupied square. + +// The figures of the rule sheet (https://www.marksteeregames.com/Counterflow_rules.pdf), all on the 5x5 board. +const FIGURE_1 = "BBBBB/BBBBB/...../RRRRR/RRRRR"; // the starting position +const FIGURE_2 = ".RRRR/BBB../.BRRB/RBRBB/RB.BR"; // Blue has won +const FIGURE_3 = "BBBBB/B.BBB/B..R./RRR.R/RRRRR"; // no red checker may move to d2 +const FIGURE_4 = "B.BBB/.BBBB/BBRRR/RRR.R/RR.R."; // distances to the opening d2; Red's only legal move is c2-d2 +// the moves that lead from the starting position to Figure 4 +const FIGURE_4_MOVES = ["d2-d3", "c4-b3", "e1-c3", "a4-a3", "c1-e3", "b5-c4"]; +// Blue to move wins at once with e3-e2, e3-d3 or c3-d3; Red has no legal move +const WINNING_MOVES = "RRRRR/...RR/BBB.B/BBBB./RRRBB"; + +// A complete game on the 5x5 board. At ply 6 Blue has no legal move (d4 would +// complete a wall, everything else is blocked) and the turn is skipped. At +// ply 8 Blue moves sideways. Red wins at ply 13. +const GAME_5 = ["a2-a3", "d4-d3", "b2-c3", "c5-e3", "b1-b3", "pass", "a1-a2", "c4-d4", "b3-c4", "b4-b1", "a3-c5", "b5-b3", "c1-b2"]; +const GAME_5_SKIP = "BB.BB/BBB.B/RRRBB/..RRR/R.RRR"; +const GAME_5_END = "B.RBB/B.RBB/.BRBB/RRRRR/.B.RR"; + +// A complete game on the 7x7 board with three skipped turns of Red. Blue wins +// at ply 48 with a sideways move that is legal only because it wins: the +// shortest distance is 0 before the move. +const GAME_7 = [ + "e3-e4", "a5-a4", "c3-c4", "c5-d4", "c4-c5", "b5-c4", "c2-c3", "e5-f4", "g3-g4", "f4-e3", "g2-g3", "b6-b4", + "f3-f4", "a6-b5", "e4-e5", "d5-e4", "c1-c2", "d6-d5", "c5-b6", "e7-c5", "e2-f3", "c7-d6", "g1-g2", "a7-a6", + "b6-c7", "e3-e2", "pass", "a6-a5", "pass", "e4-e3", "d3-e4", "b7-b6", "d2-d3", "e3-d2", "d1-c1", "e2-d1", + "f1-e2", "d4-e3", "d3-d4", "c4-d3", "c3-c4", "b4-c3", "b3-b4", "a4-b3", "pass", "a5-a4", "b4-a5", "a4-b4", +]; +const GAME_7_END = "..RB.BB/.BBBBBB/RBBBRBB/.BRRRRR/RBBBBRR/RRRBRRR/RRRBR.."; + +function fromRows(rows: string): CfBoard { + return rows.replace(/\//g, "").split("").map(ch => ch === "R" ? 1 : ch === "B" ? 2 : undefined); +} + +/** The name of a square of a board `width` columns wide and `height` rows high. */ +function name(sq: number, width: number, height: number): string { + return "abcdefghijk"[sq % width] + (height - Math.floor(sq / width)).toString(); +} + +/** The legal moves of a player in a position, in algebraic notation and sorted. */ +function movesOf(rows: string, player: playerid): string[] { + const height = rows.split("/").length; + const width = rows.indexOf("/"); + return cfMoves(fromRows(rows), player, width, height).map(m => `${name(m.from, width, height)}-${name(m.to, width, height)}`).sort(); +} + +/** The distances of the checkers of a position, by square. */ +function distancesOf(rows: string): Record { + const height = rows.split("/").length; + const width = rows.indexOf("/"); + const out: Record = {}; + cfDistances(fromRows(rows), width, height).forEach((d, sq) => { + if (d !== undefined) { + out[name(sq, width, height)] = d; + } + }); + return out; +} + +/** A game on the board of the position (5x5 or 7x7), set up with the position and the player to move. */ +function setup(rows: string, player: playerid): CounterflowGame { + const size = rows.split("/").length; + const g = new CounterflowGame(undefined, size === 7 ? [] : [`size-${size}`]); + const board = new Map(); + fromRows(rows).forEach((who, sq) => { + if (who !== undefined) { + board.set(name(sq, size, size), who); + } + }); + g.board = board; + g.currplayer = player; + return g; +} + +/** The position of a game in the notation of the fixtures. */ +function rowsOf(g: CounterflowGame): string { + const rows: string[] = []; + for (let y = 0; y < g.boardsize; y++) { + let row = ""; + for (let x = 0; x < g.boardsize; x++) { + const who = g.board.get(g.coords2algebraic(x, y)); + row += who === 1 ? "R" : who === 2 ? "B" : "."; + } + rows.push(row); + } + return rows.join("/"); +} + +function play(moves: string[], variants: string[] = []): CounterflowGame { + const g = new CounterflowGame(undefined, variants); + for (const m of moves) { + g.move(m); + } + return g; +} + +/** The cells of every annotation of the given type, in algebraic notation and sorted. */ +function annotated(g: CounterflowGame, type: string): string[][] { + const annotations = (g.render().annotations ?? []) as Array<{type: string; targets?: Array<{row: number; col: number}>}>; + return annotations.filter(a => a.type === type).map(a => a.targets!.map(t => g.coords2algebraic(t.col, t.row)).sort()); +} + +function seededRandom(seed: number): () => number { + let s = seed; + return () => { + s = (s * 1103515245 + 12345) & 0x7fffffff; + return s / 0x7fffffff; + }; +} + +describe("Counterflow", () => { + describe("Rules", () => { + it("starts with an empty middle row, Blue above it and Red below it", () => { + expect(cfStart(5, 5)).to.deep.equal(fromRows(FIGURE_1)); + expect(cfFarRow(1, 5)).to.equal(0); + expect(cfFarRow(2, 5)).to.equal(4); + // only the front row can move, one step straight or diagonally into the middle row + expect(movesOf(FIGURE_1, 1)).to.deep.equal(["a2-a3", "a2-b3", "b2-a3", "b2-b3", "b2-c3", "c2-b3", "c2-c3", "c2-d3", "d2-c3", "d2-d3", "d2-e3", "e2-d3", "e2-e3"]); + expect(movesOf(FIGURE_1, 2)).to.deep.equal(["a4-a3", "a4-b3", "b4-a3", "b4-b3", "b4-c3", "c4-b3", "c4-c3", "c4-d3", "d4-c3", "d4-d3", "d4-e3", "e4-d3", "e4-e3"]); + }); + + it("is won when all of a player's groups have a checker in the far row (Figure 2)", () => { + const board = fromRows(FIGURE_2); + const blue = cfGroups(board, 2, 5, 5).map(g => g.map(sq => name(sq, 5, 5)).sort()); + expect(blue).to.deep.equal([["a4", "b1", "b2", "b3", "b4", "c4"], ["d1", "d2", "e2", "e3"]]); + expect(cfHasWon(board, 2, 5, 5)).to.be.true; + // Red has four groups, and three of them have no checker in row 5 + expect(cfGroups(board, 1, 5, 5).length).to.equal(4); + expect(cfHasWon(board, 1, 5, 5)).to.be.false; + // nobody has won at the start + expect(cfHasWon(fromRows(FIGURE_1), 1, 5, 5)).to.be.false; + expect(cfHasWon(fromRows(FIGURE_1), 2, 5, 5)).to.be.false; + }); + + it("forbids completing a wall, but lets a checker move through the square (Figure 3)", () => { + const board = fromRows(FIGURE_3); + expect(cfIsWall(board, 1, 4, 5)).to.be.true; + expect(cfIsWall(board, 1, 3, 5)).to.be.false; + const red = movesOf(FIGURE_3, 1); + // none of the red checkers on c1, d1 and e1 may move to d2 + expect(red).to.not.include.members(["c1-d2", "d1-d2", "e1-d2"]); + // but c1 and e1 may move through d2 + expect(red).to.include.members(["c1-e3", "e1-c3", "e1-b4"]); + expect(red).to.deep.equal(["a2-b3", "b2-b3", "b2-b4", "b2-c3", "c1-e3", "c2-b3", "c2-c3", "e1-b4", "e1-c3", "e2-e3"]); + }); + + it("allows a wall in the far row and in the next row behind another wall of the same colour", () => { + // Red may complete the wall in row 5, Red's far row, without winning: the group on a1-a3 stays behind + expect(movesOf("RRRR./.R.BR/RB..R/RBBBB/RBBBB", 1)).to.deep.equal(["a3-a4", "e4-e5"]); + // 7x7, a red wall in row 7: Red may complete a second wall in row 6, again without winning + expect(movesOf("RRRRRRR/RRR.RRR/..RR..B/BBB.BB./BBBRBBB/RRBBBRR/BBBRBBB", 1)).to.deep.equal(["c5-d6", "d3-d4", "d5-d6"]); + // without the wall in row 7 the same two moves are forbidden + expect(movesOf("RRRRRR./RRR.RRR/..RR.RB/BBB.BB./BBBRBBB/RRBBBRR/BBBRBBB", 1)).to.deep.equal(["d3-d4", "f6-g7", "g6-g7"]); + }); + + it("counts as an opening every unoccupied square in the next row ahead, except where the checker's colour may not complete a wall (Figures 3 and 4)", () => { + // Figure 3: d2 is not an opening of any red checker, although it is an opening of the blue checker on a3 + const fig3 = distancesOf(FIGURE_3); + for (const cell of ["a1", "b1", "c1", "d1", "e1"]) { + expect(fig3).to.not.have.property(cell); + } + expect(fig3.a3).to.equal(3); + // Figure 4: the blue checkers on a3 and b3 have distances 3 and 2 to d2, although neither can move there + expect(distancesOf(FIGURE_4)).to.deep.equal({a3: 3, b3: 2, c3: 2, d3: 3, e3: 4}); + expect(cfShortestDistance(fromRows(FIGURE_4), 5, 5)).to.equal(2); + // an opening straight ahead is at a distance of 0 + expect(cfShortestDistance(fromRows(FIGURE_1), 5, 5)).to.equal(0); + }); + + it("allows a sideways move only if it shortens the shortest distance (Figure 5)", () => { + // Red's only legal move is the sideways move from c2 to d2 + expect(movesOf(FIGURE_4, 1)).to.deep.equal(["c2-d2"]); + const after = "B.BBB/.BBBB/BBRRR/RR.RR/RR.R."; + // the unoccupied square c2 is now an opening of the blue checker on b3 at a distance of 1 + expect(distancesOf(after).b3).to.equal(1); + expect(cfShortestDistance(fromRows(after), 5, 5)).to.equal(1); + // with the shortest distance at 0 no sideways move is legal + expect(cfShortestDistance(fromRows(FIGURE_3), 5, 5)).to.equal(0); + expect(cfMoves(fromRows(FIGURE_3), 1, 5, 5).some(m => m.sideways)).to.be.false; + }); + + it("always allows a winning move, whether it completes a wall or leaves the shortest distance as it is", () => { + const board = fromRows(WINNING_MOVES); + // e2 is not an opening of the blue checker on e3; the shortest distance is 2 (red c1 to e2) + expect(distancesOf(WINNING_MOVES)).to.deep.equal({a1: 4, b1: 3, c1: 2}); + const blue = cfMoves(board, 2, 5, 5).map(m => ({move: `${name(m.from, 5, 5)}-${name(m.to, 5, 5)}`, sideways: m.sideways, wins: m.wins})); + expect(blue).to.have.deep.members([ + {move: "e3-e2", sideways: false, wins: true}, // completes a wall + {move: "e3-d3", sideways: true, wins: true}, // leaves the shortest distance at 2 + {move: "c3-d3", sideways: true, wins: true}, + {move: "d2-e2", sideways: true, wins: false}, // shortens the shortest distance + ]); + // Red has no legal move in this position + expect(cfMoves(board, 1, 5, 5)).to.deep.equal([]); + }); + + it("never leaves both players without a move, on every position of the 3x3 and 2x5 boards", () => { + // the numbers of positions are those of the designer's own programs + for (const [width, height, positions, skipped] of [[3, 3, 720, 16], [2, 5, 849, 94]]) { + const key = (b: CfBoard): string => b.map(x => x ?? 0).join(""); + const mirror = (b: CfBoard): string => { + let out = ""; + for (let r = 0; r < height; r++) { + for (let c = width - 1; c >= 0; c--) { + out += (b[r * width + c] ?? 0).toString(); + } + } + return out; + }; + const seen = new Set([`${key(cfStart(width, height))}1`]); + const counted = new Set(); + const skips = new Set(); + const todo: [CfBoard, playerid][] = [[cfStart(width, height), 1]]; + while (todo.length > 0) { + const [board, player] = todo.pop()!; + if (cfHasWon(board, 1, width, height) || cfHasWon(board, 2, width, height)) { + continue; + } + const other: playerid = player === 1 ? 2 : 1; + // positions are counted up to left-right mirroring + const canonical = (key(board) < mirror(board) ? key(board) : mirror(board)) + player.toString(); + counted.add(canonical); + const next: CfBoard[] = []; + const list = cfMoves(board, player, width, height); + if (list.length === 0) { + expect(cfMoves(board, other, width, height).length, key(board)).to.be.greaterThan(0); + skips.add(canonical); + next.push(board); + } + for (const m of list) { + // a queen's move over unoccupied squares: along the row, or toward the far row straight or diagonally + const rows = Math.floor(m.to / width) - Math.floor(m.from / width); + const cols = (m.to % width) - (m.from % width); + expect(m.sideways).to.equal(rows === 0); + expect(rows === 0 ? cols !== 0 : (rows < 0) === (player === 1) && (cols === 0 || Math.abs(cols) === Math.abs(rows))).to.be.true; + const steps = Math.max(Math.abs(rows), Math.abs(cols)); + for (let k = 1; k <= steps; k++) { + expect(board[m.from + k * (Math.sign(rows) * width + Math.sign(cols))]).to.be.undefined; + } + const b = [...board]; + b[m.to] = b[m.from]; + b[m.from] = undefined; + // only the mover can have won + expect(cfHasWon(b, other, width, height)).to.be.false; + expect(cfHasWon(b, player, width, height)).to.equal(m.wins); + next.push(b); + } + for (const b of next) { + const k = key(b) + other.toString(); + if (!seen.has(k)) { + seen.add(k); + todo.push([b, other]); + } + } + } + expect(counted.size).to.equal(positions); + expect(skips.size).to.equal(skipped); + } + }); + }); + + describe("Setup", () => { + it("starts on the 7x7 board with three rows of checkers each, Red to move", () => { + const g = new CounterflowGame(); + expect(g.boardsize).to.equal(7); + expect(g.currplayer).to.equal(1); + expect(rowsOf(g)).to.equal("BBBBBBB/BBBBBBB/BBBBBBB/......./RRRRRRR/RRRRRRR/RRRRRRR"); + expect(g.checkers(1).length).to.equal(21); + expect(g.checkers(2).length).to.equal(21); + expect(g.moves().length).to.equal(19); + expect(g.destinations("a3")).to.deep.equal(["a4", "b4"]); + expect(g.destinations("d3").sort()).to.deep.equal(["c4", "d4", "e4"]); + expect(g.destinations("d2")).to.deep.equal([]); + }); + + it("honours the board size variants", () => { + for (const [variant, size] of [["size-5", 5], ["size-9", 9], ["size-11", 11]] as [string, number][]) { + const g = new CounterflowGame(undefined, [variant]); + expect(g.boardsize).to.equal(size); + const filled = (size - 1) / 2; + expect(g.checkers(1).length).to.equal(size * filled); + expect(g.checkers(2).length).to.equal(size * filled); + // the middle row is empty + for (let x = 0; x < size; x++) { + expect(g.board.has(g.coords2algebraic(x, filled))).to.be.false; + } + expect(g.moves().length).to.equal(3 * size - 2); + } + expect(rowsOf(new CounterflowGame(undefined, ["size-5"]))).to.equal(FIGURE_1); + }); + + it("is experimental and submits skipped turns automatically", () => { + expect(CounterflowGame.gameinfo.flags).to.include("experimental"); + expect(CounterflowGame.gameinfo.flags).to.include("autopass"); + expect(CounterflowGame.gameinfo.flags).to.not.include("pie"); + }); + }); + + describe("Moves", () => { + it("reaches Figure 4 of the rule sheet, where Red's only legal move is sideways", () => { + const g = play(FIGURE_4_MOVES, ["size-5"]); + expect(rowsOf(g)).to.equal(FIGURE_4); + expect(g.currplayer).to.equal(1); + expect(g.distance("a3")).to.equal(3); + expect(g.distance("b3")).to.equal(2); + expect(g.distance("c3")).to.equal(2); + expect(g.distance("a1")).to.be.undefined; + expect(g.shortestDistance()).to.equal(2); + expect(g.moves()).to.deep.equal(["c2-d2"]); + g.move("c2-d2"); + expect(g.shortestDistance()).to.equal(1); + expect(g.distance("b3")).to.equal(1); + expect(g.moves()).to.deep.equal(["b3-c2"]); + }); + + it("skips the turn of a player with no legal move", () => { + const g = play(GAME_5.slice(0, 5), ["size-5"]); + expect(rowsOf(g)).to.equal(GAME_5_SKIP); + // Blue has no legal move: d4 would complete a wall and everything else is blocked + expect(g.currplayer).to.equal(2); + expect(g.moves()).to.deep.equal(["pass"]); + expect(g.validateMove("pass").valid).to.be.true; + expect(g.validateMove("pass").complete).to.equal(1); + expect(g.validateMove("d5-d4").valid).to.be.false; + // the other player has a move + expect(g.moves(1)).to.not.include("pass"); + g.move("pass"); + expect(g.stack[g.stack.length - 1]._results).to.deep.equal([{type: "pass"}]); + expect(rowsOf(g)).to.equal(GAME_5_SKIP); + expect(g.currplayer).to.equal(1); + expect(g.validateMove("pass").valid).to.be.false; + expect(() => g.move("pass")).to.throw(); + }); + + it("plays a full game on the 5x5 board to a win for Red", () => { + const g = play(GAME_5.slice(0, 12), ["size-5"]); + expect(g.gameover).to.be.false; + g.move("c1-b2"); + expect(rowsOf(g)).to.equal(GAME_5_END); + expect(g.gameover).to.be.true; + expect(g.winner).to.deep.equal([1]); + // one red group, with a checker on c5 in Red's far row + expect(g.groups(1).length).to.equal(1); + expect(g.groups(1)[0]).to.include("c5"); + expect(g.moves()).to.deep.equal([]); + expect(() => g.move("b5-a4")).to.throw(); + expect(g.stack[g.stack.length - 1]._results).to.deep.equal([ + {type: "move", from: "c1", to: "b2"}, + {type: "eog", reason: "groups"}, + {type: "winners", players: [1]}, + ]); + }); + + it("plays a full game on the 7x7 board to a win for Blue by a sideways move", () => { + const g = play(GAME_7.slice(0, 47)); + expect(g.gameover).to.be.false; + expect(GAME_7.filter(m => m === "pass").length).to.equal(3); + // the shortest distance is 0, so the only legal sideways moves are those that win + expect(g.currplayer).to.equal(2); + expect(g.shortestDistance()).to.equal(0); + expect(g.moves()).to.include("a4-b4"); + g.move("a4-b4"); + expect(rowsOf(g)).to.equal(GAME_7_END); + expect(g.gameover).to.be.true; + expect(g.winner).to.deep.equal([2]); + for (const group of g.groups(2)) { + expect(group.some(cell => cell.endsWith("1"))).to.be.true; + } + }); + + it("lets a winning move complete a wall or keep the shortest distance", () => { + for (const m of ["e3-e2", "e3-d3", "c3-d3"]) { + const g = setup(WINNING_MOVES, 2); + expect(g.validateMove(m).valid, m).to.be.true; + g.move(m); + expect(g.gameover, m).to.be.true; + expect(g.winner).to.deep.equal([2]); + } + const g = setup(WINNING_MOVES, 2); + expect(g.moves().sort()).to.deep.equal(["c3-d3", "d2-e2", "e3-d3", "e3-e2"]); + g.move("d2-e2"); + expect(g.gameover).to.be.false; + // Red has no legal move in the position of the fixture + expect(setup(WINNING_MOVES, 1).moves()).to.deep.equal(["pass"]); + }); + + it("rejects moves that break the rules, with the right explanation", () => { + addResource("en"); + const t = (key: string, params?: Record): string => i18next.t(`apgames:validation.${key}`, params); + // Figure 3, Red to move: the shortest distance is 0 + let g = setup(FIGURE_3, 1); + for (const from of ["c1", "d1", "e1"]) { + expect(g.validateMove(`${from}-d2`).valid).to.be.false; + expect(g.validateMove(`${from}-d2`).message).to.equal(t("counterflow.WALL", {from, to: "d2"})); + } + expect(g.validateMove("d3-d2").message).to.equal(t("counterflow.DIRECTION", {from: "d3", to: "d2"})); + expect(g.validateMove("b2-d3").message).to.equal(t("counterflow.DIRECTION", {from: "b2", to: "d3"})); + expect(g.validateMove("a2-a3").message).to.equal(t("_general.OCCUPIED", {where: "a3"})); + expect(g.validateMove("b1-b3").message).to.equal(t("counterflow.BLOCKED", {from: "b1", to: "b3"})); + expect(g.validateMove("d3-c3").message).to.equal(t("counterflow.SIDEWAYS_ZERO", {from: "d3", to: "c3"})); + expect(g.validateMove("a3-a2").message).to.equal(t("_general.UNCONTROLLED")); + expect(g.validateMove("c3-c4").message).to.equal(t("_general.NONEXISTENT", {where: "c3"})); + expect(g.validateMove("a1").message).to.equal(t("_general.NO_MOVES", {where: "a1"})); + expect(g.validateMove("b2-z9").valid).to.be.false; + expect(g.validateMove("b2-b3-b4").valid).to.be.false; + expect(g.validateMove("pass").message).to.equal(t("counterflow.NO_PASS")); + expect(() => g.move("c1-d2")).to.throw(); + expect(() => g.move("pass")).to.throw(); + // Figure 4, Red to move: the shortest distance is 2, and only c2-d2 shortens it + g = setup(FIGURE_4, 1); + expect(g.validateMove("e2-d2").message).to.equal(t("counterflow.SIDEWAYS", {from: "e2", to: "d2"})); + expect(g.validateMove("c2-d2").valid).to.be.true; + // a player with no legal move may only have the turn skipped + g = setup(WINNING_MOVES, 1); + expect(g.validateMove("pass").message).to.equal(t("counterflow.MUST_PASS")); + }); + + it("builds moves from clicks", () => { + const g = new CounterflowGame(undefined, ["size-5"]); + const click = (move: string, cell: string) => { + const [x, y] = g.algebraic2coords(cell); + return g.handleClick(move, y, x); + }; + // an empty square or an enemy checker does nothing before a checker is selected + expect(click("", "c3").valid).to.be.false; + expect(click("", "c3").move).to.equal(""); + expect(click("", "c4").valid).to.be.false; + // a checker without a legal move cannot be selected + expect(click("", "c1").valid).to.be.false; + expect(click("", "c1").move).to.equal(""); + // select a checker + const first = click("", "c2"); + expect(first.valid).to.be.true; + expect(first.move).to.equal("c2"); + expect(first.complete).to.equal(-1); + expect(first.canrender).to.be.true; + // clicking it again deselects it + expect(click("c2", "c2").move).to.equal(""); + // another checker can be selected instead + expect(click("c2", "d2").move).to.equal("d2"); + // an illegal destination keeps the selection + const bad = click("c2", "c4"); + expect(bad.valid).to.be.false; + expect(bad.move).to.equal("c2"); + // a legal destination completes the move + const done = click("c2", "d3"); + expect(done.valid).to.be.true; + expect(done.move).to.equal("c2-d3"); + expect(done.complete).to.equal(1); + // a click on a checker after a complete move starts over + expect(click("c2-d3", "b2").move).to.equal("b2"); + expect(click("c2-d3", "c3").move).to.equal("c2-c3"); + }); + + it("serializes and clones with the history intact", () => { + const g = play(GAME_5, ["size-5"]); + const again = new CounterflowGame(g.serialize()); + expect(again.stack.length).to.equal(GAME_5.length + 1); + expect(again.boardsize).to.equal(5); + expect(again.gameover).to.be.true; + expect(again.winner).to.deep.equal([1]); + expect(rowsOf(again)).to.equal(GAME_5_END); + const c = g.clone(); + expect(c.moves()).to.deep.equal([]); + expect(rowsOf(c)).to.equal(GAME_5_END); + // load() restores the position of stack[idx] + again.load(5); + expect(again.currplayer).to.equal(2); + expect(rowsOf(again)).to.equal(GAME_5_SKIP); + expect(again.lastmove).to.equal("b1-b3"); + }); + }); + + describe("Chat log", () => { + it("reports skipped turns and names the winner", () => { + addResource("en"); + const names = ["Red player", "Blue player"]; + const g = play(GAME_5, ["size-5"]); + const entries = g.chatLogEntries(names); + expect(entries[0].lines.map(l => l.textKey)).to.deep.equal(["apresults:_general.MOVE.nowhat"]); + expect(entries[0].lines[0].textParams).to.include({from: "a2", to: "a3"}); + // the skipped turn of Blue at ply 6 + expect(entries[5].lines.map(l => l.textKey)).to.deep.equal(["apresults:counterflow.PASS.skipped"]); + expect(entries[5].lines[0].actor).to.deep.equal({kind: "seat", seat: 2}); + const last = entries[entries.length - 1]; + expect(last.lines.map(l => l.textKey)).to.deep.equal([ + "apresults:_general.MOVE.nowhat", + "apresults:counterflow.EOG.groups", + "apresults:_general.WINNERS", + ]); + expect(last.lines[1].textParams).to.deep.equal({player: "Red player"}); + assertChatLogParity(g, names); + const t = (key: string, params?: Record): string => i18next.t(key, params); + expect(g.formatEogSummary(names, t)).to.equal(i18next.t("apresults:counterflow.EOG.groups", {player: "Red player"})); + expect(g.chatLog(names).flat().some(line => line.includes("skipped"))).to.be.true; + // the 7x7 game: Blue wins + const g7 = play(GAME_7); + expect(g7.chatLogEntries(names).slice(-1)[0].lines[1].textParams).to.deep.equal({player: "Blue player"}); + assertChatLogParity(g7, names); + }); + }); + + describe("Rendering", () => { + it("renders the checkers on a board of one felt colour", () => { + const g = new CounterflowGame(undefined, ["size-5"]); + const rep = g.render(); + const board = rep.board as {style: string; width: number; height: number; checkeredLight: unknown; checkeredDark: unknown; markers?: unknown[]}; + expect(board.style).to.equal("squares-checkered"); + expect(board.width).to.equal(5); + expect(board.height).to.equal(5); + expect(board.checkeredLight).to.deep.equal(board.checkeredDark); + expect(board.markers).to.be.undefined; + expect(rep.glyphDefs).to.be.undefined; + expect(rep.pieces).to.equal("BBBBB\nBBBBB\n_\nAAAAA\nAAAAA"); + expect((rep.legend!.A as {paint: {fill: number}}).paint.fill).to.equal(1); + expect((rep.legend!.B as {paint: {fill: number}}).paint.fill).to.equal(2); + }); + + it("marks the checkers that have a legal move, and the squares a selected checker may move to", () => { + const g = new CounterflowGame(undefined, ["size-5"]); + // at the start only Red's front row can move + for (const dots of annotated(g, "dots")) { + expect(dots).to.deep.equal(["a2", "b2", "c2", "d2", "e2"]); + } + expect(annotated(g, "dots").length).to.be.greaterThan(0); + expect(annotated(g, "glyph")).to.deep.equal([]); + // a selected checker is marked, with the squares it may move to; the dots are gone + g.move("c2", {partial: true}); + expect(annotated(g, "glyph")).to.have.deep.members([["c2"], ["b3", "c3", "d3"]]); + expect(annotated(g, "dots")).to.deep.equal([]); + // the partial move changes nothing on the board + expect(rowsOf(g)).to.equal(FIGURE_1); + expect(g.stack.length).to.equal(1); + }); + + it("marks the checker moved last and the square it came from", () => { + const g = new CounterflowGame(undefined, ["size-5"]); + g.move("c2-d3"); + // the moved checker, and nothing else, carries a glyph; the square it came from carries a dot + expect(annotated(g, "glyph")).to.deep.equal([["d3"]]); + expect(annotated(g, "dots")).to.deep.include(["c2"]); + // Blue's checkers that can move are marked as well + expect(annotated(g, "dots")).to.deep.include(["a4", "b4", "c4", "d4", "e4"]); + // the marks of the last move stay while the next move is being entered + g.move("c4", {partial: true}); + expect(annotated(g, "glyph")).to.have.deep.members([["d3"], ["c4"], ["b3", "c2", "c3"]]); + expect(annotated(g, "dots")).to.deep.equal([["c2"]]); + // a complete move that has not been submitted shows the move and no dots for the next one + g.move("c4-c3", {partial: true}); + expect(annotated(g, "glyph")).to.deep.equal([["c3"]]); + expect(annotated(g, "dots")).to.deep.equal([["c4"]]); + expect(g.stack.length).to.equal(2); + }); + + it("outlines the winner's groups when the game is over", () => { + const during = play(GAME_7.slice(0, 47)); + expect((during.render().board as {markers?: unknown[]}).markers).to.be.undefined; + const g = play(GAME_7); + const rep = g.render(); + expect(rep.annotations).to.be.undefined; + const markers = (rep.board as {markers: Array<{type: string; sides: Array<{cell: {row: number; col: number}; side: string}>}>}).markers; + expect(markers.length).to.be.greaterThan(0); + // every side of a blue checker that does not face another blue checker, and no other side + const expected: string[] = []; + const rows = GAME_7_END.split("/"); + const blue = (y: number, x: number): boolean => y >= 0 && y < 7 && x >= 0 && x < 7 && rows[y][x] === "B"; + for (let y = 0; y < 7; y++) { + for (let x = 0; x < 7; x++) { + if (blue(y, x)) { + const cell = g.coords2algebraic(x, y); + if (!blue(y - 1, x)) { expected.push(`${cell}N`); } + if (!blue(y + 1, x)) { expected.push(`${cell}S`); } + if (!blue(y, x - 1)) { expected.push(`${cell}W`); } + if (!blue(y, x + 1)) { expected.push(`${cell}E`); } + } + } + } + for (const marker of markers) { + const sides = marker.sides.map(s => `${g.coords2algebraic(s.cell.col, s.cell.row)}${s.side}`); + expect(sides).to.have.members(expected); + expect(sides.length).to.equal(expected.length); + } + }); + + it("draws no outline when the game ends without a player reaching the goal", () => { + const g = play(GAME_7.slice(0, 20)); + g.resign(1); + expect(g.gameover).to.be.true; + expect(g.winner).to.deep.equal([2]); + expect((g.render().board as {markers?: unknown[]}).markers).to.be.undefined; + // nor on an earlier position of a finished game + const done = play(GAME_7); + done.load(20); + expect((done.render().board as {markers?: unknown[]}).markers).to.be.undefined; + expect(annotated(done, "glyph")).to.deep.equal([["c5"]]); + }); + }); + + describe("Random play", () => { + it("never deadlocks or repeats a position, and ends with the mover's groups in the far row, on every board", () => { + const rnd = seededRandom(2026); + let skippedTurns = 0; + for (const [variants, games] of [[["size-5"], 12], [[], 4], [["size-9"], 1], [["size-11"], 1]] as [string[], number][]) { + for (let n = 0; n < games; n++) { + const g = new CounterflowGame(undefined, variants); + const far = (player: playerid): string => (player === 1 ? g.boardsize : 1).toString(); + const seen = new Set(); + let plies = 0; + while (!g.gameover) { + const position = `${rowsOf(g)} ${g.currplayer}`; + expect(seen.has(position)).to.be.false; + seen.add(position); + const moves = g.moves(); + expect(moves.length).to.be.greaterThan(0); + if (moves[0] === "pass") { + expect(moves).to.deep.equal(["pass"]); + // the other player can always move + expect(g.moves(g.currplayer === 1 ? 2 : 1)).to.not.include("pass"); + skippedTurns++; + } + const mover = g.currplayer; + g.move(moves[Math.floor(rnd() * moves.length)]); + plies++; + expect(plies).to.be.lessThan(3000); + if (g.gameover) { + expect(g.winner).to.deep.equal([mover]); + for (const group of g.groups(mover)) { + expect(group.some(cell => cell.slice(1) === far(mover))).to.be.true; + } + const loser: playerid = mover === 1 ? 2 : 1; + expect(g.groups(loser).every(group => group.some(cell => cell.slice(1) === far(loser)))).to.be.false; + } + } + } + } + expect(skippedTurns).to.be.greaterThan(0); + }); + }); +});