-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgame.py
More file actions
523 lines (413 loc) · 15 KB
/
Copy pathgame.py
File metadata and controls
523 lines (413 loc) · 15 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
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
#2016-07-29
#Developed by XIAO TANG
#tangxiao.dalian@gmail.com
#game.py
#
from util import *
import time, os
import traceback
import sys
######################
# #
######################
class Agent:
"""
An agent must define a getAction method
"""
def __init__(self, prefix=None, index=0):
self.index = index
self.prefix = prefix
def getAction(self, state):
return 0
raiseNotDefined()
class Directions:
"""
Left and right corresponds to four Directions (north, south, east, west)
"""
NORTH = 'North'
SOUTH = 'South'
EAST = 'East'
WEST = 'West'
STOP = 'Stop'
LEFT = {NORTH: WEST,
SOUTH: EAST,
EAST: NORTH,
WEST: SOUTH,
STOP: STOP}
RIGHT = dict([(y,x) for x, y in LEFT.items()])
REVERSE = {NORTH: SOUTH,
SOUTH: WEST,
EAST: WEST,
WEST: EAST,
STOP: STOP}
class Configuration:
"""
A Configuration holds the (x,y) coordinate of a character, along with its traveling direction.
position
direction
"""
def __init__(self, pos):
self.pos = pos
# self.direction = direction
def getPosition(self):
return (self.pos)
def setPosition(self, pos):
self.pos = pos
#def getDirection(self):
# return self.direction
def isInteger(self):
x, y = self.pos
return x == int(x) and y == int(y)
def __eq__(self, other):
if other == None: return False
return (self.pos == other.pos and self.direction == other.direction)
def __hash__(self):
x = hash(self.pos)
y = hash(self.direction)
return hash(x + 13 * y)
def __str__(self):
return "(x,y)="+str(self.pos)
def generateSuccessor(self, pos):
"""
Generate a new Configuration reached by translating the current configuration by the action vector.
This is a low-level call and does not attempt to respect the legality of the movement
Actions are movement vectors.
"""
return Configuration(pos)
class AgentState:
"""
AgentStates hold the state of an agent (configuration, speed, etc)
"""
def __init__(self, startConfiguration, isTarget):
self.start = startConfiguration
self.configuration = startConfiguration
self.isTarget = isTarget
self.numCarrying = 0
self.numReturned = 0
def __str__(self):
if self.isTarget:
return "Target: "+str( self.configuration)
else:
return "Pursuer: "+str(self.configuration)
def __eq__(self, other):
if other == None:
return False
return self.configuration == other.configuration and self.scaredTimer == other.scaredTimer
def __hash__(self):
state = AgentState(self.start, self.isPacman)
state.configuration = self.configuration
state.numCarrying = self.numCarrying
state.numReturned = self.numReturned
return state
def copy(self):
state = AgentState(self.start, self.isTarget)
x, y = self.configuration.getPosition()
#state.configuration = self.configuration
state.configuration = Configuration((x, y))
state.numCarrying = self.numCarrying
state.numReturned = self.numReturned
return state
def getPosition(self):
if self.configuration == None: return None
return self.configuration.getPosition()
def setPosition(self, pos):
self.configuration.setPosition(pos)
#def getDirection(self):
# return self.configuration.getDirection()
class Grid:
"""
A 2-dimensional array of objects backed ny a list of lists.
Data is accessed via grid[x][y] where (x,y) are positions on a Game map with
x horizontal, y vertical and the origin (0, 0) in the bottom left corner
"""
def __init__(self, width, height, initialValue = False):
if initialValue not in [False, True]: raise Exception("Grid can only contain booleans")
self.CELLS_PER_INT = 30
self.width = width
self.height = height
self.data = [[initialValue for y in range(height)] for x in range(self.width)]
def __getitem__(self, i):
return self.data[i]
def __setitem__(self, key, item):
self.data[key] = item
# def __str__
# def __eq__
# def __hash__
def copy(self):
g = Grid(self.width, self.height)
g.data = [x[:] for x in self.data]
return g
# def deepCopy()
# def shallowCopy()
def count(self, item = True):
return sum([x.count(item) for x in self.data])
# def asList
# def packBits
class Actions:
"""
A collection of static methods for manipulating move actions.
"""
_directions = {Directions.NORTH: (0, 1),
Directions.SOUTH: (0, -1),
Directions.EAST: (1, 0),
Directions.WEST: (-1, 0),
Directions.STOP: (0, 0)}
_directionsAsList = _directions.items()
TOLERANCE = .001
def reverseDirection(action):
if action == Directions.NORTH:
return Directions.SOUTH
if action == Directions.SOUTH:
return Directions.NORTH
if action == Directions.EAST:
return Directions.WEST
if action == Directions.WEST:
return Directions.EAST
# stop action
return action
reverseDirection = staticmethod(reverseDirection)
def vectorToDirection(vector):
dx, dy = vector
if dy > 0:
return Directions.NORTH
if dy < 0:
return Directions.SOUTH
if dx > 0:
return Directions.EAST
if dx < 0:
return Directions.WEST
return Directions.STOP
vectorToDirection = staticmethod(vectorToDirection)
def directionToVector(direction, speed = 1.0):
dx, dy = Actions._directions[direction]
return (dx * speed, dy * speed)
directionToVector = staticmethod(directionToVector)
def getPossibleActions(config, speed, obstacles):
possible = []
x, y = config
if not obstacles[int(x + speed)][y]:
possible.append((int(x + speed), y))
if not obstacles[int(x - speed)][y]:
possible.append((int(x - speed), y))
if not obstacles[x][int(y + speed)]:
possible.append((x, int(y + speed)))
if not obstacles[x][int(y - speed)]:
possible.append((x, int(y - speed)))
possible.append((x, y))
return possible
getPossibleActions = staticmethod(getPossibleActions)
def getPossibleNeighborActions(config, speed, obstacles):
possible = []
x, y = config
if not obstacles[int(x + speed)][y]:
possible.append((int(x + speed), y))
if not obstacles[int(x - speed)][y]:
possible.append((int(x - speed), y))
if not obstacles[x][int(y + speed)]:
possible.append((x, int(y + speed)))
if not obstacles[x][int(y - speed)]:
possible.append((x, int(y - speed)))
return possible
getPossibleNeighborActions = staticmethod(getPossibleNeighborActions)
def getPossibleAbstractedNeighbors(position, abstractionMap):
node = abstractionMap.getNodeByPosition(position)
if node is None:
print position, "has no abstracted neighbors"
result = []
for neighbor in node.neighbors:
result.append(neighbor.position)
return result
getPossibleAbstractedNeighbors = staticmethod(getPossibleAbstractedNeighbors)
def getPossibleAbstractedNeighborsByChildPosition(position, abstractionMap):
node = abstractionMap.getNode(position)
result = []
for neighbor in node.neighbors:
result.append(neighbor.position)
return result
getPossibleAbstractedNeighborsByChildPosition = staticmethod(getPossibleAbstractedNeighborsByChildPosition)
def getLegalNeighbors(position, walls):
x, y = position
x_int, y_int = int(x + 0.5), int(y + 0.5)
neighbors = []
for dir, vec in Actions._directionsAsList:
dx, dy = vec
next_x = x_int + dx
if next_x < 0 or next_x == walls.width:
continue
next_y = y_int + dy
if next_y < 0 or next_y == walls.height:
continue
if not walls[next_x][next_y]:
neighbors.append((next_x, next_y))
return neighbors
getLegalNeighbors = staticmethod(getLegalNeighbors)
def getSuccessor(position, action):
dx, dy = Actions.directionToVector(action)
x, y = position
return (x + dx, y + dy)
getSuccessor = staticmethod(getSuccessor)
class GameStateData:
"""
GameState.data
"""
def __init__(self, prevState = None):
"""
Generates a new data packet by copying information from its predecessor
"""
if prevState != None:
self.agentStates = self.copyAgentStates(prevState.agentStates)
self.layout = prevState.layout
self.score = prevState.score
self._agentMoved = None
self._lose = False
self._win = False
self.scoreChange = 0
def __str__(self):
position = ""
for i in self.agentStates:
position += str(i.getPosition())
return position
def deepCopy(self):
state = GameStateData(self)
state.layout = self.layout.deepCopy()
state._agentMoved = self._agentMoved
return state
def copyAgentStates(self, agentStates):
copiedStates = []
for agentState in agentStates:
copiedStates.append(agentState.copy())
return copiedStates
# def __eq__
# def __hash__
# def __str__
def initialize(self, layout, numPursuerAgents):
"""
Creates an initial game state from a layout array
"""
self.layout = layout
self.score = 0
self.scoreChange = 0
self.agentStates = []
numPursuers = 0
for isTarget, pos in layout.agentPositions:
if not isTarget:
if numPursuers == numPursuerAgents:
continue
else:
numPursuers += 1
self.agentStates.append(AgentState(Configuration(pos), isTarget))
class Game:
"""
The Game manages the control flow, soliciting actions from agents.
"""
def __init__(self, agents, display, rules, startingIndex = 0, muteAgents = False, catchExceptions = False):
self.agents = agents
self.display = display
self.rules = rules
self.startingIndex = startingIndex
self.gameOver = False
self.moveHistory = []
self.catchExceptions = catchExceptions
self.turn = 0
def getProgress(self):
if self.gameOver:
return 1.0
else:
return self.rules.getProgress(self)
# def _agentCrashed
def run(self, prefix=None):
"""
Main control loop for game play
flow
loop agents to make plan
update the GameState
display
"""
self.display.initialize(self.state.data)
self.numMoves = 0
import time
agentIndex = self.startingIndex
numAgents = len(self.agents)
# time.sleep(10)
startTime = time.time()
# Rules are different from pacman project
# turnCount = 0
time.sleep(5)
while not self.gameOver:
# make the plan for moving
observation = self.state.deepCopy()
##agentMovement = []
turnStartTime = time.time()
#positions = []
actions = []
for agentIndex in range(len(self.agents)):
# time for step move
stepStartTime = time.time()
agent = self.agents[agentIndex]
action = agent.getAction(self.state, agentIndex)
#positions.append(observation.data.agentStates[agentIndex].getPosition())
# print "agent", agentIndex, action
self.moveHistory.append((agentIndex, action))
actions.append(action)
for agentIndex in range(len(self.agents)):
action = actions[agentIndex]
#update GameState
#positions.append(self.state.data.agentStates[agentIndex].getPosition())
self.state = self.state.generateSuccessor(action, agentIndex)
# print self.state.getPursuerPosition(1)
#stepEndTime = time.time()
#self.writeStepTimeLog(stepEndTime - stepStartTime)
self.display.update(self.state.data, agentIndex, self.turn)
#positions.append(self.state.data.agentStates[agentIndex].getPosition())
if agentIndex != 0:
if self.rules.collide(self.state, agentIndex):
endTime = time.time()
cost = endTime - startTime
#print "time cost: ", cost
self.gameOver = True
#write game time
if prefix:
self.writeLog(prefix+'.csv', cost)
#write log
break
# 10 for roundMap
if self.turn > 200:
self.gameOver = True
if prefix:
self.writeLog(prefix+'.csv', "NAN")
break
# print self.state.data
#print "positions:", positions
#positions = []
self.turn += 1
#while (time.time() - turnStartTime) <= 0.025:
# pass
"""
Real-time constraints
"""
#update GameState
#self.state = self.state.generateSuccessor(action, agentIndex)
# display for moving
# Inform a learning agent of the game result
for agentIndex, agent in enumerate(self.agents):
if "final" in dir(agent):
try:
self.mute(agentIndex)
agent.final(self.state)
self.unmute()
except Exception, data:
if not self.catchExceptions: raise
self._agentCrash(agentIndex)
self.unmute()
return
self.display.finish()
def writeLog(self, title, log):
import csv
with open('logs/'+title, 'a') as csvfile:
spamwriter = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
spamwriter.writerow([log])
def writeStepTimeLog(self, title, log):
import csv
with open('logs/'+title, 'a') as csvfile:
spamwriter = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
spamwriter.writerow([log])