Sending Moves and Commands
In the previous chapter we built the receiving side of the bot. We can now listen to PlayOK, identify tables, track players, load positions, and detect when the opponent makes a move. The missing half is sending information back. In this chapter we build the small command layer that turns our engine's decisions and user actions into PlayOK WebSocket messages.
Two Different Kinds of Outgoing Messages
From PlayOK's point of view, there is not really a separate category called “chess moves”. A move is another variation of a PlayOK command, with additional parameters containing the encoded chess move.
Technically, both a table action such as joining a table and a chess move are the same kind of thing: an outgoing PlayOK action represented by an i array. The difference is that a move requires additional parameters describing the game and the encoded move itself.
For example, joining a table can be represented as:
{"i": [JOIN_TABLE, table]}
while sending a chess move uses the same basic command mechanism with additional parameters:
{"i": [LOAD_MOVE, table, 1, move, 1]}
So, technically, send_move() is simply a specialized PlayOK command. Mentally, however, I still separate the two in our Python code because it makes the rest of the application easier to understand. send_command() handles general table and game actions, while send_move() handles the special case of an engine-generated chess move.
This distinction is about keeping our code clean, not about claiming that PlayOK has two fundamentally different outgoing protocols. Underneath, they are all PlayOK actions sent through the same WebSocket.
send_move()
send_command(action, table)
send_move() is responsible only for chess moves. send_command() is responsible only for table and game actions.
Sending an Engine Move
The entire engine-move method is surprisingly small:
def send_move(self):
move = self.engine.search()
self.send_message({"i": [LOAD_MOVE, self.active_table, 1, move, 1]})
The important part is that the complexity has already been handled by the engine layer. self.engine.search() asks the UCI engine for its best move and converts that move into the integer representation we discovered earlier.
By the time send_move() receives the result, it does not need to know anything about UCI notation, python-chess square numbering, or the XOR transformation. The engine module has already converted the move into the PlayOK representation.
The only remaining job is to put that integer into the correct PlayOK message.
The PlayOK Move Message
The outgoing message has this structure:
{
"i": [LOAD_MOVE, self.active_table, 1, move, 1]
}
The values have different roles. LOAD_MOVE identifies the PlayOK operation, self.active_table identifies the table, and move is the encoded chess move produced by our engine.
The remaining values are part of the message format required by PlayOK. We do not need to reinterpret them every time we send a move. We discovered the structure by observing what the browser sends, and our client reproduces that structure.
This is one of the main lessons of reverse engineering: once we understand a message format, we can hide its protocol-specific details behind a small function. The rest of the application can simply call send_move().
The Engine-to-Server Bridge
It is useful to look at the complete path of a move:
PlayOK
│
│ opponent move
▼
receive_messages()
│
▼
engine.load_move()
│
▼
engine.search()
│
▼
PlayOK move integer
│
▼
send_move()
│
▼
WebSocket
│
▼
PlayOK
The UCI engine never needs to know that PlayOK exists. PlayOK never needs to know how the engine calculated its move. The bridge between them is responsible for translating between the two protocols.
Commands Are Different from Moves
Chess moves are only one part of the interaction. Our bot also needs to perform table actions.
During the receive loop we already used commands such as:
self.send_command("join", table)
self.send_command("leave", table)
self.send_command("white_on", table)
self.send_command("black_on", table)
self.send_command("start", table)
Instead of constructing a different JSON object every time we need one of these actions, we use a single method and give it a human-readable action name.
def send_command(self, action, table):
This is a small abstraction, but it makes a big difference to the rest of the code. The receive loop can describe what it wants to do rather than how PlayOK encodes that action.
One Command Template
We begin with an empty request:
request = {"i": [], "s": []}
The command method then fills in the i array according to the requested action. The s array remains empty for these commands.
Instead of duplicating WebSocket code for every action, we have one place where all of the PlayOK command encodings live.
Joining a Table
The first command is joining a table:
if action == "join":
request["i"] = [JOIN_TABLE, table]
The caller does not need to know the numeric value of JOIN_TABLE. That value is defined in config.py, where we keep the protocol constants.
So the application thinks in terms of:
self.send_command("join", table)
while the protocol layer produces the encoded message:
{"i": [JOIN_TABLE, table], "s": []}
This separation keeps the reverse-engineered protocol details out of the higher-level game logic.
Leaving a Table
Leaving works in exactly the same way:
elif action == "leave":
request["i"] = [LEAVE_TABLE, table]
Again, the receive loop only needs to say that it wants to leave. It does not need to construct the PlayOK packet itself.
Taking a Side
PlayOK uses another command for taking a seat on the board. White and Black are represented by different values.
elif action == "white_on":
request["i"] = [TAKE_SIDE, table, 0]
elif action == "black_on":
request["i"] = [TAKE_SIDE, table, 1]
Although not being explicitly used, there are also corresponding commands for leaving a particular side in case if you need some debugging:
elif action == "white_off":
request["i"] = [LEAVE_SIDE, table, 0]
elif action == "black_off":
request["i"] = [LEAVE_SIDE, table, 1]
The important point is that the human-readable action name contains the meaning while the numeric protocol representation stays inside send_command().
Starting and Resigning
Starting a game is another simple table command:
elif action == "start":
request["i"] = [START_GAME, table]
Resigning requires additional parameters:
elif action == "resign":
request["i"] = [RESIGN_GAME, table, 4, 0]
This is a good example of why the command abstraction is useful. The rest of the program does not have to remember that resignation requires four values in the i array or what those values mean. It simply calls:
self.send_command("resign", table)
The protocol-specific structure stays in one place.
Sending the Request
Once the appropriate command has been selected, the request is passed to the common WebSocket sending method:
self.send_message(request)
This is another important separation in the design.
send_command() knows how to construct a PlayOK command. send_message() knows how to actually serialize and transmit a message through the WebSocket.
send_command()
│
▼
construct protocol message
│
▼
send_message()
│
▼
JSON serialization
│
▼
WebSocket.send()
Neither method needs to know how the other layer works internally.
The Interesting Part: Updating State Indirectly
There is one particularly deliberate design decision at the end of send_command():
self.send_message(request)
# Track state variables
self.user_status()
At first this may look unnecessary. We have just sent a command, so why immediately send another request?
The reason is that send_command() does not directly modify any of our table-state variables. Instead, after performing the action, it asks PlayOK to report the user's current table state. The response comes back through the normal receive loop and updates active_table there.
This gives us a very clean separation:
send_command()
│
├── send the requested action
│
└── request current user state
│
▼
PlayOK response
│
▼
receive_messages()
│
▼
update state
We deliberately do not do something like this inside send_command():
self.active_table = table
That would make our local state an assumption about what happened on the server.
Instead, we let PlayOK tell us what the resulting state actually is. The command says what we want to do. The server response tells us what state we are actually in.
Why This Keeps the Code Clean
This distinction becomes especially useful when commands can fail or produce a state different from what we expected.
For example, suppose we send a command to join a table. Rather than immediately assuming that we are now sitting there, we wait for the server's response. The same mechanism works after leaving a table, joining a side, or performing another action that changes the user's table state.
Our receive loop therefore remains the single place responsible for interpreting PlayOK state.
Commands
│
▼
What we ask PlayOK to do
│
▼
WebSocket
│
▼
What PlayOK says happened
│
▼
Receive loop
│
▼
Our actual state
This is much cleaner than having different methods independently modify active_table, player_white, player_black, and other state variables.
Commands Describe Actions, Not State
This leads to a useful architectural rule for the whole client:
Outgoing commands describe actions. Incoming messages establish state.
When we call send_command("join", table), we are saying, “ask PlayOK to join this table.” We are not saying, “the bot is now definitely on this table.”
When PlayOK later sends the user information response, receive_messages() interprets that response and updates active_table.
This distinction prevents the client from confusing an attempted action with the result of that action.
Why user_status() Belongs Here
Putting user_status() at the end of send_command() also means every command automatically refreshes our table state.
We do not need to remember to write this after every individual action:
send_command("join", table)
user_status()
send_command("leave", table)
user_status()
send_command("start", table)
user_status()
Instead, the command method handles it consistently:
send_command("join", table)
Internally, that becomes:
construct command
↓
send command
↓
request current user state
This is exactly the kind of small abstraction that makes a reverse-engineered client manageable. Once we discover a protocol pattern that should happen every time, we encode that pattern in one function rather than relying on ourselves to remember it everywhere else.
The Complete Command Layer
The finished method is compact because all the protocol details have been concentrated into one place:
def send_command(self, action, table):
request = {"i": [], "s": []}
if action == "join": request["i"] = [JOIN_TABLE, table]
elif action == "leave": request["i"] = [LEAVE_TABLE, table]
elif action == "white_on": request["i"] = [TAKE_SIDE, table, 0]
elif action == "white_off": request["i"] = [LEAVE_SIDE, table, 0]
elif action == "black_on": request["i"] = [TAKE_SIDE, table, 1]
elif action == "black_off": request["i"] = [LEAVE_SIDE, table, 1]
elif action == "start": request["i"] = [START_GAME, table]
elif action == "resign": request["i"] = [RESIGN_GAME, table, 4, 0]
self.send_message(request)
self.user_status()
Notice how little WebSocket code exists here. There is no connection management, no JSON serialization, and no state interpretation. Those responsibilities belong to other methods.
The Architecture So Far
We now have three distinct layers working together:
PlayOK WebSocket
▲ │
│ ▼
send_message() recv()
▲ │
│ ▼
┌────────────┐ receive_messages()
│ Commands │ │
│ │ ▼
│ send_move │ PlayOK state
│send_command│ │
└──────┬─────┘ ▼
│ ChessEngine
│ │
└──────────────┘
The ChessEngine handles chess. The receive loop interprets server events and maintains state. The command methods translate our desired actions into PlayOK's protocol. Finally, send_message() provides the common transport layer.
From UCI Move to PlayOK Move
We can now follow an entire engine move from the moment the opponent moves:
- PlayOK sends a
LOAD_MOVEmessage. receive_messages()receives it.- The SAN move is loaded into the local
python-chessboard. - The receive loop detects that the move belongs to the opponent.
send_move()callsself.engine.search().- The engine produces a move and the engine layer converts it to the PlayOK integer representation.
send_move()places that integer into aLOAD_MOVErequest.send_message()serializes the request and sends it through the WebSocket.- PlayOK receives the move and updates the game.
That is the complete UCI-to-WebSocket bridge.
The Important Design Principle
At this point, the individual methods are small, but together they form a very deliberate architecture.
The engine does not know about WebSockets. The WebSocket transport does not know about chess. The command layer does not directly maintain server state. The receive loop does not construct every outgoing packet itself.
Each part has one job:
ChessEngine
│
└── chess position and engine moves
receive_messages()
│
└── interpret PlayOK events and update state
send_move()
│
└── send an engine-generated chess move
send_command()
│
└── translate user actions into PlayOK commands
send_message()
│
└── serialize and transmit WebSocket messages
This separation is especially valuable in a reverse-engineering project because our understanding of the protocol will continue to evolve. If we discover that a command uses a different field or parameter, we can change the command mapping without rewriting the rest of the bot.
We Are No Longer Reproducing the Browser Blindly
The goal of reverse engineering was never to copy the entire PlayOK browser client. The browser contains a huge amount of functionality that our engine does not need.
Instead, we observed what the browser does, identified the messages that matter to chess, and reproduced only the subset required by our bot.
Our client can now perform the essential actions:
- connect to PlayOK;
- keep the connection alive;
- discover tables;
- join and leave tables;
- take White or Black;
- start a game;
- receive the current position;
- receive opponent moves;
- generate engine moves;
- send those moves back to PlayOK.
That is enough to turn a UCI chess engine that knows nothing about PlayOK into an automated online player.
The Protocol Is Now Becoming an API
One of the most satisfying parts of this process is seeing the reverse-engineered protocol disappear behind our own interface.
At the beginning, we saw messages such as:
{"i":[72,301],"s":[]}
Without context, this is just a collection of numbers. After reverse engineering, the same message can be represented in our code as:
self.send_command("join", table)
Likewise, instead of thinking about the exact integer representation of a chess move every time we play, the rest of the application can simply call:
self.send_move()
This is the point where reverse engineering becomes software engineering. We have discovered the protocol, and now we are wrapping it in a clean interface that our own program can use.
Our command layer translates readable actions such as join, leave, and start into PlayOK's numeric protocol. The rest of the application does not need to know those numbers. This keeps the reverse-engineered protocol details in one place.
Next Step
We now have both directions of communication working conceptually: PlayOK can send events to our client, and our client can send commands and engine moves back.
The next step is to put everything together into the main application. We need a small console interface that starts the client, connects it to PlayOK, keeps the program running, and gives us a way to control the bot from the terminal.
Once that is in place, we will have the complete application: configuration, UCI engine, WebSocket connection, message processing, command handling, and the bridge that allows ABC to play chess through PlayOK.