def __init__(self, layoutText): self.width = len(layoutText[0]) self.height = len(layoutText) self.walls = Grid(self.width, self.height, False) self.food = Grid(self.width, self.height, False) self.capsules = [] self.agentPositions = [] self.numGhosts = 0 self.numPacmen = 0 # TODO If already has more than total, need to remove? # Should be fine # if fillRandom: # # Randomly adds more ghosts and pacmen # self.fillWithType(layoutText, numPacmen, 'P') # self.fillWithType(layoutText, numGhosts, 'G') # # if generateFood: # numWalls = sum([line.count('%') for line in layoutText]) # numFood = (self.width * self.height - numWalls - numPacmen - numGhosts) * foodDensity # numFood = int(numFood) # self.fillWithType(layoutText, numFood, '.') self.processLayoutText(layoutText) self.layoutText = layoutText self.totalFood = len(self.food.asList())
def drawWallandPositionBeliefs(self, known_map=None, possibleLocations=None, direction="North", visited_states_to_render=[], pacman_position=None): import random import __main__ from graphicsUtils import draw_background, refresh known_walls, known_non_walls = self.get_known_walls_non_walls_from_known_map( known_map) wallGrid = Grid(self.problem.walls.width, self.problem.walls.height, initialValue=False) wallGrid.data = known_walls allTrueWallGrid = Grid(self.problem.walls.width, self.problem.walls.height, initialValue=True) # Recover list of non-wall coords: non_wall_coords = [] for x in range(len(known_non_walls)): for y in range(len(known_non_walls[x])): if known_non_walls[x][y] == 1: non_wall_coords.append((x, y)) self.display.clearExpandedCells() # Erase previous colors self.display.drawWalls(wallGrid, formatColor(.9, 0, 0), allTrueWallGrid) self.display.colorCircleSquareCells(possibleLocations, square_cells=non_wall_coords, direction=direction, pacman_position=pacman_position) refresh()
def __init__(self, layoutText=None, seed=None, width=None, height=None, vpi=False): if layoutText: self.width = len(layoutText[0]) self.height = len(layoutText) self.walls = Grid(self.width, self.height, False) self.redWalls = Grid(self.width, self.height, False) self.blueWalls = Grid(self.width, self.height, False) self.food = Grid(self.width, self.height, False) self.capsules = [] self.agentPositions = [] self.numGhosts = 0 self.processLayoutText(layoutText) self.layoutText = layoutText self.totalFood = len(self.food.asList()) elif vpi: layoutText = generateVPIHuntersBoard(seed) self.__init__(layoutText) else: layoutText = generateRandomHuntersBoard(seed, width, height) self.__init__(layoutText)
def __init__(self, layoutText): self.width = len(layoutText[0]) self.height = len(layoutText) self.walls = Grid(self.width, self.height, False) self.food = Grid(self.width, self.height, False) self.capsules = [] self.agentPositions = [] self.numGhosts = 0 self.processLayoutText(layoutText) self.layoutText = layoutText
def __init__(self, layoutText): width = len(layoutText[0]) height= len(layoutText) walls = Grid(width, height, False) food = Grid(width, height, False) capsules = [] agentPositions = [] numGhosts = 0 Layout.__init__(self, width, height, walls, food, capsules, agentPositions, numGhosts) self.processLayoutText(layoutText) self.layoutText = layoutText
def __init__(self, layout_text): self.width = len(layout_text[0]) self.height = len(layout_text) self.walls = Grid(self.width, self.height, False) self.food = Grid(self.width, self.height, False) self.capsules = [] self.agent_positions = [] self.num_ghosts = 0 self.process_layout_text(layout_text) self.layout_text = layout_text self.total_food = len(self.food.as_list())
def __init__(self, layoutText): self.width = len(layoutText[0]) self.height = len(layoutText) self.walls = Grid(self.width, self.height, False) self.food = Grid(self.width, self.height, False) self.capsules = [] self.agentpacman_positions = [] self.numGhosts = 0 self.processLayoutText(layoutText) self.layoutText = layoutText self.totalFood = len(self.food.asList())
def __init__(self, layoutText): self.width = len(layoutText[0]) self.height= len(layoutText) self.walls = Grid(self.width, self.height, False) self.block = Grid(self.width, self.height, False) self.items = [] self.bomb = [] self.agentPositions = [] self.numAgents = 0 self.processLayoutText(layoutText) self.layoutText = layoutText
def setNewGame(self, height, width, n_mines): self.grid = Grid(height, width, n_mines) self.time_start = 0 #serve as a control variable too self.lab_n_flags["text"] = "0/{}".format(n_mines) self.lab_time["text"] = "00:00" self.lab_match.config(fg="#f1c232", text="WAITING") self.but_overagain.config(bg="#ffd966", text="Start over", state="disabled", disabledforeground="black", command=self.overAgain)
def __init__(self, layoutText, maxGhosts): self.width = len(layoutText[0]) self.height = len(layoutText) self.walls = Grid(self.width, self.height, False) self.food = Grid(self.width, self.height, False) self.capsules = [] self.agentPositions = [] self.numGhosts = 0 self.maxGhosts = maxGhosts # Total number of ghosts that game will have (limit on how many we want to display) self.processLayoutText(layoutText) self.layoutText = layoutText self.totalFood = len(self.food.asList())
def handle_general(self, cmd, args): if cmd == 'MSG': msg = deserialize(args, 'unicode') print 'MSG', self.client_id, self.nicks, repr(msg) self.bcast_cmd('MSG', serialize((self.client_id, msg), 'tuple', ['int', 'unicode']), not_to_self = False) elif cmd == 'CHALLENGE_CREATE': clients, map, players = deserialize(args, 'tuple', [['list', 'int'], 'str', ['list', 'Player']]) if self.client_id in self.serv.challenges: self.die('Duplicate challenge') else: self.serv.challenges[self.client_id] = (map, set(clients), {self.client_id: players}) self.mcast_cmd('CHALLENGE_CREATED', serialize((self.client_id, clients, map), 'tuple', ['int', ['list', 'int'], 'str']), self.serv.challenges[self.client_id][1]) elif cmd == 'CHALLENGE_ACCEPT': client_id, players = deserialize(args, 'tuple', ['int', ['list', 'Player']]) if self.challenge_valid(client_id): self.serv.challenges[client_id][2][self.client_id] = players self.mcast_cmd('CHALLENGE_ACCEPTED_BY', serialize((client_id, self.client_id), 'tuple', ['int', 'int']), self.serv.challenges[client_id][1]) self.challenge_cancel_all(except_ = client_id) if self.serv.challenges[client_id][1] == set(self.serv.challenges[client_id][2]): players = [(cid, p) for cid, ps in self.serv.challenges[client_id][2].items() for p in ps] map, (width, height), spawns = load_map(self.serv.challenges[client_id][0]) map = Grid(width, height, map) map.cell_size = (1, 1) map.x = map.y = 0 game = Game(map, spawns, []) teams = [(p.name, None, p.team) for cid, p in players] spawns = game.get_spawnpoints(teams) class Dummy: pass main = Dummy() main.map = game.map main.res = None game.all_players = [GamePlayer(name, [(char, x, y, 0) for char, (x, y) in zip(characters, spawn)], main, None) for (name, remote, characters), spawn in zip(teams, spawns)] game.client_ids = self.serv.challenges[client_id][1] for client in self.serv.clients: if client.client_id not in self.serv.challenges[client_id][1]: continue client.game = game self.mcast_cmd('GAME_START', serialize((self.serv.challenges[client_id][0], spawns, players), 'tuple', ['str', ['list', 'list', ':coord'], ['list', 'tuple', ['int', 'Player']]]), self.serv.challenges[client_id][1]) elif cmd == 'CHALLENGE_REJECT': client_id = deserialize(args, 'int') if self.challenge_valid(client_id): self.challenge_cancel(client_id, self.client_id) elif cmd == 'GAME_MOVE': p, c, t = deserialize(args, 'tuple', ['int', 'int', ':coord']) self.push_actions(self.game.move(self.game.all_players[p].all_characters[c], t)) elif cmd == 'GAME_ATTACK': p, c, t = deserialize(args, 'tuple', ['int', 'int', ':coord']) self.push_actions(self.game.attack(self.game.all_players[p].all_characters[c], t)) elif cmd == 'GAME_ENDTURN': self.push_actions(self.game.end_turn()) else: self.die('Unknown command: ' + repr(cmd))
def __init__(self, layoutText): """ Initialize the layout display the user has chosen. """ self.width = len(layoutText[0]) self.height = len(layoutText) self.walls = Grid(self.width, self.height, False) self.food = Grid(self.width, self.height, False) self.capsules = [] self.agentPositions = [] self.numGhosts = 0 self.processLayoutText(layoutText) self.layoutText = layoutText
def __init__(self, layoutText): self.width = len(layoutText[0]) self.height= len(layoutText) self.walls = Grid(self.width, self.height, 0) self.food = Grid(self.width, self.height, False) self.capsules = [] self.agentPositions = [] ## TODO: (True, pos) if its pacman, (False, pos) otherwise self.MyPacmanPos = (0,0) self.numGhosts = 0 self.numEnemyPacmans = 0 self.processLayoutText(layoutText) self.layoutText = layoutText self.totalFood = len(self.food.asList())
def load(grid_id): "Load game state from examples" difficulty = request.args['difficulty'] if grid_id not in grid_data or grid_data[grid_id] == None: return 'invalid id', 403 grid = Grid(load_from=grid_data[grid_id]) grid.read_file(f'examples/{grid.box_len}/{difficulty}.txt') grid_data[grid_id] = repr(grid) save_data() return 'loaded'
def __init__(self, layoutText, srv): self.server = srv self.width = len(layoutText[0]) self.height = len(layoutText) self.walls = Grid(self.width, self.height, False) self.food = Grid(self.width, self.height, False) self.capsules = [] # self.allCapsules = [] self._hiddenCapsule = [] self.agentPositions = [] self.numGhosts = 0 self.processLayoutText(layoutText) self.layoutText = layoutText self.totalFood = len(self.food.asList())
def __init__(self, startingGameState): """ Stores the walls, pacman's starting position and corners. """ self.walls = startingGameState.getWalls() self.startingPosition = startingGameState.getPacmanPosition() print(self.startingPosition) top, right = self.walls.height - 2, self.walls.width - 2 self.corners = ((1, 1), (1, top), (right, 1), (right, top) ) # corner position as of (x,y) self.mapping = { (1, 1): [1, 0], (1, top): [0, 0], (right, 1): [1, 1], (right, top): [0, 1] } for corner in self.corners: if not startingGameState.hasFood(*corner): print('Warning: no food in corner ' + str(corner)) self._expanded = 0 # Number of search nodes expanded # Please add any code here which you would like to use # in initializing the problem "*** YOUR CODE HERE ***" self.start = (self.startingPosition, Grid(2, 2, False)) self.walls = startingGameState.getWalls() self.startingGameState = startingGameState self.heuristicInfo = { } # A dictionary for the heuristic to store information
def evaluationFunction(self, currentGameState: GameState, action: str) -> float: """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) walls = successorGameState.getWalls() width = walls.width height = walls.height newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghosts = Grid(width, height) for i in range(len(newGhostStates)): if newScaredTimes[i] <= 0: x, y = newGhostStates[i].getPosition() ghosts[int(x)][int(y)] = True queue = util.Queue() queue.push((newPos, 0)) visited = set() shortest = float('inf') ghosts_dis = [] while not queue.isEmpty(): cur, dis = queue.pop() x, y = cur if in_range(cur, width, height) and not walls[x][y] and cur not in visited: visited.add(cur) if newFood[x][y]: shortest = min(dis, shortest) if ghosts[x][y]: ghosts_dis.append(dis) for d in DIRECTIONS: queue.push(((x + d[0], y + d[1]), dis + 1)) if shortest == float('inf'): shortest = 0 score = successorGameState.getScore() def d(x): if x == 0: return float('inf') return 9 / (x**2) score -= shortest + sum(map(d, ghosts_dis)) if action == 'Stop': score -= 10 return score
def _ghost_cost(_ghosts: List[AgentState], pos: Tuple[int, int], walls: Grid): width = walls.width height = walls.height ghosts = Grid(width, height) for i in range(len(_ghosts)): x, y = _ghosts[i].getPosition() ghosts[int(x)][int(y)] = _ghosts[i].scaredTimer queue = util.Queue() queue.push((pos, 0)) visited = set() ghosts_dis = [] s_ghosts_dis = [] while not queue.isEmpty(): cur, dis = queue.pop() x, y = cur if in_range(cur, width, height) and not walls[x][y] and cur not in visited: visited.add(cur) if ghosts[x][y] != False: if ghosts[x][y] <= 0: ghosts_dis.append(dis) else: s_ghosts_dis.append((dis, ghosts[x][y])) pass for d in DIRECTIONS: queue.push(((x + d[0], y + d[1]), dis + 1)) return ghosts_dis, s_ghosts_dis
def initializeVisibilityMatrix(self): global VISIBILITY_MATRIX_CACHE if reduce(str.__add__, self.layoutText) not in VISIBILITY_MATRIX_CACHE: from game import Directions vecs = [(-0.5, 0), (0.5, 0), (0, -0.5), (0, 0.5)] dirs = [ Directions.NORTH, Directions.SOUTH, Directions.WEST, Directions.EAST ] vis = Grid( self.width, self.height, { Directions.NORTH: set(), Directions.SOUTH: set(), Directions.EAST: set(), Directions.WEST: set(), Directions.STOP: set() }) for x in range(self.width): for y in range(self.height): if self.walls[x][y] == False: for vec, direction in zip(vecs, dirs): dx, dy = vec nextx, nexty = x + dx, y + dy while (nextx + nexty) != int(nextx) + int( nexty) or not self.walls[int(nextx)][int( nexty)]: vis[x][y][direction].add((nextx, nexty)) nextx, nexty = x + dx, y + dy self.visibility = vis VISIBILITY_MATRIX_CACHE[reduce(str.__add__, self.layoutText)] = vis else: self.visibility = VISIBILITY_MATRIX_CACHE[reduce( str.__add__, self.layoutText)]
def __init__(self, startingGameState): """ Stores the walls, pacman's starting position and corners. """ self.walls = startingGameState.getWalls() self.startingPosition = startingGameState.getPacmanPosition() top, right = self.walls.height - 2, self.walls.width - 2 self.corners = ((1, 1), (1, top), (right, 1), (right, top)) for corner in self.corners: if not startingGameState.hasFood(*corner): print('Warning: no food in corner ' + str(corner)) self._expanded = 0 # DO NOT CHANGE; Number of search nodes expanded # Please add any code here which you would like to use # in initializing the problem self._visited, self._visitedlist = {}, [] # DO NOT CHANGE cor = Grid(right + 1, top + 1) #a grid for the corners, just like the foodgrid# for x in range(0, right + 1): for y in range(0, top + 1): cor[x][y] = False for corner in self.corners: x = corner[0] y = corner[1] cor[x][y] = True self.start = (startingGameState.getPacmanPosition(), cor)
def __init__(self): pygame.init() pygame.display.set_caption("Grid World") self.clock = pygame.time.Clock() self.last_tick = pygame.time.get_ticks() self.screen_res = [400, 470] self.font = pygame.font.SysFont("Calibri", 16) self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32) self.show_checked = True self.quit = False self.type = "dfs" self.grid = Grid(True) self.ai = AI(self.grid, self.type) self.run = False self.pause = False
def initializeVisibilityMatrix(self): """ Create the visibility matrix of what"s on the display. """ global vismatcache if reduce(str.__add__, self.layoutText) not in vismatcache: from game import Directions vecs = [(-0.5, 0), (0.5, 0), (0, -0.5), (0, 0.5)] dirs = [ Directions.NORTH, Directions.SOUTH, Directions.WEST, Directions.EAST ] vis = Grid( self.width, self.height, { Directions.NORTH: set(), Directions.SOUTH: set(), Directions.EAST: set(), Directions.WEST: set(), Directions.STOP: set() }) for x in range(self.width): for y in range(self.height): if self.walls[x][y] == False: for vec, direction in zip(vecs, dirs): dx, dy = vec nextx, nexty = x + dx, y + dy while (nextx + nexty) != int(nextx) + int( nexty) or not self.walls[int(nextx)][int( nexty)]: vis[x][y][direction].add((nextx, nexty)) nextx, nexty = x + dx, y + dy self.visibility = vis vismatcache[reduce(str.__add__, self.layoutText)] = vis else: self.visibility = vismatcache[reduce(str.__add__, self.layoutText)]
def load(): box_len = get_box_len() difficulties = {1: 'easy', 2: 'medium', 3: 'hard', 4: 'harder'} print('Pick a difficulty to solve:') print(' 1. Easy') print(' 2. Medium') print(' 3. Hard') print(' 4. Harder') difficulty = difficulties[int(input())] choice = f'examples/{box_len}/{difficulty}.txt' grid = Grid(box_len) grid.read_file(choice) return grid
def __init__(self, layoutText): #here self.width = len(layoutText[0]) self.height= len(layoutText) self.walls = Grid(self.width, self.height, False) self.food = Grid(self.width, self.height, False) # Here global portal portal =[] self.portal = Grid(self.width,self.height,False) self.capsules = [] self.agentPositions = [] self.numGhosts = 0 self.processLayoutText(layoutText) self.layoutText = layoutText self.totalFood = len(self.food.asList())
def test_set_initial_state(self): initial_state = [ [True, True], [True, True] ] test_grid = Grid(2, initial_state) for y in range(2): for x in range(2): assert test_grid.diagram[y][x].alive is True
def enter(): box_len = get_box_len() grid = Grid(box_len) for row in range(box_len * box_len): for col in range(box_len * box_len): print(grid) val = input(f'Value for ({row + 1}, {col + 1}): ') or 0 try: val = int(val) except ValueError: val = ord(val.upper()) - 55 grid.get_cell(row, col).value = val if not grid.is_valid(): print('invalid board') exit() return grid
def __init__(self, layoutText, numAgents = 2): self.width = len(layoutText[0]) self.height = len(layoutText) self.obstacles = Grid(self.width, self.height, False) self.agentPositions = [] self.numPursuers = 0 self.numAgents = numAgents self.processLayoutText(layoutText) self.layoutText = layoutText
def main(): world = World( Grid(3, [[False, False, False], [True, True, True], [False, False, False]])) for i in range(100): world.tick() for event in world.history: for row in event.display(): print(" ".join(row)) print("\n")
def __init__(self, layoutText): self.width = len(layoutText[0]) self.height = len(layoutText) self.racetrack = Grid(self.width, self.height, False) self.startStates = [] self.finishStates = [] self.agentPositions = [] self.possibleAgentPositions = [] self.processLayoutText(layoutText) self.layoutText = layoutText
def new(): "Start a new game and register a new id" grid_id = str(len(grid_data)) size = int(request.args['size']) grid = Grid(size) grid_data[grid_id] = repr(grid) save_data() return grid_id
def halfGrid(grid, red): halfway = grid.width // 2 halfgrid = Grid(grid.width, grid.height, False) if red: xrange = range(halfway) else: xrange = range(halfway, grid.width) for y in range(grid.height): for x in xrange: if grid[x][y]: halfgrid[x][y] = True return halfgrid
def __init__(self, layoutText): self.width = len(layoutText[0]) self.height= len(layoutText) self.walls = Grid(self.width, self.height, False) self.food = Grid(self.width, self.height, False) self.capsules = [] self.agentPositions = [] self.numGhosts = 0 self.processLayoutText(layoutText) self.layoutText = layoutText self.totalFood = len(self.food.asList())
def test_shift_left(): grid = Grid() assert(grid.shift_left([2, 0, 0, 0]) == [2, 0, 0, 0]) assert(grid.shift_left([0, 0, 0, 2]) == [2, 0, 0, 0]) assert(grid.shift_left([2, 2, 0, 0]) == [4, 0, 0, 0]) assert(grid.shift_left([2, 0, 2, 0]) == [4, 0, 0, 0]) assert(grid.shift_left([2, 0, 0, 2]) == [4, 0, 0, 0]) assert(grid.shift_left([0, 0, 2, 2]) == [4, 0, 0, 0]) assert(grid.shift_left([2, 2, 2, 0]) == [4, 2, 0, 0]) assert(grid.shift_left([2, 4, 0, 0]) == [2, 4, 0, 0]) assert(grid.shift_left([0, 0, 2, 4]) == [2, 4, 0, 0]) assert(grid.shift_left([2, 2, 2, 2]) == [4, 4, 0, 0]) assert(grid.shift_left([4, 4, 4, 4]) == [8, 8, 0, 0]) assert(grid.shift_left([2, 0, 4, 4]) == [2, 8, 0, 0]) assert(grid.shift_left([2, 2, 0, 2]) == [4, 2, 0, 0]) assert(grid.shift_left([2, 2, 4, 4]) == [4, 8, 0, 0]) assert(grid.shift_left([8, 8, 4, 2]) == [16, 4, 2, 0]) print "Left tests passed."
def test_shift_right(): grid = Grid() assert(grid.shift_right([2, 0, 0, 0]) == [0, 0, 0, 2]) assert(grid.shift_right([2, 2, 0, 0]) == [0, 0, 0, 4]) assert(grid.shift_right([2, 0, 2, 0]) == [0, 0, 0, 4]) assert(grid.shift_right([2, 0, 0, 2]) == [0, 0, 0, 4]) assert(grid.shift_right([0, 0, 2, 2]) == [0, 0, 0, 4]) assert(grid.shift_right([2, 4, 0, 0]) == [0, 0, 2, 4]) assert(grid.shift_right([2, 2, 2, 2]) == [0, 0, 4, 4]) assert(grid.shift_right([4, 4, 4, 4]) == [0, 0, 8, 8]) assert(grid.shift_right([2, 0, 4, 4]) == [0, 0, 2, 8]) assert(grid.shift_right([2, 2, 0, 2]) == [0, 0, 2, 4]) assert(grid.shift_right([2, 2, 4, 4]) == [0, 0, 4, 8]) assert(grid.shift_right([8, 8, 4, 2]) == [0, 16, 4, 2]) print "Right tests passed."
def __init__(self, parent, image_repository): super(Board, self).__init__(parent) self.started = True self.paused = False self.image_repository = image_repository self.config = Config.get() self.size = 50 self.grid = Grid.random(self.config.properties['board_width'], self.config.properties['board_height'], self.config.properties['rock_count'], self.config.properties['diamond_count']) self.game_state = GameState(self.grid, self.grid.cells[1][1], self) for x in range(self.grid.width): for y in range(self.grid.height): self.grid.cells[x][y].game_state = self.game_state self.initUI() self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update_game) self.timer.start(100)
def __init__(self, layoutText=None, seed=None, width=None, height=None, vpi=False): if layoutText: self.width = len(layoutText[0]) self.height= len(layoutText) self.walls = Grid(self.width, self.height, False) self.redWalls = Grid(self.width, self.height, False) self.blueWalls = Grid(self.width, self.height, False) self.food = Grid(self.width, self.height, False) self.capsules = [] self.agentPositions = [] self.numGhosts = 0 self.processLayoutText(layoutText) self.layoutText = layoutText self.totalFood = len(self.food.asList()) elif vpi: layoutText = generateVPIHuntersBoard(seed) self.__init__(layoutText) else: layoutText = generateRandomHuntersBoard(seed, width, height) self.__init__(layoutText)
class Layout: """ A Layout manages the static information about the game board. """ def __init__(self, layoutText): self.width = len(layoutText[0]) self.height= len(layoutText) self.walls = Grid(self.width, self.height, False) self.food = Grid(self.width, self.height, False) self.capsules = [] self.agentPositions = [] self.numGhosts = 0 self.processLayoutText(layoutText) self.layoutText = layoutText self.totalFood = len(self.food.asList()) # self.initializeVisibilityMatrix() def getNumGhosts(self): return self.numGhosts def initializeVisibilityMatrix(self): global VISIBILITY_MATRIX_CACHE if reduce(str.__add__, self.layoutText) not in VISIBILITY_MATRIX_CACHE: from game import Directions vecs = [(-0.5,0), (0.5,0),(0,-0.5),(0,0.5)] dirs = [Directions.NORTH, Directions.SOUTH, Directions.WEST, Directions.EAST] vis = Grid(self.width, self.height, {Directions.NORTH:set(), Directions.SOUTH:set(), Directions.EAST:set(), Directions.WEST:set(), Directions.STOP:set()}) for x in range(self.width): for y in range(self.height): if self.walls[x][y] == False: for vec, direction in zip(vecs, dirs): dx, dy = vec nextx, nexty = x + dx, y + dy while (nextx + nexty) != int(nextx) + int(nexty) or not self.walls[int(nextx)][int(nexty)] : vis[x][y][direction].add((nextx, nexty)) nextx, nexty = x + dx, y + dy self.visibility = vis VISIBILITY_MATRIX_CACHE[reduce(str.__add__, self.layoutText)] = vis else: self.visibility = VISIBILITY_MATRIX_CACHE[reduce(str.__add__, self.layoutText)] def isWall(self, pos): x, col = pos return self.walls[x][col] def getRandomLegalPosition(self): x = random.choice(range(self.width)) y = random.choice(range(self.height)) while self.isWall( (x, y) ): x = random.choice(range(self.width)) y = random.choice(range(self.height)) return (x,y) def getRandomCorner(self): poses = [(1,1), (1, self.height - 2), (self.width - 2, 1), (self.width - 2, self.height - 2)] return random.choice(poses) def getFurthestCorner(self, pacPos): poses = [(1,1), (1, self.height - 2), (self.width - 2, 1), (self.width - 2, self.height - 2)] dist, pos = max([(manhattanDistance(p, pacPos), p) for p in poses]) return pos def isVisibleFrom(self, ghostPos, pacPos, pacDirection): row, col = [int(x) for x in pacPos] return ghostPos in self.visibility[row][col][pacDirection] def __str__(self): return "\n".join(self.layoutText) def deepCopy(self): return Layout(self.layoutText[:]) def processLayoutText(self, layoutText): """ Coordinates are flipped from the input format to the (x,y) convention here The shape of the maze. Each character represents a different type of object. % - Wall . - Food o - Capsule G - Ghost P - Pacman Other characters are ignored. """ maxY = self.height - 1 for y in range(self.height): for x in range(self.width): layoutChar = layoutText[maxY - y][x] self.processLayoutChar(x, y, layoutChar) self.agentPositions.sort() self.agentPositions = [ ( i == 0, pos) for i, pos in self.agentPositions] def processLayoutChar(self, x, y, layoutChar): if layoutChar == '%': self.walls[x][y] = True elif layoutChar == '.': self.food[x][y] = True elif layoutChar == 'o': self.capsules.append((x, y)) elif layoutChar == 'P': self.agentPositions.append( (0, (x, y) ) ) elif layoutChar in ['G']: self.agentPositions.append( (1, (x, y) ) ) self.numGhosts += 1 elif layoutChar in ['1', '2', '3', '4']: self.agentPositions.append( (int(layoutChar), (x,y))) self.numGhosts += 1