Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

game.py 25 KB

You have to be logged in to leave a comment. Sign In
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
  1. # game.py
  2. # -------
  3. # Licensing Information: Please do not distribute or publish solutions to this
  4. # project. You are free to use and extend these projects for educational
  5. # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
  6. # John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
  7. # For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html
  8. from utilities.util import *
  9. from utilities.util import raiseNotDefined
  10. import time
  11. import traceback
  12. try:
  13. import boinc
  14. _BOINC_ENABLED = True
  15. except:
  16. _BOINC_ENABLED = False
  17. #######################
  18. # Parts worth reading #
  19. #######################
  20. class Agent:
  21. """
  22. An agent must define a getAction method, but may also define the
  23. following methods which will be called if they exist:
  24. def registerInitialState(self, state): # inspects the starting state
  25. """
  26. def __init__(self, index=0):
  27. self.index = index
  28. def getAction(self, state):
  29. """
  30. The Agent will receive a GameState (from either {pacman, capture, sonar}.py) and
  31. must return an action from Directions.{North, South, East, West, Stop}
  32. """
  33. raiseNotDefined()
  34. class Directions:
  35. NORTH = 'North'
  36. SOUTH = 'South'
  37. EAST = 'East'
  38. WEST = 'West'
  39. STOP = 'Stop'
  40. LEFT = {NORTH: WEST,
  41. SOUTH: EAST,
  42. EAST: NORTH,
  43. WEST: SOUTH,
  44. STOP: STOP}
  45. RIGHT = dict([(y, x) for x, y in LEFT.items()])
  46. REVERSE = {NORTH: SOUTH,
  47. SOUTH: NORTH,
  48. EAST: WEST,
  49. WEST: EAST,
  50. STOP: STOP}
  51. class Configuration:
  52. """
  53. A Configuration holds the (x,y) coordinate of a character, along with its
  54. traveling direction.
  55. The convention for positions, like a graph, is that (0,0) is the lower left corner, x increases
  56. horizontally and y increases vertically. Therefore, north is the direction of increasing y, or (0,1).
  57. """
  58. def __init__(self, pos, direction):
  59. self.pos = pos
  60. self.direction = direction
  61. def getPosition(self):
  62. return (self.pos)
  63. def getDirection(self):
  64. return self.direction
  65. def isInteger(self):
  66. x, y = self.pos
  67. return x == int(x) and y == int(y)
  68. def __eq__(self, other):
  69. if other == None: return False
  70. return (self.pos == other.pos and self.direction == other.direction)
  71. def __hash__(self):
  72. x = hash(self.pos)
  73. y = hash(self.direction)
  74. return hash(x + 13 * y)
  75. def __str__(self):
  76. return "(x,y)=" + str(self.pos) + ", " + str(self.direction)
  77. def generateSuccessor(self, vector):
  78. """
  79. Generates a new configuration reached by translating the current
  80. configuration by the action vector. This is a low-level call and does
  81. not attempt to respect the legality of the movement.
  82. Actions are movement vectors.
  83. """
  84. x, y = self.pos
  85. dx, dy = vector
  86. direction = Actions.vectorToDirection(vector)
  87. if direction == Directions.STOP:
  88. direction = self.direction # There is no stop direction
  89. return Configuration((x + dx, y + dy), direction)
  90. class AgentState:
  91. """
  92. AgentStates hold the state of an agent (configuration, speed, scared, etc).
  93. """
  94. def __init__(self, startConfiguration, isPacman):
  95. self.start = startConfiguration
  96. self.configuration = startConfiguration
  97. self.isPacman = isPacman
  98. self.scaredTimer = 0
  99. def __str__(self):
  100. if self.isPacman:
  101. return "Pacman: " + str(self.configuration)
  102. else:
  103. return "Ghost: " + str(self.configuration)
  104. def __eq__(self, other):
  105. if other == None:
  106. return False
  107. return self.configuration == other.configuration and self.scaredTimer == other.scaredTimer
  108. def __hash__(self):
  109. return hash(hash(self.configuration) + 13 * hash(self.scaredTimer))
  110. def copy(self):
  111. state = AgentState(self.start, self.isPacman)
  112. state.configuration = self.configuration
  113. state.scaredTimer = self.scaredTimer
  114. return state
  115. def getPosition(self):
  116. if self.configuration == None: return None
  117. return self.configuration.getPosition()
  118. def getDirection(self):
  119. return self.configuration.getDirection()
  120. class Grid:
  121. """
  122. A 2-dimensional array of objects backed by a list of lists. Data is accessed
  123. via grid[x][y] where (x,y) are positions on a Pacman map with x horizontal,
  124. y vertical and the origin (0,0) in the bottom left corner.
  125. The __str__ method constructs an output that is oriented like a pacman board.
  126. """
  127. def __init__(self, width, height, initialValue=False, bitRepresentation=None):
  128. if initialValue not in [False, True]: raise Exception('Grids can only contain booleans')
  129. self.CELLS_PER_INT = 30
  130. self.width = width
  131. self.height = height
  132. self.data = [[initialValue for y in range(height)] for x in range(width)]
  133. self.__class__.__lt__ = lambda x, y: (True)
  134. if bitRepresentation:
  135. self._unpackBits(bitRepresentation)
  136. def __getitem__(self, i):
  137. return self.data[i]
  138. def __setitem__(self, key, item):
  139. self.data[key] = item
  140. def __str__(self):
  141. out = [[str(self.data[x][y])[0] for x in range(self.width)] for y in range(self.height)]
  142. out.reverse()
  143. return '\n'.join([''.join(x) for x in out])
  144. def __eq__(self, other):
  145. if other == None: return False
  146. return self.data == other.data
  147. def __hash__(self):
  148. # return hash(str(self))
  149. base = 1
  150. h = 0
  151. for l in self.data:
  152. for i in l:
  153. if i:
  154. h += base
  155. base *= 2
  156. return hash(h)
  157. def copy(self):
  158. g = Grid(self.width, self.height)
  159. g.data = [x[:] for x in self.data]
  160. return g
  161. def deepCopy(self):
  162. return self.copy()
  163. def shallowCopy(self):
  164. g = Grid(self.width, self.height)
  165. g.data = self.data
  166. return g
  167. def count(self, item=True):
  168. return sum([x.count(item) for x in self.data])
  169. def asList(self, key=True):
  170. list = []
  171. for x in range(self.width):
  172. for y in range(self.height):
  173. if self[x][y] == key: list.append((x, y))
  174. return list
  175. def packBits(self):
  176. """
  177. Returns an efficient int list representation
  178. (width, height, bitPackedInts...)
  179. """
  180. bits = [self.width, self.height]
  181. currentInt = 0
  182. for i in range(self.height * self.width):
  183. bit = self.CELLS_PER_INT - (i % self.CELLS_PER_INT) - 1
  184. x, y = self._cellIndexToPosition(i)
  185. if self[x][y]:
  186. currentInt += 2 ** bit
  187. if (i + 1) % self.CELLS_PER_INT == 0:
  188. bits.append(currentInt)
  189. currentInt = 0
  190. bits.append(currentInt)
  191. return tuple(bits)
  192. def _cellIndexToPosition(self, index):
  193. x = index / self.height
  194. y = index % self.height
  195. return x, y
  196. def _unpackBits(self, bits):
  197. """
  198. Fills in data from a bit-level representation
  199. """
  200. cell = 0
  201. for packed in bits:
  202. for bit in self._unpackInt(packed, self.CELLS_PER_INT):
  203. if cell == self.width * self.height: break
  204. x, y = self._cellIndexToPosition(cell)
  205. self[x][y] = bit
  206. cell += 1
  207. def _unpackInt(self, packed, size):
  208. bools = []
  209. if packed < 0: raise ValueError("must be a positive integer")
  210. for i in range(size):
  211. n = 2 ** (self.CELLS_PER_INT - i - 1)
  212. if packed >= n:
  213. bools.append(True)
  214. packed -= n
  215. else:
  216. bools.append(False)
  217. return bools
  218. def reconstituteGrid(bitRep):
  219. if type(bitRep) is not type((1, 2)):
  220. return bitRep
  221. width, height = bitRep[:2]
  222. return Grid(width, height, bitRepresentation=bitRep[2:])
  223. ####################################
  224. # Parts you shouldn't have to read #
  225. ####################################
  226. class Actions:
  227. """
  228. A collection of static methods for manipulating move actions.
  229. """
  230. # Directions
  231. _directions = {Directions.NORTH: (0, 1),
  232. Directions.SOUTH: (0, -1),
  233. Directions.EAST: (1, 0),
  234. Directions.WEST: (-1, 0),
  235. Directions.STOP: (0, 0)}
  236. _directionsAsList = _directions.items()
  237. TOLERANCE = .001
  238. def reverseDirection(action):
  239. if action == Directions.NORTH:
  240. return Directions.SOUTH
  241. if action == Directions.SOUTH:
  242. return Directions.NORTH
  243. if action == Directions.EAST:
  244. return Directions.WEST
  245. if action == Directions.WEST:
  246. return Directions.EAST
  247. return action
  248. reverseDirection = staticmethod(reverseDirection)
  249. def vectorToDirection(vector):
  250. dx, dy = vector
  251. if dy > 0:
  252. return Directions.NORTH
  253. if dy < 0:
  254. return Directions.SOUTH
  255. if dx < 0:
  256. return Directions.WEST
  257. if dx > 0:
  258. return Directions.EAST
  259. return Directions.STOP
  260. vectorToDirection = staticmethod(vectorToDirection)
  261. def directionToVector(direction, speed=1.0):
  262. dx, dy = Actions._directions[direction]
  263. return (dx * speed, dy * speed)
  264. directionToVector = staticmethod(directionToVector)
  265. def getPossibleActions(config, walls):
  266. possible = []
  267. x, y = config.pos
  268. x_int, y_int = int(x + 0.5), int(y + 0.5)
  269. # In between grid points, all agents must continue straight
  270. if (abs(x - x_int) + abs(y - y_int) > Actions.TOLERANCE):
  271. return [config.getDirection()]
  272. for dir, vec in Actions._directionsAsList:
  273. dx, dy = vec
  274. next_y = y_int + dy
  275. next_x = x_int + dx
  276. if not walls[next_x][next_y]: possible.append(dir)
  277. return possible
  278. getPossibleActions = staticmethod(getPossibleActions)
  279. def getLegalNeighbors(position, walls):
  280. x, y = position
  281. x_int, y_int = int(x + 0.5), int(y + 0.5)
  282. neighbors = []
  283. for dir, vec in Actions._directionsAsList:
  284. dx, dy = vec
  285. next_x = x_int + dx
  286. if next_x < 0 or next_x == walls.width: continue
  287. next_y = y_int + dy
  288. if next_y < 0 or next_y == walls.height: continue
  289. if not walls[next_x][next_y]: neighbors.append((next_x, next_y))
  290. return neighbors
  291. getLegalNeighbors = staticmethod(getLegalNeighbors)
  292. def getSuccessor(position, action):
  293. dx, dy = Actions.directionToVector(action)
  294. x, y = position
  295. return (x + dx, y + dy)
  296. getSuccessor = staticmethod(getSuccessor)
  297. class GameStateData:
  298. def __init__(self, prevState=None):
  299. """
  300. Generates a new data packet by copying information from its predecessor.
  301. """
  302. if prevState != None:
  303. self.food = prevState.food.shallowCopy()
  304. self.capsules = prevState.capsules[:]
  305. self.agentStates = self.copyAgentStates(prevState.agentStates)
  306. self.layout = prevState.layout
  307. self._eaten = prevState._eaten
  308. self.score = prevState.score
  309. self._foodEaten = None
  310. self._capsuleEaten = None
  311. self._agentMoved = None
  312. self._lose = False
  313. self._win = False
  314. self.scoreChange = 0
  315. def deepCopy(self):
  316. state = GameStateData(self)
  317. state.food = self.food.deepCopy()
  318. state.layout = self.layout.deepCopy()
  319. state._agentMoved = self._agentMoved
  320. state._foodEaten = self._foodEaten
  321. state._capsuleEaten = self._capsuleEaten
  322. return state
  323. def copyAgentStates(self, agentStates):
  324. copiedStates = []
  325. for agentState in agentStates:
  326. copiedStates.append(agentState.copy())
  327. return copiedStates
  328. def __eq__(self, other):
  329. """
  330. Allows two states to be compared.
  331. """
  332. if other == None: return False
  333. # TODO Check for type of other
  334. if not self.agentStates == other.agentStates: return False
  335. if not self.food == other.food: return False
  336. if not self.capsules == other.capsules: return False
  337. if not self.score == other.score: return False
  338. return True
  339. def __hash__(self):
  340. """
  341. Allows states to be keys of dictionaries.
  342. """
  343. for i, state in enumerate(self.agentStates):
  344. try:
  345. int(hash(state))
  346. except(TypeError, e):
  347. print(e)
  348. # hash(state)
  349. return int((hash(tuple(self.agentStates)) + 13 * hash(self.food) + 113 * hash(
  350. tuple(self.capsules)) + 7 * hash(self.score)) % 1048575)
  351. def __str__(self):
  352. width, height = self.layout.width, self.layout.height
  353. map = Grid(width, height)
  354. if type(self.food) == type((1, 2)):
  355. self.food = reconstituteGrid(self.food)
  356. for x in range(width):
  357. for y in range(height):
  358. food, walls = self.food, self.layout.walls
  359. map[x][y] = self._foodWallStr(food[x][y], walls[x][y])
  360. for agentState in self.agentStates:
  361. if agentState == None: continue
  362. if agentState.configuration == None: continue
  363. x, y = [int(i) for i in nearestPoint(agentState.configuration.pos)]
  364. agent_dir = agentState.configuration.direction
  365. if agentState.isPacman:
  366. map[x][y] = self._pacStr(agent_dir)
  367. else:
  368. map[x][y] = self._ghostStr(agent_dir)
  369. for x, y in self.capsules:
  370. map[x][y] = 'o'
  371. return str(map) + ("\nScore: %d\n" % self.score)
  372. def _foodWallStr(self, hasFood, hasWall):
  373. if hasFood:
  374. return '.'
  375. elif hasWall:
  376. return '%'
  377. else:
  378. return ' '
  379. def _pacStr(self, dir):
  380. if dir == Directions.NORTH:
  381. return 'v'
  382. if dir == Directions.SOUTH:
  383. return '^'
  384. if dir == Directions.WEST:
  385. return '>'
  386. return '<'
  387. def _ghostStr(self, dir):
  388. return 'G'
  389. if dir == Directions.NORTH:
  390. return 'M'
  391. if dir == Directions.SOUTH:
  392. return 'W'
  393. if dir == Directions.WEST:
  394. return '3'
  395. return 'E'
  396. def initialize(self, layout, numGhostAgents):
  397. """
  398. Creates an initial game state from a layout array (see layout.py).
  399. """
  400. self.food = layout.food.copy()
  401. self.capsules = layout.capsules[:]
  402. self.layout = layout
  403. self.score = 0
  404. self.scoreChange = 0
  405. self.agentStates = []
  406. numGhosts = 0
  407. for isPacman, pos in layout.agentPositions:
  408. if not isPacman:
  409. if numGhosts == numGhostAgents:
  410. continue # Max ghosts reached already
  411. else:
  412. numGhosts += 1
  413. self.agentStates.append(AgentState(Configuration(pos, Directions.STOP), isPacman))
  414. self._eaten = [False for a in self.agentStates]
  415. class Game:
  416. """
  417. The Game manages the control flow, soliciting actions from agents.
  418. """
  419. def __init__(self, agents, display, rules, startingIndex=0, muteAgents=False,
  420. catchExceptions=False):
  421. self.agentCrashed = False
  422. self.agents = agents
  423. self.display = display
  424. self.rules = rules
  425. self.startingIndex = startingIndex
  426. self.gameOver = False
  427. self.muteAgents = muteAgents
  428. self.catchExceptions = catchExceptions
  429. self.moveHistory = []
  430. self.totalAgentTimes = [0 for agent in agents]
  431. self.totalAgentTimeWarnings = [0 for agent in agents]
  432. self.agentTimeout = False
  433. def getProgress(self):
  434. if self.gameOver:
  435. return 1.0
  436. else:
  437. return self.rules.getProgress(self)
  438. def _agentCrash(self, agentIndex, quiet=False):
  439. """
  440. Helper method for handling agent crashes
  441. """
  442. if not quiet: traceback.print_exc()
  443. self.gameOver = True
  444. self.agentCrashed = True
  445. self.rules.agentCrash(self, agentIndex)
  446. OLD_STDOUT = None
  447. OLD_STDERR = None
  448. def mute(self):
  449. if not self.muteAgents: return
  450. global OLD_STDOUT, OLD_STDERR
  451. import cStringIO
  452. OLD_STDOUT = sys.stdout
  453. OLD_STDERR = sys.stderr
  454. sys.stdout = cStringIO.StringIO()
  455. sys.stderr = cStringIO.StringIO()
  456. def unmute(self):
  457. if not self.muteAgents: return
  458. global OLD_STDOUT, OLD_STDERR
  459. sys.stdout.close()
  460. sys.stderr.close()
  461. # Revert stdout/stderr to originals
  462. sys.stdout = OLD_STDOUT
  463. sys.stderr = OLD_STDERR
  464. def run(self):
  465. """
  466. Main control loop for game play.
  467. """
  468. self.display.initialize(self.state.data)
  469. self.numMoves = 0
  470. ###self.display.initialize(self.state.makeObservation(1).data)
  471. # inform learning agents of the game start
  472. for i in range(len(self.agents)):
  473. agent = self.agents[i]
  474. if not agent:
  475. # this is a null agent, meaning it failed to load
  476. # the other team wins
  477. self._agentCrash(i, quiet=True)
  478. return
  479. if ("registerInitialState" in dir(agent)):
  480. self.mute()
  481. if self.catchExceptions:
  482. try:
  483. timed_func = TimeoutFunction(agent.registerInitialState,
  484. int(self.rules.getMaxStartupTime(i)))
  485. try:
  486. start_time = time.time()
  487. timed_func(self.state.deepCopy())
  488. time_taken = time.time() - start_time
  489. self.totalAgentTimes[i] += time_taken
  490. except(TimeoutFunctionException):
  491. print("Agent %d ran out of time on startup!" % i)
  492. self.unmute()
  493. self.agentTimeout = True
  494. self._agentCrash(i, quiet=True)
  495. return
  496. except(Exception):
  497. self.unmute()
  498. self._agentCrash(i, quiet=True)
  499. return
  500. else:
  501. agent.registerInitialState(self.state.deepCopy())
  502. ## TODO: could this exceed the total time
  503. self.unmute()
  504. agentIndex = self.startingIndex
  505. numAgents = len(self.agents)
  506. while not self.gameOver:
  507. # Fetch the next agent
  508. agent = self.agents[agentIndex]
  509. move_time = 0
  510. skip_action = False
  511. # Generate an observation of the state
  512. if 'observationFunction' in dir(agent):
  513. self.mute()
  514. if self.catchExceptions:
  515. try:
  516. timed_func = TimeoutFunction(agent.observationFunction,
  517. int(self.rules.getMoveTimeout(agentIndex)))
  518. try:
  519. start_time = time.time()
  520. observation = timed_func(self.state.deepCopy())
  521. except(TimeoutFunctionException):
  522. skip_action = True
  523. move_time += time.time() - start_time
  524. self.unmute()
  525. except(Exception):
  526. self.unmute()
  527. self._agentCrash(agentIndex, quiet=True)
  528. return
  529. else:
  530. observation = agent.observationFunction(self.state.deepCopy())
  531. self.unmute()
  532. else:
  533. observation = self.state.deepCopy()
  534. # Solicit an action
  535. action = None
  536. self.mute()
  537. if self.catchExceptions:
  538. try:
  539. timed_func = TimeoutFunction(agent.getAction,
  540. int(self.rules.getMoveTimeout(agentIndex)) - int(
  541. move_time))
  542. try:
  543. start_time = time.time()
  544. if skip_action:
  545. raise (TimeoutFunctionException())
  546. action = timed_func(observation)
  547. except(TimeoutFunctionException):
  548. print("Agent %d timed out on a single move!" % agentIndex)
  549. self.agentTimeout = True
  550. self.unmute()
  551. self._agentCrash(agentIndex, quiet=True)
  552. return
  553. move_time += time.time() - start_time
  554. if move_time > self.rules.getMoveWarningTime(agentIndex):
  555. self.totalAgentTimeWarnings[agentIndex] += 1
  556. print("Agent %d took too long to make a move! This is warning %d" % (
  557. agentIndex, self.totalAgentTimeWarnings[agentIndex]))
  558. if self.totalAgentTimeWarnings[agentIndex] > self.rules.getMaxTimeWarnings(
  559. agentIndex):
  560. print("Agent %d exceeded the maximum number of warnings: %d" % (
  561. agentIndex, self.totalAgentTimeWarnings[agentIndex]))
  562. self.agentTimeout = True
  563. self.unmute()
  564. self._agentCrash(agentIndex, quiet=True)
  565. self.totalAgentTimes[agentIndex] += move_time
  566. # print("Agent: %d, time: %f, total: %f" % (agentIndex, move_time, self.totalAgentTimes[agentIndex]))
  567. if self.totalAgentTimes[agentIndex] > self.rules.getMaxTotalTime(agentIndex):
  568. print("Agent %d ran out of time! (time: %1.2f)" % (
  569. agentIndex, self.totalAgentTimes[agentIndex]))
  570. self.agentTimeout = True
  571. self.unmute()
  572. self._agentCrash(agentIndex, quiet=True)
  573. return
  574. self.unmute()
  575. except(Exception):
  576. self.unmute()
  577. self._agentCrash(agentIndex)
  578. return
  579. else:
  580. action = agent.getAction(observation)
  581. self.unmute()
  582. # Execute the action
  583. self.moveHistory.append((agentIndex, action))
  584. if self.catchExceptions:
  585. try:
  586. self.state = self.state.generateSuccessor(agentIndex, action)
  587. except(Exception):
  588. self._agentCrash(agentIndex)
  589. return
  590. else:
  591. self.state = self.state.generateSuccessor(agentIndex, action)
  592. # Change the display
  593. self.display.update(self.state.data)
  594. ###idx = agentIndex - agentIndex % 2 + 1
  595. ###self.display.update( self.state.makeObservation(idx).data )
  596. # Allow for game specific conditions (winning, losing, etc.)
  597. self.rules.process(self.state, self)
  598. # Track progress
  599. if agentIndex == numAgents + 1: self.numMoves += 1
  600. # Next agent
  601. agentIndex = (agentIndex + 1) % numAgents
  602. if _BOINC_ENABLED:
  603. boinc.set_fraction_done(self.getProgress())
  604. # inform a learning agent of the game result
  605. for agent in self.agents:
  606. if "final" in dir(agent):
  607. try:
  608. self.mute()
  609. agent.final(self.state)
  610. self.unmute()
  611. except(Exception):
  612. if not self.catchExceptions: raise
  613. self.unmute()
  614. print("Exception", data)
  615. self._agentCrash(agent.index)
  616. return
  617. self.display.finish()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...