-
Notifications
You must be signed in to change notification settings - Fork 27
/
communication.py
83 lines (66 loc) · 1.89 KB
/
communication.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import sys
import chess
import argparse
from movegeneration import next_move
def talk():
"""
The main input/output loop.
This implements a slice of the UCI protocol.
"""
board = chess.Board()
depth = get_depth()
while True:
msg = input()
command(depth, board, msg)
def command(depth: int, board: chess.Board, msg: str):
"""
Accept UCI commands and respond.
The board state is also updated.
"""
msg = msg.strip()
tokens = msg.split(" ")
while "" in tokens:
tokens.remove("")
if msg == "quit":
sys.exit()
if msg == "uci":
print("id name Andoma") # Andrew/Roma -> And/oma
print("id author Andrew Healey & Roma Parramore")
print("uciok")
return
if msg == "isready":
print("readyok")
return
if msg == "ucinewgame":
return
if msg.startswith("position"):
if len(tokens) < 2:
return
# Set starting position
if tokens[1] == "startpos":
board.reset()
moves_start = 2
elif tokens[1] == "fen":
fen = " ".join(tokens[2:8])
board.set_fen(fen)
moves_start = 8
else:
return
# Apply moves
if len(tokens) <= moves_start or tokens[moves_start] != "moves":
return
for move in tokens[(moves_start+1):]:
board.push_uci(move)
if msg == "d":
# Non-standard command, but supported by Stockfish and helps debugging
print(board)
print(board.fen())
if msg[0:2] == "go":
_move = next_move(depth, board)
print(f"bestmove {_move}")
return
def get_depth() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--depth", default=3, help="provide an integer (default: 3)")
args = parser.parse_args()
return max([1, int(args.depth)])