def CreateMaze(): g = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) maze = Maze(MAZE_ROWS, MAZE_COLS, SQUARE_SIZE) x = (g.getWidth() - maze.getWidth()) / 2 y = (g.getHeight() - maze.getHeight()) / 2 createRandomMaze(maze) g.add(maze, x, y)
def __init__(self,width = 20,height = 20,cell_size = 20): self.width = width self.height = height self.cell_size = cell_size self.maze = Maze() self.options = ["dungeon","prims"]
def CreateMaze(): maze = Maze(MAZE_ROWS, MAZE_COLS, SQUARE_SIZE) x = (g.getWidth() - maze.getWidth()) / 2 y = (g.getHeight() - maze.getHeight()) / 2 createRandomMaze(maze) g.add(maze, x, y)
def _generate(self, w, h, complex): ''' 产生一个特定的迷宫 :param w: int 迷宫宽度 :param h: int 迷宫高度 :param complex: float 算法复杂度,与搜索复杂度不同 :return: Maze 迷宫对象 ''' m = Maze() m.generator = CellularAutomaton(w, h, complex, default_density) m.generate() m.solver = BacktrackingSolver() #m.start = (1, 1) #m.end = (w, h) m.generate_entrances() m.solve() return m
def handle(self, *args, **options): m = Maze() m.generator = Prims(10, 10) m.generate() m.generate_entrances() print() self.stdout.write(self.style.SUCCESS('Successfully generated'))
def generate_maps(tag: str, dest: str, count: int, xsize: int, ysize: int): for i in range(count): # Initialise ith maze. m = Maze(i) # Set up generator and generate. # CellularAutomaton is used as it often gives multiple # possible solutions for larger map sizes. m.generator = CellularAutomaton(xsize, ysize) m.generate() m.generate_entrances(False, False) with open(path_join(dest, f"{tag}.{i}.unsolved.map"), "w") as f: f.write(str(m)) m.solver = ShortestPath() m.solve() with open(path_join(dest, f"{tag}.{i}.solved.map"), "w") as f: f.write(str(m))
def make_maze(grid_size, num_objs, length, img_size, inter, render_resize_factor): """ Args: grid_size: G num_objs: N colors: list of length N, in range (0, 1) Returns: imgs: (T, H, W, 3), uint8 grid: (H, W), binary trajs: (T, N, 2), 2 indices grid """ m = Maze() m.generator = Kruskal(grid_size, grid_size) m.generate() remove_deadend(m.grid) # uint8, binary grid = m.grid # Generate trajectories trajs = [] # import ipdb; ipdb.set_trace() for i in range(num_objs): traj = random_trajectory(m.grid, length) trajs.append(traj) # SQUARE = np.full((16, 16, 3), 0, dtype=np.uint8) # CIRCLE = imageio.imread('shapes/circle16.png') render_size = (m.grid.shape[0]) * render_resize_factor # render_size = img_size # render_size = img_size if SHAPE is CIRCLE: imgs = smooth_render2(grid, trajs, render_size, img_size, SHAPE, inter) else: imgs = smooth_render(grid, trajs, render_size, img_size, SHAPE, inter) imgs, grid, trajs = (np.array(x) for x in [imgs, grid, trajs]) # (N, T, 2) -> (T, N, 2) trajs = trajs.transpose(1, 0, 2) return imgs, grid, trajs
def generate_data(self): results = [] for i in range(self.count): m = Maze() m.generator = Prims(20, 20) m.generate() m.generate_entrances() results.append(toHTML(m.grid, m.start, m.end, 25)) self.data = results return self.data
def labyrinthe(carte, case_init, case_fin): lab = Maze() lab.start = case_init lab.end = case_fin lab.generator = Prims(6, 6) lab.generate() n = random.randint(0, 1) for i in range(11): for j in range(11): if lab.grid[i + 1][j + 1] == 1: if n == 0: carte[i][j] = "eau" else: carte[i][j] = "lave" else: carte[i][j] = "herbe"
def CreateMaze2(): g = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) maze = Maze(MAZE_ROWS, MAZE_COLS, SQUARE_SIZE) x = (g.getWidth() - maze.getWidth()) / 2 y = (g.getHeight() - maze.getHeight()) / 2 #createRandomMaze(maze) #g.add(maze, x, y) #g.setInterval(g.add(wall.setColor("Black")), 2000) walls = maze.getWalls() random.shuffle(walls) squares = maze.getSquares() for square in squares: square.setColor(randomColor()) for wall in walls: updateMaze(maze, wall, g)
def main(): x = int(argv[1]) y = int(argv[2]) maze = Maze() maze.generator = BacktrackingGenerator(x, y) maze.generate() aux = maze.tostring().split('\n') print(len(aux), len(aux[0])) for i, l in enumerate(aux): if i == 1: print('S' + l[1:]) elif i == x * 2 - 1: print(l[:-1] + 'E') else: print(l)
def __init__(self, n=10, cycles=3, seed=np.random.randint(0, 10000), state_representation='integer'): ''' Initialize a maze parameters : n : (int) Maze has diameter 2n+1 cycles : (int) number of blocks to remove to create cycles seed : (int) seed for random initialization state_representation : (str) how state ought to be represented for the agent ''' Maze.set_seed(seed) m = Maze() m.generator = DungeonRooms(n, n) m.generate() self.grid = m.grid # remove some walls to create cycles walls = np.argwhere(self.grid[1:(2 * n), 1:(2 * n)]) np.random.shuffle(walls) for i in range(cycles): row, col = walls[i] row += 1 col += 1 self.grid[row, col] = 0 corners = [[1, 1], [1, 2 * n - 1], [2 * n - 1, 1], [2 * n - 1, 2 * n - 1]] self.start = random.choice(corners) corners.remove(self.start) self.end = random.choice(corners) self.loc = self.start # location of agent self.action_space = spaces.Discrete(4) if state_representation == 'integer': self.gen_state = self.gen_integer_state self.observation_space = spaces.Discrete(np.prod(self.grid.shape)) elif state_representation == 'one_hot': self.gen_state = self.gen_one_hot_state self.observation_space = spaces.Discrete(np.prod(self.grid.shape)) self.observation_space = spaces.Box(low=0, high=1, shape=(np.prod( self.grid.shape), ), dtype=np.int8) elif state_representation == 'flat_grid': self.gen_state = self.gen_flat_grid_state self.observation_space = spaces.Box( low=0, high=5, shape=(np.prod(self.grid.shape), ), dtype=np.int8) # not sure if this is right? else: raise NotImplementedError # add other ways to represent state here self.episode_length = 0 self.MAX_LENGTH = 1000 # episodes are cut off at this length
from mazelib import Maze from mazelib.generate.Prims import Prims m = Maze() m.generator = Prims(27, 34) m.generate() print(m.grid)
from mazelib import Maze from mazelib.generate.Prims import Prims import pygame as py screen_height = 880 screen_width = int(screen_height * 1.0) mx = 11 my = 11 # width and height of the maze size = screen_height / mx colors = [(0, 0, 0), (0, 200, 0), (255, 0, 0), (255, 255, 0)] # RGB colors of the maze m = Maze() m.generator = Prims(5, 5) m.generate() m.generate_entrances(True, True) print(m.tostring(True)) m.grid[m.start[0]][m.start[1]] = 2 m.grid[m.end[0]][m.end[1]] = 3 py.init() screen = py.display screen_surf = screen.set_mode((screen_width, screen_height)) class Player(object): def __init__(self, pos):
from mazelib import Maze from mazelib.generate.Prims import Prims m = Maze() m.generator = Prims(60, 60) m.generate() print(m)
from mazelib import Maze from mazelib.generate.Prims import Prims import matplotlib.pyplot as plt """ Kullanilmiyor eger daha zor labirentler gerekirse diye """ def generate_maze(arg): pass # grid ile maze ayni sey olmaya bilir def showPNG(grid): """Generate a simple image of the maze.""" plt.figure(figsize=(10, 5)) plt.imshow(grid, cmap=plt.cm.binary, interpolation='nearest') plt.xticks([]), plt.yticks([]) plt.show() if __name__ == "__main__": maze = Maze() maze.generator = Prims(5, 5) maze.generate() print(maze)
from mazelib import Maze from mazelib.solve.BacktrackingSolver import BacktrackingSolver import numpy as np m = Maze() m.solver = BacktrackingSolver() miz = [[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1], [ 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1 ], [ 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 ], [ 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ], [ 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1 ], [ 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1 ], [ 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1
class MazeGenerator: """Helper class to generate mazes using mazelib """ def __init__(self,width = 20,height = 20,cell_size = 20): self.width = width self.height = height self.cell_size = cell_size self.maze = Maze() self.options = ["dungeon","prims"] @property def mesh(self): return self.maze.grid def make_mask(self): mask = mesh_to_mask(self.mesh,self.cell_size) # return mask img = mask_to_image3d(mask)#.astype(np.int8) img = np.asarray(img,dtype=np.uint8) return img def generate(self,method = ["dungeon"],rooms = None,width = None,height = None): if width is None: width = self.width if height is None: width = self.height width = width // 2 height = height // 2 if method == "dungeon": self.maze.generator = DungeonRooms(width,height, rooms=rooms) elif method == "prims": self.maze.generator = Prims(width,height) else: raise Exception(f"Maze generation method must be in {self.options}") self.maze.generate() def explore(self,**kwargs): @interact( method = Dropdown(desc = "Generation method",options = self.options), i = IntSlider(desc = "Generation",min = 0,max = 100,value = 0), width = IntSlider(desc = "Width",min = 10,max = 300,value = 20), height = IntSlider(desc = "Height",min = 10,max = 300,value = 20), ) def show(method,i,width,height): self.generate(method = method,width = width,height = height,**kwargs) mesh = self.mesh plt.figure(figsize = (8,8)) plt.imshow(mesh) plt.title("Generated maze") plt.show() def save(self,folder = "."): filename = f"GeneratedMaze_cellsize={self.cell_size}.png" filepath = os.path.join(folder,filename) mask = self.make_mask() Image.fromarray(mask).save(filepath) print(f"... Saved maze in {filepath}")