Chapter 8

The Main Driver

At this point, the individual pieces of the bot are in place. We have configuration, a UCI engine, a PlayOK WebSocket client, a receive loop, and methods for sending moves and commands. We still need something to bring all of those pieces together. That is the job of main.py.

The Main Program

The main driver is intentionally small. It creates the PlayOK client, connects to the server, and then waits for commands from the console while the background WebSocket threads handle the actual PlayOK session.

# Packages
from playok import PlayOK
import json
from config import *

# Connect to PlayOK
playok = PlayOK()
playok.connect()

There is not much code here because most of the complexity has already been moved into the appropriate modules. main.py is not responsible for understanding the WebSocket protocol or playing chess. It simply controls the lifetime of the application.

Keep the Driver Small

The main driver should coordinate the application rather than contain its internal logic. If main.py starts becoming responsible for WebSocket messages, chess calculations, or PlayOK state, that is usually a sign that some responsibility belongs in another module.

Creating the PlayOK Client

The first line creates our client object:

playok = PlayOK()

The constructor initializes the WebSocket state, PlayOK state, and chess engine that we built in the previous chapters.

We then establish the connection:

playok.connect()

Once connect() succeeds, the PlayOK object starts its background threads. One thread keeps the connection alive and periodically requests user state. The other continuously receives and processes messages from PlayOK.

This means the main thread does not need to sit there waiting for WebSocket messages. That work is already happening independently.

The Main Loop

After connecting, the main program enters a simple loop:

while playok.running:
    message = input()

The condition is tied directly to the client's running state. As long as the PlayOK session is active, the console remains available for commands.

This gives us three separate execution paths:

                 main.py
                    │
                    ▼
             console input
                    │
          ┌─────────┴─────────┐
          ▼                   ▼
     user commands       PlayOK client
                              │
                    ┌─────────┴─────────┐
                    ▼                   ▼
              keep-alive            receive
                 thread              thread

The main thread handles human interaction while the background threads handle the live PlayOK session.

Why Use Console Commands?

The console is not meant to be a replacement for the PlayOK interface. It is simply a convenient control panel while we are developing and testing the bot.

Because the browser interface has been replaced by our own Python client, we need some way to inspect what the client believes is happening. A few simple commands give us exactly that without having to build another graphical interface.

Quitting the Session

The first command we handle is quit.

if message.lower() == "quit":
    playok.close()
    continue

The important detail here is that we do not simply break out of the loop. We call playok.close() so that the client can shut down its resources properly.

The close() method stops the running state, closes the WebSocket, and terminates the chess engine. Once running becomes false, the main loop naturally terminates.

running = True
    │
    ▼
while running
    │
    ├── user commands
    ├── WebSocket receive
    └── keep-alive
    │
    ▼
close()
    │
    ▼
running = False
    │
    ▼
main loop exits

This gives the application one central lifecycle flag that all of its threads can observe.

Resigning a Game

The next command is resign:

elif message == "resign":
    playok.send_command(message, playok.active_table)
    continue

This is a nice example of why we created send_command() in the previous chapter. The main driver does not need to know the numeric PlayOK command for resignation or the parameters it requires.

It simply passes the human-readable action and the current table:

playok.send_command("resign", playok.active_table)

The PlayOK client takes care of converting that into the correct WebSocket message and then requesting the latest user state.

Use the Same Interface Everywhere

The console should use the same command methods as the automated parts of the client. Whether a command originates from the human at the keyboard or from the receive loop, the PlayOK protocol should still be handled in one place.

Inspecting the Session

The info command gives us a snapshot of the internal PlayOK state:

elif message == "info":
    print("running:", playok.running)
    print("active table:", playok.active_table)
    print("player white:", playok.player_white)
    print("player black:", playok.player_black)
    print("active game:", "Idle" if playok.active_game == NONE else "Play")
    print("engine side:", "None" if playok.engine_side == NONE else "White" if playok.engine_side == WHITE else "Black")
    print("first move:", "No" if playok.first_move == NONE else "Played")
    continue

This command is particularly useful while reverse engineering because the server's messages are being translated into our own state variables. We can therefore compare what PlayOK is sending with what our client thinks those messages mean.

The information displayed includes:

These values represent the internal state we built throughout the previous chapters.

Inspecting the Chess Board

The board command gives us another useful debugging tool:

elif message == "board":
    print(playok.engine.board)
    continue

This prints the current python-chess board maintained by our engine wrapper.

This is extremely useful when debugging synchronization. We can watch the moves arriving from PlayOK and then inspect the local board to verify that our engine has reconstructed the same position.

PlayOK game
     │
     │ opponent move
     ▼
receive_messages()
     │
     ▼
engine.load_move()
     │
     ▼
python-chess board
     │
     ▼
board command
     │
     ▼
  console

If the printed position is wrong, we know that the problem is somewhere in the path between the PlayOK move message and engine.load_move(). This is much easier to debug than trying to reason about the entire application at once.

The Main Driver Is Mostly Glue

Notice what main.py does not contain.

It does not parse incoming WebSocket messages. It does not determine which tables are available. It does not decode PlayOK move integers. It does not maintain the chess board. It does not communicate with the UCI engine directly.

All of those responsibilities already belong to the modules we created earlier.

config.py
    │
    └── constants and configuration

engine.py
    │
    └── chess board and UCI engine

playok.py
    │
    ├── WebSocket
    ├── PlayOK state
    ├── receive loop
    ├── commands
    └── engine integration

main.py
    │
    └── application control and console

This is exactly what we want. The main driver is the glue connecting the components, not another place where protocol logic accumulates.

Human Control and Automation Can Coexist

There is also something useful about this design from a debugging perspective. The bot is already automated, but we retain a small amount of manual control.

The background threads can automatically join a table, start a game, receive moves, search with the engine, and send responses. At the same time, we can type info or board into the console and inspect what the bot is doing.

This gives us a practical development loop:

Bot runs
   │
   ▼
PlayOK sends events
   │
   ▼
Bot updates state
   │
   ├── automatic actions
   │
   └── manual inspection
          │
          ├── info
          └── board

During development, this is much more useful than immediately building a completely unattended program with no visibility into its internal state.

Why the Console Is Enough

For this project we do not need a graphical interface. PlayOK already provides the visual chess interface for human users, but our Python program only needs to communicate with the server.

The console therefore becomes a lightweight control surface for the client. The actual chess-playing logic happens in the background.

This is also consistent with the goal of the project. We are not trying to recreate PlayOK's entire browser interface. We are extracting the protocol behavior necessary to connect our own chess engine to it.

The Complete Application

With main.py added, the architecture of the project is now complete:

                         main.py
                            │
                     console commands
                            │
                            ▼
                       playok.py
                  ┌─────────┼─────────┐
                  │         │         │
                  ▼         ▼         ▼
              WebSocket  PlayOK    ChessEngine
                  │       state         │
                  │                     ▼
                  │                  engine.py
                  │                     │
                  │                     ▼
                  │                  ABC / UCI
                  │
                  ▼
               PlayOK

The direction of information is now clear.

PlayOK sends events into playok.py. The PlayOK client interprets those events and updates its state. When the opponent moves, the engine receives the updated position and searches for a response. The resulting move is converted into PlayOK's representation and sent back through the same WebSocket.

Meanwhile, main.py remains available for manual inspection and control.

From Browser Behavior to Our Own Program

When we started this project, PlayOK's WebSocket traffic was just a stream of JSON messages containing numbers and strings. We did not have an API designed for our engine. We had to discover what the browser was doing and determine which parts were actually necessary.

Now we have replaced the relevant browser behavior with our own program:

Browser behavior
       │
       │ reverse engineer
       ▼
PlayOK protocol
       │
       │ implement
       ▼
Python client
       │
       ├── receive events
       ├── maintain state
       ├── send commands
       └── send chess moves
       │
       ▼
UCI engine ABC

The browser is no longer required for the chess-playing logic. Our Python program has become the client.

The Browser Was Our Specification

We did not receive a formal PlayOK protocol specification. The browser itself became our specification. By observing what it sent and how it reacted to server messages, we reconstructed the subset of the protocol required by our bot.

One More Look at the Driver

The final driver remains remarkably small:

from playok import PlayOK
import json
from config import *

playok = PlayOK()
playok.connect()

while playok.running:
    message = input()

    if message.lower() == "quit":
        playok.close()
        continue

    elif message == "resign":
        playok.send_command(message, playok.active_table)
        continue

    elif message == "info":
        print("running:", playok.running)
        print("active table:", playok.active_table)
        print("player white:", playok.player_white)
        print("player black:", playok.player_black)
        print("active game:", "Idle" if playok.active_game == NONE else "Play")
        print("engine side:", "None" if playok.engine_side == NONE else "White" if playok.engine_side == WHITE else "Black")
        print("first move:", "No" if playok.first_move == NONE else "Played")
        continue

    elif message == "board":
        print(playok.engine.board)
        continue

That small amount of code starts an application containing a WebSocket client, a chess engine, a protocol implementation, background threads, state tracking, and an automated game-playing loop.

Most importantly, the complexity is no longer concentrated in one giant script. We have separated the responsibilities so that each part can be understood independently.

What We Have Built

At this point, the complete bridge exists:

The final result is not a browser automation script. It is a custom client that communicates directly with the server using the protocol we reverse engineered from the browser.

That is the real goal of this project: not to imitate clicks, but to understand what the browser is communicating and reproduce the useful parts ourselves.