-
Notifications
You must be signed in to change notification settings - Fork 0
/
play_kothserver.py
125 lines (100 loc) · 2.62 KB
/
play_kothserver.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
from http import server
import json
import websocket
import asyncio
import random
import rel
from chesscpp import bestmove
from chesspy.game import import_fen
playerId = 467309
# playerId = 467309
gameId = 68852
username = "chessua_bengio"
server_host = 'ws://koth.df1ash.de:8026'
def on_message(ws, message):
print(message)
data = json.loads(message)
if(data["type"] == 0):
# create_game(ws)
get_games(ws)
# join(ws)
if(data["type"] == 1):
games = data["games"]
game = next((x for x in games if x["ID"] == gameId), None)
print("###########")
print(game)
move(ws, game["fen"])
if(data["type"] == 8):
move(ws, data["fen"])
if(data["type"] == 4):
move(ws, data["fen"])
if(data["type"] == 3):
global gameId
gameId = data["ID"]
move(ws, data["fen"])
def on_error(ws, error):
print(error)
def on_close(ws, close_status_code, close_msg):
print("### closed ###")
def on_open(ws):
print("Opened connection")
# login
ws.send(json.dumps({
"type": 0,
"username": username,
"playerID": playerId
}))
# join
# join(ws)
def join(ws):
print("Joining game")
ws.send(json.dumps({
"type": 3,
"username": username,
"playerID": playerId,
"joinAsPlayer": 1,
"gameID": gameId
}))
def move(ws, fen):
board = import_fen(fen)
en_passant = board.en_passant_tile if len(board.en_passant_tile) > 0 else []
move, _ = bestmove(
120.0,
10,
board.board_state,
board.to_move,
en_passant,
*board.can_castle,
board.n_reversible_halfmoves,
board.n_moves
)
ws.send(json.dumps({
"type": 4,
"playerID": playerId,
"username": username,
"gameID": gameId,
"move": move,
}))
print("picked best move: " + move)
def create_game(ws):
print("Creating game")
ws.send(json.dumps({
"type": 2,
"playerID": playerId,
"username": username,
}))
def get_games(ws):
print("Fetching games")
ws.send(json.dumps({
"type": 1,
}))
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp(server_host,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever(dispatcher=rel) # Set dispatcher to automatic reconnection
rel.signal(2, rel.abort) # Keyboard Interrupt
rel.dispatch()