-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgui.py
282 lines (244 loc) · 9.75 KB
/
gui.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#!/usr/bin/env python3
"""
GUI interface for the Avalam game.
Author: Cyrille Dejemeppe <[email protected]>
Copyright (C) 2014, Université catholique de Louvain
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
"""
import signal
import sys
import ssl
import logging
import time
import threading
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer, SimpleSSLWebSocketServer
from optparse import OptionParser
from game import Viewer, Game
import super_agent2
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
CONFIG_MSG = 'CONFIG'
READY_MSG = 'READY'
PLAYMOVE_MSG = 'PLAY'
PAUSE_MSG = 'PAUSE'
NEXT_MSG = 'NEXT'
PREVIOUS_MSG = 'PREVIOUS'
FINISHED_MSG = 'FINISHED'
ACKNOWLEDGEMENT_MSG = 'ACKNOWLEDGEMENT'
ACTIONS_MSG = 'ACTIONS'
HASMOVED_MSG = 'MOVE'
CONFIG_HvH = 'human vs human'
CONFIG_HvA = 'human vs ai'
CONFIG_AvH = 'ai vs human'
CONFIG_AvA = 'ai vs ai'
CONFIG_R = 'replay'
connectedEvent = threading.Event()
acknowledgementEvent = threading.Event()
hasPlayedEvent = threading.Event()
lastActionPlayed = ''
class SimpleMessager(WebSocket):
def giveViewerRef(self, viewer):
self.viewer = viewer
def handleMessage(self):
if self.data is None:
self.data = ''
try:
message = self.data.decode("utf-8").split('\n')
#logging.info("Message received: " + message[0])
if message[0] == READY_MSG:
if message[1] == CONFIG_R:
self.sendTraceStep()
elif message[0] == PAUSE_MSG:
self.server.paused = True
elif message[0] == PLAYMOVE_MSG:
self.server.paused = False
self.sendTraceStep()
elif message[0] == PREVIOUS_MSG:
self.sendPreviousStep()
elif message[0] == NEXT_MSG:
self.sendNextStep()
elif message[0] == ACKNOWLEDGEMENT_MSG:
acknowledgementEvent.set()
elif message[0] == HASMOVED_MSG:
self.hasMoved(message[1:])
hasPlayedEvent.set()
except Exception as n:
logging.error(n)
def update(self, step, action, player):
self.sendMessage(PLAYMOVE_MSG + "\n" + str(player) + "\n" + self.actionToString(action))
self.server.step += 1
def finished(self, steps, winner, reason=""):
self.sendMessage(FINISHED_MSG + "\n" + self.finished_msg())
def handleConnected(self):
logging.info("Web client connected at " + str(self.address))
try:
if self.server.configuration == CONFIG_R:
self.sendMessage(CONFIG_MSG + "\n" + CONFIG_R)
elif self.server.configuration == CONFIG_HvH:
self.sendMessage(CONFIG_MSG + "\n" + CONFIG_HvH)
elif self.server.configuration == CONFIG_HvA:
self.sendMessage(CONFIG_MSG + "\n" + CONFIG_HvA)
elif self.server.configuration == CONFIG_AvH:
self.sendMessage(CONFIG_MSG + "\n" + CONFIG_AvH)
elif self.server.configuration == CONFIG_AvA:
self.sendMessage(CONFIG_MSG + "\n" + CONFIG_AvA)
connectedEvent.set()
except Exception as n:
logging.error(n)
def handleClose(self):
logging.info("Connection with " + str(self.address) + " closed")
def sendPreviousStep(self):
if self.server.step > 0:
self.server.step -= 1
player, action, t = self.server.trace.actions[self.server.step]
i1, j1, i2, j2 = action
formerTowerFrom = self.server.boards[self.server.step].m[i1][j1]
formerTowerTo = self.server.boards[self.server.step].m[i2][j2]
self.sendMessage(PREVIOUS_MSG + "\n" + str(player) + "\n" + self.actionToString(action) + "\n" + str(formerTowerFrom) + " " + str(formerTowerTo))
def sendNextStep(self):
if self.server.step < len(self.server.trace.actions) - 1:
player, action, t = self.server.trace.actions[self.server.step]
self.sendMessage(PLAYMOVE_MSG + "\n" + str(player) + "\n" + self.actionToString(action))
self.server.step += 1
elif self.server.step == len(self.server.trace.actions) - 1:
player, action, t = self.server.trace.actions[self.server.step]
self.server.step += 1
self.sendMessage(PLAYMOVE_MSG + "\n" + str(player) + "\n" + self.actionToString(action) + "\n" + self.finished_msg())
def sendTraceStep(self):
def waitAndResend(waitTime, step):
time.sleep(waitTime)
if not self.server.paused and step == self.server.step:
player, action, t = self.server.trace.actions[self.server.step]
if self.server.step < len(self.server.trace.actions) - 1:
self.sendMessage(PLAYMOVE_MSG + "\n" + str(player) + "\n" + self.actionToString(action))
self.server.step += 1
self.sendTraceStep()
elif self.server.step == len(self.server.trace.actions) - 1:
self.server.step += 1
self.sendMessage(PLAYMOVE_MSG + "\n" + str(player) + "\n" + self.actionToString(action) + "\n" + self.finished_msg())
if self.server.step <= len(self.server.trace.actions) and not self.server.paused:
waitTime = -t / self.server.speed if self.server.speed < 0 else self.server.speed
waitThread = threading.Thread(target=waitAndResend, args=(waitTime, self.server.step))
waitThread.start()
def actionToString(self, action):
fromI, fromJ, toI, toJ = action
return str(self.server.step) + "\n" + str(fromI) + " " + str(fromJ) + "\n" + str(toI) + " " + str(toJ)
def finished_msg(self):
msg = ""
try:
if self.server.trace.winner == 0:
msg += "Draw game\n"
elif self.server.trace.winner > 0:
msg += "Player 1 has won"
else:
msg += "Player 2 has won"
msg += " after " + str(len(self.server.trace.actions)) + " steps.\n"
if self.server.trace.reason:
msg += self.server.trace.reason
except Exception as e:
logging.error(e)
return msg
def play(self, actions, player, step, time_left):
msg = ACTIONS_MSG + "\n"
msg += str(player) + "\n"
msg += str(step) + "\n"
for action in actions:
msg += str(action[0]) + " " + str(action[1]) + " " + str(action[2]) + " " + str(action[3]) + "\n"
self.sendMessage(msg)
def hasMoved(self, msg):
fromPos = (int(msg[0]), int(msg[1]))
toPos = (int(msg[2]), int(msg[3]))
global lastActionPlayed
lastActionPlayed = (int(msg[0]), int(msg[1]), int(msg[2]), int(msg[3]))
class WebViewer(Viewer):
def __init__(self):
self.running = False
self.host_address = ''
self.port = 8500
self.server = SimpleWebSocketServer(self.host_address, self.port, SimpleMessager)
self.game = None
def init_viewer(self, board, game=None):
self.board = board
if not self.game:
self.game = game
self.server.game = self.game
if game:
if type(self.game.agents[0]) == WebViewer and type(self.game.agents[1]) == WebViewer:
self.server.configuration = CONFIG_HvH
elif type(self.game.agents[0]) == WebViewer and type(self.game.agents[1]) != WebViewer:
self.server.configuration = CONFIG_HvA
elif type(self.game.agents[0]) != WebViewer and type(self.game.agents[1]) == WebViewer:
self.server.configuration = CONFIG_AvH
elif type(self.game.agents[0]) != WebViewer and type(self.game.agents[1]) != WebViewer:
self.server.configuration = CONFIG_AvA
else:
self.server.configuration = CONFIG_R
if not connectedEvent.is_set():
self.serverThread = threading.Thread(target=self.server.serveforever)
self.serverThread.start()
connectedEvent.wait()
def run(self):
"""Launch the GUI."""
if self.running:
return
self.running = True
#self.server.serveforever()
def replay(self, trace, speed, show_end=False):
"""Replay a game given its saved trace.
Attributes:
trace -- trace of the game
speed -- speed scale of the replay
show_end -- start with the final state instead of the initial state
"""
self.trace = trace
self.speed = speed
# generate all boards to access them backwards
self.boards = [trace.get_initial_board()]
for step in range(len(trace.actions)):
player, action, t = trace.actions[step]
b = self.boards[-1].clone()
b.play_action(action)
self.boards.append(b)
self.step = 0
self.server.initialize_replay(self.trace, self.speed, self.boards)
self.init_viewer(self.boards[0], None)
def close_sig_handler(signal, frame):
self.server.close()
sys.exit()
def playing(self, step, player):
print("Step", step, "- Player", player, "is playing")
def update(self, step, action, player):
print("Step", step, "- Player", player, "has played", action)
acknowledgementEvent.clear()
self.server.update(step, action, player)
acknowledgementEvent.wait()
def play(self, percepts, player, step, time_left):
try:
hasPlayedEvent.clear()
self.server.play(percepts, player, step, time_left)
hasPlayedEvent.wait()
except EOFError:
exit(1)
try:
return lastActionPlayed
except (ValueError, AssertionError):
pass
def finished(self, steps, winner, reason=""):
if winner == 0:
print("Draw game")
else:
print("Player 1" if winner > 0 else "Player 2", "has won!")
if reason:
print("Reason:", reason)
self.server.initialize_replay(self.game.trace, 1.0, [])
self.server.finished(steps, winner, reason)
signal.signal(signal.SIGINT, close_sig_handler)
signal.signal(signal.SIGTERM, close_sig_handler)
#signal.signal(signal.SIGQUIT, close_sig_handler)