def generateMaze(self): # TODO """Generate maze using Prim's algorithm""" import random center_x = Maze.width // 2 center_y = Maze.height // 2 center_tile = self.getTile(center_x, center_y) # Add center tile and center's walls cells = [self.getTile(center_x, center_y)] walls = [(center_x, center_y, direction) for direction in [RIGHT, UP, LEFT, DOWN]] while walls != []: # Choose a random wall wall = walls[random.randint(0, len(walls) - 1)] x, y = wall[0], wall[1] direction = wall[2] try: # Get wall's neighboring tile newTile = self.getTileDelta(x, y, direction) # If neighbor tile is not already in cells, add it and its walls if newTile not in cells: # Do some magic that I can't be bothered to explain nx, ny = x + getDelta(direction)[0], y + getDelta( direction)[1] self.setTile(x, y, direction, False) cells.append(newTile) for d in [RIGHT, UP, LEFT, DOWN]: newWall = (nx, ny, d) newWallAlt = (nx + getDelta(d)[0], ny + getDelta(d)[1], getOpposite(d)) if (newWall not in walls) and (newWallAlt not in walls): walls.append(newWall) else: walls.remove(wall) except AssertionError: # If the wall's neighbor is outside of the grid, remove it walls.remove(wall) pass
def generateMaze(self): # TODO """Generate maze using Prim's algorithm""" import random center_x = Maze.width // 2 center_y = Maze.height // 2 center_tile = self.getTile(center_x, center_y) # Add center tile and center's walls cells = [self.getTile(center_x, center_y)] walls = [(center_x, center_y, direction) for direction in [RIGHT, UP, LEFT, DOWN]] while walls != []: # Choose a random wall wall = walls[random.randint(0, len(walls) - 1)] x, y = wall[0], wall[1] direction = wall[2] try: # Get wall's neighboring tile newTile = self.getTileDelta(x, y, direction) # If neighbor tile is not already in cells, add it and its walls if newTile not in cells: # Do some magic that I can't be bothered to explain nx, ny = x + getDelta(direction)[0], y + getDelta(direction)[1] self.setTile(x, y, direction, False) cells.append(newTile) for d in [RIGHT, UP, LEFT, DOWN]: newWall = (nx, ny, d) newWallAlt = (nx + getDelta(d)[0], ny + getDelta(d)[1], getOpposite(d)) if (newWall not in walls) and (newWallAlt not in walls): walls.append(newWall) else: walls.remove(wall) except AssertionError: # If the wall's neighbor is outside of the grid, remove it walls.remove(wall) pass
def setTile(self, x, y, direction, val): """Sets the wall state of a tile (x, y) in <direction> >>> m = Maze() >>> m.hasWall(4, 4, RIGHT) False >>> m.setTile(4, 4, RIGHT, True) >>> m.hasWall(4, 4, RIGHT) True >>> m.hasWall(6, 6, RIGHT) False >>> m.hasWall(5, 4, LEFT) # Also updates neighboring wall True """ assert x < Maze.width, "X coordinate larger than grid width" assert y < Maze.height, "Y coordinate larger than grid height" self._grid[x][y].setWall(direction, val) try: self.getTileDelta(x, y, direction).setWall(getOpposite(direction), val) except AssertionError: pass