-
Notifications
You must be signed in to change notification settings - Fork 0
/
otherBustersAgents.py
287 lines (244 loc) · 11.3 KB
/
otherBustersAgents.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
from __future__ import print_function
# bustersAgents.py
# ----------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# ([email protected]) and Dan Klein ([email protected]).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel ([email protected]).
from builtins import range
from builtins import object
import util
from game import Agent
from game import Directions
from keyboardAgents import KeyboardAgent
import inference
import busters
import numpy as np
import os.path
class NullGraphics(object):
"Placeholder for graphics"
def initialize(self, state, isBlue = False):
pass
def update(self, state):
pass
def pause(self):
pass
def draw(self, state):
pass
def updateDistributions(self, dist):
pass
def finish(self):
pass
class KeyboardInference(inference.InferenceModule):
"""
Basic inference module for use with the keyboard.
"""
def initializeUniformly(self, gameState):
"Begin with a uniform distribution over ghost positions."
self.beliefs = util.Counter()
for p in self.legalPositions: self.beliefs[p] = 1.0
self.beliefs.normalize()
def observe(self, observation, gameState):
noisyDistance = observation
emissionModel = busters.getObservationDistribution(noisyDistance)
pacmanPosition = gameState.getPacmanPosition()
allPossible = util.Counter()
for p in self.legalPositions:
trueDistance = util.manhattanDistance(p, pacmanPosition)
if emissionModel[trueDistance] > 0:
allPossible[p] = 1.0
allPossible.normalize()
self.beliefs = allPossible
def elapseTime(self, gameState):
pass
def getBeliefDistribution(self):
return self.beliefs
class BustersAgent(object):
"An agent that tracks and displays its beliefs about ghost positions."
def __init__( self, index = 0, inference = "ExactInference", ghostAgents = None, observeEnable = True, elapseTimeEnable = True):
inferenceType = util.lookup(inference, globals())
self.inferenceModules = [inferenceType(a) for a in ghostAgents]
self.observeEnable = observeEnable
self.elapseTimeEnable = elapseTimeEnable
def registerInitialState(self, gameState):
"Initializes beliefs and inference modules"
import __main__
self.display = __main__._display
for inference in self.inferenceModules:
inference.initialize(gameState)
self.ghostBeliefs = [inf.getBeliefDistribution() for inf in self.inferenceModules]
self.firstMove = True
def observationFunction(self, gameState):
"Removes the ghost states from the gameState"
agents = gameState.data.agentStates
gameState.data.agentStates = [agents[0]] + [None for i in range(1, len(agents))]
return gameState
def getAction(self, gameState):
"Updates beliefs, then chooses an action based on updated beliefs."
#for index, inf in enumerate(self.inferenceModules):
# if not self.firstMove and self.elapseTimeEnable:
# inf.elapseTime(gameState)
# self.firstMove = False
# if self.observeEnable:
# inf.observeState(gameState)
# self.ghostBeliefs[index] = inf.getBeliefDistribution()
#self.display.updateDistributions(self.ghostBeliefs)
return self.chooseAction(gameState)
def chooseAction(self, gameState):
"By default, a BustersAgent just stops. This should be overridden."
return Directions.STOP
def update(self, *args, **kwargs):
return
class BustersKeyboardAgent(BustersAgent, KeyboardAgent):
"An agent controlled by the keyboard that displays beliefs about ghost positions."
def __init__(self, index = 0, inference = "KeyboardInference", ghostAgents = None):
KeyboardAgent.__init__(self, index)
BustersAgent.__init__(self, index, inference, ghostAgents)
def getAction(self, gameState):
return BustersAgent.getAction(self, gameState)
def chooseAction(self, gameState):
return KeyboardAgent.getAction(self, gameState)
from distanceCalculator import Distancer
from game import Actions
from game import Directions
import random, sys
'''Random PacMan Agent'''
class RandomPAgent(BustersAgent):
def registerInitialState(self, gameState):
BustersAgent.registerInitialState(self, gameState)
self.distancer = Distancer(gameState.data.layout, False)
''' Example of counting something'''
def countFood(self, gameState):
food = 0
for width in gameState.data.food:
for height in width:
if(height == True):
food = food + 1
return food
''' Print the layout'''
def printGrid(self, gameState):
table = ""
##print(gameState.data.layout) ## Print by terminal
for x in range(gameState.data.layout.width):
for y in range(gameState.data.layout.height):
food, walls = gameState.data.food, gameState.data.layout.walls
table = table + gameState.data._foodWallStr(food[x][y], walls[x][y]) + ","
table = table[:-1]
return table
def chooseAction(self, gameState):
move = Directions.STOP
legal = gameState.getLegalActions(0) ##Legal position from the pacman
move_random = random.randint(0, 3)
if ( move_random == 0 ) and Directions.WEST in legal: move = Directions.WEST
if ( move_random == 1 ) and Directions.EAST in legal: move = Directions.EAST
if ( move_random == 2 ) and Directions.NORTH in legal: move = Directions.NORTH
if ( move_random == 3 ) and Directions.SOUTH in legal: move = Directions.SOUTH
return move
class GreedyBustersAgent(BustersAgent):
"An agent that charges the closest ghost."
def registerInitialState(self, gameState):
"Pre-computes the distance between every two points."
BustersAgent.registerInitialState(self, gameState)
self.distancer = Distancer(gameState.data.layout, False)
def chooseAction(self, gameState):
"""
First computes the most likely position of each ghost that has
not yet been captured, then chooses an action that brings
Pacman closer to the closest ghost (according to mazeDistance!).
To find the mazeDistance between any two positions, use:
self.distancer.getDistance(pos1, pos2)
To find the successor position of a position after an action:
successorPosition = Actions.getSuccessor(position, action)
livingGhostPositionDistributions, defined below, is a list of
util.Counter objects equal to the position belief
distributions for each of the ghosts that are still alive. It
is defined based on (these are implementation details about
which you need not be concerned):
1) gameState.getLivingGhosts(), a list of booleans, one for each
agent, indicating whether or not the agent is alive. Note
that pacman is always agent 0, so the ghosts are agents 1,
onwards (just as before).
2) self.ghostBeliefs, the list of belief distributions for each
of the ghosts (including ghosts that are not alive). The
indices into this list should be 1 less than indices into the
gameState.getLivingGhosts() list.
"""
pacmanPosition = gameState.getPacmanPosition()
legal = [a for a in gameState.getLegalPacmanActions()]
livingGhosts = gameState.getLivingGhosts()
livingGhostPositionDistributions = \
[beliefs for i, beliefs in enumerate(self.ghostBeliefs)
if livingGhosts[i+1]]
return Directions.EAST
class BasicAgentAA(BustersAgent):
def registerInitialState(self, gameState):
BustersAgent.registerInitialState(self, gameState)
self.distancer = Distancer(gameState.data.layout, False)
self.countActions = 0
''' Example of counting something'''
def countFood(self, gameState):
food = 0
for width in gameState.data.food:
for height in width:
if(height == True):
food = food + 1
return food
''' Print the layout'''
def printGrid(self, gameState):
table = ""
#print(gameState.data.layout) ## Print by terminal
for x in range(gameState.data.layout.width):
for y in range(gameState.data.layout.height):
food, walls = gameState.data.food, gameState.data.layout.walls
table = table + gameState.data._foodWallStr(food[x][y], walls[x][y]) + ","
table = table[:-1]
return table
def printInfo(self, gameState):
print("---------------- TICK ", self.countActions, " --------------------------")
# Map size
width, height = gameState.data.layout.width, gameState.data.layout.height
print("Width: ", width, " Height: ", height)
# Pacman position
print("Pacman position: ", gameState.getPacmanPosition())
# Legal actions for Pacman in current position
print("Legal actions: ", gameState.getLegalPacmanActions())
# Pacman direction
print("Pacman direction: ", gameState.data.agentStates[0].getDirection())
# Number of ghosts
print("Number of ghosts: ", gameState.getNumAgents() - 1)
# Alive ghosts (index 0 corresponds to Pacman and is always false)
print("Living ghosts: ", gameState.getLivingGhosts())
# Ghosts positions
print("Ghosts positions: ", gameState.getGhostPositions())
# Ghosts directions
print("Ghosts directions: ", [gameState.getGhostDirections().get(i) for i in range(0, gameState.getNumAgents() - 1)])
# Manhattan distance to ghosts
print("Ghosts distances: ", gameState.data.ghostDistances)
# Pending pac dots
print("Pac dots: ", gameState.getNumFood())
# Manhattan distance to the closest pac dot
print("Distance nearest pac dots: ", gameState.getDistanceNearestFood())
# Map walls
print("Map:")
print( gameState.getWalls())
# Score
print("Score: ", gameState.getScore())
def chooseAction(self, gameState):
self.countActions = self.countActions + 1
self.printInfo(gameState)
move = Directions.STOP
legal = gameState.getLegalActions(0) ##Legal position from the pacman
move_random = random.randint(0, 3)
if ( move_random == 0 ) and Directions.WEST in legal: move = Directions.WEST
if ( move_random == 1 ) and Directions.EAST in legal: move = Directions.EAST
if ( move_random == 2 ) and Directions.NORTH in legal: move = Directions.NORTH
if ( move_random == 3 ) and Directions.SOUTH in legal: move = Directions.SOUTH
return move
def printLineData(self, gameState):
return "XXXXXXXXXX"