-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgameplayer
executable file
·436 lines (369 loc) · 14.5 KB
/
gameplayer
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#!/usr/bin/env python
from threading import Thread
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from ggp.kif import *
from ggp.gd import GameDescription
from ggp.sim import CachedSimulator
from ggp.heuristic import ConstantHeuristic
from ggp.search import Search
import time
import sys
import os
import string
import traceback
import random
import signal
class TimeoutFunctionException(Exception):
"""Exception to raise on a timeout"""
pass
class TimeoutFunction:
def __init__(self, function, timeout):
self.timeout = int(timeout)
self.function = function
if self.timeout == 0:
raise TimeoutFunctionException()
def handle_timeout(self, signum, frame):
raise TimeoutFunctionException()
def __call__(self, *args):
old = signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.timeout)
try:
result = self.function(*args)
finally:
signal.signal(signal.SIGALRM, old)
signal.alarm(0)
return result
class PoliteThread(Thread):
def __init__(self, func):
Thread.__init__(self)
self.stop = False
self.func = func
def requestStop(self):
self.stop = True
def stopRequested(self):
return self.stop
def run(self):
self.func()
class GamePlayer(HTTPServer):
class GPHandler(BaseHTTPRequestHandler):
def do_POST(self):
try:
self.server.lastMsgTime = time.time()
length = int(self.headers['content-length'])
text = self.rfile.read(length)
msg = self.server.parser.parse('Message', text)
print('Received ' + str(msg.msgType) + ' message of length: ' + str(length))
self.server.handler = self
self.server.processMessage(msg)
self.server.logMessage(msg)
except Exception, e:
sys.stderr.write('Error in incoming message: ' + str(e) + '\n')
traceback.print_exc()
return
try:
self.server.act()
except KeyboardInterrupt:
raise
except:
sys.stderr.write('Error in GamePlayer.act():\n')
traceback.print_exc()
def log_message(self, format, *args):
pass # suppress logging messages to stderr
def send(self, text):
self.send_response(200, 'OK')
self.send_header('Content-type', 'text/acl')
self.send_header('Content-length', str(len(text)))
self.end_headers()
self.wfile.write(string.upper(text))
def __init__(self, name, port, logging):
HTTPServer.__init__(self, ('', port), self.GPHandler)
self.name = name
self.logging = logging
self.matchID = None
self.sim = None
self.messageLog = None
self.playerLog = None
self.msgLogID = None
self.plyLogID = None
self.buffer = 1.0
self.parser = KIFParser()
self.prologParse = PrologParser()
self.logDir = os.path.join('log', time.strftime('%Y%m%d%H%M%S')+'_'+str(port))
if logging:
os.makedirs(self.logDir)
def handle_error(self, request, client_address):
try:
raise
except:
traceback.print_exc()
def logMessage(self, msg):
if self.logging:
if self.matchID != self.msgLogID:
self.msgLogID = self.matchID
filename = self.logDir + '/' + str(self.matchID) + '.msg'
try:
if self.messageLog:
self.messageLog.close()
self.messageLog = open(filename, 'w')
except Exception:
sys.stderr.write('Error: Cannot create message log: ' + \
filename + '\n')
self.messageLog = None
if self.messageLog:
try:
self.messageLog.write(str(msg) + '\n')
self.messageLog.flush()
except Exception:
sys.stderr.write('Error: Cannot write to message log\n')
self.messageLog.close()
self.messageLog = None
def logPrint(self, obj):
if self.logging:
if self.matchID != self.plyLogID:
self.plyLogID = self.matchID
filename = self.logDir + '/' + str(self.matchID) + '.ply'
try:
if self.playerLog:
self.playerLog.close()
self.playerLog = open(filename, 'w')
except Exception:
sys.stderr.write('Error: Cannot create player log: ' + \
filename + '\n')
self.playerLog = None
if self.playerLog:
try:
self.playerLog.write(str(obj) + '\n')
# do not flush right away. wait until send
except Exception:
sys.stderr.write('Error: Cannot write to player log\n')
self.playerLog.close()
self.playerLog = None
def saveGameDescription(self, sents):
try:
outFile = open(self.logDir + '/' + str(self.matchID) + '.kif', 'w')
for s in sents:
outFile.write(str(s) + '\n')
except Exception, e:
sys.stderr.write('Unable to save game description: ' + str(e) + '\n')
def processMessage(self, msg):
if msg.msgType == 'start':
self.processStartMessage(msg)
elif msg.msgType == 'play':
self.processPlayMessage(msg)
elif msg.msgType == 'replay':
self.processReplayMessage(msg)
elif msg.msgType == 'stop':
self.processStopMessage(msg)
else:
raise Exception('Unknown message type: ' + str(msg.msgType))
def processStartMessage(self, msg):
# Make sure Match ID is new
if msg.matchID == self.matchID:
raise Exception('Start message contains old match id: ' + \
str(self.matchID))
self.matchID = msg.matchID
# Store clocks
self.startClock = msg.startClock
self.playClock = msg.playClock
# Process new game description
self.gd = GameDescription();
self.gd.processKIF(msg.sents)
if self.logging:
self.saveGameDescription(msg.sents)
# Get role
self.role = self.gd.roleIndex(msg.role)
# Create a new cached simulator
if self.sim:
self.sim.cleanup()
self.sim = CachedSimulator(self.gd)
# Reset "state" to this game description's initial state
self.state = self.gd.initialState
self.status = 'init'
def processPlayMessage(self, msg):
# Make sure we're still in the same game
if msg.matchID != self.matchID:
raise Exception('Error: Match id in message: ' + str(msg.matchID) + \
' does not match current id: ' + str(self.matchID))
# Extract and convert the last moves
self.lastMoves = None
if msg.lastMoves:
self.lastMoves = [self.gd.moveIndex(x) for x in msg.lastMoves]
# If the set of last moves is empty, then this is the
# initial state. Otherwise, we need to advance to the
# next state
if self.lastMoves:
self.state = self.sim.computeNextState(self.state, self.lastMoves)
self.status = 'play'
def processReplayMessage(self, msg):
# Make sure we're still in the same game
if msg.matchID != self.matchID:
raise Exception('Error: Match id in message: ' + str(msg.matchID) + \
' does not match current id: ' + str(self.matchID))
self.status = 'play'
def processStopMessage(self, msg):
# Make sure we're still in the same game
if msg.matchID != self.matchID:
raise Exception('Error: Match id in message: ' + str(msg.matchID) + \
' does not match current id: ' + str(self.matchID))
# Extract and convert the last moves
lastMoves = [self.gd.moveIndex(x) for x in msg.lastMoves]
# Advance to final state
self.state = self.sim.computeNextState(self.state, lastMoves)
# If the final state isn't terminal according to us, then
# there is some kind of problem
if not self.sim.isTerminal(self.state):
raise Exception('Error: Got stop message in non-terminal state')
self.status = 'done'
def recover(self, msgFile):
try:
text = open(msgFile, 'r').read()
lst = self.parser.parse('Messages', text)
for msg in lst:
self.processMessage(msg)
self.logMessage(msg)
except Exception, e:
raise Exception('Error in recovery: ' + str(e))
def updateReplyTime(self, clock):
self.replyTime = self.lastMsgTime + clock
def safeTimeLeft(self):
return self.replyTime - time.time() - self.buffer
def outOfTime(self):
return self.safeTimeLeft() <= 0
def response(self):
return str(self.gd.moveTerm(self.selectedMove))
def send(self, text):
self.handler.send(text)
print('Sent: ' + text)
self.logPrint('Sent: ' + text)
spareTime = self.replyTime - time.time()
self.logPrint('Spare time: ' + str(spareTime))
if spareTime < 0:
print '*** Negative Spare Time:', spareTime
self.buffer = max((self.buffer, min((abs(spareTime)+5, 0.25 * self.playClock))))
print '*** Adjusting spare time to:', self.buffer
self.logPrint('Adjusting spare time to: ' + str(self.buffer))
self.logPrint('---------------------------------------------------')
if self.playerLog:
self.playerLog.flush()
def act(self):
if self.status == 'init':
self.doInit()
elif self.status == 'play':
self.doPlay()
elif self.status == 'done':
self.doDone()
else:
raise Exception('Unknown status: ' + str(self.status))
def doInit(self):
self.updateReplyTime(self.startClock)
self.buffer = 1.0 # Reset time buffer before match
timeToInit = self.safeTimeLeft()
self.logPrint('Time to init: ' + str(timeToInit))
self.logPrint('Initial State:')
for index in self.state:
self.logPrint(self.gd.stateTerm(index))
# Choose strategy
self.heuristic = ConstantHeuristic(self.gd.averageReward())
self.search = Search(self.gd, self.sim, self.role, self.outOfTime, self.processResponse)
try:
warmupTimeout = TimeoutFunction(self.warmup, self.safeTimeLeft())
timeOut = False
try:
warmupTimeout()
except TimeoutFunctionException:
timeOut = True
finally:
self.send('ready')
def doPlay(self):
self.updateReplyTime(self.playClock)
self.logPrint('Last Moves:')
if self.lastMoves == None:
self.logPrint('None')
else:
self.logPrint([str(self.gd.moveTerm(idx)) for idx in self.lastMoves])
self.logPrint('State:')
for index in self.state:
self.logPrint(self.gd.stateTerm(index))
timeToAct = self.safeTimeLeft()
self.logPrint('Time to act: ' + str(timeToAct))
self.logPrint('Select Move:')
legal = self.sim.computeLegalMoves(self.state)[self.role]
self.selectedMove = random.choice(legal)
try:
selectMoveTimeout = TimeoutFunction(self.selectMove, self.safeTimeLeft())
timeOut = False
maxOpp = -1
try:
selectMoveTimeout(maxOpp)
except TimeoutFunctionException:
timeOut = True
finally:
self.send(self.response())
def doDone(self):
self.updateReplyTime(float('inf'))
self.logPrint('Last Moves:')
if self.lastMoves == None:
self.logPrint('None')
else:
self.logPrint([str(self.gd.moveTerm(idx)) for idx in self.lastMoves])
self.logPrint('State:')
for index in self.state:
self.logPrint(self.gd.stateTerm(index))
goals = self.sim.computeGoals(self.state)
self.logPrint('Goals: ' + str(goals))
print('Goal: ' + str(goals[self.role]))
self.send('done')
def processResponse(self, sr):
self.logPrint('Got response: ' + str(sr))
self.selectedMove = sr.bestMove
def warmup(self):
"""
Warm-up procedure. Put code here to
run during the init clock before the
match begins.
"""
pass
def selectMove(self, maxOpp):
"""
Move selection. Put code here to
run during the play clock while the
match is proceeding.
"""
self.search.search(self.state, self.heuristic, maxOppMoves = maxOpp)
from optparse import OptionParser
DEFAULT_NAME = 'TestPlayer'
DEFAULT_PORT = 5600
DEFAULT_LOGGING = True
def main():
parser = OptionParser()
parser.add_option('-n', '--name', dest='name',
help='set name to NAME', metavar='NAME',
default=DEFAULT_NAME)
parser.add_option('-p', '--port', dest='port',
help='set listening port to PORT', metavar='PORT',
default=DEFAULT_PORT)
parser.add_option('-l', '--log', dest='logging',
help='enable logging',
action='store_true', default=DEFAULT_LOGGING)
parser.add_option('-q', '--quiet', dest='logging',
help='disable logging',
action='store_false', default=DEFAULT_LOGGING)
parser.add_option('-r', '--recover', dest='recoverFile',
help='recover from message FILE', metavar='FILE')
(opts, args) = parser.parse_args()
print('Option Name: ' + opts.name)
print('Option Logging: ' + { True: 'on', False: 'off' }[opts.logging])
gp = GamePlayer(opts.name, int(opts.port), opts.logging)
if opts.recoverFile:
print 'GamePlayer recovering from message file: ' + \
str(opts.recoverFile)
gp.recover(opts.recoverFile)
try:
print 'GamePlayer waiting for connection on port ' + \
str(opts.port) + '...'
gp.serve_forever()
except KeyboardInterrupt:
print '^C received. Shutting down player...'
gp.socket.close()
if __name__ == '__main__':
main()