Beispiel #1
0
 def __init__(self):
     self.actual_maze = Maze().readfiftymazes()[random.randint(0, 49)]
     self.blank_maze = None
     self.size = 101
     self.start_node_actual, self.goal_node_actual = Metrics().generate_random_start_and_goal_nodes(
                 self.actual_maze, self.size)
     self.actual_mazes = Maze().readfiftymazes()
Beispiel #2
0
    def main(self):
        actual_mazes = Maze().readfiftymazes()
        size = 101
        for i in range(50):
            actual_maze = actual_mazes[i]
            start_node_actual, goal_node_actual = Metrics().generate_random_start_and_goal_nodes(
            actual_maze, size)

            agent_maze = Maze().generate_blank_maze(size)
            start_node = agent_maze[start_node_actual.x][start_node_actual.y]
            goal_node = agent_maze[goal_node_actual.x][goal_node_actual.y]
            RepeatedAlgo(size, actual_maze, agent_maze, start_node, goal_node, start_node_actual,
                             goal_node_actual, 0).repeated_algorithm()

            agent_maze = Maze().generate_blank_maze(size)
            start_node = agent_maze[start_node_actual.x][start_node_actual.y]
            goal_node = agent_maze[goal_node_actual.x][goal_node_actual.y]
            RepeatedAlgo(size, actual_maze, agent_maze, start_node, goal_node, start_node_actual,
                            goal_node_actual, 1).repeated_algorithm()

            agent_maze = Maze().generate_blank_maze(size)
            start_node = agent_maze[start_node_actual.x][start_node_actual.y]
            goal_node = agent_maze[goal_node_actual.x][goal_node_actual.y]
            RepeatedAlgo(size, actual_maze, agent_maze, start_node, goal_node, start_node_actual,
                             goal_node_actual, 2).repeated_algorithm()

            agent_maze = Maze().generate_blank_maze(size)
            start_node = agent_maze[start_node_actual.x][start_node_actual.y]
            goal_node = agent_maze[goal_node_actual.x][goal_node_actual.y]
            RepeatedAlgo(size, actual_maze, agent_maze, start_node, goal_node, start_node_actual,
                             goal_node_actual, 3).repeated_algorithm()
Beispiel #3
0
def main(seed=None, debug=False):
	"""
	Main flow of the program. Print statement
	"""
	## Get maze
	if seed:
		maze = Maze(seed)
	else:
		response = make_request(BASE_URL)
		maze_data = json.loads(response.content)
		maze = Maze(maze_data)
	
	print('Starting to solve for a maze of size {} by {}'.format(maze.height, maze.width))

	if debug:
		reveal_maze_board(maze)
		print('Maze looks like this!')
		print(maze)

	## Get the path that solves
	path = maze_solver_dfs(maze)
	print('A solution looks like this... blank means no solution')
	print(path)

	## Decode path to solution
	solution = decode_path_solution(maze.start, path)

	## Valid solution?
	print('Is this solution valid? {}'.format(is_solution_valid(maze, solution)))
	print('Maze {} is done.'.format(maze.id))
Beispiel #4
0
    def __init__(self):
        self.mode = 0  #mapping mode
        '''
        Constructor
        mode=0 er mapping
        mode=1 er goToPath
        '''
        self.logger = logging.getLogger("robot.Mapping")
        self.logger.info("Mapping initialised")
        self.mode = 0  #mapping
        self.maze = Maze()
        self.globalCompass = [0, 1, 2, 3]  #north/east/south/west
        self.startDirection = self.globalCompass[2]
        self.direction = self.startDirection  #south

        self.startPosition = [0, 0]
        self.currentPosition = self.startPosition  #x,y

        self.lastWas180 = False
        self.lastPosition = self.currentPosition
        self.funcDict = {
            0: self.subY,
            1: self.addX,
            2: self.addY,
            3: self.subX
        }

        self.stack = []
        '''
Beispiel #5
0
def main():
    """Lets run!"""

    try:
        parameters = sys.argv
        json_file = open(parameters[1])

        start_node = parameters[2]
        if int(start_node) > 0:
            print 'STARTING AT ID: '+start_node
        else:
            print 'YOU DONT KNOW HOW TO PLAY :-)'

        search_parameters = []
        for item in parameters[3:]:
            if item:
                search_parameters.append(item)

        if len(search_parameters) == 0:
            print 'YOU DONT KNOW HOW TO PLAY :-)'
            sys.exit(0)
        else:
            print 'SEARCHING:'
            pprint(search_parameters)

        maze = Maze(int(start_node), json_file, search_parameters)
        maze.print_output()
    except:
        print 'YOU DONT KNOW HOW TO PLAY :-)'
Beispiel #6
0
 def test_brain_adds_new_information(self):
     maze = Maze(3)
     brain = Brain(maze)
     prevLength = len(brain.informationCache)
     brain.accept_information([1, 2, 3, 4])
     newLength = len(brain.informationCache)
     self.assertEqual(prevLength + 1, newLength)
Beispiel #7
0
    def __init__(self, size=6):
        super(MainWindow, self).__init__()
        self.title('maze')
        self.geometry("800x600")

        # 界面控件
        self.button_confirm = tk.Button(text="生成地图", command=self.show_maze, width=8, font=("幼圆",14))
        self.button_confirm.pack()
        self.button_begin = tk.Button(text="寻找路径", command=self.find_path, width=8, font=("幼圆",14))
        self.button_begin.pack()
        self.button_showpath = tk.Button(text="显示路径", command=self.show_path, width=8, font=("幼圆",14))
        self.button_begin.pack()
        self.v = tk.StringVar()
        self.label_progress = tk.Label(textvariable=self.v, font=("幼圆",16))
        self.label_progress.pack()
        info = """
        Tips:
                根据下拉框选择类型
                  并自动生成地图。
                   黑色代表墙壁
                   蓝色代表夹子
                   橙色代表火焰
                   红色代表老鼠
                   黄色代表终点
                    Have fun :)
        """
        self.label_info = tk.Label(text=info,font=("幼圆",14),anchor="w")
        self.label_info.pack()
        self.menu_size = ttk.Combobox(width=8, height=3, font="幼圆")
        self.menu_size['value'] = ("6x6", "8x8", "10x10", "12x12")
        self.size_dict = {"6x6":6, "8x8":8, "10x10":10, "12x12":12}
        self.difficulty_dict = {"简单":0, "中等":1, "困难":2}
        self.type_dict = {"q-learning":0, "E-Sarsa":1}
        self.menu_size.pack()
        self.menu_size.current(0)
        self.menu_difficulty = ttk.Combobox(width=8, height=3, font="幼圆")
        self.menu_difficulty['value'] = ("简单", "中等", "困难")
        self.menu_difficulty.pack()
        self.menu_difficulty.current(0)
        self.menu_type = ttk.Combobox(width=12, height=3, font="幼圆")
        self.menu_type['value'] = ("q-learning", "E-Sarsa")
        self.menu_type.pack()
        self.menu_type.current(0)
        self.menu_type.place(relx=0.77,rely=0.08)
        self.menu_size.place(relx=0.8, rely=0.16)
        self.menu_difficulty.place(relx=0.8, rely=0.24)
        self.button_confirm.place(relx=0.74, rely=0.3)
        self.button_begin.place(relx=0.86, rely=0.3)
        self.button_showpath.place(relx=0.8, rely=0.4)
        self.label_progress.place(relx=0.7, rely=0.5)
        self.label_info.place(relx=0.5, rely=0.65)
        self.canvas = tk.Canvas(self, bg='white', height=480, width=480)
        self.canvas.place(x=40, y=40)
        #初始化其他参数
        self.size = size
        self.difficulty = 0
        self.maze = Maze()  # 迷宫类
        action_list = self.maze.action
        self.model = Q_Learning(action_list)  # Q_Learning算法
        self.show_maze()
Beispiel #8
0
def run_training(maze_size=(6, 6),
                 trap_number=1,
                 epoch=20,
                 epsilon0=0.3,
                 alpha=0.3,
                 gamma=0.9):

    # # 可选的参数:
    # epoch = 20

    # # 随机探索的初始概率
    # epsilon0 = 0.3

    # # 松弛变量
    # alpha = 0.3

    # # 折扣因子
    # gamma = 0.9

    # # 地图大小
    # maze_size = (6, 6)

    # # 陷阱数量
    # trap_number = 1

    g = Maze(maze_size=maze_size, trap_number=trap_number)
    r = Robot(g, alpha=alpha, epsilon0=epsilon0, gamma=gamma)
    r.set_status(learning=True)

    runner = Runner(r, g)
    runner.run_training(epoch, display_direction=True)
    # runner.generate_movie(filename = "final1.mp4") # 你可以注释该行代码,加快运行速度,不过你就无法观察到视频了。

    # runner.plot_results()
    return runner
Beispiel #9
0
    def generateBacteriaLayout(x, y):
        mazeLayout = Maze(x, y)
        currentLayer = []
        nextLayer = []

        start = Position(randint(0, mazeLayout.width - 1),
                         randint(0, mazeLayout.height - 1))

        mazeLayout.getByPosition(start).visited = True
        currentLayer.append(start)

        while len(currentLayer) > 0:
            for pos in currentLayer:
                neighbors = mazeLayout.getByPosition(pos).getAllNeighbors(
                    mazeLayout.width, mazeLayout.height)

                for i in neighbors:
                    if not mazeLayout.getByPosition(i).visited:
                        mazeLayout.getByPosition(pos).connect(
                            mazeLayout.getByPosition(i))
                        mazeLayout.getByPosition(i).visited = True
                        nextLayer.append(i)
            shuffle(nextLayer)
            currentLayer = nextLayer
            nextLayer = []

        return mazeLayout
Beispiel #10
0
    def __init__(self, root):
        """
            Creates instance of MazeView.

            root: parameter containing Tkinter window
            maze: current instance of Maze
            state: Contains the state of the current maze
            canvas: Canvas containing the grid from self.maze
            userFrame: Frame containing all user input
        """
        root.title("A* Algorithm Demo")
        root.geometry("500x580")
        root.resizable(0, 0)
        self.root = root

        self.maze = Maze(20, 20, MazeView.probWall)

        self.state = Label(root, text="Click \"Generate New Maze\" to Begin")
        self.state.pack()

        self.canvas = Canvas(self.root,
                             height=480,
                             width=480,
                             borderwidth=5,
                             bg="#474861")
        self.canvas.pack()

        self.userFrame = Frame(self.root)
        self.userFrame.pack(side="bottom")

        self.setup(self.canvas, self.userFrame)
        self.root.update()
Beispiel #11
0
def playMaze():

    # Step 1: init BrainDQN
    actions = 4
    brain = BrainDQN(actions)
    # Step 2: init Maze Game
    maze = Maze()
    # Step 3: play game
    # Step 3.1: obtain init state

    observation = [1, 0, 0, 0, 0, 0, 0, 0]
    observation += wgn(7)

    brain.setInitState(observation)
    tt = 0  # number of termials
    # Step 3.2: run the game
    while 1:
        stateIndex = np.argmax(observation)
        actions = [0, 1, 2,
                   3]  # the index of available actions: UP DOWN LEFT RIGHT
        action = brain.getAction(actions)
        reward, terminal, observation = maze.takeAction(action)
        observation += wgn(7)
        brain.setPerception(observation, action, reward, terminal)
        if terminal:
            tt += 1
            if tt == 1000:
                brain.printExit()
            print 'Terminal'
            maze.newGame()
            oberservation = [1, 0, 0, 0, 0, 0, 0, 0]
            observation += wgn(7)
            brain.setInitState(observation)
Beispiel #12
0
    def __init__(self):
        pygame.init()
        # make a window 600 by 600 pixel
        self.window = pygame.display.set_mode((600, 600))
        self.font = pygame.font.Font(None, 40)
        self.load_element()

        self.position = self.player.get_rect()
        self.keeper_position = (14 * 40, 14 * 40)

        self.text = None
        self.textpos = None

        my_maze = Maze()
        self.allowed_tiles = my_maze.get_map()

        # generate 3 random object coordinates
        self.first_object = [
            position for position in random.sample(self.allowed_tiles, 1)
        ]
        self.second_object = [
            position for position in random.sample(self.allowed_tiles, 1)
        ]
        self.third_object = [
            position for position in random.sample(self.allowed_tiles, 1)
        ]
        self.objects = [
            self.first_object, self.second_object, self.third_object
        ]
Beispiel #13
0
def kruskal_slide1(screen):
    """

    """
    maze_kruskal = Maze(8, 'square', 'kruskal')
    maze_kruskal.create((screen_size[0] // 4, screen_size[1] // 2), graph_bool=True)
    maze_kruskal.draw_grid(screen, graph_bool=True, cell_text_bool=True, cell_text_type=1)

    highlight_color = Color.red_light
    delay = 100
    index_text_size = 15

    maze_kruskal.draw_frame(screen)

    for i in range(0, len(maze_kruskal.maze_order)):
        cell0, cell1 = maze_kruskal.maze_order[i][0], maze_kruskal.maze_order[i][1]

        MazeFunctions.highlight_edge_delete(screen, maze_kruskal, cell0, cell1, highlight_color, True, index_text_size, i)

        Functions.update_delay(delay)
        MazeFunctions.edge_color(screen, (cell0, cell1), highlight_color, graph=True,
                                 graph_color=maze_kruskal.color_line)

        MazeFunctions.highlight_edge_delete(screen, maze_kruskal, cell0, cell1, maze_kruskal.color_background, True,
                              index_text_size, i)
        MazeFunctions.edge_color(screen, (cell0, cell1), maze_kruskal.color_background, graph=True,
                                 graph_color=maze_kruskal.color_line)

        maze_kruskal.draw_frame(screen)

        Functions.update_delay(delay)
        Functions.buttonpress_detect()

    Functions.update_delay(500)
    maze_kruskal.draw(screen, True, False)
 def test_robot_move_changes_robotpos(self):
     maze = Maze(7)
     brain = Brain(maze)
     robot_pos = [1, 4]
     bat = RoboBat(maze, robot_pos, brain)
     bat.move_in_direction("left")
     self.assertNotEqual(robot_pos, bat.pos)
Beispiel #15
0
 def __init__(self):
     pygame.init()
     pygame.mixer.music.load('sounds/bg-music.wav')
     self.screen = pygame.display.set_mode(
         (800, 600)
     )
     pygame.display.set_caption('PacMan Portal')
     self.clock = pygame.time.Clock()
     self.score_keeper = ScoreController(screen=self.screen,
                                         sb_pos=((self.screen.get_width() // 5),
                                                 (self.screen.get_height() * 0.965)),
                                         items_image='cherry.png',
                                         itc_pos=(int(self.screen.get_width() * 0.6),
                                                  self.screen.get_height() * 0.965))
     self.maze = Maze(screen=self.screen, maze_map_file='maze_map.txt')
     self.life_counter = PacManCounter(screen=self.screen, ct_pos=((self.screen.get_width() // 3),
                                                                   (self.screen.get_height() * 0.965)),
                                       images_size=(self.maze.block_size, self.maze.block_size))
     self.level_transition = LevelTransition(screen=self.screen, score_controller=self.score_keeper)
     self.game_over = True
     self.pause = False
     self.player = PacMan(screen=self.screen, maze=self.maze)
     self.ghosts = pygame.sprite.Group()
     self.ghost_sound_manager = SoundManager(sound_files=['ghost-blue.wav', 'pacman_eatghost.wav', 'ghost-std.wav'],
                                             keys=['blue', 'eaten', 'std'],
                                             channel=Ghost.GHOST_AUDIO_CHANNEL)
     self.ghost_active_interval = 2500
     self.ghosts_to_activate = None
     self.first_ghost = None
     self.other_ghosts = []
     self.spawn_ghosts()
     self.actions = {PacManPortalGame.START_EVENT: self.init_ghosts,
                     PacManPortalGame.REBUILD_EVENT: self.rebuild_maze,
                     PacManPortalGame.LEVEL_TRANSITION_EVENT: self.next_level}
Beispiel #16
0
 def __init__(self):
     self._running = True
     self._display_surf = None
     self.player_image = None  # png image of player block
     self.block_image = None  # png image obstacle block
     self.player = Player()
     self.maze = Maze()
Beispiel #17
0
def gen_answers():
    m = Maze("maze.png")
    with open("P5.txt", 'w') as f:
        f.write("Outputs:\n")
        f.write("@id\n")
        f.write("pjmatthews\n")
        f.write("@plot\n")
        f.write(f'{str(m)}\n')
        f.write("@succ\n")
        for row in m.get_successor_matrix():
            for cell in row[:-1]:
                f.write(f'{cell},')
            f.write(f'{cell}\n')
        f.write("@solution\n")
        f.write(f'\n')
        f.write("@plot_solution\n")
        f.write(f'\n')
        f.write("@bfs\n")
        f.write(f'\n')
        f.write("@dfs\n")
        f.write(f'\n')
        f.write("@distances\n")
        f.write(f'\n')
        f.write("@a_manhattan\n")
        f.write(f'\n')
        f.write("@a_euclidean\n")
        f.write(f'\n')
        f.write("@answer_10\n")
        f.write("None\n")
 def test_robot_moves_in_right_direction(self):
     maze = Maze(7)
     brain = Brain(maze)
     robot_pos = [3, 4]
     bat = RoboBat(maze, robot_pos, brain)
     bat.move_in_direction("left")
     self.assertEqual(bat.pos, [2, 4])
Beispiel #19
0
def main():
    pygame.init()

    display_info = pygame.display.Info()
    display = pygame.display.set_mode(
        (display_info.current_w, display_info.current_h))
    pygame.display.set_caption("Demotastic")

    running = True
    clock = pygame.time.Clock()

    animations = [Rainbow(display), Maze(display)]
    animations = get_animation_array(display)
    animations.append(Rainbow(display))

    while running:
        running = handle_events(animations, display)
        mouse_position = pygame.mouse.get_pos()

        for animation in animations:
            animation.update(mouse_position)

        pygame.display.update()

        clock.tick(10)
    def __init__(self,
                 cell_rows: int,
                 cell_cols: int,
                 cell_size: int = 20,
                 maze_generators=None,
                 maze_solvers=None):

        super().__init__()
        self.rows = cell_rows
        self.cols = cell_cols
        self.width = screen_width = (
            cell_rows *
            cell_size) + MazeInterface.right_margin + MazeInterface.left_margin
        self.height = screen_height = (
            cell_cols *
            cell_size) + MazeInterface.top_margin + MazeInterface.bottom_margin
        self.canvas = pg.display.set_mode((screen_width, screen_height))

        # Give the MazeCanvas control over the main canvas so the algorithms can draw onto the screen
        self.algorithm_interface = MazeCanvas((cell_rows, cell_cols),
                                              self.canvas)
        self.maze = Maze(cell_rows, cell_cols)  # maze instance

        if not maze_generators:
            self.maze_generators = [
                DepthFirst.DepthFirst(self.maze, self.algorithm_interface)
            ]
        else:
            self.maze_generators = maze_generators.append(
                DepthFirst.DepthFirst(self.maze, self.algorithm_interface))

        # TODO, when maze solvers are made, append a default one to the solver
        self.maze_solvers = maze_solvers
        self.init_interface()
Beispiel #21
0
def main():
    tamanhos = [50, 100, 250]
    n_labirintos = 10
    space_result = dict()
    path_result = dict()

    algorithms = [
        "depth first search", "breadth first search", "best first search",
        "a* search", "hill climbing search"
    ]

    for t in tamanhos:
        temp = np.zeros((5 * 2, n_labirintos))
        print("Dimensões:", t)
        for i in range(n_labirintos):
            print("Criando Labirinto...")
            maze = Maze(random=True, height=t, width=t)

            print("Gerando caminhos...")
            path, min_ = Algorithm.depth_first_search(maze)
            temp[0][i] = len(path)
            temp[1][i] = len(min_)

            path, min_ = Algorithm.breadth_first_search(maze)
            temp[2][i] = len(path)
            temp[3][i] = len(min_)

            path, min_ = Algorithm.best_first_search(maze)
            temp[4][i] = len(path)
            temp[5][i] = len(min_)

            path, min_ = Algorithm.a_star_search(maze)
            temp[6][i] = len(path)
            temp[7][i] = len(min_)

            path, min_ = Algorithm.hill_climbing_search(maze)
            temp[8][i] = len(path)
            temp[9][i] = len(min_)

        print("Calculando Médias...")

        i = 0
        for alg in algorithms:
            if alg in space_result:
                space_result[alg].append(np.mean(temp[2 * i]))
                path_result[alg].append(np.mean(temp[2 * i + 1]))
            else:
                space_result[alg] = [np.mean(temp[2 * i])]
                path_result[alg] = [np.mean(temp[2 * i + 1])]

            i += 1

        print()

    plot_result(tamanhos, space_result, 'Comparação por Número de Iterações')
    plot_result(tamanhos, path_result, 'Comparação por Caminho Mínimo')
    print("Numero de Iterações:", space_result)
    print("Caminho Mínimo:", path_result)
    plt.show()
Beispiel #22
0
 def generate_maze(self):
     """the command that is given the to button on teh gui that generates a maze to the canvas"""
     #asking the user the size of the maze they want to generate and generating the starting grid with it
     self.grid_size = simpledialog.askstring("input", "Enter the size of the maze (heightxwidth / rowsxcolumns)")
     self.grid_size = [int(self.grid_size[:self.grid_size.index("x")]), int(self.grid_size[self.grid_size.index("x") + 1:])]
     self.maze = Maze(self.grid_size)
     self.maze.generate_maze()
     self.display_array(self.maze.grid)
 def walk(self, walker):
     m = Maze(self.mazefile, walker.path, False, 8)
     m.walk()
     walker.score = fitness(m)
     walker.positions = m.positions
     walker.complete = m.complete
     if walker.complete:
         walker.solution = m.solution
 def test_robot_move_updates_maze(self):
     maze = Maze(7)
     brain = Brain(maze)
     robot_pos = [1, 4]
     bat = RoboBat(maze, robot_pos, brain)
     bat.move_in_direction("left")
     self.assertFalse(maze.value_at_point(robot_pos) == 3)
     self.assertTrue(maze.value_at_point(bat.pos) == 3)
Beispiel #25
0
    def __init__(self):
        self.maze = Maze()
        self.metrics = Metrics()

        self.size = 25
        self.actual_maze = self.maze.generate_actual_maze(self.size)
        self.start_node_actual, self.goal_node_actual = self.metrics.generate_random_start_and_goal_nodes(
            self.actual_maze, self.size)
 def test_1_space_all_directions(self):
     maze = Maze(5)
     brain = Brain(maze)
     robot_pos = [2, 2]
     bat = RoboBat(maze, robot_pos, brain)
     self.assertEqual(bat.submit_observation("left"), 1)
     self.assertEqual(bat.submit_observation("down"), 1)
     self.assertEqual(bat.submit_observation("up"), 1)
     self.assertEqual(bat.submit_observation("right"), 1)
 def test_next_to_wall_returns_zero(self):
     maze = Maze(3)
     brain = Brain(maze)
     robot_pos = [1, 1]
     bat = RoboBat(maze, robot_pos, brain)
     self.assertEqual(bat.submit_observation("left"), 0)
     self.assertEqual(bat.submit_observation("down"), 0)
     self.assertEqual(bat.submit_observation("up"), 0)
     self.assertEqual(bat.submit_observation("right"), 0)
Beispiel #28
0
 def __init__(self, size, manager, drawing_camera):
     super().__init__(size, manager, drawing_camera)
     self.maze = Maze(10, 10, size)
     self.character = Character(
         (self.maze.start.x * self.maze.tile_scale * 16, 0),
         self.maze.tile_scale, 1, 8)
     self.colors["background"] = (33, 30, 39)
     self.next_screen = self.manager.screens[0]
     self.screen_name = "Maze"
Beispiel #29
0
 def Generate(self):
     self.m_Maze = Maze(self.m_W, self.m_H)  
     self.InitSet()
     for y in range(self.m_H - 1):   
         self.DestroyLeftWalls(y)
         self.DestroyDownLines(y)
         self.UpdateSet(y)
     self.ProcessLastLine()
     return self.m_Maze
Beispiel #30
0
def generate_problem():
    rows, columns = get_rows_columns()
    maze = Maze(int(rows), int(columns))
    maze.generate_wilson()

    json_manager.generate_maze_json(maze, maze.rows, maze.columns)
    json_manager.generate_problem_json(maze.rows, maze.columns)

    maze.body.clear()