def transformToMazeFor3Arms(arm, goals, obstacles, window, granularity): """This function transforms the given 2D map to the maze in MP1. Args: arm (Arm): arm instance goals (list): [(x, y, r)] of goals obstacles (list): [(x, y, r)] of obstacles window (tuple): (width, height) of the window granularity (int): unit of increasing/decreasing degree for angles Return: Maze: the maze instance generated based on input arguments. """ alphaLimits, betaLimits, gammaLimits = arm.getArmLimit() alphaMin, alphaMax = alphaLimits betaMin, betaMax = betaLimits gammaMin, gammaMax = gammaLimits rows = int(((alphaMax - alphaMin) / granularity) + 1) cols = int(((betaMax - betaMin) / granularity) + 1) depths = int(((gammaMax - gammaMin) / granularity) + 1) startAngles = arm.getArmAngle() map = [] # subtracts one because it will just add one in first loop alpha = alphaMin - granularity for x in range(rows): # all alpha values row = [] alpha += granularity # subtracts one because it will just add one in first loop arm.setArmAngle((alpha, betaMin, gammaMin)) armPos = arm.getArmPos() isWallFirstArm = doesArmTouchObstacles( [armPos[0]], obstacles) or not isArmWithinWindow([armPos[0]], window) if (isWallFirstArm): depth = [] for y in range(cols): for z in range(depths): depth.append(WALL_CHAR) row.append(depth) map.append(row) continue beta = betaMin - granularity for y in range(cols): # all beta values at the current alpha depth = [] beta += granularity gamma = gammaMin - granularity arm.setArmAngle((alpha, beta, gammaMin)) armPos = arm.getArmPos() isWallSecondArm = doesArmTouchObstacles( [armPos[0]], obstacles) or not isArmWithinWindow([armPos[0]], window) if (isWallSecondArm): depth = [] for z in range(depths): depth.append(WALL_CHAR) row.append(depth) continue for z in range(depths): gamma += granularity arm.setArmAngle((alpha, beta, gamma)) armPos = arm.getArmPos() armEnd = arm.getEnd() isWall = doesArmTouchObstacles( armPos, obstacles) or not isArmWithinWindow(armPos, window) if isWall: depth.append(WALL_CHAR) continue doesGoThrough = not doesArmTouchGoals( armEnd, goals) and doesArmTouchObstacles(armPos, goals) if doesGoThrough: depth.append(WALL_CHAR) continue isObjective = doesArmTouchGoals(armEnd, goals) if isObjective: depth.append(OBJECTIVE_CHAR) continue # not objective or wall then free space depth.append(SPACE_CHAR) row.append(depth) map.append(row) # transforms start angles to index in maze startIndexes = angleToIdx(startAngles, (alphaMin, betaMin, gammaMin), granularity) startAlpha, startBeta, startGamma = startIndexes # adds start to maze map[startAlpha][startBeta][startGamma] = START_CHAR maze = Maze(map, (alphaMin, betaMin, gammaMin), granularity) return maze
def pmaze(array): """Solves maze with depth-first search.""" m = Maze() m.maze = array m.solve((), (), Maze.Solve.DEPTH)
import copy from datetime import datetime from maze import Maze grid_size = (30, 30) m = Maze(False, grid_size, None, None, (grid_size[0] - 1, grid_size[1] - 1)) m.robot.x = 0 m.robot.y = 0 while not m.started: m.parse_events(True) m.draw() r = copy.deepcopy(m.robot) c = copy.deepcopy(m.cells) s = copy.deepcopy(m.star_loc) l = (r.x, r.y) print("STARTING TRAINING") now = datetime.now() wins = 0 win_percentage = 0 i = 0 r.epsilon = 0.1 r.alpha = 0.9 r.gamma = 0.9 while 1: i += 1 win_percentage = (wins / 100) * 100 if win_percentage > 90:
'down': 'u', 'left': 'r' } # test and score parameters max_time = 1000 train_score_mult = 1 / 30. if __name__ == '__main__': ''' This script tests a robot based on the code in robot.py on a maze given as an argument when running the script. ''' # Create a maze based on input argument on command line. testmaze = Maze(str(sys.argv[1])) # Intitialize a robot; robot receives info about maze dimensions. testrobot = Robot(testmaze.dim) # Record robot performance over two runs. runtimes = [] total_time = 0 for run in range(2): print "Starting run {}.".format(run) # Set the robot in the start position. Note that robot position # parameters are independent of the robot itself. robot_pos = {'location': [0, 0], 'heading': 'up'} run_active = True
import benchmark as bm from maze import Maze def pmaze(array): """Solves maze with depth-first search.""" m = Maze() m.maze = array m.solve((), (), Maze.Solve.DEPTH) def cmaze(array): """Solves maze with depth-first search in C.""" m = Maze() m.maze = array m.solve((), (), Maze.Solve.C) mz = Maze() mz.create(100, 100, Maze.Create.C) bm.versus(pmaze, cmaze, 50, mz.maze) input()
def get_maze_from_img(filepath, maze_size=None): """ parse maze image and generate maze object """ # get src image img = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE) # print('shape: ', img.shape) # show(img) # resize width = 1000 scale = width / img.shape[1] img = cv2.resize(img, dsize=None, fx=scale, fy=scale) # inversion img = cv2.bitwise_not(img) # show(img) # binarization retval, img = cv2.threshold( img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # show(img) # ノイズ除去 w = 5 kernel = np.ones((w, w), np.uint8) img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel, iterations=1) w = 6 kernel = np.ones((w, w), np.uint8) img = cv2.dilate(img, kernel, iterations=1) # show(img), plt.show(), exit() # 輪郭抽出 # 行の和、列の和をとる sum_col = np.sum(img, axis=0) sum_row = np.sum(img, axis=1) # plt.figure() # plt.plot(sum_col) # plt.figure() # plt.plot(sum_row) # plt.show() # 和を半分に分割する sl, sr = np.array_split(np.sum(img, axis=0), 2) st, sb = np.array_split(np.sum(img, axis=1), 2) # l = np.argmax(sl) # r = np.argmax(sr) + len(sl) # t = np.argmax(st) # b = np.argmax(sb) + len(st) ratio = 0.97 lm = np.where(sl > np.max(sl) * ratio)[0] l = lm[len(lm)//2] rm = np.where(sr > np.max(sr) * ratio)[0] r = rm[len(rm)//2] + len(sl) tm = np.where(st > np.max(st) * ratio)[0] t = tm[len(tm)//2] bm = np.where(sb > np.max(sb) * ratio)[0] b = bm[len(bm)//2] + len(st) # print(f'l:{l}, r:{r}, t:{t}, b:{b}') img = img[t:b, l:r] show(img) # 迷路サイズの推定 if maze_size == None: sum_col = np.sum(img, axis=1) sum_col = sum_col < np.average(sum_col) diff_col = np.append(sum_col, 0) - np.append(0, sum_col) maze_size = sum(diff_col > 0) maze_size = int(maze_size) print('maze size:', maze_size) # 迷路オブジェクトの作成 maze = Maze(maze_size) x_indexes = np.linspace(0, img.shape[1], maze_size+1, dtype='int32') y_indexes = np.linspace(img.shape[0], 0, maze_size+1, dtype='int32') x_width = img.shape[1] // maze_size y_width = img.shape[0] // maze_size for y in range(maze_size): for x in range(maze_size-1): w = img[y_indexes[y]-y_width//2, x_indexes[x+1]] maze.wall(x, y, Maze.East, new_state=w, new_known=True) for x in range(maze_size): for y in range(maze_size-1): w = img[y_indexes[y+1], x_indexes[x]+x_width//2] maze.wall(x, y, Maze.North, new_state=w, new_known=True) # スタート区画を設定 maze.start.append([0, 0]) # ゴール区画を設定; ここでは幅優先探索で壁のない柱のあるマスをゴールとする step_map = StepMap(maze) step_map.update(maze.start) for x in range(maze.size): for y in range(maze.size): if not maze.is_inside_of_field(x, y) \ or not np.isfinite(step_map[maze.get_cell_index(x, y)]): continue # 柱のまわりの4マスを列挙 around_pillar = [ [x, y, Maze.East], [x+1, y, Maze.North], [x+1, y+1, Maze.West], [x, y+1, Maze.South], ] if all(not maze.wall(x, y, d) for x, y, d in around_pillar): for x, y, d in around_pillar: maze.goals.append([x, y]) maze.goals = list(map(list, set(map(tuple, maze.goals)))) # 重複を除く # 図を表示 plt.show() # 終了 return maze
import numpy as np from maze import Maze from nsarsa import NSarsa grid = Maze(6, 9, np.array([7, 11, 16, 20, 25, 29, 41]), np.array([8])) ntd = NSarsa(54, 4, [8], grid) ntd.estimateQ(0.1, 0.95, 0.1, 4, 10000) print(ntd.getQValues()) print() print(ntd.getPolicy()) grid.drawPolicy(ntd.getPolicy())
def make_maze(cls): return Maze()
#!/usr/bin/env python3 import json import os from maze import Maze # setting constants WIDTH = int(os.environ.get('WIDTH')) if 'WIDTH' in os.environ else 400 HEIGHT = int(os.environ.get('HEIGHT')) if 'HEIGHT' in os.environ else 400 QTD = int(os.environ.get('QTD')) if 'QTD' in os.environ else 1 W = int(os.environ.get('W')) if 'W' in os.environ else 20 for x in range(QTD): m = Maze(WIDTH, HEIGHT, W) m.create() data = m.export() filename = "data-%d.json" % x with open('data/' + filename, 'w') as fp: json.dump(data, fp)
def runner(dim=(30, 30), edgeLen=16, seed=23, population=10, mutRate=0.1, enablePlot=False): ''' dim .... dimention of the maze in squares seed ......... Random seed to start with mutRate ...... Mutation Rate to use enablePlot ... Plot result in TK ''' border = 10 population = 20 # number of bots per generation mut_rate = 0.1 # mutation rate enablePlot = True plotN = 100 maze = None bot = [RefferenceBot()] while not bot[0].target_found: maze = Maze(dimentions=dim) bot[0].find_path(maze) maze.set_min_path_lenght(bot[0].path_len) print("The reference path length is %d" % bot[0].path_len) m = np.full(dim, 0) m[2][2] = 3 m[int(dim[0] - 3)][int(dim[1] / 2)] = 2 m[int(dim[0] / 2)][int(dim[1] / 2)] = 1 maze = Maze(matrix=m) bot[0].find_path(maze) if enablePlot: gui = Gui((640, 640)) gui.draw_maze(maze) try: bot[0].add_turtle(gui.turtle.clone(), color="blue") except NameError: pass target_count = 0 target_bots = [] np.random.seed(seed) cor = [1.0, 0.3, 0.1] for i in range(1, population + 1): bot.append(DNNBot()) try: bot[i].add_turtle(gui.turtle.clone(), tuple(cor)) except NameError: pass cor[1] += 0.03 cor[0] -= 0.03 dna = [None] * (population + 1) generation = 1 last_gen = 0 maze_tries = 0 maze_nr = 0 while True: survivor = [] finisher = [] uniquePath = [] uniquePathBots = [] weights = {} time_start = time.process_time() time_cros = 0 for i in range(1, population + 1): bot[i].find_path(maze) if bot[i].cost in weights.keys(): weights[bot[i].cost].append(bot[i]) else: weights[bot[i].cost] = [bot[i]] if bot[i].target_found: # target_bots.append(bt[i]) # target_count+=1 survivor.append(i) finisher.append(i) # print("Bot %d costs %f, made %d steps and found the goal!" % (i,bot[i].cost,bot[i].path_len-1)) elif bot[i].crashed: pass # print("Bot %d costs %f, made %d steps and crshed!" % (i,bot[i].cost,bot[i].path_len-1)) else: survivor.append(i) # print("Bot %d costs %f, made %d steps and dit not find the goal!" % (i,bot[i].cost,bot[i].path_len-1)) dna[i] = bot[i].get_dna() if not uniquePath.count(bot[i].get_path()): uniquePath.append(bot[i].get_path()) uniquePathBots.append(bot[i]) newMaze = False newPlot = False if len(finisher) > population / 2: maze_tries = 0 if generation > last_gen: newPlot = enablePlot last_gen = generation else: newPlot = False if maze_nr < dim[1] / 2 - 3: maze.add_obstical((int(dim[0] / 4), maze_nr)) maze.add_obstical((int(dim[0] / 4), dim[1] - 1 - maze_nr)) elif maze_nr < 2 * dim[1] / 2 - (3 + 3): mn = maze_nr - (dim[1] / 2 - 3) maze.add_obstical((int(dim[0] / 2), mn)) maze.add_obstical((int(dim[0] / 2), dim[1] - 1 - mn)) elif maze_nr < 3 * dim[1] / 2 - (3 + 3 + 2): mn = maze_nr - (2 * dim[1] / 2 - (3 + 3)) maze.add_obstical((int(dim[0] * 3 / 4), dim[1] / 2 + mn)) maze.add_obstical((int(dim[0] * 3 / 4), dim[1] / 2 - mn)) elif maze_nr < 4 * dim[1] / 2 - (3 + 3 + 2 + 4): mn = maze_nr - (3 * dim[1] / 2 - (3 + 3 + 2)) maze.add_obstical((int(dim[0] / 2) + mn, dim[1] / 2)) maze.add_obstical((int(dim[0] / 2) - mn, dim[1] / 2)) newMaze = enablePlot maze_nr += 1 else: time_pre = time.process_time() crossover(bot[1:], cros=[9, 3, 1, 1, 1], mutation=0.3) time_cros = time.process_time() - time_pre generation += 1 maze_tries += 1 print("Maze %i/ Generation %i: %i bots survived and %i bots finished! " % \ (maze_nr, generation, len(survivor), len(finisher)), \ "(%i uniqu path found;" % (len(uniquePath)), "Time round: %f, Time crossover: %f)" % (time.process_time()-time_start, time_cros)) # if not maze_tries%plotN or newPlot: if newPlot: try: gui.clean_path(bot) gui.draw_path(uniquePathBots) except NameError: pass if newMaze: try: gui.draw_maze(maze) except NameError: pass if enablePlot: gui.master.mainloop()
maze.grid.updateMatrixWidg() if step_by_step: input() if verbose: if done: print("OK") else: print("NO") maze.grid.display_path(path) if load_settings['SAVE_MAZE']: save_maze(maze, load_settings['filename_save']) if load_settings['SAVE_AGENT']: save_agent(Q, load_settings['filename_save']) maze.running = False load_settings['LOAD_MAZE'] = False if __name__ == "__main__": maze = Maze("MazeSolver", (800, 900)) maze.window.show_fps = True maze.window.fps_perc = 4 maze.window.FPS_CAP = 60 maze.start() Q = None main()
def main(): # pylint: disable=undefined-variable """Main function """ #Load Window fullwindow = pygame.display.set_mode((900, 900)) fond = pygame.image.load('ressources/fond5.jpg').convert() fond = pygame.transform.scale(fond, (900, 900)) #level structure level = Maze() level.analyse() level.map(fullwindow) #Items allitems = Items(variables.SYRINGE, variables.NEEDLE, variables.ETHER, level, fullwindow) #Character mac = Charac(variables.MAC, level) pygame.display.flip() continuer = 1 game = mac.game while continuer: for event in pygame.event.get(): if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE: continuer = 0 if game != 0: #Items Counter itemsget = str(len(mac.inventory)) font = pygame.font.SysFont("comicsansms", 18) text = font.render("Items: " + itemsget, True, (255, 0, 0)) fullwindow.blit(fond, (0, 0)) level.map(fullwindow) if 's' not in mac.inventory: fullwindow.blit(allitems.setitem1, (allitems.item1x, allitems.item1y)) if 'n' not in mac.inventory: fullwindow.blit(allitems.setitem2, (allitems.item2x, allitems.item2y)) if 'e' not in mac.inventory: fullwindow.blit(allitems.setitem3, (allitems.item3x, allitems.item3y)) fullwindow.blit(mac.macg, (mac.pos_x, mac.pos_y)) fullwindow.blit(text, (0, 0)) pygame.display.flip() #Moves of MacGyver if event.type == KEYDOWN: if event.key == K_RIGHT: mac.move('droite') mac.getitems(fullwindow) elif event.key == K_LEFT: mac.move('gauche') mac.getitems(fullwindow) elif event.key == K_UP: mac.move('haut') mac.getitems(fullwindow) elif event.key == K_DOWN: mac.move('bas') mac.getitems(fullwindow) game = mac.game
def viewer_run(): viewer = MazeViewer( Maze(blocks=[(1, 1), (1, 2), (1, 3), (2, 1), (3, 1), (4, 2)])) while True: viewer.render()
def transformToMazeFor1Arm(arm, goals, obstacles, window, granularity): """This function transforms the given 2D map to the maze in MP1. Args: arm (Arm): arm instance goals (list): [(x, y, r)] of goals obstacles (list): [(x, y, r)] of obstacles window (tuple): (width, height) of the window granularity (int): unit of increasing/decreasing degree for angles Return: Maze: the maze instance generated based on input arguments. """ alphaLimits = arm.getArmLimit()[0] alphaMin = alphaLimits[0] alphaMax = alphaLimits[1] rows = int(((alphaMax - alphaMin) / granularity) + 1) startAngles = arm.getArmAngle() map = [] # subtracts one because it will just add one in first loop alpha = alphaMin - granularity for x in range(rows): # all alpha values alpha += granularity # subtracts one because it will just add one in first loop arm.setArmAngle((alpha, )) armPos = arm.getArmPos() armEnd = arm.getEnd() isWall = doesArmTouchObstacles( armPos, obstacles) or not isArmWithinWindow(armPos, window) if isWall: map.append(WALL_CHAR) continue doesGoThrough = not doesArmTouchGoals( armEnd, goals) and doesArmTouchObstacles(armPos, goals) if doesGoThrough: map.append(WALL_CHAR) continue isObjective = doesArmTouchGoals(armEnd, goals) if isObjective: map.append(OBJECTIVE_CHAR) continue # not objective or wall then free space map.append(SPACE_CHAR) # transforms start angles to index in maze startIndexes = angleToIdx(startAngles, (alphaMin, ), granularity) startAlpha = startIndexes[0] # adds start to maze map[startAlpha] = START_CHAR maze = Maze(map, (alphaMin, ), granularity) return maze
def current_room_info(user: User, maze: Maze) -> str: res = f'---\nВы находитесь в комнате номер {user.current_room_number}.\n' creature_signs = maze.signs_in_current_room() if creature_signs: res += f'В соседних комнатах что-то происходит: \n' for sign in creature_signs: res += sign + "\n" res += f'Отсюда можно перейти в комнаты {", ".join([str(x) for x in maze.available_user_moves()])} \n' return res if __name__ == '__main__': print('---\nДобро пожаловать в игру "Охота на Вампуса!"') user = User() rooms = create_rooms() dangers = create_dangers() maze = Maze(user, rooms, dangers) while True: maze.dangers_actions_in_user_room() if user.is_dead or user.is_win or user.arrows_count == 0: print('Вот и все!') break print(current_room_info(user, maze)) action = input('Выстрелить или идти? (в-и) : ') actions_mapper.get(action.lower() if action.isalpha() else ACTION_DEFAULT, action_default)(user, maze)
from maze import Maze maze = Maze(1000) maze.find_path()
def main(): """Launch functions.""" # Launch pygame pygame.init() # Pygame parameters pygame.key.set_repeat(config.KEY_SET_REPEAT_DELAY, config.KEY_SET_REPEAT_INTERVAL) pygame.time.Clock().tick(config.TIME_CLOCK_TICK) # -tc- si big_loop, game_loop et menu_loop sont des booléan, utiliser # -tc- True/False. Plus proche de l'intension et donc plus lisible. big_loop = 1 while big_loop: game_loop = 1 menu_loop = 1 if Maze.game_count != 0: Maze.print_count() # -tc- faire les prints directement ici et pas # -tc- dans Maze. Par ailleurs, quel intérêt de faire des prints # -tc- dans le programme pygame # MENU LOOP ########################################## while menu_loop: nb_obj = 0 message = Display_mess() message.display_message(config.MENU_MESS) for event in pygame.event.get(): # Close window # -tc- utiliser des parenthèses plutôt qu'un \ if event.type == QUIT \ or (event.type == KEYDOWN and event.key == K_ESCAPE): menu_loop = 0 # -tc- False big_loop = 0 # -tc- False # Choose number of objects elif event.type == KEYDOWN: if event.key == K_F1: # créer un dictionnaire de config pour les niveau est simplement obtenir la valeur de nb_obj de ce dictionnaire nb_obj = 3 menu_loop = 0 elif event.key == K_F2: nb_obj = 4 menu_loop = 0 # END MENU LOOP ###################################### # Loads if nb_obj != 0: # Load & generate the maze from the file level = Maze(nb_obj) # Manage player movements and generate inventory player = Player(level) # Display the maze display_maze = Display_maze(level, player) # GAME LOOP ########################################## while game_loop: for event in pygame.event.get(): # Back to menu if event.type == QUIT \ or (event.type == KEYDOWN and event.key == K_ESCAPE): game_loop = 0 # Movements reactions keys_events = { 'UP': K_UP, 'DOWN': K_DOWN, 'LEFT': K_LEFT, 'RIGHT': K_RIGHT, } if event.type == KEYDOWN: for move, value in keys_events.items(): if event.key == value: player.movement(move, level) # Add loot in Inventory player.loot(level) # Re-paste images # -tc- Pourquoi redessine tu l'ensemble du labyrinthe à chaque # -tc- tour de boucle. Il suffit de dessiner un background # -tc- avec le labyrinthe au début du programme avec les # -tc- éléments qui ne bougent pas. Après, tu utilises des # -tc- classes qui héritent de pygame.sprite.Sprite et tu # -tc- les stocke dans un pygame.sprite.Group. Tu pourras # -tc- manipuler leur affichage de manière beaucoup plus propre # -tc- et idiomatique. display_maze.repaste_display(level, player) # Meeting BadGuy # -tc- avoir un player.position sous forme de tuple semble plus # -tc- logique au vu de ce que tu as fais dans maze.py if (player.x, player.y) == level.coord_badguy: # Check inventory if len(player.inventory_list) != nb_obj: message.display_message(config.LOOSE_MESS) # -tc- utiliser des parenthèses plutôt qu'un \ for event in pygame.event.get(): # Close window # -tc- utiliser des parenthèses plutôt qu'un \ if event.type == QUIT \ or (event.type == KEYDOWN and event.key == K_ESCAPE): game_loop = 0 # -tc- False big_loop = 0# -tc- False # Choose replay or quit elif event.type == KEYDOWN: if event.key == K_F1: # -tc- ton code est très très répétitif. Code déjà vu plus haut. Tu peux factoriser très facilement game_loop = 0# -tc- False elif event.key == K_F2: game_loop = 0# -tc- False big_loop = 0# -tc- False else: display_maze.badguy_sleeping = True # Check Exit if (player.x, player.y) == level.outdoor_coord: # Check if badguy is sleeping for event in pygame.event.get(): # Close window # -tc- une 3e fois pratiquement le même code!!! if event.type == QUIT \ or (event.type == KEYDOWN and event.key == K_ESCAPE): game_loop = 0 big_loop = 0 # Choose replay or quit elif event.type == KEYDOWN: if event.key == K_F1: game_loop = 0 if event.key == K_F2: game_loop = 0 big_loop = 0 if display_maze.badguy_sleeping is True: message.display_message(config.WIN_MESS) else: message.display_message(config.CHEAT_MESS)
from mazeProblem import mazeProblem from maze import Maze from Filtering import filtering import random test1 = Maze("testmaze1") problem = mazeProblem(test1) filtering(problem, 50) # to generate random maze teststr = "" for x in range(10): for y in range(10): rand = random.random() if rand < .2: teststr += "#" elif rand < .4: teststr += "r" elif rand < .6: teststr += "b" elif rand < .8: teststr += "y" else: teststr += "g" teststr += '\n' # to make a new random maze, uncomment below lines, run the program, then place a robot in an non-wall location #f = open("randomtest", "w") #f.write(teststr) #f.close()
def main(): """Main program""" pygame.init() pygame.display.set_caption("MacGyver's Maze") cell_size = 40 maze = Maze("structure", cell_size) height = maze.maze_height * cell_size width = maze.maze_width * cell_size screen = pygame.display.set_mode((width, height)) maze.maze(screen) player = Player(maze.coord_list[2][0], cell_size) guard = Item("guard", pygame.image.load("ressource/guard.png"), cell_size) guard.place(screen, maze.coord_list[3]) ether = Item("ether", pygame.image.load("ressource/ether.png"), cell_size) ether.image.set_colorkey((0, 0, 0)) pipe = Item("pipe", pygame.image.load("ressource/pipe.png"), cell_size) pipe.image.set_colorkey((0, 0, 0)) needle = Item("needle", pygame.image.load("ressource/needle.png"), cell_size) ether.place(screen, maze.coord_list[1]) pipe.place(screen, maze.coord_list[1]) needle.place(screen, maze.coord_list[1]) run = True while run: pygame.time.Clock().tick(10) screen.blit(maze.floor, player.rect) # Mouse and keyboard's events detection for event in pygame.event.get(): if event.type == pygame.QUIT: run = False elif event.type == pygame.KEYDOWN: player.pressed[event.key] = True elif event.type == pygame.KEYUP: player.pressed[event.key] = False # Player move if player.pressed.get(pygame.K_UP) and (player.rect.x, player.rect.y - cell_size) \ not in maze.coord_list[0] and player.rect.y - cell_size >= 0: player.move("up") elif player.pressed.get(pygame.K_DOWN) and (player.rect.x, player.rect.y + cell_size) \ not in maze.coord_list[0] and player.rect.y + cell_size < height: player.move("down") elif player.pressed.get(pygame.K_RIGHT) and (player.rect.x + cell_size, player.rect.y) \ not in maze.coord_list[0] and player.rect.x + cell_size < width: player.move("right") elif player.pressed.get(pygame.K_LEFT) and (player.rect.x - cell_size, player.rect.y) \ not in maze.coord_list[0] and player.rect.x - cell_size >= 0: player.move("left") # Collecting items if player.rect.colliderect(ether.rect): player.objects["ether"] = ether elif player.rect.colliderect(pipe.rect): player.objects["pipe"] = pipe elif player.rect.colliderect(needle.rect): player.objects["needle"] = needle screen.blit(player.image, player.rect) # Two possible endings if player.rect.colliderect(guard.rect): if len(player.objects) == 3: win = pygame.image.load("ressource/win.jpg") win = pygame.transform.scale(win, (width, height)) screen.blit(win, (0, 0)) else: lose = pygame.image.load("ressource/lose.jpg") lose = pygame.transform.scale(lose, (width, height)) screen.blit(lose, (0, 0)) run = False pygame.display.flip()
def test_prueba(file, goalF): m = Maze(file) m.solve() assert m.goal == goalF
def transformToMaze(arm, goals, obstacles, window, granularity): """This function transforms the given 2D map to the maze in MP1. Args: arm (Arm): arm instance goals (list): [(x, y, r)] of goals obstacles (list): [(x, y, r)] of obstacles window (tuple): (width, height) of the window granularity (int): unit of increasing/decreasing degree for angles Return: Maze: the maze instance generated based on input arguments. """ alpha_min = arm.getArmLimit()[0][0] alpha_max = arm.getArmLimit()[0][1] num_rows = int(((alpha_max-alpha_min)/granularity))+1 beta_min = arm.getArmLimit()[1][0] beta_max = arm.getArmLimit()[1][1] num_cols = int(((beta_max-beta_min)/granularity))+1 maze = [] for i in range(int(num_rows)): maze.insert(len(maze), []) for i in range(int(num_rows)): for j in range(int(num_cols)): maze[i].insert(len(maze[i]), ' ') #print(maze) print(alpha_min,beta_min) """print('y not',len(maze)) print('goals are:',goals) print('obstacles are:',obstacles) print('window',window) print('rows and cols',(num_rows,num_cols))""" start_point = arm.getArmAngle() print(start_point) print('f**k me',int((start_point[0]-alpha_min)/granularity),int((start_point[1]-beta_min)/granularity)) maze[int((start_point[0]-alpha_min)/granularity)][int((start_point[1]-beta_min)/granularity)] = 'P' alpha = alpha_min alpha_index = 0 while(alpha <= alpha_max): beta = beta_min beta_index = 0 while(beta <= beta_max): arm.setArmAngle((alpha, beta)) cur_armEnd = arm.getEnd() cur_armPos = arm.getArmPos() if(doesArmTouchObstacles(cur_armPos, obstacles)): maze[alpha_index][beta_index] = '%' if(doesArmTouchGoals(cur_armEnd, goals)): maze[alpha_index][beta_index] = '.' if not (isArmWithinWindow(cur_armPos, window)): maze[alpha_index][beta_index] = '%' #print(cur_coord) beta += granularity beta_index += 1 alpha += granularity alpha_index += 1 f = open('mazeyichen.txt','w') for i in range(num_rows): for j in range(num_cols): f.write(maze[i][j]) f.write('\n') f.close() maze_ret = Maze(maze,[alpha_min,beta_min],granularity) #maze_ret.saveToFile('bb.txt') return maze_ret pass
r,c = square north = r-1,c # row above south = r+1,c # row below east = r,c+1 # etc. west = r,c-1 # update list of to-do items: if m.isClear(north): todo.add(north) if m.isClear(west): todo.add(west) if m.isClear(south): todo.add(south) if m.isClear(east): todo.add(east) # pause, for demonstration if pausing: clear() print(m) response = input('?') done = response == 'q' pausing = response != 'g' def clear(): print('\033[H\033[J',end='') if __name__ == "__main__": from sys import argv assert len(argv) > 1, "Usage: python3 solve.py maze-definition" m = Maze(argv[1]) solve(m,pausing=True)
def transformToMaze(arm, goals, obstacles, window, granularity): """This function transforms the given 2D map to the maze in MP1. Args: arm (Arm): arm instance goals (list): [(x, y, r)] of goals obstacles (list): [(x, y, r)] of obstacles window (tuple): (width, height) of the window granularity (int): unit of increasing/decreasing degree for angles Return: Maze: the maze instance generated based on input arguments. """ dim = len(arm.getArmAngle()) if (dim == 1): alpha = arm.getArmAngle()[0] beta = 0 gamma = 0 alimit = arm.getArmLimit()[0] blimit = (0, 0) hlimit = (0, 0) row_num = int((alimit[1] - alimit[0]) / granularity + 1) col_num = 1 hei_num = 1 cur_r, cur_c, cur_h = angleToIdx((alpha, beta, gamma), (alimit[0], blimit[0], hlimit[0]), granularity) if (dim == 3): alpha, beta, gamma = arm.getArmAngle() alimit, blimit, hlimit = arm.getArmLimit() row_num = int((alimit[1] - alimit[0]) / granularity + 1) col_num = int((blimit[1] - blimit[0]) / granularity + 1) hei_num = int((hlimit[1] - hlimit[0]) / granularity + 1) cur_r, cur_c, cur_h = angleToIdx((alpha, beta, gamma), (alimit[0], blimit[0], hlimit[0]), granularity) # print(cur_r,cur_c) map = [[[SPACE_CHAR for i in range(hei_num)] for j in range(col_num)] for k in range(row_num)] # go through map # print(obstacles) for i in range(row_num): for j in range(col_num): flag = False for k in range(hei_num): # if(flag): # map[i][j][k] = WALL_CHAR # continue cur_alpha, cur_beta, cur_gamma = idxToAngle( (i, j, k), (alimit[0], blimit[0], hlimit[0]), granularity) arm.setArmAngle([cur_alpha, cur_beta, cur_gamma]) if (not isArmWithinWindow(arm.getArmPos(), window)): map[i][j][k] = WALL_CHAR elif (doesArmTouchObjects(arm.getArmPosDist(), obstacles, False)): map[i][j][k] = WALL_CHAR elif (i == cur_r and j == cur_c and k == cur_h): map[i][j][k] = START_CHAR elif (dim == 1 and i == cur_r): map[i][j][k] = START_CHAR elif (doesArmTipTouchGoals(arm.getEnd(), goals)): map[i][j][k] = OBJECTIVE_CHAR # flag=True elif (doesArmTouchObjects(arm.getArmPosDist(), goals, True)): map[i][j][k] = WALL_CHAR return Maze(map, [alimit[0], blimit[0], hlimit[0]], granularity)
lobby_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lobby_socket.connect((HOST, MGMT_PORT)) print("Connected to Lobby") print("Waiting for lobby delegation...") json_data = lobby_socket.recv(4096) lobby_data = json.loads(json_data.decode('ascii')) lobby_id = lobby_data["lobby_id"] lobby_socket.close() print("Assigned to Lobby %s" % str(lobby_id)) game_port = BASE_PORT + (lobby_id * 2) io_port = BASE_PORT + (lobby_id * 2) + 1 print(io_port) # Show title screen maze = Maze() running = True while running: inp = maze.get_input() if "SPACE" in inp: running = False maze.draw_title_screen() # Connect to I/O Server io_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) io_socket.connect((HOST, io_port)) print("Connected I/O to server") # Connect to Game Server client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((HOST, game_port))
def cmaze(array): """Solves maze with depth-first search in C.""" m = Maze() m.maze = array m.solve((), (), Maze.Solve.C)
def main(): # main boucle running = 1 while running: # Load home screen screen.blit(BACKGROUND, (30, 30)) screen.blit(ACCUEIL, (100, 100)) # Reload display pygame.display.flip() # main boucle running_welcome = 1 while running_welcome: # delay boucle pygame.time.Clock().tick(30) for event in pygame.event.get(): # Quit the program if event.type == QUIT: print("See you next Time!") running = 0 running_welcome = 0 running_game = 0 # Quit home boucle to enter in game boucle with taping any key if event.type == KEYDOWN : #Welcome to the game screen.blit(BACKGROUND, (30, 30)) screen.blit(WELCOME, (75, 100)) pygame.display.flip() time.sleep(2) #################################### running_welcome = 0 running_game = 1 # Load the game's maze from file FILE = "level_game" if FILE != "": # We assure that the file really exists and is not empty # loading the background screen.blit(BACKGROUND, (30, 30)) # generation of the maze maze = Maze(FILE) maze.generate() maze.display(screen) # Get the 3 items in the maze seringue = Items("seringue", SERINGUE, maze) seringue.position_items() seringue.pin_items() ether = Items("ether", ETHER, maze) ether.position_items() ether.pin_items() tube = Items("tube", TUBE, maze) tube.position_items() tube.pin_items() # And God create an Heroe MacGyver = Player(maze) # la boucle du jeu # Initialization de chaque boucle du jeu dans une liste vide pour y mettre les items box = [] while running_game: pygame.time.Clock().tick(30) for event in pygame.event.get(): # Quit the program if event.type == QUIT: print("Bye bye!") running = 0 running_game = 0 if event.type == KEYDOWN: # Quit the game and go back Home if event.key == K_ESCAPE: running_game = 0 # Move our heroe! if event.key == K_RIGHT: MacGyver.move("right") if event.key == K_LEFT: MacGyver.move("left") if event.key == K_DOWN: MacGyver.move("bottom") if event.key == K_UP: MacGyver.move("up") screen.blit(BACKGROUND, (0 + 30, 0 + 30)) maze.display(screen) # Add the hero MacGyver in the Labyrinth with his position screen.blit(MG, (MacGyver.x + 30, MacGyver.y + 30)) # + 30 for the offset of the black outline # conditionnal add display of each items in the maze tube.display_items(screen, MacGyver, box) seringue.display_items(screen, MacGyver, box) ether.display_items(screen, MacGyver, box) pygame.display.flip() if maze.structure[MacGyver.sprite_y][MacGyver.sprite_x] == "a": # The game user wins if he gets the tree items if len(box) < 3: #DISPLAY GAME OVER screen.blit(GAMEOVER, (150 + 30, 150 + 30)) pygame.display.flip() time.sleep(2) ###### print("You have lost ! Try again later") running_game = 0 if len(box) == 3: #DISPLAY that you have won screen.blit(WIN, (-100 , -100 )) pygame.display.flip() time.sleep(2) ### print("You win! congratulations !") running_game = 0
else: current_up = True if right_openings: current_position = right_openings[0] del right_openings[0] elif left_openings: current_position = left_openings[0] del left_openings[0] start_column_spot = current_position solution_path = list(dict.fromkeys(solution_path)) return solution_path # Testing below test_maze = Maze(5, 0, 21) test_maze.fill_maze() test_maze.tiles[5].passable = False test_maze.tiles[6].passable = False test_maze.tiles[8].passable = False test_maze.tiles[13].passable = False test_maze.tiles[16].passable = False test_maze.tiles[17].passable = False test_maze.tiles[18].passable = False test_maze.tiles[22].passable = False simple_maze = [] row = [] column = 0
# Import Python functions import cv2 from datetime import datetime as dtime # Import our classes from maze import Maze from robot import Robot write_to_video = True show_visualization = False userInput = False # Construct maze object maze = Maze('maze.txt') # Contstruct the robot robot = Robot(maze, userInput) # Record the start time so we can compute run time at the end starttime = dtime.now() # Run Search print("Starting search: ") robot.A_star() if robot.foundGoal: searchtime = dtime.now() searchtime = searchtime - starttime robot.generate_path() print('Found Path in ' + str(searchtime) + ' (hours:min:sec)')
def hill_climb(seed_state, iterations=20, search_algo=Search.A_star_man, metric_function=max_fringe_size, reset_limit=20, log=False): """An implementation of the hill climbing algorithm. The search will generate neighbor states of a seed state. Over each neighbor state, the input search_algo is conducted over it. A running account of the state that maximizes the metric_function is kept. Each iteration, a new set of neighbor states is generated. The search halts after a certain number of iterations has been met or a local maximia has been met. """ # Gather parameters from the seed state dim = seed_state.maze.dim p = seed_state.maze.p # variable that returns the metric values metric_list = [] # initial and goal states for the search algorithm initial_state = Position([0, 0]) goal_state = Position([dim - 1, dim - 1]) # Generates all neighboring states neighbors = generate_neighbor_states(seed_state) current_best = seed_state.copy() # This is the list of current_best states on which a local maximia was reached # If the reset_limit condition is met, we will return the hardest maze # in this list. local_maximas = [] # Loops for number of iterations. Iter must be an int value. i = 0 # Set the reset counter. reset_count = 0 while (i < iterations): metric_list.append(metric_function(current_best.metrics)) if log: print("iter {}..".format(i), end='') found_new_best = False neighbors = generate_neighbor_states(current_best) # For each state in the neighbors of current_best, # Check if the neighbor is the new currest_best for state in neighbors: valid, _, metrics = search_algo(state.maze, initial_state, goal_state) state.metrics = metrics if valid: metric = metric_function(metrics) if metric > metric_function(current_best.metrics): # Update current best # if log: print("\tFound new best: {}".format(metric)) current_best = state.copy() found_new_best = True # If none of the neighbors can top the current best # We are at a local maximia. if not found_new_best: if log: print("**At a local maxima...metric val:{}".format( metric_function(current_best.metrics))) # At this maze to the local maximia list. local_maximas.append(current_best) # If we've reset beyond the limit, return the best of local maximia if reset_count == reset_limit: if log: print( "**Max reset limit reached. Returning best of local maximia." ) # Finding best maximia best = current_best for maximia in local_maximas: score = metric_function(maximia.metrics) if score > metric_function(best.metrics): best = maximia return best, metric_list # Preparing to reset the serach at a new maze reset_count += 1 valid = False # Loop to ensure the new maze is solveable before restarting while (not valid): current_best = HardState(Maze(dim, p, 0)) valid, _, metrics = search_algo(current_best.maze, initial_state, goal_state) current_best.metrics = metrics # Reset iter index. Restart the search. i = 0 if log: print("**Resetting...{} of {}.\n".format( reset_count, reset_limit)) continue i += 1 # Total iteration cap has been met. Return current_best if log: print("Max iterations met.") return current_best, metric_list
def transformToMaze(arm, goals, obstacles, window, granularity): """This function transforms the given 2D map to the maze in MP1. Args: arm (Arm): arm instance goals (list): [(x, y, r)] of goals obstacles (list): [(x, y, r)] of obstacles window (tuple): (width, height) of the window granularity (int): unit of increasing/decreasing degree for angles Return: Maze: the maze instance generated based on input arguments. """ #create new maze with dims = (range of angle) / granulity dims = arm.getArmLimit().copy() for i in range(len(dims)): dims[i] = int((dims[i][1] - dims[i][0]) / granularity) + 1 maze = [] for i in range(dims[0]): column = [] for j in range(dims[1]): column.append(" ") maze.append(column) startAngles = [] for i in range(len(arm.getArmAngle())): startAngles.append( int((arm.getArmAngle()[i] - arm.getArmLimit()[i][0]) / granularity)) maze[startAngles[0]][startAngles[1]] = "P" #start point for i in range(dims[0]): longways = "" for j in range(dims[1]): alpha = int(i * granularity + arm.getArmLimit()[0][0]) beta = int(j * granularity + arm.getArmLimit()[1][0]) arm.setArmAngle((alpha, beta)) armPos = arm.getArmPos() ty = 0 if isArmWithinWindow(armPos, window) is False: maze[i][j] = "%" ty = 1 elif doesArmTipTouchGoals(arm.getEnd(), goals) is True: maze[i][j] = "." elif doesArmTouchObjects(arm.getArmPosDist(), obstacles, False) is True: maze[i][j] = "%" ty = 2 elif doesArmTouchObjects(arm.getArmPosDist(), goals, True) is True: maze[i][j] = "%" ty = 3 elif maze[i][j] == "P": print("I FOUND THE P!") else: maze[i][j] = " " if ty == 1 or ty == 0: longways += maze[i][j] elif ty == 2: longways += "#" elif ty == 3: longways += "$" print(longways) retMaze = Maze(maze, (arm.getArmLimit()[0][0], arm.getArmLimit()[1][0]), granularity) #retMaze.saveToFile("check2.txt") return retMaze