-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.py
More file actions
94 lines (74 loc) · 3.26 KB
/
Copy pathgame.py
File metadata and controls
94 lines (74 loc) · 3.26 KB
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
import threading
from bot import Bot
import sys
from mockclient import MockClient
class Game(threading.Thread):
def __init__(self, client, game_id, fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", **kwargs):
super().__init__(**kwargs)
self.game_id = game_id
self.client = client
#set stream to test stream or lichess stream
#initialize test_mode var to know where to make moves
if (isinstance(client, MockClient)):
self.stream = client.stream()
self.test_mode = True
else: #set stream to lichess game event stream
self.stream = client.bots.stream_game_state(game_id)
self.test_mode = False
#define variable to store which side the bot plays
self.botpieces = "white"
self.current_state = next(self.stream) #stores JSON on all pertinent info to the game on start
if 'id' in self.current_state['black']:
if (self.current_state['black']['id'] == 'whenchess'):
self.botpieces = "black"
#intialize a bot object to pass board state to
self.bot = Bot(self.botpieces, fen)
self.start()
def run(self):
#play the first move if white
if (self.botpieces == "white"):
self.handle_state_change(self.current_state['state'])
#event loop for game state updates
for event in self.stream:
if event['type'] == 'gameState':
game_running = self.handle_state_change(event)
if not (game_running):
sys.exit()
elif event['type'] == 'chatLine':
self.handle_chat_line(event)
#Handle any game state change
#Returns False if game has ended, True if game continues but it is not the bot's turn, and returns the move made if applicable.
def handle_state_change(self, game_state):
if ((game_state['status'] == 'created') or (game_state['status'] == 'started')): #game in progress
#logic here to be implemented on when to accept draws
#if test mode, support inputting an arbitrary position
if (self.test_mode):
gamecont = self.bot.updateboardall(game_state["moves"])
else:
gamecont = self.bot.updateboard(game_state["moves"])
#get a uci string move from bot.py
if (gamecont):
move = self.bot.getmove()
else:
print("draw made")
return False
#make move if it is bot's turn, null move is ignored if not
if (move):
self.makemove(move)
return move
else:
return True
else: #game has ended
print("game end")
return False
def handle_chat_line(self, chat_line):
#ignoring chat for now
pass
#passes uci strings to lichess
def makemove(self, move: str):
if not (self.test_mode):
self.client.bots.make_move(self.game_id, move)
else:
self.client.makemockmove(move)
def getbot(self):
return self.bot