Chapter 4

UCI Chess Engine Module

The PlayOK client knows how to communicate with the server, but it does not know how to play chess. For that we need another component: the UCI chess engine. In this project, engine.py is the bridge between our chess engine and the PlayOK protocol.

The engine itself already understands chess. It understands positions, legal moves, search, evaluation, and the UCI protocol. What it does not understand is PlayOK's internal move representation. Our Python module therefore has two jobs: communicate with the UCI engine and translate the engine's chess moves into the compact integer representation expected by PlayOK.

Imports

# Packages
import chess
import chess.engine
from config import *

The first two imports come from python-chess. The chess package provides the chess board and move representation, while chess.engine provides the interface for communicating with a UCI engine.

The configuration module provides values such as ENGINE_PATH and SEARCH_TIME. This means the engine module does not need to know where the executable is located or how much time it should spend searching.

The ChessEngine Class

Everything related to the chess engine is contained in the ChessEngine class.

class ChessEngine:
    # Create chess board
    def __init__(self):
        self.board = chess.Board()
        self.engine = chess.engine.SimpleEngine.popen_uci(ENGINE_PATH)

When a ChessEngine object is created, two things happen. First, a new chess board is created. Second, the UCI engine executable is started.

chess.Board() creates a standard chess position with all pieces in their initial locations. The board will be maintained by our Python program so that the engine always knows the current game position.

The second line starts the external chess engine through UCI. SimpleEngine.popen_uci() launches the executable and establishes the communication channel that python-chess will use to send commands and receive engine responses.

From this point forward, we do not need to manually construct UCI commands. Python-chess handles the UCI communication for us.

Starting a New Game

def new_game(self):
    self.board.reset()

Every chess game starts with a fresh position. The new_game() method resets the board to the standard starting position.

This is important because the same engine object can be used for multiple games. After one game finishes, we do not want the next game to inherit the previous game's position.

The engine process itself does not need to be recreated for every game. We can keep the UCI engine running and simply reset the position maintained by our Python-side board.

Loading an Opponent Move

When our opponent makes a move on PlayOK, the PlayOK client receives that move. The engine must then be informed about it.

def load_move(self, move):
    try: self.board.push_san(move)
    except ValueError as e:
        raise ValueError(
            f"Invalid move '{move}' at position {self.board.fullmove_number}: {e}"
        )

The PlayOK protocol gives us a human-readable chess move, such as a normal SAN move. The push_san() method takes that move and applies it to the board.

This is an important separation of responsibilities. PlayOK tells us what happened in the game. The engine module takes that information and updates its own representation of the position.

If PlayOK gives us an invalid move for the current position, python-chess raises a ValueError. We catch that error and add useful context before raising it again. Instead of seeing only a generic parsing error, we can see which move caused the problem and at which point in the game it happened.

Asking the Engine for a Move

The most important method in this module is search().

def search(self):
    result = self.engine.play(self.board.copy(), chess.engine.Limit(time=SEARCH_TIME))
    source = result.move.from_square ^ 56
    target = result.move.to_square ^ 56
    move = source | (target << 6)
    if result.move.promotion: move |= (1 << 12)
    return move

The first line asks the UCI engine to calculate a move.

result = self.engine.play(
    self.board.copy(),
    chess.engine.Limit(time=SEARCH_TIME)
)

We pass a copy of our current board to the engine. The search is limited by SEARCH_TIME, which comes from config.py.

The result contains a python-chess Move object. Conceptually, the move contains a source square and a target square. For example, an engine result could represent a move from e2 to e4.

This is where we leave the world of normal chess notation and enter the PlayOK protocol.

Why Do We Need Move Conversion?

UCI and PlayOK do not represent chess moves in the same way.

A UCI engine might return:

e2e4

To a human, this is perfectly understandable. It means move the piece from e2 to e4.

PlayOK, however, does not send this string when it needs to represent a move internally. The protocol uses a compact integer containing the source and target square information.

For a loaded move, the relevant PlayOK message has the following general structure:

{"i": [LOAD_MOVE, self.active_table, 1, move, 1]}

The value represented by move is therefore not a UCI string. It is a packed integer. Our search() method converts the python-chess move into exactly this representation.

Understanding python-chess Square Numbers

To understand the conversion, we first need to understand how python-chess numbers the chess board.

python-chess uses a zero-based square index. The squares are numbered from a1 = 0 through h8 = 63.

The important detail is that the numbering starts at the bottom-left from White's perspective and proceeds across the first rank before moving to the next rank.

                 python-chess square numbers
        
                a   b   c   d   e   f   g   h
              +---+---+---+---+---+---+---+---+
        8     |56 |57 |58 |59 |60 |61 |62 |63 |
              +---+---+---+---+---+---+---+---+
        7     |48 |49 |50 |51 |52 |53 |54 |55 |
              +---+---+---+---+---+---+---+---+
        6     |40 |41 |42 |43 |44 |45 |46 |47 |
              +---+---+---+---+---+---+---+---+
        5     |32 |33 |34 |35 |36 |37 |38 |39 |
              +---+---+---+---+---+---+---+---+
        4     |24 |25 |26 |27 |28 |29 |30 |31 |
              +---+---+---+---+---+---+---+---+
        3     |16 |17 |18 |19 |20 |21 |22 |23 |
              +---+---+---+---+---+---+---+---+
        2     | 8 | 9 |10 |11 |12 |13 |14 |15 |
              +---+---+---+---+---+---+---+---+
        1     | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
              +---+---+---+---+---+---+---+---+

For example, python-chess represents e2 as square 12, while e4 is square 28.

But PlayOK's internal numbering is oriented differently. To convert between these two representations, our code uses an XOR operation with 56.

The PlayOK Board Orientation

The conversion is:

playok_square = python_chess_square ^ 56

The XOR operation changes the square numbering so that the board is effectively flipped vertically. The files remain in the same left-to-right order, while the ranks are reversed.

We can visualize the relationship like this:

                          python-chess                          PlayOK representation

                a   b   c   d   e   f   g   h              a   b   c   d   e   f   g   h
              +---+---+---+---+---+---+---+---+          +---+---+---+---+---+---+---+---+
        8     |56 |57 |58 |59 |60 |61 |62 |63 |    8     | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
              +---+---+---+---+---+---+---+---+          +---+---+---+---+---+---+---+---+
        7     |48 |49 |50 |51 |52 |53 |54 |55 |    7     | 8 | 9 |10 |11 |12 |13 |14 |15 |
              +---+---+---+---+---+---+---+---+          +---+---+---+---+---+---+---+---+
        6     |40 |41 |42 |43 |44 |45 |46 |47 |    6     |16 |17 |18 |19 |20 |21 |22 |23 |
              +---+---+---+---+---+---+---+---+          +---+---+---+---+---+---+---+---+
        5     |32 |33 |34 |35 |36 |37 |38 |39 |    5     |24 |25 |26 |27 |28 |29 |30 |31 |
              +---+---+---+---+---+---+---+---+          +---+---+---+---+---+---+---+---+
        4     |24 |25 |26 |27 |28 |29 |30 |31 |    4     |32 |33 |34 |35 |36 |37 |38 |39 |
              +---+---+---+---+---+---+---+---+          +---+---+---+---+---+---+---+---+
        3     |16 |17 |18 |19 |20 |21 |22 |23 |    3     |40 |41 |42 |43 |44 |45 |46 |47 |
              +---+---+---+---+---+---+---+---+          +---+---+---+---+---+---+---+---+
        2     | 8 | 9 |10 |11 |12 |13 |14 |15 |    2     |48 |49 |50 |51 |52 |53 |54 |55 |
              +---+---+---+---+---+---+---+---+          +---+---+---+---+---+---+---+---+
        1     | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |    1     |56 |57 |58 |59 |60 |61 |62 |63 |
              +---+---+---+---+---+---+---+---+          +---+---+---+---+---+---+---+---+

There is an important detail here: we are not changing the chess move itself. The move is still from one chess square to another. We are only changing the numerical representation of those squares so that it matches the representation expected by PlayOK.

Why XOR 56?

The number 56 is not arbitrary. It corresponds to the bit pattern needed to flip the rank portion of the six-bit square index.

A chess board contains 64 squares, so six bits are sufficient to represent every square:

0 through 63 = 6 bits

The square index can be thought of as two three-bit components: one for the file and one for the rank.

The number 56 is:

56 = binary 111000

The lower three bits represent the file, while the upper three bits represent the rank. XORing with 111000 changes the rank bits while leaving the file bits unchanged.

That is exactly what we need. We want a through h to remain in the same order, while the ranks are flipped.

For example, python-chess gives e2 = 12:

12      = 001100
56      = 111000
          ------
12 ^ 56 = 110100 = 52

Therefore PlayOK's square number for e2 is 52.

For e4, python-chess gives 28:

28      = 011100
56      = 111000
          ------
28 ^ 56 = 100100 = 36

Therefore PlayOK's square number for e4 is 36.

Encoding e2e4

Now we can follow the entire conversion for a real move.

Suppose the UCI engine returns:

e2e4

python-chess gives us the source and target squares:

e2 = 12
e4 = 28

Our code converts both values using XOR:

source = 12 ^ 56
       = 52

target = 28 ^ 56
       = 36

We now have the PlayOK square values:

source = 52
target = 36

The next step is to pack these two values into one integer.

Packing Source and Target into One Integer

PlayOK stores the source square in the lower six bits and the target square in the next six bits.

The expression used by our code is:

move = source | (target << 6)

The left shift moves the target six positions to the left, leaving the lower six bits available for the source square.

For e2e4:

source = 52
target = 36

target << 6
= 36 × 64
= 2304

move
= 52 | 2304
= 2356

So the PlayOK move integer for e2e4 is:

2356

We can see the same thing in binary:

source = 52
52     = 110100

target = 36
36     = 100100

target << 6
        = 100100000000

source
        = 000000110100

OR
        = 100100110100

The resulting binary value contains the target in the upper six bits and the source in the lower six bits.

This is why the expression works:

source | (target << 6)

There is no overlap between the two values because each square uses exactly six bits.

Another Example: e7e5

Let's encode another common opening move: e7e5.

python-chess represents the squares as:

e7 = 52
e5 = 36

Apply the PlayOK transformation:

source = 52 ^ 56
       = 12

target = 36 ^ 56
       = 28

Now pack the values:

move = 12 | (28 << 6)

28 × 64 = 1792

move = 12 | 1792
     = 1804

So e7e5 becomes the PlayOK move integer 1804.

This also demonstrates an important property of the encoding. The transformation is reversible. If PlayOK gives us a packed move, we can extract the source and target values and apply the same XOR transformation to get back to python-chess square numbers.

Extracting the Source and Target

The lower six bits contain the source square, so we can obtain it with a bit mask:

source = move & 63

The target is stored six bits higher, so we shift the value back:

target = (move >> 6) & 63

Promotion Moves

There is one additional piece of information that does not fit into the twelve bits used for the source and target squares: pawn promotion.

The code handles this with:

if result.move.promotion:
    move |= (1 << 12)

The source occupies bits 0 through 5, and the target occupies bits 6 through 11. Bit 12 is therefore the next available bit.

If the engine's move contains a promotion, we set that bit:

1 << 12 = 4096

For a promotion move, the same source and target encoding is used, with bit 12 set to 1 to indicate promotion to a queen.

For simplicity, our engine always promotes to a queen, so we only need to detect that the move is a promotion and set bit 12 accordingly. The PlayOK client will later place this encoded move into the appropriate WebSocket message.

The Complete Conversion

We can now understand the entire search() method as a sequence of simple transformations:

  1. Ask the UCI engine for a move.
  2. Get the source square from the python-chess move.
  3. Get the target square from the python-chess move.
  4. Flip the square numbering with ^ 56.
  5. Store the source in the lower six bits.
  6. Shift the target six bits to the left.
  7. Combine source and target with bitwise OR.
  8. Set bit 12 when the move is a promotion.
  9. Return the resulting integer.

The important thing is that the engine does not need to know anything about PlayOK. It returns a normal chess move. The Python bridge performs the protocol-specific conversion afterward.

From Engine Move to PlayOK Message

Once search() returns the encoded integer, the PlayOK module can place it into the WebSocket message expected by the server.

The relevant structure is:

{"i": [LOAD_MOVE, self.active_table, 1, move, 1]}

Here LOAD_MOVE identifies the type of operation, self.active_table identifies the current game table, and move contains the packed source and target information generated by our engine module.

This gives us the complete bridge:

UCI engine
    ↓
e2e4
    ↓
python-chess Move
    ↓
e2 = 12, e4 = 28
    ↓
XOR 56
    ↓
source = 52, target = 36
    ↓
source | (target << 6)
    ↓
2356
    ↓
{"i": [LOAD_MOVE, table, 1, 2356, 1]}
    ↓
PlayOK

This is one of the most important pieces of reverse engineering in the entire project. We have taken a normal chess move produced by an existing UCI engine and transformed it into the compact binary-style representation used inside PlayOK's application protocol.

Translate at the Boundary

We do not want PlayOK-specific square encoding scattered throughout the chess code. The conversion happens at the boundary between the UCI engine and the PlayOK client. This keeps normal chess operations expressed in standard python-chess terms until the moment a move has to leave the engine.

Closing the Engine

When the bot shuts down, we also need to terminate the external engine process.

def close(self):
    if self.engine is not None:
        self.engine.quit()
        self.engine = None

The quit() method tells python-chess to terminate communication with the UCI engine and shut down the engine process. Setting self.engine to None makes the object's state explicit and prevents us from accidentally trying to use an engine that has already been closed.

This may seem like a small detail, but properly managing an external process is important for a long-running bot. We do not want every test run to leave another chess engine process running in the background.

The Role of engine.py

At this point, the purpose of engine.py should be clear. It is not another chess engine. It is an adapter between an existing UCI chess engine and our PlayOK client.

The UCI engine operates in the language of chess software: positions and UCI moves. PlayOK operates in the language of its WebSocket protocol: tables, commands, and compact encoded move integers.

engine.py sits between those two worlds. It maintains the chess position, sends the position to the engine, receives the engine's move, converts the move's square numbering, packs the source and target into the PlayOK integer format, and returns that value to the PlayOK client.

Once this conversion is understood, the seemingly mysterious number inside a PlayOK WebSocket message is no longer mysterious. It is simply two six-bit square indexes packed into an integer, with the square indexes transformed by flipping the board's rank numbering. That understanding will allow us to build the PlayOK client around the engine rather than trying to make the engine itself understand the PlayOK protocol.

Keep the Engine Independent

The chess engine should know how to play chess, not how PlayOK works. Our Python engine wrapper is the adapter between those worlds: it maintains the chess position, communicates with the UCI engine, and converts the resulting move into the representation required by PlayOK.