Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

Repository files navigation

Chess Engine in APL

A fully functional chess engine where 100% of the chess logic is written in GNU APL. Python serves only as a thin UCI bridge and tournament harness -- it never holds board state, generates moves, evaluates positions, or searches.

Developed by Mathieu Acher and Codex (5.3 extra high reasoning).

Language Breakdown

Component Language Lines Chess Logic?
src/apl/engine.apl GNU APL ~2,000 Yes -- 100%
scripts/uci_proxy.py Python ~170 No -- UCI relay
scripts/run_matches.py Python ~300 No -- tournament harness
tests/ Python ~530 No -- test harness

If you replaced the Python bridge with any other UCI adapter, the APL engine would work identically.

Architecture

UCI GUI  <-->  Python uci_proxy.py  <--[stdin/stdout pipe]-->  GNU APL engine.apl (worker mode)

The APL engine runs as a persistent worker process in a read-eval-print loop. The Python proxy spawns apl -s --safe -f engine.apl -- worker, relays UCI commands through pipes, and parses responses. When successive position ... moves ... commands extend the current line, the worker applies only the new move suffix instead of reparsing the whole position.

APL Engine Internals

The engine core lives in src/apl/engine.apl. It is organized as flat APL functions (no namespaces) in logical sections:

Board Representation & State

  • State vector: 6-element tuple (BOARD, SIDE, CASTLE, EP, HALFMOVE, FULLMOVE)
  • Board: 64-element character array indexed 1-64
  • FEN parsing (PARSE_BOARD_FEN) and UCI position parsing (PARSE_POSITION)
  • Coordinate conversion utilities (SQUARE_TO_IDX, IDX_TO_SQUARE, RANK_OF, FILE_OF)

Move Generation

Complete and legal move generation for all piece types:

  • Pawns: single/double advances, captures, en passant, promotion (Q/R/B/N)
  • Knights: 8-direction lookups with boundary checking
  • Sliding pieces: bishops, rooks, queens via ray-casting (CLEAR_PATH)
  • King: 8-direction movement plus castling with full validation (path clear, no passing through check, rook unmoved)
  • Pipeline: GENERATE_PSEUDO (all pseudo-legal moves) -> GENERATE_LEGAL (filtered for king safety)

Validated via perft: start position depth 3 = 8,902 nodes, Kiwipete depth 2 = 2,039.

Evaluation (Tapered)

The evaluation uses a standard tapered approach that blends opening and endgame scores based on remaining material:

  • Material: P=100, N=320, B=330, R=500, Q=900
  • Piece-square tables: separate opening and endgame PSTs for all piece types (including distinct king tables for middlegame vs endgame)
  • Mobility: 4 points per legal move (opening), 2 points (endgame)
  • Pawn structure: doubled pawn penalty (-14), isolated pawn penalty (-12), passed pawn bonus (+6 opening / +14 endgame, scaled by advancement)
  • King safety: castled king bonus (+18), castling rights bonus (+8), pawn shield bonus (+12 per nearby pawn), open file near king penalty (-10)
  • Phase blending: game phase from 0-24 based on non-pawn material (N/B=1, R=2, Q=4); final score = (phase * open + (24 - phase) * end) / 24

Search

  • Alpha-beta negamax with iterative deepening (depths 1 through N)
  • Quiescence search: captures and promotions only (all moves if in check), max 6 plies
  • Move ordering:
    • Transposition table hint: +20,000
    • Captures (MVV-LVA): +10,000 + 10 * victim - attacker
    • Promotions: +8,000 + promotion delta
    • Castling: +500
  • Transposition table: 16,384 entries, direct-mapped with polynomial rolling hash (mod 1,000,000,007). Stores depth, value, flag (exact/lower/upper), and best move hint.

Time Management

  • Fixed depth mode: search to specified depth
  • Move time mode: allocates budget from movetime with 25ms safety margin (min 10ms)
  • Clock mode (wtime/btime): (time / moves_left) + 0.8 * increment, with safety margin
  • Node-level deadline checking via MARK_SEARCH_NODE with abort flag

Worker Protocol

The WORKER_HANDLE function dispatches on commands: isready, position, go, setoption, debug, quit. Search statistics (depth, nodes, elapsed time, abort status) are emitted as structured text and relayed by the Python proxy as info string UCI messages.

What is in Python

  • scripts/uci_proxy.py: UCI stdin/stdout bridge. Manages the persistent APL worker subprocess, translates UCI commands, relays search stats as info string.
  • scripts/run_matches.py: cutechess-cli match runner with balanced openings, color swapping, and Elo estimation (weighted average across rungs, inverse-variance weighting).

Current Status

The engine is legal and complete but not strong yet.

Measured Strength (2026-03-20)

  • Provisional calibrated estimate: about 1040 Elo
  • Calibration run: 6 games vs Stockfish UCI_Elo=1320 at 120+1, depth cap 8
  • Observed result: 1-5-0
  • Computed Elo diff: -279.6
  • Implied absolute Elo: 1040.4

This number is only a rough benchmark, not a stable rating yet. The sample is small, there is only one calibrated anchor in the run, and GNU APL search speed still constrains how much useful depth the engine reaches at standard time controls.

As a weaker-opponent sanity check, the engine also scored 6-0-2 against an APL-backed random-move opponent at 30+0.5 with depth cap 4. That confirms it is well above random play, but that result is not convertible into Elo.

Strengths

  • Genuinely pure APL -- the boundary between APL (chess logic) and Python (transport) is clean and strict
  • Complete chess rules implementation verified by perft at multiple positions and depths
  • Solid search fundamentals: alpha-beta + transposition table + iterative deepening + quiescence
  • Tapered evaluation is a real technique used in competitive engines
  • Good test coverage across move generation, evaluation preferences, special rules, search, and worker protocol

Current Limitations

  • No null-move pruning, late-move reductions, or killer/history heuristics
  • Transposition table is small (16K entries) with no Zobrist hashing (string-based polynomial hash)
  • GNU APL's interpreted overhead makes deep searches slow in practice
  • Time management is still crude and can fail to complete even depth 1 under short budgets
  • Evaluation is hand-tuned with no automated tuning
  • Opening book is minimal (3 openings in PGN)

Prerequisites

  • Python 3.11+
  • GNU APL
  • stockfish
  • cutechess-cli

Quick Start

Direct APL engine:

apl -s --safe -f src/apl/engine.apl -- bestmove position startpos depth 1

UCI bridge:

printf 'uci\nisready\nposition startpos\ngo depth 1\nquit\n' \
  | python3 scripts/uci_proxy.py --apl-bin apl --apl-script src/apl/engine.apl

Engine Commands

The APL engine exposes a small CLI that the UCI wrapper uses:

# List legal moves
apl -s --safe -f src/apl/engine.apl -- legalmoves position startpos

# Best move from a FEN position
apl -s --safe -f src/apl/engine.apl -- bestmove position fen '7k/8/8/8/8/8/6r1/7K' w - - 0 1 depth 1

# Perft (move generation validation)
apl -s --safe -f src/apl/engine.apl -- perft position startpos depth 3

# Static evaluation
apl -s --safe -f src/apl/engine.apl -- eval position startpos

Estimate Elo

For a calibration-aligned estimate, use Stockfish with UCI_LimitStrength=true at the same 120+1 time control used for the Stockfish UCI_Elo scale:

python3 scripts/run_matches.py \
  --games 6 \
  --time-control 120+1 \
  --search-depth 8 \
  --opponent-elos 1320

On 2026-03-20, that setup produced a provisional estimate of 1040.4 Elo from a 1-5-0 score against Stockfish 1320.

If you want a broader estimate instead of a single anchor, test multiple calibrated rungs:

python3 scripts/run_matches.py \
  --games 12 \
  --time-control 120+1 \
  --search-depth 8 \
  --opponent-elos 1320 1500 1700

To save the finished games as PGN while benchmarking:

python3 scripts/run_matches.py \
  --games 2 \
  --time-control 120+1 \
  --search-depth 8 \
  --opponent-elos 1320 \
  --pgn-out results/benchmarks/stockfish-1320_tc120plus1_2g.pgn

To run a small sanity tournament against an APL-backed random-move opponent:

python3 scripts/run_matches.py \
  --games 8 \
  --time-control 30+0.5 \
  --search-depth 4 \
  --random-opponent \
  --pgn-out results/tournaments/apl-vs-random_8g.pgn

On 2026-03-20, that random-opponent tournament finished 6-0-2. Treat it only as a sanity check against very weak opposition, not as an Elo estimate.

If the engine is still weaker than Stockfish's minimum calibrated rung of 1320, do a coarse pre-scan first:

python3 scripts/run_matches.py \
  --games 6 \
  --search-depth 1 \
  --opponent-skills 0 2 4 6

That pre-scan is not an Elo estimate. It is only for finding roughly similar opposition.

Tests

python3 -m unittest discover -s tests -v

The test suite checks APL-side chess behavior directly, including:

  • Perft references: start position (depths 1-3), Kiwipete (depths 1-2), rook endgame (depths 1-2), castling/en passant/promotion positions
  • Evaluation preferences: centralization, mobility, king safety, pawn structure, endgame king activity
  • Search: depth-2 search through the iterative root path, timed worker search (go movetime, go wtime/btime), search stats tracking
  • Worker protocol: persistent session across multiple commands, incremental position updates, transposition table reuse across searches
  • UCI proxy: bridging correctness
  • Match runner: tournament invocation and result parsing

Roadmap

See docs/roadmap.md for phased improvement plans covering correctness hardening, evaluation tuning, search improvements, and bridge overhead reduction.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages