-
Notifications
You must be signed in to change notification settings - Fork 0
/
myTeam.py
1552 lines (1364 loc) · 54.7 KB
/
myTeam.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
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from captureAgents import CaptureAgent
import distanceCalculator
import random, time, util, sys
from game import Directions
import game
from util import nearestPoint
from game import Grid
import math
#################
# Team creation #
#################
def createTeam(firstIndex, secondIndex, isRed,
first = 'OffensiveReflexAgent', second = 'OffensiveReflexAgent'):
"""
This function should return a list of two agents that will form the
team, initialized using firstIndex and secondIndex as their agent
index numbers. isRed is True if the red team is being created, and
will be False if the blue team is being created.
As a potentially helpful development aid, this function can take
additional string-valued keyword arguments ("first" and "second" are
such arguments in the case of this function), which will come from
the --redOpts and --blueOpts command-line arguments to capture.py.
For the nightly contest, however, your team will be created without
any extra arguments, so you should make sure that the default
behavior is what you want for the nightly contest.
"""
return [eval(first)(firstIndex), eval(second)(secondIndex)]
def getAggression(gameState, pos, isRed):
walls = gameState.getWalls()
x, y = pos
if isRed:
return 1.0 * x / walls.width
else:
return 1.0 * (walls.width - x) / walls.width
def getDeepFood(gameState, agent, isRed):
food = agent.getFood(gameState)
shallowFood = food.copy()
if isRed:
shallowDistThresholdCol = int(0.8 * food.width)
for c in range(shallowDistThresholdCol):
for r in range(food.height):
shallowFood[c][r] = False
else:
shallowDistThresholdCol = int(0.2 * food.width)
for c in range(shallowDistThresholdCol, food.width):
for r in range(food.height):
shallowFood[c][r] = False
return shallowFood
def getShallowFood(gameState, agent, isRed):
food = agent.getFood(gameState)
deepFood = food.copy()
if isRed:
deepDistThresholdCol = int(0.8 * food.width)
for c in range(deepDistThresholdCol, food.width):
for r in range(food.height):
deepFood[c][r] = False
else:
deepDistThresholdCol = int(0.2 * food.width)
for c in range(deepDistThresholdCol):
for r in range(food.height):
deepFood[c][r] = False
return deepFood
def getMinDistToCapsule(gameState, agent, pos, capsules):
if len(capsules) == 0:
return 0
minDist = 1000
for capsule in capsules:
dist = agent.getMazeDistance(pos, capsule)
if dist < minDist:
minDist = dist
return minDist
def getCloseSafePoints(gameState, isRed):
walls = gameState.getWalls()
if isRed:
col = (walls.width / 2) - 1
else:
col = (walls.width / 2)
safePoints = []
for y in range(walls.height):
if not walls[col][y]:
safePoints.append((col,y))
return safePoints
def getPositionAfterAction(pos, action):
x,y = pos
if action == 'East':
return (x + 1, y)
if action == 'West':
return (x - 1, y)
if action == 'North':
return (x, y + 1)
if action == 'South':
return (x, y - 1)
else:
return pos
def getPossibleActions(gameState, pos):
x,y = pos
walls = gameState.getWalls()
actions = list()
if not walls[x + 1][y]:
actions.append('East')
if not walls[x - 1][y]:
actions.append('West')
if not walls[x][y + 1]:
actions.append('North')
if not walls[x][y - 1]:
actions.append('South')
actions.append('Stop')
return actions
# Find all points with just one possible action -> Dead ends
# Travel along dead ends until an opening is found -> choke point
# Find depths of positions from prior movement
def getDeadEnds(gameState):
walls = gameState.getWalls()
deadEnds = []
for r in range(walls.height):
for c in range(walls.width):
pos = (c,r)
if not walls[c][r]:
if len(getPossibleActions(gameState, pos)) <= 2: #Stop and one other action
deadEnds.append(pos)
return deadEnds
def getChokePointAndDirection(gameState, deadEnd):
walls = gameState.getWalls()
pos = deadEnd
actions = getPossibleActions(gameState, pos)
action = actions[0]
newPos = getPositionAfterAction(pos, action)
actions = getPossibleActions(gameState, newPos)
actions.remove('Stop')
while len(actions) == 2:
newestPos1 = getPositionAfterAction(newPos, actions[0])
newestPos2 = getPositionAfterAction(newPos, actions[1])
if newestPos1 == pos:
newestPos = newestPos2
else:
newestPos = newestPos1
pos = newPos
newPos = newestPos
actions = getPossibleActions(gameState, newPos)
actions.remove('Stop')
dirPos = pos
chokePoint = newPos
actions = getPossibleActions(gameState, newPos)
for action in actions:
if getPositionAfterAction(chokePoint, action) == dirPos:
dirAction = action
break
return chokePoint, dirAction
def getChokePointAndDirectionRestricted(gameState, deadEnd, directionsRestricted):
walls = gameState.getWalls()
pos = deadEnd
actions = getPossibleActions(gameState, pos)
for action in actions:
if action in directionsRestricted or action == 'Stop':
actions.remove(action)
action = actions[0]
newPos = getPositionAfterAction(pos, action)
actions = getPossibleActions(gameState, newPos)
actions.remove('Stop')
while len(actions) == 2:
newestPos1 = getPositionAfterAction(newPos, actions[0])
newestPos2 = getPositionAfterAction(newPos, actions[1])
if newestPos1 == pos:
newestPos = newestPos2
else:
newestPos = newestPos1
pos = newPos
newPos = newestPos
actions = getPossibleActions(gameState, newPos)
actions.remove('Stop')
dirPos = pos
chokePoint = newPos
actions = getPossibleActions(gameState, newPos)
for action in actions:
if getPositionAfterAction(chokePoint, action) == dirPos:
dirAction = action
break
return chokePoint, dirAction
def getChokePoints(gameState):
walls = gameState.getWalls()
deadEnds = getDeadEnds(gameState)
chokePointList = []
chokePoints = {}
toCheck = {}
stillGoing = False
for deadEnd in deadEnds:
chokePoint, direction = getChokePointAndDirection(gameState, deadEnd)
if not chokePoint in chokePoints:
chokePoints[chokePoint] = []
chokePoints[chokePoint].append(direction)
if len(getPossibleActions(gameState, chokePoint)) - 2 == len(chokePoints[chokePoint]):
toCheck[chokePoint] = chokePoints[chokePoint]
del chokePoints[chokePoint]
stillGoing = True
for chokePoint in chokePoints:
chokePointList.append((chokePoint, chokePoints[chokePoint]))
while stillGoing:
deadEnds = toCheck.copy()
toCheck = {}
chokePoints = {}
stillGoing = False
for deadEnd in deadEnds:
chokePoint, direction = getChokePointAndDirectionRestricted(gameState, deadEnd, deadEnds[deadEnd])
if not chokePoint in chokePoints:
chokePoints[chokePoint] = []
chokePoints[chokePoint].append(direction)
if len(getPossibleActions(gameState, chokePoint)) - 2 == len(chokePoints[chokePoint]):
toCheck[chokePoint] = chokePoints[chokePoint]
chokePoints = chokePoints.pop(chokePoint)
stillGoing = True
for chokePoint in chokePoints:
chokePointList.append((chokePoint, chokePoints[chokePoint]))
return chokePointList
def getMinDistChokePoints(gameState, agent, pos, chokePoints):
minDist = 1000
walls = gameState.getWalls()
for choke, dirs in chokePoints:
dist = agent.getMazeDistance(pos, choke)
if dist < minDist:
minDist = dist
return minDist
def bfsDepthGrid(gameState, chokePoint, direction, depthGrid):
x,y = chokePoint
depthGrid[x][y] = 9
newPos = getPositionAfterAction(chokePoint, direction)
posQueue = util.Queue()
posQueue.push((newPos, 1))
while not posQueue.isEmpty():
pos, depth = posQueue.pop()
x,y = pos
if depthGrid[x][y] == 0:
depthGrid[x][y] = depth
actions = getPossibleActions(gameState, pos)
for action in actions:
nextPos = getPositionAfterAction(pos, action)
newDepth = depth + 1
posQueue.push((nextPos, newDepth))
x,y = chokePoint
depthGrid[x][y] = 0
return depthGrid
def getDepthsAndChokePoints(gameState):
walls = gameState.getWalls()
depthGrid = Grid(walls.width, walls.height, initialValue=0)
chokePoints = getChokePoints(gameState)
for chokePoint, directions in chokePoints:
for direction in directions:
depthGrid = bfsDepthGrid(gameState, chokePoint, direction, depthGrid)
return depthGrid, chokePoints
def getDistToSafety(gameState, agent):
agentIndex = agent.index
isPacman = gameState.getAgentState(agentIndex).isPacman
#if not isPacman:
# return 0
isRed = agent.red
pos = gameState.getAgentPosition(agentIndex)
closestSafePoints = getCloseSafePoints(gameState, isRed)
closestDist = 1000
for point in closestSafePoints:
dist = agent.getMazeDistance(pos, point)
if dist < closestDist:
closestDist = dist
return closestDist
def getDistAdvantage(gameState, agent, enemyPos, isDefending):
agentIndex = agent.index
isRed = agent.red
pos = gameState.getAgentPosition(agentIndex)
if isDefending:
closestSafePoints = getCloseSafePoints(gameState, not isRed)
minAdvantage = 1000
else:
closestSafePoints = getCloseSafePoints(gameState, isRed)
maxAdvantage = -1000
if len(closestSafePoints) == 0:
return 0
for point in closestSafePoints:
dist = agent.getMazeDistance(pos, point)
enemyDist = agent.getMazeDistance(enemyPos, point)
advantage = enemyDist - dist
if isDefending:
if advantage < minAdvantage:
minAdvantage = advantage
else:
if advantage > maxAdvantage:
maxAdvantage = advantage
if isDefending:
return minAdvantage
else:
return maxAdvantage
def getDistAdvantageCapsule(gameState, agent, enemyPos, isDefending):
agentIndex = agent.index
isRed = agent.red
pos = gameState.getAgentPosition(agentIndex)
minAdvantage = 1000
if isDefending:
closestSafePoints = agent.getCapsulesYouAreDefending(gameState)
minAdvantage = 1000
else:
closestSafePoints = agent.getCapsules(gameState)
maxAdvantage = -1000
if len(closestSafePoints) == 0:
return 0
for point in closestSafePoints:
dist = agent.getMazeDistance(pos, point)
enemyDist = agent.getMazeDistance(enemyPos, point)
advantage = enemyDist - dist
if isDefending:
if advantage < minAdvantage:
minAdvantage = advantage
else:
if advantage > maxAdvantage:
maxAdvantage = advantage
if isDefending:
return minAdvantage
else:
return maxAdvantage
enemyLocationPredictor = None
PERSIST = 10
class EnemyLocationPredictor:
def __init__(self, gameState, agent):
self.depthGrid = agent.depthGrid
self.enemyIndices = agent.getOpponents(gameState)
self.teamIndices = agent.getTeam(gameState)
self.walls = gameState.getWalls()
self.pastFood = agent.getFoodYouAreDefending(gameState)
self.pastCapsules = agent.getCapsulesYouAreDefending(gameState)
self.possiblePositions1 = Grid(self.walls.width, self.walls.height)
self.possiblePositions2 = Grid(self.walls.width, self.walls.height)
self.positionsToInvestigate = []
self.positionsToAvoid = []
self.enemies = agent.getOpponents(gameState)
self.isRed = not agent.red
self.pastTeamLocation1 = agent.start
self.pastTeamLocation2 = agent.start
x, y = agent.start
enemyX = self.walls.width - x - 1
enemyY = self.walls.height - y - 1
self.enemyStartPos = (enemyX, enemyY)
self.enemy1KnownLocation = self.enemyStartPos
self.enemy2KnownLocation = self.enemyStartPos
self.possiblePositions1[enemyX][enemyY] = True
self.possiblePositions2[enemyX][enemyY] = True
self.ignoreCounterInvestigate = 0
self.ignoreCounterAvoid = 0
def getGridWithPositions(self, positions):
g = Grid(self.walls.width, self.walls.height)
for pos in positions:
x, y = pos
x,y = int(x), int(y)
g[x][y] = True
return g
def adjustConsideration(self, invaders, defenders):
if len(self.positionsToAvoid) > defenders:
while len(self.positionsToAvoid) > defenders and len(self.positionsToAvoid) > 0:
self.positionsToAvoid.pop(0)
if len(self.positionsToInvestigate) > invaders:
while len(self.positionsToInvestigate) > invaders and len(self.positionsToInvestigate) > 0:
self.positionsToInvestigate.pop(0)
if self.ignoreCounterInvestigate > 0:
self.ignoreCounterInvestigate -= 1
elif len(self.positionsToInvestigate) > 0:
self.ignoreCounterInvestigate = PERSIST
pos = self.positionsToInvestigate.pop(0)
if self.ignoreCounterAvoid > 0:
self.ignoreCounterAvoid -= 1
elif len(self.positionsToAvoid) > 0:
self.ignoreCounterAvoid = PERSIST
pos = self.positionsToAvoid.pop(0)
def addPositionForConsideration(self, pos, invaders, defenders, isRed):
x,y = pos
if (x < (self.walls.width / 2) and isRed) or (x >= (self.walls.width / 2) and not isRed):
#Add position to avoid
self.ignoreCounterAvoid = PERSIST
if not pos in self.positionsToAvoid:
if len(self.positionsToAvoid) > defenders:
while len(self.positionsToAvoid) >= defenders and len(self.positionsToAvoid) > 0:
self.positionsToAvoid.pop(0)
self.positionsToAvoid.append(pos)
else:
#Add position to investigate
self.ignoreCounterInvestigate = PERSIST
if not pos in self.positionsToInvestigate:
if len(self.positionsToInvestigate) > invaders:
while len(self.positionsToInvestigate) > invaders and len(self.positionsToInvestigate) > 0:
self.positionsToInvestigate.pop(0)
self.positionsToInvestigate.append(pos)
def expandProb(self, prob):
newProb = prob.copy()
for r in range(prob.height):
for c in range(prob.width):
if prob[c][r]:
newProb[c][r] = True
if c > 0:
newProb[c - 1][r] = True
if c < prob.width - 1:
newProb[c + 1][r] = True
if r > 0:
newProb[c][r - 1] = True
if r < prob.height - 1:
newProb[c][r + 1] = True
return newProb
def updatePart(self, gameState, agent, teamPosition1, teamPosition2, verbose = False):
invaders = len([a for a in self.enemies if gameState.getAgentState(a).isPacman])
defenders = len([a for a in self.enemies if not gameState.getAgentState(a).isPacman])
knownPos1 = None
knownPos2 = None
isRed = self.isRed
possiblePositions1 = self.expandProb(self.possiblePositions1)
possiblePositions2 = self.expandProb(self.possiblePositions2)
for r in range(self.walls.height):
for c in range(self.walls.width):
if self.walls[c][r]:
possiblePositions1[c][r] = False
possiblePositions2[c][r] = False
newFood = agent.getFoodYouAreDefending(gameState)
newCapsules = agent.getCapsulesYouAreDefending(gameState)
enemy1State = gameState.getAgentState(self.enemyIndices[0])
enemy2State = gameState.getAgentState(self.enemyIndices[1])
enemiesRed = not agent.red
team1X, team1Y = teamPosition1
team2X, team2Y = teamPosition2
eatenFood = []
eatenCapsules = []
# If the enemy's position is known, use that. Otherwise, no enemy can be near a team member
if not gameState.getAgentState(self.enemyIndices[0]).getPosition() is None:
knownPos1 = gameState.getAgentState(self.enemyIndices[0]).getPosition()
else:
for r in range(self.walls.height):
for c in range(self.walls.width):
manhattanDist1 = abs(c - team1X) + abs(r - team1Y)
manhattanDist2 = abs(c - team2X) + abs(r - team2Y)
if min(manhattanDist1, manhattanDist2) <= 5:
possiblePositions1[c][r] = False
if not gameState.getAgentState(self.enemyIndices[1]).getPosition() is None:
knownPos2 = gameState.getAgentState(self.enemyIndices[1]).getPosition()
else:
for r in range(self.walls.height):
for c in range(self.walls.width):
manhattanDist1 = abs(c - team1X) + abs(r - team1Y)
manhattanDist2 = abs(c - team2X) + abs(r - team2Y)
if min(manhattanDist1, manhattanDist2) <= 5:
possiblePositions2[c][r] = False
# If an enemy was captured, it must be at its spawn (POS KNOWN)
if agent.getMazeDistance(self.pastTeamLocation1, teamPosition1) > 1:
team1Captured = True
else:
team1Captured = False
if agent.getMazeDistance(self.pastTeamLocation2, teamPosition2) > 1:
team2Captured = True
else:
team2Captured = False
if not self.enemy1KnownLocation is None and knownPos1 is None:
dist = min(agent.getMazeDistance(self.enemy1KnownLocation, self.pastTeamLocation1), agent.getMazeDistance(self.enemy1KnownLocation, self.pastTeamLocation2))
if dist < 3:
enemy1Captured = True
else:
enemy1Captured = False
else:
enemy1Captured = False
if not self.enemy2KnownLocation is None and knownPos2 is None:
dist = min(agent.getMazeDistance(self.enemy2KnownLocation, self.pastTeamLocation1), agent.getMazeDistance(self.enemy2KnownLocation, self.pastTeamLocation2))
if dist < 3:
enemy2Captured = True
else:
enemy2Captured = False
else:
enemy2Captured = False
if enemy1Captured:
self.addPositionForConsideration(self.enemyStartPos, invaders, defenders, isRed)
knownPos1 = self.enemyStartPos
if enemy2Captured:
self.addPositionForConsideration(self.enemyStartPos, invaders, defenders, isRed)
knownPos2 = self.enemyStartPos
# If a team member was captured, assume that the nearest enemy to that team member is now where the team member was. (POS NOT KNOWN)
# An enemy can't capture a team member without the team member knowing where the enemy is at the time of the capture
if team1Captured and team2Captured:
if not self.enemy1KnownLocation is None and not self.enemy2KnownLocation is None:
dist11 = agent.getMazeDistance(self.enemy1KnownLocation, self.pastTeamLocation1)
dist12 = agent.getMazeDistance(self.enemy1KnownLocation, self.pastTeamLocation2)
dist21 = agent.getMazeDistance(self.enemy2KnownLocation, self.pastTeamLocation1)
dist22 = agent.getMazeDistance(self.enemy2KnownLocation, self.pastTeamLocation2)
canBothCapture1 = False
canBothCapture2 = False
if dist11 < 3 and dist21 < 3:
#Both agents could capture team1
canBothCapture1 = True
elif dist11 < 3 and knownPos1 is None:
#Enemy1 must have captured team1
knownPos1 = self.pastTeamLocation1
self.addPositionForConsideration(self.pastTeamLocation1, invaders, defenders, isRed)
elif dist21 < 3 and knownPos2 is None:
#Enemy2 must have captured team1
knownPos2 = self.pastTeamLocation1
self.addPositionForConsideration(self.pastTeamLocation1, invaders, defenders, isRed)
if dist12 < 3 and dist22 < 3:
#Both agents could capture team2
canBothCapture2 = True
elif dist12 < 3 and knownPos1 is None:
#Enemy1 must have captured team2
knownPos1 = self.pastTeamLocation2
self.addPositionForConsideration(self.pastTeamLocation2, invaders, defenders, isRed)
elif dist22 < 3 and knownPos2 is None:
#Enemy2 must have captured team2
knownPos2 = self.pastTeamLocation2
self.addPositionForConsideration(self.pastTeamLocation2, invaders, defenders, isRed)
if canBothCapture1 and canBothCapture2:
#Make arbitrary assumption
self.addPositionForConsideration(self.pastTeamLocation1, invaders, defenders, isRed)
self.addPositionForConsideration(self.pastTeamLocation2, invaders, defenders, isRed)
elif canBothCapture1:
self.addPositionForConsideration(self.pastTeamLocation1, invaders, defenders, isRed)
elif canBothCapture2:
self.addPositionForConsideration(self.pastTeamLocation2, invaders, defenders, isRed)
elif not self.enemy1KnownLocation is None and knownPos1 is None:
#Enemy1 Captured both agents at once
knownPos1 = self.pastTeamLocation1
self.addPositionForConsideration(self.pastTeamLocation1, invaders, defenders, isRed)
elif knownPos2 is None:
#Enemy2 Captured both agents at once
knownPos2 = self.pastTeamLocation1
self.addPositionForConsideration(self.pastTeamLocation1, invaders, defenders, isRed)
elif team1Captured:
if not self.enemy1KnownLocation is None and not self.enemy2KnownLocation is None:
dist1 = agent.getMazeDistance(self.enemy1KnownLocation, self.pastTeamLocation1)
dist2 = agent.getMazeDistance(self.enemy2KnownLocation, self.pastTeamLocation1)
if dist1 < 3 and dist2 < 3:
pass
elif dist1 < 3 and knownPos1 is None:
#Enemy1 must have captured team1
knownPos1 = self.pastTeamLocation1
self.addPositionForConsideration(self.pastTeamLocation1, invaders, defenders, isRed)
elif knownPos2 is None:
knownPos2 = self.pastTeamLocation1
#Enemy2 must have captured team1
self.addPositionForConsideration(self.pastTeamLocation1, invaders, defenders, isRed)
elif not self.enemy1KnownLocation is None and knownPos1 is None:
#Enemy1 must have captured team1
knownPos1 = self.pastTeamLocation1
self.addPositionForConsideration(self.pastTeamLocation1, invaders, defenders, isRed)
elif knownPos2 is None:
knownPos2 = self.pastTeamLocation1
#Enemy2 must have captured team1
self.addPositionForConsideration(self.pastTeamLocation1, invaders, defenders, isRed)
elif team2Captured:
if not self.enemy1KnownLocation is None and not self.enemy2KnownLocation is None:
dist1 = agent.getMazeDistance(self.enemy1KnownLocation, self.pastTeamLocation2)
dist2 = agent.getMazeDistance(self.enemy2KnownLocation, self.pastTeamLocation2)
if dist1 < 3 and dist2 < 3 and knownPos1 is None and knownPos2 is None:
#Both agents could capture team1, arbitrary decision
self.addPositionForConsideration(self.pastTeamLocation2, invaders, defenders, isRed)
elif dist1 < 3 and knownPos1 is None:
#Enemy1 must have captured team1
knownPos1 = self.pastTeamLocation2
self.addPositionForConsideration(self.pastTeamLocation2, invaders, defenders, isRed)
elif dist2 < 3 and knownPos2 is None:
#Enemy2 must have captured team1
knownPos2 = self.pastTeamLocation2
self.addPositionForConsideration(self.pastTeamLocation2, invaders, defenders, isRed)
elif not self.enemy1KnownLocation is None and knownPos1 is None:
#Enemy1 must have captured team1
knownPos1 = self.pastTeamLocation2
self.addPositionForConsideration(self.pastTeamLocation2, invaders, defenders, isRed)
elif knownPos2 is None:
#Enemy2 must have captured team1
knownPos2 = self.pastTeamLocation2
self.addPositionForConsideration(self.pastTeamLocation2, invaders, defenders, isRed)
# If food was eaten, assume that the nearest enemy to that food is now where the food was. Otherwise, no enemy can be at a food location (POS NOT KNOWN)
if len(self.pastFood.asList()) > len(newFood.asList()):
for r in range(self.walls.height):
for c in range(self.walls.width):
if self.pastFood[c][r] and not newFood[c][r]:
pos = (c,r)
eatenFood.append(pos)
#for each food eaten, get the total probability of spaces surrounding the food for both enemies.
for pos in eatenFood:
self.addPositionForConsideration(pos, invaders, defenders, isRed)
for r in range(self.walls.height):
for c in range(self.walls.width):
if newFood[c][r]:
possiblePositions1[c][r] = False
possiblePositions2[c][r] = False
# If a capsule was eaten, assume that the nearest enemy to that capsule is now where the capsule was. Otherwise, no enemy can be at a capsule location (POS NOT KNOWN)
if len(self.pastCapsules) > len(newCapsules):
for capsule in self.pastCapsules:
if not capsule in newCapsules:
eatenCapsules.append(capsule)
for pos in eatenCapsules:
self.addPositionForConsideration(pos, invaders, defenders, isRed)
for pos in newCapsules:
x, y = pos
possiblePositions1[x][y] = False
possiblePositions2[x][y] = False
# If an enemy is defending, it must be on its side of the field. Otherwise, it must be on your side of the field. (POS NOT KNOWN)
if enemy1State.isPacman:
for r in range(self.walls.height):
for c in range(self.walls.width):
if enemiesRed:
if c < self.walls.width / 2:
possiblePositions1[c][r] = False
else:
if c >= self.walls.width / 2:
possiblePositions1[c][r] = False
else:
for r in range(self.walls.height):
for c in range(self.walls.width):
if enemiesRed:
if c >= self.walls.width / 2:
possiblePositions1[c][r] = False
else:
if c < self.walls.width / 2:
possiblePositions1[c][r] = False
if enemy2State.isPacman:
for r in range(self.walls.height):
for c in range(self.walls.width):
if enemiesRed:
if c < self.walls.width / 2:
possiblePositions2[c][r] = False
else:
if c >= self.walls.width / 2:
possiblePositions2[c][r] = False
else:
for r in range(self.walls.height):
for c in range(self.walls.width):
if enemiesRed:
if c >= self.walls.width / 2:
possiblePositions2[c][r] = False
else:
if c < self.walls.width / 2:
possiblePositions2[c][r] = False
if not knownPos1 is None:
possiblePositions1 = self.getGridWithPositions([knownPos1])
if not knownPos2 is None:
possiblePositions2 = self.getGridWithPositions([knownPos2])
self.pastTeamLocation1 = teamPosition1
self.pastTeamLocation2 = teamPosition2
self.pastFood = agent.getFoodYouAreDefending(gameState)
self.pastCapsules = agent.getCapsulesYouAreDefending(gameState)
self.enemy1KnownLocation = knownPos1
self.enemy2KnownLocation = knownPos2
self.adjustConsideration(invaders, defenders)
return possiblePositions1, possiblePositions2
def update(self, gameState, agent, teamPosition1, teamPosition2, verbose = False):
self.possiblePositions1, self.possiblePositions2 = self.updatePart(gameState, agent, teamPosition1, teamPosition2, verbose)
def getPositionPossibleGrid(self):
g = Grid(self.walls.width, self.walls.height)
for r in range(self.walls.height):
for c in range(self.walls.width):
g[c][r] = self.possiblePositions1[c][r] or self.possiblePositions2[c][r]
return g
def getPositionsToInvestigate(self):
return self.positionsToInvestigate
def getPositionsToAvoid(self):
return self.positionsToAvoid
def removePositionFromInvestigation(self, pos):
self.positionsToInvestigate.remove(pos)
def removePositionFromAvoidance(self, pos):
self.positionsToAvoid.remove(pos)
ENOUGH_DOTS = 4
target1 = None
target2 = None
mode1 = None
mode2 = None
needHelp = False
chargeInvaderCounter = 0
invaderPresentCounter = 0
ignoreCounter1 = 0
ignoreCounter2 = 0
random1 = 0
class ReflexCaptureAgent(CaptureAgent):
"""
A base class for reflex agents that chooses score-maximizing actions
"""
def registerInitialState(self, gameState):
global enemyLocationPredictor
global mode1
global mode2
CaptureAgent.registerInitialState(self, gameState)
self.ignoreCounter = 0
self.start = gameState.getAgentPosition(self.index)
self.pastLocation = self.start
self.depthGrid, self.chokePoints = getDepthsAndChokePoints(gameState)
if enemyLocationPredictor == None:
self.isLead = True
self.targetId = 1
enemyLocationPredictor = EnemyLocationPredictor(gameState, self)
else:
self.targetId = 2
self.isLead = False
self.prevFood = self.getFood(gameState)
self.prevFoodDef = self.getFoodYouAreDefending(gameState)
self.prevScore = self.getScore(gameState)
self.prevCapsules = self.getCapsules(gameState)
self.prevEnemyCapsules = self.getCapsules(gameState)
self.openSpaces = 0
for a in gameState.getWalls():
for b in a:
if not b:
self.openSpaces += 1
#Starting Mode
self.mode = 'Travel to Center'
if self.targetId == 1:
mode1 = self.mode
else:
mode2 = self.mode
self.justSpawned = True
self.dotsHeld = 0
self.dotsHeldByInvaders = 0
teamIndices = self.getTeam(gameState)
if teamIndices[0] != self.index:
self.teamIndex = teamIndices[0]
else:
self.teamIndex = teamIndices[1]
self.capsuleOn = False
self.enemyCapsuleOn = False
self.timeUntilCapsuleOver = 0
self.timeUntilEnemyCapsuleOver = 0
self.target = None
# Switches between Charge Capsule and Shallow Offense
def getNextMode(self, gameState, verbose = False):
global mode1
global mode2
global chargeInvaderCounter
global invaderPresentCounter
global target1
global target2
currentMode = self.mode
if self.targetId == 1:
otherMode = mode2
else:
otherMode = mode1
state = gameState.getAgentState(self.index)
currentPos = gameState.getAgentPosition(self.index)
enemies = [gameState.getAgentState(i) for i in self.getOpponents(gameState)]
enemiesKnown = [a for a in enemies if a.getPosition() != None]
invaders = [a for a in enemies if a.isPacman]
invadersKnown = [a for a in enemies if a.isPacman and a.getPosition() != None]
defenders = [a for a in enemies if not a.isPacman]
defendersKnown = [a for a in enemies if not a.isPacman and a.getPosition() != None]
invaderKnownPositions = [a.getPosition() for a in invadersKnown]
defenderKnownPositions = [a.getPosition() for a in defendersKnown]
defenderDist = 1000
for pos in defenderKnownPositions:
dist = self.getMazeDistance(pos, currentPos)
if dist < defenderDist:
defenderDist = dist
invaderDist = 1000
for pos in invaderKnownPositions:
dist = self.getMazeDistance(pos, currentPos)
if dist < invaderDist:
invaderDist = dist
scoreDiff = self.getScore(gameState)
"""
Important Factors:
- Last mode
- Was just captured
- Invader near
- Defender near
- Aggression
- Score Advantage
- Whether shallow targets exist
- Whether there are invaders
- Whether on Offense
- Whether Capsule can be charged safely
- Whether holding enough food
- is Capsule on
- is Enemy Capsule on
"""
teamPos = gameState.getAgentPosition(self.teamIndex)
shallowTargetsExist = False
for shallow in getShallowFood(gameState, self, self.red).asList():
if self.getMazeDistance(shallow, currentPos) < self.getMazeDistance(shallow, teamPos):
shallowTargetsExist = True
break
if len(defendersKnown) > 0:
capsuleAdvantage = min([getDistAdvantageCapsule(gameState, self, a.getPosition(), not state.isPacman) for a in defendersKnown])
else:
capsuleAdvantage = -1
#TODO
captured = self.justSpawned
invaderNear = invaderDist < 6
defenderNear = defenderDist < 4
isAggressive = getAggression(gameState, currentPos, self.red) >= 0.25
significantAdvantage = scoreDiff > 8
invadersExist = len(invaders)
onOffense = state.isPacman
canChargeCapsule = capsuleAdvantage >= 0
holdingEnoughFood = self.dotsHeld >= ENOUGH_DOTS
isCapsuleOn = self.capsuleOn
isEnemyCapsuleOn = self.enemyCapsuleOn
needHelp = chargeInvaderCounter > 30
aLotOfFoodHeldByEnemies = self.dotsHeldByInvaders > 4
invaderPresentForAWhile = invaderPresentCounter > 12
if currentMode == "Travel to Center":
if invaderNear and (not isEnemyCapsuleOn):
return "Charge Invader"
elif isAggressive:
if significantAdvantage and (not onOffense):
return "Sentry"
elif shallowTargetsExist:
return "Shallow Offense"
else:
return "Deep Offense"
else:
return "Travel to Center"
elif currentMode == "Charge Invader":
if captured:
return "Travel to Center"
elif ((invadersExist and (not invaderNear)) or ((not invadersExist) and significantAdvantage)) and (not onOffense):
return "Sentry"
elif (not invadersExist) and (not significantAdvantage) and shallowTargetsExist and (not significantAdvantage):
return "Shallow Offense"
elif (not invadersExist) and (not significantAdvantage) and (not shallowTargetsExist) and (not significantAdvantage):
return "Deep Offense"
else:
return "Charge Invader"
elif currentMode == "Retreat":
if captured:
return "Travel to Center"
elif invaderNear and onOffense and canChargeCapsule and (not isCapsuleOn):
return "Charge Capsule"
elif not onOffense:
return "Sentry"
else:
return "Retreat"
elif currentMode == "Charge Capsule":
if captured:
return "Travel to Center"
elif (not canChargeCapsule) and defenderNear:
return "Retreat"
elif (not defenderNear) and shallowTargetsExist and (not holdingEnoughFood) and (not significantAdvantage):
return "Shallow Offense"
elif (not defenderNear) and (not shallowTargetsExist) and (not holdingEnoughFood) and (not significantAdvantage):
return "Deep Offense"
elif not isCapsuleOn:
return "Charge Capsule"
else:
return "Shallow Offense"
elif currentMode == "Intercept Invader":
if captured:
return "Travel to Center"
elif invaderNear and (not onOffense) and ((otherMode != "Charge Invader" and otherMode != "Intercept Invader" and otherMode != "Sentry") or needHelp):
return "Charge Invader"
elif defenderNear and (not canChargeCapsule) and (not isCapsuleOn):
return "Retreat"
elif defenderNear and canChargeCapsule and (not isCapsuleOn):
return "Charge Capsule"
elif (not onOffense) and invadersExist:
return "Sentry"
elif (not invaderNear) and (not defenderNear) and shallowTargetsExist and (not holdingEnoughFood) and (not aLotOfFoodHeldByEnemies) and (not invaderPresentForAWhile) and (not significantAdvantage):
return "Shallow Offense"
elif (not invaderNear) and (not defenderNear) and (not shallowTargetsExist) and (not holdingEnoughFood) and (not aLotOfFoodHeldByEnemies) and (not invaderPresentForAWhile) and (not significantAdvantage):
return "Deep Offense"
else:
return "Intercept Invader"
elif currentMode == "Shallow Offense":
if captured:
return "Travel to Center"
elif (defenderNear and (not canChargeCapsule) and (not isCapsuleOn)) or holdingEnoughFood or significantAdvantage:
return "Retreat"
elif defenderNear and canChargeCapsule and (not isCapsuleOn):
return "Charge Capsule"
elif ((not defenderNear) and invaderNear or aLotOfFoodHeldByEnemies or invaderPresentForAWhile) and ((otherMode != "Charge Invader" and otherMode != "Intercept Invader" and otherMode != "Sentry") or needHelp):
return "Intercept Invader"
elif (not defenderNear) and (not shallowTargetsExist) and (not holdingEnoughFood):
return "Deep Offense"
else:
return "Shallow Offense"
elif currentMode == "Deep Offense":
if captured:
return "Travel to Center"
elif (defenderNear and (not canChargeCapsule) and (not isCapsuleOn)) or holdingEnoughFood or significantAdvantage:
return "Retreat"