Position State and Rules
An engine stores piece locations, the side to move, check information, and move history. The value of a position depends on both the board and the path that reached it, especially for perpetual check, perpetual chase, and move limits.
This page follows official Pikafish commit 1c66b9b. It describes this implementation; other versions and rule options require their own code checks. See Search Algorithms for search methods.
What Does Each File Do?
| File | Main responsibility |
|---|---|
types.h | Defines pieces, colors, squares, and moves. |
bitboard.h | Represents and combines sets of squares using bit operations. |
attacks.h/.cpp | Queries attacks using piece locations and blockers. |
movegen.h/.cpp | Combines origins, reachable destinations, and target sets into moves. |
position.h/.cpp | Stores positions and handles make/undo, king safety, and historical rules. |
For a horse, the attack query handles its blocking leg, the generator creates candidates, and legal() checks king safety after the move. Sources: basic types, generation and filtering, attack queries.
Why Store Several Views of the Board?
Position maintains a square-indexed board, bitboards by piece type and color, and piece counts. Each supports a different query: an array lookup finds the piece on a square; combining color and type finds all Red chariots; intersecting attack and enemy sets finds attacked enemy pieces.
Each bit represents a square; Pikafish uses 128 bits for 90 squares. Ranks, files, board halves, and palaces have their own sets. Making and undoing moves keeps these representations in sync.
Precomputed tables accelerate chariot and cannon lines, horse legs, and elephant eyes. Magic and PEXT/PDEP provide indexing paths; see Bitboards and Attack Tables.
Sources: position members, bitboard type, square sets and operations.
How Is a Move Generated?
generate_moves() takes the moving side's bitboard for a piece type, extracts origins with pop_lsb(), calculates attacks, and intersects them with target. Each remaining destination becomes Move(from, to).
| Request | Meaning of target |
|---|---|
CAPTURES | Squares occupied by enemy pieces. |
QUIETS | Empty squares; a non-capture may still give check. |
PSEUDO_LEGAL | Squares outside the friendly piece set. |
EVASIONS | Targets narrowed by the check line, with special evasions added. |
Cannon moves use two paths: captures query the cannon's screened attacks and intersect with enemies; non-captures query chariot-style rays and intersect with empty squares.
Consider only the e file: a cannon on e2, a friendly piece on e5, an enemy on e8, and the intervening squares empty. In that direction, the quiet candidates are e2e3 and e2e4, and the capture is e2e8, using e5 as the screen. The cannon cannot jump the screen to stop on empty e6 or e7.
A horse on e4 has upward candidates e4d6 and e4f6; a piece on e5 blocks both through the horse's leg. Pawn queries also take color to handle forward direction and sideways movement after crossing the river. Advisor, king, and elephant tables enforce the palace, board-half, and elephant-eye restrictions.
Against a single checker, generation considers capturing it, blocking the line, and moving the king. Cannon checks also add moves that remove a friendly screen. With several checkers, all pseudo-legal candidates are passed to safety checking. Finally, generate<LEGAL>() filters using pos.legal(), replacing an illegal entry with the last entry and shortening the list.
Ordering and search then judge candidate quality. Source: generation by type, cannon paths, and evasions.
Making and Undoing Moves
Search repeatedly tries a move, recurses, and returns. Pikafish modifies the current Position and creates a StateInfo with hash keys, counters, checks, the move, and the captured piece. previous links to the preceding state; some fields are copied and others updated incrementally.
undo_move() restores the moving and captured pieces and returns the state pointer to its predecessor. Board, hashes, and historical counters must be restored together, so the next branch starts from the same state. Game moves and temporary search moves each follow their state chains.
Sources: StateInfo, making a move, undoing a move.
Zobrist Hashing: Locate Positions Quickly
Zobrist assigns numbers to piece-square combinations and XORs the active ones with side-to-move information. A move removes the origin contribution and adds the destination; a capture also removes the captured piece. XORing the same number twice cancels it, keeping updates local.
The 64-bit base key, st->key, mainly represents placement and turn, with a possibility of hash collisions. The caching key() also adjusts for move-limit groups and repetition-filter information. Repetition detection traces base keys through the state chain, whose checks and moves determine perpetual-check and chase outcomes.
Identical placements can follow different checking and chasing histories. Cache code therefore needs to be read alongside rule checks and cache protections. See The Transposition Table.
Sources: Zobrist setup, base-key construction, incremental updates, cache-key adjustments.
Move Legality and Historical Adjudication
legal() assumes the candidate follows the basic movement rules. It constructs post-move occupancy as (pieces() ^ from) | to: remove the origin and retain or add the destination. King moves check attacks on the destination; other moves check the king's existing square, excluding a captured attacker when necessary. Maintained pin and blocker information enables fast paths for some moves.
checkers_to() checks pawns, horses, chariots, cannons, and facing kings using the new occupancy. Moving a cannon screen can create or remove a check, and moving a horse-leg blocker can uncover one, so the post-move blockers matter.
rule_judge() handles historical adjudication after search enters a node, using checks, chases, repetitions, and move limits to determine wins, losses, or draws. Some search repetitions supply score bounds for narrowing the search window.
Sources: legal and king-attack queries, rule adjudication. Overview: Rules and Search.
Finding and Adjudicating a Cycle
This implementation calculates a lookback limit from the capture-related counter, additional checking plies, and distance from the most recent search null move. With at least four plies available and a possible repetition indicated by the Bloom filter, it follows previous two plies at a time and compares base keys for the same side to move. A filter hit still requires individual key comparisons.
During the scan it accumulates whether each side gives check on every turn. One perpetual checker receives a decisive loss score; both perpetual checkers produce a draw. If neither checks perpetually, a position copy calls detect_chases().
This version distinguishes game history from the path after the search root. Two earlier matches at or before the root, or a qualifying earlier match after the root, enter the relevant repetition branch. Third occurrences and established repetition draws can return immediately. Some second-occurrence win/loss predictions continue checking whether a draw remains possible: rule_judge() can set result while returning false, after which search adjusts alpha or beta and continues.
These details describe the fixed commit on this page. Actual play requires rules matching the platform. For another rule version, check occurrence counts, chase definitions, and how mutual violations are adjudicated.
Sources: history scan and repetition branches, search handling of provisional repetition results.
Recognizing Chases and Tracking the Same Piece
chased() returns a set of piece identities, with one bit per chased piece. It first filters attackers and targets. This implementation allows kings and pawns to chase perpetually and has dedicated exclusions for uncrossed enemy pawns and attacks on the king. A pinned attacker is restricted to the relevant pinning targets.
After chase_legal() checks a candidate attack, the code branches by piece type. Horse or cannon attacks on a chariot, and advisor or elephant attacks on qualifying stronger pieces, are marked directly. Other candidates are tested with a temporary capture: the code finds recapturers on the destination and checks each for king safety. A legal recapture excludes that candidate from this branch's chase set. Same-type mutual attacks also have symmetry and pin exceptions.
detect_chases() assigns identities to the surviving pieces on both sides and moves those identities with the pieces during rollback. At each step it compares chase sets before and after the move, uses after & ~before for newly created chases, and intersects that with the running set.
For example, new target sets {Horse A, Cannon B} and {Cannon B, Chariot C} leave {Cannon B} in their intersection. Changing targets each turn can leave an empty intersection. At the end, if only one side has a common target, that side loses for perpetual chase; if both or neither do, the result is a draw. A check encountered during rollback has a separate branch, so this set example applies to the described chase path.
Source: lightweight capture simulation, chase filtering, and identity intersections. Background: Xiangqi Rule Controversies.
Move Limits and Material Draws
do_move() maintains the move-limit counter. In this code, captures reset it and both check counters; checks beyond ten per side and their corresponding replies receive counting exemptions. At rule60 >= 120, rule_judge() checks for legal moves: a position with moves is drawn; one without them is a loss, preserving a decisive result on the final move.
Material-draw recognition then considers pawnless boards and specific chariot, horse, cannon, advisor, and elephant configurations. Some qualify directly; others require terminal checks. The latter first check whether the current side has no legal moves, then whether any move leaves the opponent with none. The applicable combinations are those explicitly listed in the source.
Sources: counter updates, move-limit and material-draw branches.
Rebuilding History with FEN and Moves
FEN stores pieces, turn, and counters. set(fen) establishes a new starting state from those fields; earlier checks, chases, and repetitions need their move sequence. To reproduce a historical issue, save a starting FEN and subsequent moves, then rebuild the chain using position … moves ….
A rule report should include the starting FEN, moves, version, rule settings, and expected ruling. FEN parsing checks format and position conditions. Establishing reachability from the initial position requires a game record or separate reachability analysis.
Sources: FEN initialization, replaying moves. Command syntax: UCI Protocol.
Perft and Rule Regression Tests
Perft uses MoveList<LEGAL>, do_move(), and undo_move() to expand to a specified positive depth and count paths reaching it. Different move orders count separately even if they reach the same board. Root counts for individual moves help locate missing or extra branches.
Perft enumerates moves; dedicated regression cases check complete historical rules:
| Test | Main question |
|---|---|
| Perft | Do generation, king-safety filtering, and make/undo match expected counts? |
| Rule regressions | Given a start and history, does adjudication occur correctly at the expected time? |
| Search regressions and match tests | Is search behaving abnormally, and how does a change affect game results? |
Perft does not call rule_judge(). Perpetual check, chase, and move limits require full-history tests; strength changes require match statistics. Source: perft implementation.
