在瀏覽器中視覺化王兵殘局幾何:兵的方格、對峙與關鍵格
Visualizing King-and-Pawn Endgame Geometry in the Browser: Square of the Pawn, Opposition, and Key Squares
瀏覽器端的王兵對王殘局視覺化工具,以幾何方式呈現兵的方格、王的對峙和關鍵格,並以精確的 KPK 復盤驗證判定勝局或和局。幾何演算法在用戶端運行,無需 WASM,運算時間少於 1 ms;精確驗證約需 25 毫秒。
Chess players learn King-and-Pawn (K+P vs K) endgames visually—drawing an imaginary bounding box from a passed pawn to the promotion rank ("the rule of the square") or counting files and ranks between rival kings to claim direct, distant, or diagonal opposition. Yet most web chess boards treat endgame instruction as static arrows drawn manually over PGN comments: the moment a student drags the defending king one square to the left to ask "what if Black plays ...Kf6 instead?", the static arrows vanish.
While building the browser endgame visualizers at chess-trainer.arte-soft.com/tools/ as open web companions to our AGPLv3 native Stockfish 18 trainer Brass Pawn, we wanted instant (< 1 ms), zero-WASM client-side algorithms that compute both human geometric heuristics and exact game-theoretic win/draw truth for any legal K+P vs K configuration.
Here is how the geometry works—and where human rules of thumb diverge from exact retrograde truth.
1. Chebyshev Distance and the "Square of the Pawn"
On an $8 \times 8$ board indexed by file $f \in [0..7]$ (a–h) and rank $r \in [0..7]$ (1–8), a chess king moves in every direction by 1 unit per turn, meaning king travel time in an unobstructed plane is governed by the Chebyshev ($L_\infty$) metric:
$$d_\infty(A, B) = \max(|f_A - f_B|, |r_A - r_B|)$$
For a White passed pawn at $(f_P, r_P)$ promoting at $(f_P, 7)$, naive distance to queening is $7 - r_P$ moves—with one crucial classical adjustment: if the pawn still stands on its starting rank ($r_P = 1$, rank 2), its double-step option reduces effective promotion distance to $7 - 2 = 5$ tempos, meaning the geometric square starts from rank 3 (rEffective = Math.max(rP, 2) when White is to move, or after accounting for side-to-move tempo).
export function computeSquareOfPawn(pawn, defendingKing, pawnSide = "w", sideToMove = "w") {
const promoRank = pawnSide === "w" ? 7 : 0;
const startRank = pawnSide === "w" ? 1 : 6;
const effectiveRank = pawn.rank === startRank ? (pawnSide === "w" ? 2 : 5) : pawn.rank;
const span = Math.abs(promoRank - effectiveRank);
const defenderTempo = sideToMove !== pawnSide ? 1 : 0;
const bounds = {
minFile: Math.max(0, pawn.file - span),
maxFile: Math.min(7, pawn.file + span),
minRank: Math.min(effectiveRank, promoRank),
maxRank: Math.max(effectiveRank, promoRank),
};
const distToPromoSquare = Math.max(
Math.abs(defendingKing.file - pawn.file),
Math.abs(defendingKing.rank - promoRank)
);
return {
bounds,
span,
distToPromoSquare,
catchesGeometrically: distToPromoSquare <= span + defenderTempo,
};
}
Why the Geometric Overlay Needs an Obstruction Warning
Every strong club player remembers famous studies (most notably Réti, 1921) where the pure Square-of-the-Pawn formula misleads casual students for two reasons:
-
Self-Interference / Friendly King Obstruction: If the attacking king stands directly on the pawn's file ahead of the pawn, the pawn may lose a tempo waiting for its own king to step aside—or conversely, the attacking king can shoulder (
shouldering) the defending king off its shortest Chebyshev path! - Dual Threats: A king pursuing a passed pawn along a diagonal simultaneously approaches a second target (such as supporting its own passed pawn).
Showing both the translucent geometric square and the exact win/draw badge immediately teaches students when the shortcut holds and when king interference overrides it.
2. Classifying Direct, Distant, and Diagonal Opposition in $O(1)$
Two kings at $(f_W, r_W)$ and $(f_B, r_B)$ stand in generalized opposition whenever the file gap $\Delta f = |f_W - f_B|$ and rank gap $\Delta r = |r_W - r_B|$ are both even (so they occupy squares of the same color and an odd number of squares separates them along ranks/files):
| $\Delta f = |f_W - f_B|$ | $\Delta r = |r_W - r_B|$ | Classification | Who Holds the Opposition? |
|---|---|---|---|
0 |
2 |
Direct Vertical Opposition | The side NOT to move |
2 |
0 |
Direct Horizontal Opposition | The side NOT to move |
2 |
2 |
Direct Diagonal Opposition | The side NOT to move |
0 and $\Delta r \in {4, 6}$ (or vice versa) |
Even | Distant Orthogonal Opposition | The side NOT to move |
| Even ($\ge 2$) | Even ($\ge 2$), $\max \ge 4$ | Virtual / Distant Rectangle Opposition | The side NOT to move |
That parity invariant ((df % 2 === 0) && (dr % 2 === 0)) explains in one line why diagonal and distant opposition work: whichever player just moved into the even-parity state forces the opponent to break parity on the next half-move, allowing the holder to step closer while restoring even (df, dr) parity until converting distant opposition into direct opposition!
3. Key Squares vs. Rook-Pawn Corner Exceptions
When the defending king is inside the square of the pawn, K+P vs K revolves around Key Squares (critical squares): if the attacking king reaches any key square—regardless of whose turn it is—the pawn promotes by force:
-
Non-Rook Pawns (
b–gfiles) on Ranks 2, 3, or 4 (White): The 3 squares two ranks ahead of the pawn:(fP - 1, rP + 2),(fP, rP + 2),(fP + 1, rP + 2). Reaching them with opposition from one rank below relies on who has the move, whereas occupying them wins unconditionally! -
Non-Rook Pawns on Rank 5 or 6: Expanded to 6 key squares—both one rank ahead and two ranks ahead across
(fP - 1 .. fP + 1)—because the sixth-rank rule eliminates stalemating defenses! -
Rook Pawns (
aandhfiles): Classic geometric rules break down completely on the board edge! Even if White's king occupiesa6ahead of ana5pawn, if Black's king reachesc7orc8(ora8/b8), Black draws by perpetual corner stalemate or trapping White's king in front of its own pawn (b7/c7boxing).
4. Exact Client-Side Retrograde KPK Verification in ~25 Milliseconds
Because rook pawns, pawn captures, and king-blocking create tactical exceptions to textbook key-square charts, an educational visualizer should never guess. Instead of downloading a 7 MB Stockfish WebAssembly binary just to verify a 3-piece endgame, you can build a complete in-memory K+P vs K retrograde tablebase in pure JavaScript right on page load!
Using horizontal symmetry (pawnFile mirrored into 0..3, i.e., files a–d), the entire state space is tiny:
$$64 \text{ (White King)} \times 64 \text{ (Black King)} \times 24 \text{ (Pawn: 4 files} \times \text{6 ranks)} \times 2 \text{ (Side to Move)} = 196,608 \text{ states}$$
A Uint8Array(196608) occupies just 192 KB of RAM:
-
Seed Terminal & Promotion Transitions: Mark illegal overlapping/adjacent-king states invalid; mark states where Black legally captures the undefended pawn as
DRAW; for pawn promotions to Queen/Rook (remembering underpromotion to Rook avoids rare corner stalemates!), check whether Black is immediately stalemated or captures the new queen; otherwise markWIN. -
Iterative Retrograde Fixed-Point Loop:
- An
UNKNOWNWhite-to-move state becomesWINas soon as any legal White move enters aWINstate. - An
UNKNOWNBlack-to-move state becomesWINonly when every legal Black move leads to aWINstate (and Black is not stalemated!).
- An
- Repeat until a pass marks zero new
WINstates (~28 passes, completing in ~22 ms on a laptop or modern phone). Every remaining legal state is a proven theoreticalDRAW!
With that 192 KB table in memory, dragging any of the three pieces updates every legal destination square on the chessboard in O(1) microseconds—coloring winning king steps green and drawing blunders amber while overlaying the classical Square-of-the-Pawn and Key-Square geometry on top.
Try the Interactive Endgame Visualizers & Open-Source Engine
You can experiment with interactive endgame geometry, opposition, and tactics visualizers directly in your browser (zero sign-up) at chess-trainer.arte-soft.com/tools/, or train across 14,351 Stockfish 18 tactics puzzles, 116 positional judgement studies, and offline endgame drills in Brass Pawn.
來源:DEV Community · dev.to