class Main(object): def __init__(self): size = (500, 500) self.surface = pygame.display.set_mode(size) mazeOrigin = (250, 250) self.maze = Maze(mazeOrigin) done = False while(not done): self.surface.fill((255,255,255)) self.maze.update() self.maze.draw(self.surface) pygame.display.flip() event = pygame.event.get() for e in event: if(e.type == QUIT): done = True elif(e.type == KEYDOWN): if(e.key == K_q): done = True if(e.key == K_r): self.maze = Maze(mazeOrigin)
def test_neighbors(): m = Maze(sample_layout) ns = m.get_neighbors(1,1) assert len(ns) == 2 # unintuitive method for set size assert (1,2) in ns assert (0,1) in ns ns = m.get_neighbors(4,0) assert ns == set([(3,0)])
class Gui: def __init__(self, rows, cols): pygame.init() self.rows = rows self.cols = cols self.maze = Maze(self.rows, self.cols) self.maze.generate() self.screen = pygame.display.set_mode((self.cols * SIZE_CELL, self.rows*SIZE_CELL)) pygame.display.set_caption("OnlineByrinth") self.show_solution = False self.quit = False def update(self): return def draw(self): self.screen.fill((WHITE)) for pos, cell in self.maze.grid.items(): row, col = pos row, col = row * SIZE_CELL, col * SIZE_CELL if cell.n_wall: pygame.draw.line(self.screen, RED, (col, row), (col + SIZE_CELL, row)) if cell.s_wall: pygame.draw.line(self.screen, RED, (col, row + SIZE_CELL), (col + SIZE_CELL, row + SIZE_CELL)) if cell.w_wall: pygame.draw.line(self.screen, RED, (col, row), (col, row + SIZE_CELL)) if cell.e_wall: pygame.draw.line(self.screen, RED, (col + SIZE_CELL, row), (col + SIZE_CELL, row + SIZE_CELL)) # Bordure sud et est pygame.draw.line(self.screen, RED, (0, self.rows * SIZE_CELL - 1), (self.cols * SIZE_CELL, self.rows * SIZE_CELL - 1)) pygame.draw.line(self.screen, RED, (self.cols * SIZE_CELL - 1, self.rows), (self.cols * SIZE_CELL - 1, self.rows * SIZE_CELL - 1)) if self.show_solution: for cell in self.maze.path: row, col = cell.row * SIZE_CELL, cell.col * SIZE_CELL pygame.draw.ellipse(self.screen, GREEN, pygame.Rect(col + SIZE_CELL / 4, row + SIZE_CELL / 4, SIZE_CELL / 2, SIZE_CELL / 2)) pygame.display.flip() def main_loop(self): while not self.quit: for event in pygame.event.get(): if event.type == QUIT: self.quit = True if event.type == KEYDOWN and event.key == pygame.K_SPACE: self.maze.generate() if event.type == KEYDOWN and event.key == pygame.K_s: self.show_solution = not self.show_solution self.update() self.draw()
def main(): files = os.listdir(MAZES) # for f in files: m = Maze(MAZES + "big.maze") solved = m.solveUsing(method=BFS, timeseries=True) if not solved: return "No solution" else: printMaze(solved)
def main(): argv = sys.argv m = Maze(MAZES + argv[1] + '.maze') solved =m.solveUsing(A_Star, timeseries=True, heuristic=manhattanDist, comparisonFunc=comparisonFunc, costAssign=costAssignment) print m.expandedNodes() with open(argv[1] + '_a_star_+1forward_newheur.out', 'w') as f: for row in solved: for elem in row: f.write(elem) f.write('\n')
def main(): argv = sys.argv m = Maze(MAZES + argv[1] + '.maze') solved = m.solveUsing(greedyBFS, True, euclideanDist, comparisonFunc) print m.expandedNodes() with open(argv[1] + '_greedy_bfs.out', 'w') as f: for row in solved: for elem in row: f.write(elem) f.write('\n')
def main(): argv = sys.argv m = Maze(MAZES + argv[1] + ".maze") solved = m.solveUsing(DFS, True) print m.expandedNodes() with open(argv[1] + "_dfs.out", "w") as f: for row in solved: for elem in row: f.write(elem) f.write("\n")
class Pacman(object): Up, Right, Down, Left = range(4) tronches = { Up : 'V', Down : '^', Left : '>', Right : '<', } def __init__(self): self.maze = Maze(10, 10) self.x = 0 self.y = 0 self.direction = Pacman.Left self.score = 0 def bouge(self): oldx = self.x oldy = self.y if self.direction == Pacman.Down: #if self.y < self.maze.longueur - 1: self.y = (self.y + 1)% self.maze.longueur elif self.direction == Pacman.Up: #if self.y > 0: self.y = (self.y - 1)% self.maze.longueur elif self.direction == Pacman.Left: #if self.x > 0: self.x = (self.x - 1)% self.maze.largeur elif self.direction == Pacman.Right: #if self.x < self.maze.largeur - 1: self.x = (self.x + 1)% self.maze.largeur if self.maze.get(self.x,self.y) == '+': self.x = oldx self.y = oldy return self.mange() def mange(self): if self.maze.get(self.x, self.y) == '*': self.score += 1 self.maze.set(self.x, self.y, '.') @property def tronche(self): return self.tronches[self.direction]
def game_loop(self): """Main loop. """ pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) score = 0 high_score = 0 maze = Maze(self.maze_tiles, HORIZONTAL_TILES, VERTICAL_TILES) maze.load_level(maze.MAZE) pac = PacMan(104, 204, self.pacman_tiles) delta = (0, 0) while True: event = pygame.event.poll() if event.type == pygame.QUIT: sys.exit(0) if event.type == pygame.KEYUP: if event.key == pygame.K_ESCAPE: sys.exit(0) pressed = pygame.key.get_pressed() if pressed[pygame.K_LEFT]: delta = (-1, 0) elif pressed[pygame.K_RIGHT]: delta = (1, 0) elif pressed[pygame.K_DOWN]: delta = (0, 1) elif pressed[pygame.K_UP]: delta = (0, -1) x, y = self.screen_to_tile(pac.x, pac.y) if maze[(x, y)] > 0: score += 10 maze[(x, y)] = 0 if score > high_score: high_score = score if self.legal_move(maze, pac, delta): pac.delta = delta elif not self.legal_move(maze, pac, pac.delta): pac.delta = (0, 0) pac.move() maze.draw() pac.draw() self.write_message(3, 0, "1UP") self.write_message(4, 1, str(score)) self.write_message(9, 0, "HIGH SCORE") self.write_message(10, 1, str(score)) pygame.display.flip()
def main(): win = Window(fullscreen=True, visible=False) camera = Camera(win.width, win.height, (0, 0), 100) renderer = Renderer() maze = Maze() maze.create(50, 30, 300) keyboard = Keyboard() keyboard.key_handlers[key.ESCAPE] = win.close keyboard.key_handlers.update(camera.key_handlers) clock.schedule(maze.update) win.on_draw = lambda: renderer.on_draw(maze, camera, win.width, win.height) win.on_key_press = keyboard.on_key_press keyboard.print_handlers() win.set_visible() app.run()
class TestMazeParsing(unittest.TestCase): def setUp(self): self.maze_repr_bad = """ +-+-+-+ |aaaaa| +-+-+-+ """ self.maze_repr_bad_semantic = """ +-+-+-+ | | | +-+-+-+ """ self.maze_repr = """ +-+-+-+ | |*| + + + + |*| | +-+-+-+ """ self.horiz_walls = [[True, True, True], [False, False, False], [True, True, True]] self.vert_walls = [[True, False, True, True], [True, True, False, True]] def test_parse_bad(self): self.assertRaises(Maze.ParseError, Maze, self.maze_repr_bad) def test_parse_bad_semantic(self): self.assertRaises(Maze.SemanticError, Maze, self.maze_repr_bad_semantic) def test_parse(self): self.maze = Maze(self.maze_repr) self.assertEqual(self.horiz_walls, self.maze.horiz_walls) self.assertEqual(self.vert_walls, self.maze.vert_walls) self.assertEqual(3, self.maze.width()) self.assertEqual(2, self.maze.height()) def test_walls(self): self.maze = Maze(self.maze_repr) self.assertEqual([True, True, False, False], self.maze.walls(0, 1)) self.assertEqual([False, True, True, True], self.maze.walls(1, 0))
def restart(self): self.maze_obj = Maze(*self.dim)# pass args to change maze size: Maze(10, 10) if self.diff == 0: self.maze_obj.generate(self.maze_obj.maze[(0,0)]) else: self.maze_obj.generate() self.draw_maze() self.reset_player()
def build(self): material = self.material min_x, max_x = self.mc.min_x, self.mc.max_x min_z, max_z = self.mc.min_z, self.mc.max_z # Don't forget the zero block! 1 - -1 == 2, but it is 3 blocks! x_width = max_x - min_x + 1 z_width = max_z - min_z + 1 c_dim, c_height = 6, 3 # in world block units # in labyrinth cell units (remember walls overlap, need exact fit + 1 for outermost wall) x_cells, z_cells = (x_width - 1) / (c_dim - 1), (z_width - 1) / (c_dim - 1) castle_cells = 13 maze = Maze(z_cells, x_cells) # Disconnect cells where castle resides, ensures compatible maze blk_x, blk_z = (x_cells - castle_cells) / 2, (z_cells - castle_cells) / 2 for bx in xrange(blk_x, blk_x + castle_cells): for bz in xrange(blk_z, blk_z + castle_cells): maze[bz, bx].disconnect() maze.generate() # Remove the wall from graph where the labyrinth will meet with castle maze[blk_z + castle_cells / 2, blk_x + castle_cells].remove_wall(NORTH) # Render the labyrinth by generating blocks where there are walls for cell_x in xrange(0, x_cells): for cell_z in xrange(0, z_cells): walls = maze[cell_z, cell_x].walls north, west = min_x + cell_x * (c_dim - 1), min_z + cell_z * (c_dim - 1) if walls[NORTH] and walls[SOUTH] and walls[EAST] and walls[WEST]: self.mc.make_cube(north, 0, west, c_dim, c_height, c_dim, material) else: if walls[NORTH]: self.mc.make_cube(north, 0, west, 1, c_height, c_dim, material) if walls[SOUTH]: self.mc.make_cube(north + (c_dim - 1), 0, west, 1, c_height, c_dim, material) if walls[EAST]: self.mc.make_cube(north, 0, west + (c_dim - 1), c_dim, c_height, 1, material) if walls[WEST]: self.mc.make_cube(north, 0, west, c_dim, c_height, 1, material)
def init_maze(self): # custom map is a list containing each row # and the width is the length of the first row custom_map = [] f = open('map.txt', 'r') for line in f.readlines(): custom_map.append(line) f.close() width = len(custom_map[0]) height = len(custom_map) self.maze = Maze(width, height, custom_map) hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 10, 0) hbox.addWidget(self.maze) vbox = QVBoxLayout() vbox.setContentsMargins(0, 10, 0, 0) hbox.addLayout(vbox) self.agents = QLineEdit("s") vbox.addWidget(QLabel("agent to watch:")) vbox.addWidget(self.agents) self.btn_watch = QPushButton("Watch Agent") self.btn_watch.clicked.connect(self.watchAgent) vbox.addWidget(self.btn_watch) self.btn_remove = QPushButton("Remove path") self.btn_remove.clicked.connect(self.remove) vbox.addWidget(self.btn_remove) self.btn_solve = QPushButton("Start") self.btn_solve.clicked.connect(self.startSolving) vbox.addWidget(self.btn_solve) self.btn_step = QPushButton("Next Step") self.btn_step.clicked.connect(self.doStep) vbox.addWidget(self.btn_step) self.btn_stop = QPushButton("Stop") self.btn_stop.setEnabled(False) self.btn_stop.clicked.connect(self.stopSolving) vbox.addWidget(self.btn_stop) self.btn_restart = QPushButton("Restart") self.btn_restart.setEnabled(True) self.btn_restart.clicked.connect(self.restart) vbox.addWidget(self.btn_restart) vbox.addStretch() proxy_widget = QWidget() proxy_widget.setLayout(hbox) self.setCentralWidget(proxy_widget) self.maze.init()
def test_construction(): if len(sys.argv) == 2: parsed_info = Maze.parse_layout(sys.argv[1]) test_layout = parsed_info[0] test_info = parsed_info[1] else: test_layout = sample_layout test_info = None m = Maze(test_layout) assert str(m).strip() == test_layout.strip()
def __init__(self, **kwargs): super(Dungeon, self).__init__(**kwargs) self.gameworld.init_gameworld( ['cymunk_physics', 'rotate_renderer', 'rotate', 'position', # 'cymunk_touch', 'camera1'], callback=self.init_game) self.mazeobj = Maze() self.mazeobj.makeMap(50, 50, 100, 10, 30) self.maze = self.mazeobj.mapArr
def create_maze(): """Series of operations which create our Maze.""" maze = Maze() room1 = Room(1) room2 = Room(2) thedoor = Door(room1, room2) maze.add_room(room1) maze.add_room(room2) room1.set_side(Direction.NORTH, Wall()) room1.set_side(Direction.EAST, thedoor) room1.set_side(Direction.SOUTH, Wall()) room1.set_side(Direction.WEST, Wall()) room2.set_side(Direction.NORTH, Wall()) room2.set_side(Direction.EAST, Wall()) room2.set_side(Direction.SOUTH, Wall()) room2.set_side(Direction.WEST, thedoor) return maze
def detect_maze(vertex, width, height): """Try to detect maze with given maze size, starting at given vertex.""" maze = Maze(width, height) dualmaze = Maze(width, height) last_vertex = vertex stack = [vertex] while len(stack) > 0: vertex = stack.pop() if is_done(vertex, maze, dualmaze): continue if vertex != last_vertex: run(maze.bfs(last_vertex, vertex), maze) last_vertex = detect_walls(vertex, maze, dualmaze) # Fill stack; avoid unnecessary paths stack.extend([v for v in maze.get_reachables(*vertex) if v != last_vertex and not is_done(v, maze, dualmaze)]) if vertex != last_vertex: stack.append(last_vertex) return maze
def maze(request, size): ''' creates a maze. accepts a 'size' param on the querysting Generates an image that is sent as the whole reponse Should experiment with displaying a html page within which an image is displayed, the source of which is this ''' try: size = int(size) if size > 30: size = 30 m = Maze(size, size) image = m.as_image() response = HttpResponse(mimetype="image/png") image.save(response, "PNG") return response except: pass
class MazeTests(unittest.TestCase): def setUp(self): self.maze = Maze(10, 10) def test_le_laby_possede_des_supers_attributs(self): assert self.maze.largeur assert self.maze.longueur assert self.maze.tableau def test_on_peut_regarder_dans_le_laby(self): self.maze.largeur = 3 self.maze.longueur = 2 self.maze.tableau = [0,1,2,3,4,5] self.assertEqual(self.maze.get(1,1), 4) def test_import_maze_from_string(self): mazeString = "+..*+.*\n+..*+.*\n+..*+.*\n" self.maze.loadMaze(mazeString) self.assertEqual(self.maze.longueur,3) self.assertEqual(self.maze.largeur,7) self.assertEqual(self.maze.tableau[0],'+') self.assertEqual(self.maze.tableau[6],'*') self.assertEqual(self.maze.tableau[14],'+') def test_on_peut_modifier_le_laby(self): self.maze.set(2,2,'*') self.assertEqual(self.maze.get(2,2), '*')
def __init__(self, rows, cols): pygame.init() self.rows = rows self.cols = cols self.maze = Maze(self.rows, self.cols) self.maze.generate() self.screen = pygame.display.set_mode((self.cols * SIZE_CELL, self.rows*SIZE_CELL)) pygame.display.set_caption("OnlineByrinth") self.show_solution = False self.quit = False
def submitscore(mazeid, user, score, solution=None): r = web.ctx.db.where("published_mazes", what="lowscore,data", id=mazeid) try: row = r[0] except IndexError: return {"error": "INCORRECT_MAZE_ID"} lowscore = row.lowscore maze_data = json.loads(row.data) maze = Maze.fromJSON(maze_data["maze"]) board = CircuitBoard.fromJSON(json.loads(solution)) # check that solution is valid try: time = run_maze(maze, board) except MazeRunError, e: return {"error": e.args[0]}
def create (self): self.player = Player(self.width/2, self.height - 2) self.player.offset_x = - 16 self.player.offset_y = - 32 self.maze = Maze(self.width, self.height, self.tile_size) self.maze.create() self.music = Loader.get('music') self.music.play(-1) if self.enable_sound: self.music.set_volume(0.2) else: self.music.set_volume(0) # black screen fade out self.fade_timer = Timer(2000) self.castle = Sprite(0, -16, 'castle') self.torches = [] self.torches.append(Sprite(336, 80, 'torch')) self.torches.append(Sprite(480, 80, 'torch')) self.torches.append(Sprite(83, 140, 'flame')) self.lights = [] self.lights.append(Sprite(240, 0, 'light')) self.lights.append(Sprite(384, 0, 'light')) self.lights.append(Sprite(-13, 58, 'light')) for t in self.torches: t.play('default', loop=True) for l in self.lights: l.play('default', loop=True) self.sound = Sprite(common.GAME_WIDTH - 80, 10, 'sound') self.nosound = Sprite(common.GAME_WIDTH - 80, 14, 'nosound') self.restart = Sprite(common.GAME_WIDTH - 70, 15, 'restart') self.fog = pygame.Surface((self.maze.image.get_width(), self.maze.image.get_height())) self.fog.set_colorkey((255, 0, 255))
def __init__(self, mazesize=20): # game characters self.p1 = 'H' self.p2 = 'G' self.exit = 'E' # game maze self.maze = Maze(mazesize) self.boot = 1 self.size = int() # game objects self.player = None self.clock = None # game objects pygame.init() self.exit_sprite = pygame.image.load("../images/exit.png") self.exit_rect = self.exit_sprite.get_rect() self.gameover_sprite = pygame.image.load("../images/gameover.png") self.gameover_rect = self.gameover_sprite.get_rect() self.gameover_rect = self.gameover_rect.move(SCREEN_SIZE/4, SCREEN_SIZE/4) self.gameoverl_sprite = pygame.image.load("../images/gameover_l.png") self.gameoverl_rect = self.gameoverl_sprite.get_rect() self.gameoverl_rect = self.gameoverl_rect.move(SCREEN_SIZE/4, SCREEN_SIZE/4) self.bg = pygame.image.load("../images/background.png") self.bg_rect = self.bg.get_rect() self.wait_screen = pygame.image.load("../images/wait_screen.png") self.wait_rect = self.wait_screen.get_rect() #self.bg_rect = self.bg_rect.move(SCREEN_SIZE/2, SCREEN_SIZE/2) self.size = self.width, self.height = SCREEN_SIZE, SCREEN_SIZE self.green = 0, 255, 0 self.connected = 0 self.opponent = [(MAZE_SIZE/2 - 1) * WALL_SIZE * SCALE, 0, "../images/ghost_down.png"] self.ghostImage = pygame.image.load(self.opponent[2]) self.ghostRect = self.ghostImage.get_rect() self.ghostRect.centerx = self.opponent[0] self.ghostRect.centery = self.opponent[1] # network self.ghostProtocol = None
def __init__(self): # Initialize pygame pygame.init() pygame.font.init() # initialize font self.font = pygame.font.SysFont(None, 40) self.smallfont = pygame.font.SysFont(None, 25) # Set the dimension the window self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption("Maze") pygame.display.flip() self.game_over = False self.game_exit = False # Create and generatethe Maze self.maze = Maze()
def __init__(self, filename='../data/gc-maze.txt', refine=False): self.maze = Maze.from_file(filename) self.original_start = tuple(self.maze.start) self.original_end = tuple(self.maze.end) self.cachefile = filename + '.tsp-results.pickle' self.refine = refine self.do_reconnaissance = 10000 self.maze.load_products(filename='../data/gc-products.txt') self.num = self.maze.product_count self.products = self.maze.products_dict # initialize array for the distances. if os.path.exists(self.cachefile): print 'Loading from cachefile: %s' % self.cachefile self.load_cache() else: size = len(self.locations()) self.results = map(list, [[TSPMaze.EMPTY] * size] * size)
def buildMaze(filename): with open(filename) as infile: # Read the size of the maze. nrows, ncols = readValuePair(infile) maze = Maze(nrows, ncols) # Read the starting and exiting positions. row, col = readValuePair(infile) maze.setStart(row, col) row, col = readValuePair(infile) maze.setExit(row, col) # Read the maze itself. for row in range(nrows): line = infile.readline() for col in range(len(line)): if line[col] == '*': maze.setWall(row, col) return maze
class Game: def __init__(self): self._player = Player() self._maze = Maze(10, 10) def get_player(self): return self._player def move(self, player, x, y): player_maze = self.get_player().known_maze() src_cell = self._maze.getItem(x, y) dest_cell = player_maze.getItem(x, y) dest_cell.setLeftWall(src_cell.getLeftWall()) dest_cell.setTopWall(src_cell.getTopWall()) dest_cell.setRightWall(src_cell.getRightWall()) dest_cell.setBottomWall(src_cell.getBottomWall()) self._player._x = x self._player._y = y def game_ended(self): return False
def buildMaze(filename): infile = open(filename,'r') nrows,ncols = readValuePair(infile) maze = Maze(nrows,ncols) row.col = readValuePair(infile) maze.setStart(row,col) row.col = readValuePair(infile) maze.setExit(row,col) for row in range(nrows): line = infile.readline() for col in range(len(line)): maze.setWall(row,col) infile.close() return maze
def buildMaze(filename): infile = open(filename, "r") # Read the size of the maze. nrows, ncols = readValuePair(infile) maze = Maze(nrows, ncols) # Read the starting and exit positions. row, col = readValuePair(infile) maze.setStart(row, col) row, col = readValuePair(infile) maze.setExit(row, col) # Read the maze itself. for row in range(nrows): line = infile.readline() for col in range(len(line)): if line[col] == "*": maze.setWall(row, col) # Close the maze file and return the newly constructed maze. infile.close() return maze
[1, 1, 1, 1, 0, 0], [1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 0, 1, 1, 0], [1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 0], [1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 1, 0], [1, 1, 1, 1, 1, 1], ] my_maze = Maze(michelangelo, vertical, horizontal) my_maze.prepare_turtle(5, 'orange', 'turtle') my_maze.set_start((30, 230)) my_maze.draw() my_maze.wait_donatelo() don = turtle.Turtle() donatelo = Mouse(don, my_maze) donatelo.prepare_turtle(3, 'purple', 'turtle', 1) donatelo.set_start((-135, 185)) sprinter = Tree((0, 0)) sprinter.update_tree(donatelo.positions_options) sprinter.find_exit() directions = sprinter.trace_route()