From 9663ea237e1f048381a6f554e15187fef14455fc Mon Sep 17 00:00:00 2001 From: noobpwnftw Date: Thu, 26 Nov 2026 06:45:59 +0800 Subject: [PATCH] Add polyglot book writing make_entry() encodes a move in a position as a book entry, and write_book() writes entries sorted by position, then by weight, highest first. Choosing and weighting entries is up to the caller. --- chess/polyglot.py | 45 +++++++++++++++++++++++++++++++++++++++- docs/polyglot.rst | 8 +++++-- test.py | 53 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 3 deletions(-) diff --git a/chess/polyglot.py b/chess/polyglot.py index 526b2095d..31b7be686 100644 --- a/chess/polyglot.py +++ b/chess/polyglot.py @@ -10,7 +10,7 @@ from types import TracebackType from typing import NamedTuple, TypeAlias -from collections.abc import Callable, Container, Iterator +from collections.abc import Callable, Container, Iterable, Iterator StrOrBytesPath: TypeAlias = str | bytes | os.PathLike[str] | os.PathLike[bytes] @@ -502,6 +502,49 @@ def close(self) -> None: self.mmap.close() +def make_entry(board: chess.Board, move: chess.Move, *, weight: int = 1, learn: int = 0) -> Entry: + """ + Creates an entry for playing *move* in the position *board*. + + :param weight: Up to 65535. Readers pick higher weights more often. + :param learn: Up to 4294967295, for any extra information. + :raises: :exc:`ValueError` for a pawn drop, which has no encoding. + """ + # Castling as king takes rook; a drop as a move from and to its square. + stored = move if board.chess960 else board._to_chess960(move) + if stored.drop == chess.PAWN: + raise ValueError(f"pawn drops have no polyglot encoding: {move.uci()}") + piece = stored.drop or stored.promotion + raw_move = stored.to_square | stored.from_square << 6 | (piece - 1 if piece else 0) << 12 + return Entry(zobrist_hash(board), raw_move, weight, learn, move) + + +def write_book(path: StrOrBytesPath, entries: Iterable[Entry]) -> None: + """ + Writes a book with the given entries, as created by :func:`make_entry()` + or read from another book, to the file at the given path. + + Entries are sorted by position, then by weight, highest first, as + Polyglot writes them. Choosing and weighting the entries is up to the + caller. The following example writes a book with the moves of a game: + + >>> import chess + >>> import chess.polyglot + >>> + >>> board = chess.Board() + >>> entries = [] + >>> for san in ["e4", "e5", "Nf3", "Nc6", "Bb5"]: + ... move = board.parse_san(san) + ... entries.append(chess.polyglot.make_entry(board, move)) + ... board.push(move) + >>> + >>> chess.polyglot.write_book("ruy-lopez.bin", entries) + """ + with open(path, "wb") as f: + for entry in sorted(entries, key=lambda entry: (entry.key, -entry.weight)): + f.write(ENTRY_STRUCT.pack(entry.key, entry.raw_move, entry.weight, entry.learn)) + + def open_reader(path: StrOrBytesPath) -> MemoryMappedReader: """ Creates a reader for the file at the given path. diff --git a/docs/polyglot.rst b/docs/polyglot.rst index 18c94c426..6ed3b6ab4 100644 --- a/docs/polyglot.rst +++ b/docs/polyglot.rst @@ -1,5 +1,5 @@ -Polyglot opening book reading -============================= +Polyglot opening books +====================== .. autofunction:: chess.polyglot.open_reader @@ -10,6 +10,10 @@ Polyglot opening book reading .. autoclass:: chess.polyglot.MemoryMappedReader :members: +.. autofunction:: chess.polyglot.make_entry + +.. autofunction:: chess.polyglot.write_book + .. py:data:: chess.polyglot.POLYGLOT_RANDOM_ARRAY :value: [0x9D39247E33776D41, ..., 0xF8D626AAAF278509] diff --git a/test.py b/test.py index 400bc2bda..7c84dd956 100755 --- a/test.py +++ b/test.py @@ -9,6 +9,7 @@ import pathlib import platform import random +import struct import sys import tempfile import textwrap @@ -2223,6 +2224,58 @@ def test_castling(self): entry = book.find(pos) self.assertEqual(entry.move, chess.Move.from_uci("e1a1")) + def test_write_book(self): + with tempfile.TemporaryDirectory() as directory: + # Rewriting a book gives the same file. + path = os.path.join(directory, "performance.bin") + with chess.polyglot.open_reader("data/polyglot/performance.bin") as book: + entries = list(book) + chess.polyglot.write_book(path, entries) + with open(path, "rb") as written, open("data/polyglot/performance.bin", "rb") as original: + self.assertEqual(written.read(), original.read()) + + # Shuffled entries come out by position, then weight, highest first. + random.Random(1).shuffle(entries) + chess.polyglot.write_book(path, entries) + with chess.polyglot.open_reader(path) as book: + order = [(entry.key, -entry.weight) for entry in book] + self.assertEqual(order, sorted(order)) + self.assertEqual(len(order), len(entries)) + + # Entries made from moves read back as those moves. + boards_and_sans = [ + (chess.Board(), "e4", 7, 3), + (chess.Board("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1"), "O-O", 1, 0), + (chess.Board("r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1"), "O-O-O", 65535, 4294967295), + (chess.Board("4k3/8/8/8/8/8/8/RK5R w AH - 0 1", chess960=True), "O-O-O", 1, 0), + (chess.Board("8/5P2/8/8/8/2k5/8/K7 w - - 0 1"), "f8=N", 1, 0), + (chess.Board("4k3/8/8/8/8/8/8/R3K3 w - - 0 1"), "Ra2", 1, 0), + ] + entries = [chess.polyglot.make_entry(board, board.parse_san(san), weight=weight, learn=learn) + for board, san, weight, learn in boards_and_sans] + path = os.path.join(directory, "written.bin") + chess.polyglot.write_book(path, entries) + with chess.polyglot.open_reader(path) as book: + self.assertEqual(len(book), len(entries)) + for (board, san, weight, learn), entry in zip(boards_and_sans, entries): + found = book.find(board) + self.assertEqual(found, entry) + self.assertEqual(found.move, board.parse_san(san)) + self.assertEqual((found.weight, found.learn), (weight, learn)) + + # Drops, except pawn drops, which have no encoding. + board = chess.variant.CrazyhouseBoard("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR[Np] w KQkq - 0 1") + chess.polyglot.write_book(path, [chess.polyglot.make_entry(board, chess.Move.from_uci("N@e4"))]) + with chess.polyglot.open_reader(path) as book: + self.assertEqual(book.find(board).move, chess.Move.from_uci("N@e4")) + board.push_uci("N@e4") + with self.assertRaises(ValueError): + chess.polyglot.make_entry(board, chess.Move.from_uci("P@e5")) + + # Weights must fit. + with self.assertRaises(struct.error): + chess.polyglot.write_book(path, [chess.polyglot.make_entry(chess.Board(), chess.Move.from_uci("e2e4"), weight=65536)]) + def test_empty_book(self): with chess.polyglot.open_reader(os.devnull) as book: self.assertEqual(len(book), 0)