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 __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 __init__(self, layout_text): """Create Layout from 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): if layoutText[0][0] not in ['X', '%']: layoutText = layoutText[1:] 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): """ 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 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 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, layoutText): self.width = len(layoutText[0]) self.height = len(layoutText) global lW lW = self.width global lH lH = self.height 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 _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 __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 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 __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.unexplored = Grid(self.width, self.height, True) #To keep track of self.unexploredAccessible = Grid(self.width, self.height, False) #keeps track of what's unexplored, but resets when everything is explored self.unexploredRepeat = Grid(self.width, self.height, True) self.capsules = [] self.agentPositions = [] self.numGhosts = 0 self.processLayoutText(layoutText) self.layoutText = layoutText self.totalFood = len(self.food.asList())
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 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 __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 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 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 drawWallBeliefs(self, known_map=None, direction="North", visited_states_to_render=[]): 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) self.display.clearExpandedCells() # Erase previous colors self.display.drawWalls(wallGrid, formatColor(.9, 0, 0), allTrueWallGrid) refresh()
def halfGrid(grid, red): halfway = grid.width / 2 halfgrid = Grid(grid.width, grid.height, False) if red: xrange = list(range(int(halfway))) else: xrange = list(range(int(halfway), int(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=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 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 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): layoutText = self.mirror(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.transport = defaultdict(list) self.processLayoutText(layoutText) self.layoutText = layoutText self.totalFood = len(self.food.asList()) for char in self.transport.keys(): posList = self.transport[char] self.transport[posList[0]] = posList[1] self.transport[posList[1]] = posList[0] del self.transport[char]
def gridCopy(grid): gridList = [] gridInfo = grid.packBits() #def __init__(self, width, height, initialValue=False, bitRepresentation=None): x = gridInfo[0] y = gridInfo[1] gridCP = Grid(x / 2, y / 2, False, None) for i in range(x / 2): for j in range(y / 2): gridCP[i][j] = grid[i][j] gridList.append(gridCP) print 'grid copy' print gridCP gridCP = Grid(x / 2 + x % 2, y / 2, False, None) for i in range(x / 2 + x % 2): for j in range(y / 2): gridCP[i][j] = grid[i + x / 2][j] gridList.append(gridCP) print gridCP gridCP = Grid(x / 2, y / 2 + y % 2, False, None) for i in range(x / 2): for j in range(y / 2 + y % 2): gridCP[i][j] = grid[i][j + y / 2] gridList.append(gridCP) print gridCP gridCP = Grid(x / 2 + x % 2, y / 2 + y % 2, False, None) for i in range(x / 2 + x % 2, ): for j in range(y / 2 + y % 2): gridCP[i][j] = grid[i + x / 2][j + y / 2] gridList.append(gridCP) print gridCP print gridList print 'gridList[0]' print gridList[0] print 'return' return gridList
def solve(grid_id): "Solve the grid for the given id" 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]) solver = Solver(grid) solver.solve() grid_data[grid_id] = repr(grid) save_data() return repr(grid)
def halfGrid(grid, red): halfway = grid.height / 2 halfgrid = Grid(grid.width, grid.height, False) if red: yrange = range(halfway) else: yrange = range(halfway, grid.height) for x in range(grid.width): for y in yrange: if grid[x][y]>0: halfgrid[x][y] = grid[x][y] return halfgrid
def __init__(self, layoutText,isRand = False): 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 """ Insert New Food """ """ Random for Maze in PositionSearch Problem """ maxY = self.height - 1 hasfood = [] for y in range(self.height): for x in range(self.width): layoutChar = layoutText[maxY - y][x] if isfoodcell(layoutChar): hasfood.append((x,y)) if isRand and len(hasfood) == 1: # Remove food (x,y) xremove, yremove = hasfood[0] layoutText[maxY - yremove] = layoutText[maxY - yremove][:xremove] + ' ' + layoutText[maxY - yremove][xremove + 1:] # Candidate for cell food canchoice = [] for y in range(self.height): for x in range(self.width): layoutChar = layoutText[maxY - y][x] if isemptycell(layoutChar): canchoice.append((x,y)) xrand, yrand = random.choice(canchoice) #Repalce ' ' -> '.' at cell (xrand,yrand) layoutText[maxY - yrand] = layoutText[maxY - yrand][:xrand] + '.' + layoutText[maxY - yrand][xrand + 1:] 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'