def find_the_path(screen, grid, start, end, algo): if algo == "Breadth-First Search": pathfinding.bfs(screen, grid, start, end) elif algo == "Depth-First Search": pathfinding.dfs(screen, grid, start, end) elif algo == "Dijkstra's Algorithm": pathfinding.dijkstra(screen, grid, start, end) elif algo == "A* Search": pathfinding.a_star(screen, grid, start, end) else: print("-----Select an Algorithm-----")
def test_a_star_basic(self): heuristics = {'a': 5, 'b': 3, 'c': 9, 'd': 0} graph = {'a': {'b': 1, 'c': 2}, 'b': {'a': 1, 'c': 2, 'd': 3}, 'c': {'a': 2, 'b': 2, 'd': 1}, 'd': {'b': 3, 'c': 1} } start, end = 'a', 'd' self.assertEqual(('abd', 4), a_star(graph, heuristics, start, end))
def __init__(self,x,y,image_files,collid_list,pix_size,area = 1): super().__init__(x,y,image_files) self.pix_size = pix_size self.path_finder = a_star(collid_list,pix_size) self.mob_type = 'M' self.exp = self.level*10 * area self.level = area * 2 self.stats_reroll()
def __init__(self, x, y, image_files, collid_list, pix_size, area=1): super().__init__(x, y, image_files) self.pix_size = pix_size self.path_finder = a_star(collid_list, pix_size) self.mob_type = 'M' self.exp = self.level * 10 * area self.level = area * 2 self.stats_reroll()
def test_a_star_advanced(self): graph = { 'a': {'b': 5, 'd': 3, 'c': 7}, 'b': {'a': 5, 'f': 2}, 'c': {'a': 7, 'f': 3, 'e': 3}, 'd': {'a': 3, 'e': 2}, 'e': {'d': 2, 'c': 3}, 'f': {'b': 2, 'c': 3} } heuristics = {'a': 5, 'b': 30, 'c': 5, 'd': 15, 'e': 10, 'f': 0} start, end = 'a', 'f' self.assertEqual(('acf', 10), a_star(graph, heuristics, start, end))
def __init__(self): rospy.init_node("robot") self.current_pose = rospy.get_param("/robot_start") self.previous_pose = self.current_pose self.controller = Controller() self.goals = PriorityQueue() self.map_cells = self.get_map() self.hz = rospy.Rate(10) rospy.Subscriber("/base_pose_ground_truth", Odometry, self.set_pose) self.marker_path = MyMarker(rgb=ORANGE, namespace="path", frame="/map", size=[.07, .07, .1]) self.marker_traversed = MyMarker(rgb=GREEN, namespace="real", frame="/map", size=[.05, .05, .15]) self.marker_goals = MyMarker(rgb=YELLOW, namespace="goals", frame="/map", size=[.07, .07, .07]) self.marker_reached_goals = MyMarker(rgb=GREEN, namespace="reached", frame="/map", size=[.1, .1, .1]) self.get_goals_and_add_markers() self.sort_goals() for goal in self.goals: print "Next destination is: ", goal[0], " ", goal[1] goal = (round(goal[0], 1), round(goal[1], 1)) start_point = (round(self.current_pose[0], 1), round(self.current_pose[1], 1)) current_path = pathfinding.a_star(start_point, goal, self.map_cells) if goal not in current_path: current_path.append(goal) self.marker_path.add_line(current_path) for point in current_path: while not rospy.is_shutdown(): x = self.current_pose[0] y = self.current_pose[1] goal_x = point[0] goal_y = point[1] if abs(x - goal_x) + abs(y - goal_y) < .12: if abs(x - goal[0]) + abs(y - goal[1]) < .12: self.marker_reached_goals.add_marker(goal) self.marker_reached_goals.draw_markers() break self.marker_traversed.add_marker([x, y]) self.marker_goals.draw_markers() self.marker_reached_goals.draw_markers() self.marker_path.draw_markers() self.marker_traversed.draw_markers() self.controller.drive(goal_x, goal_y) self.hz.sleep()
def __find_shortest_path(self) -> None: """ Callback function to find the shortest path. Displays an error message if a starting and ending point are not selected. """ if self.__start is None or self.__end is None: messagebox.showerror( "Error", "Please select both a starting and ending point before running the" " pathfinding algorithm!") else: import pathfinding path = pathfinding.a_star(self) if not path: messagebox.showinfo("Info", "No path found!") return self.__draw_shortest_path(path)
def game_loop(): # INICIALIZAMOS LA APP pygame.display.set_caption('My game') clock = pygame.time.Clock() x_change = 0 y_change = 0 player = [15, 8] goal_x = 15 goal_y = 22 player_facing_east = True path = pathfinding.a_star(player[1], player[0], goal_x, goal_y, steppable_tiles, map) print(path, end="\n\n") step = 0 # GAME LOOP finished = False while not finished: # DRAW THE FRAME WITH THE NEEDED TILES draw_image(player, player_facing_east) # READ USER INPUT # finished, x_change, y_change, player_facing_east = read_user_input(x_change, y_change, player_facing_east) # player = update_player_pos(player, x_change, y_change) if step > 0: if path != None and step < len(path): player = path[step] else: finished = True print(player, end=", ") step += 1 sleep(0.5) # UPDATEAMOS EL DISPLAY Y AVANZAMOS EN EL TIEMPO pygame.display.update() clock.tick()
def main(): """ Main Program """ pygame.init() # Set the height and width of the screen size = [SCREEN_WIDTH, SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("Dungeon Dreams Demo") # Create the player map_pix_size = 30 # Create all the levels level_list = [] # level_list.append( Level_01(player) ) # Set the current level current_level_no = 0 current_level = 0 # current_level = level_list[current_level_no] active_sprite_list = pygame.sprite.Group() # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() all_sprites_list = pygame.sprite.LayeredDirty() collid_list = pygame.sprite.LayeredDirty() mobiles_list = pygame.sprite.Group() m_attacks = pygame.sprite.Group() area = None image_files = glob.glob('HumanMage.PNG') hud = Hud(screen) player = Player(100,100,image_files,hud) hud.display_player_stats(player.stats) player.set_all_sprites(all_sprites_list) screen_size = (screen.get_width(),screen.get_height()) m_fact = Monster_Factory(area,collid_list,50,screen_size,all_sprites_list,player) map_tool = Map_Handler(screen,all_sprites_list,collid_list,player,mobiles_list, m_fact,hud) map_tool.build_area() item_fact = map_tool.get_item_fact() shift_x = 0 shift_y = 0 all_mobiles = m_fact.get_mobiles_group() dam_mod = 1 #init path finding... path_finder = a_star(collid_list,50) player.group_add(all_mobiles) image_files = glob.glob('*.PNG') #init events for following and monsters, start at 3 seconds because #player needs a second or two catch bearings FOLLOW_EVENT = USEREVENT + 1 M_ATTACK_EVENT = USEREVENT + 2 pygame.time.set_timer(FOLLOW_EVENT, 3000) pygame.time.set_timer(M_ATTACK_EVENT,3000) game_start = False #-------- Main Program Loop ----------- while not done: #Probably would make a class just to handle #client events. #These handle the movements keys = pygame.key.get_pressed() if keys[pygame.K_h]: player.changespeed(-1, 0) if keys[pygame.K_l]: player.changespeed(1, 0) if keys[pygame.K_k]: player.changespeed(0, -1) if keys[pygame.K_j]: player.changespeed(0, 1) if keys[pygame.K_n]: player.changespeed(1,1) if keys[pygame.K_b]: player.changespeed(-1,1) if keys[pygame.K_y]: player.changespeed(-1,-1) if keys[pygame.K_u]: player.changespeed(1,-1) #More events, quit and attacks and stopping the player #when the button goes up. for event in pygame.event.get(): if event.type == pygame.QUIT: done = True player.check_events(event) if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: r_attack = player.ranged_attack(all_sprites_list, None, player.r_attack_images, dam_mod) m_fact.set_check_attack(r_attack) if event.type == pygame.KEYUP: if event.key == pygame.K_h: player.stop() if event.key == pygame.K_y: player.stop() if event.key == pygame.K_k: player.stop() if event.key == pygame.K_u: player.stop() if event.key == pygame.K_l: player.stop() if event.key == pygame.K_n: player.stop() if event.key == pygame.K_j: player.stop() if event.key == pygame.K_b: player.stop() #Really for testing pathfinding, pathfinding is really for monsters. if event.type == pygame.MOUSEBUTTONUP: pos = pygame.mouse.get_pos() player.follow_path(path_finder.get_path(player.get_pos(),pos), map_pix_size, pos) #Monsters follow every two seconds to cut down on pathfinding #Calculations if event.type == FOLLOW_EVENT: m_fact.monster_group_follow(player.get_pos()) pygame.time.set_timer(FOLLOW_EVENT, 2000) #Attack every second which is kind of a lot still #Otherwise player would get hurt too fast or too slow. if event.type == M_ATTACK_EVENT: m_attacks = m_fact.monsters_attack(player.get_pos()) player.set_check_attack(m_attacks) pygame.time.set_timer(M_ATTACK_EVENT,1000) #Move the player and then check for game end or picked up item. player_pos = player.move(collid_list,all_mobiles) lost = player.damaged() m_fact.move_monsters(all_mobiles) got_item = item_fact.is_picked_up() #For now just one item and if it is picked up the player wins. if got_item: end_text = [] end_text.append('You Found the Scepter of Yendor and Won the Game!') end_text.append('To replay press r!') end_text.append('To quit press q!') end_text.append('To continue press Space Bar!') done = game_end(True,end_text,screen,map_tool) map_tool.map_move(0,0) player.stop() player.ranged_item = 3 player.speed = 8 player.dam_mod = 10 elif(lost): end_text = [] end_text.append('You perished!') end_text.append('To replay press r!') end_text.append('To quit press q!') done = game_end(False,end_text,screen,map_tool) if(map_tool.map_section_change(player_pos)): area = map_tool.get_area() m_fact.gen_monsters(area) player.is_moving(map_pix_size) all_mobiles.update(None,None) if m_attacks: m_attacks.update() all_sprites_list.draw(screen) clock.tick(25) pygame.display.flip() pygame.quit()
def main(): """ Main Program """ pygame.init() # Set the height and width of the screen size = [SCREEN_WIDTH, SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("Dungeon Dreams Demo") # Create the player map_pix_size = 30 # Create all the levels level_list = [] # level_list.append( Level_01(player) ) # Set the current level current_level_no = 0 current_level = 0 # current_level = level_list[current_level_no] active_sprite_list = pygame.sprite.Group() # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() all_sprites_list = pygame.sprite.LayeredDirty() collid_list = pygame.sprite.LayeredDirty() mobiles_list = pygame.sprite.Group() m_attacks = pygame.sprite.Group() area = None image_files = glob.glob('HumanMage.PNG') hud = Hud(screen) player = Player(100, 100, image_files, hud) hud.display_player_stats(player.stats) player.set_all_sprites(all_sprites_list) screen_size = (screen.get_width(), screen.get_height()) m_fact = Monster_Factory(area, collid_list, 50, screen_size, all_sprites_list, player) map_tool = Map_Handler(screen, all_sprites_list, collid_list, player, mobiles_list, m_fact, hud) map_tool.build_area() item_fact = map_tool.get_item_fact() shift_x = 0 shift_y = 0 all_mobiles = m_fact.get_mobiles_group() dam_mod = 1 #init path finding... path_finder = a_star(collid_list, 50) player.group_add(all_mobiles) image_files = glob.glob('*.PNG') #init events for following and monsters, start at 3 seconds because #player needs a second or two catch bearings FOLLOW_EVENT = USEREVENT + 1 M_ATTACK_EVENT = USEREVENT + 2 pygame.time.set_timer(FOLLOW_EVENT, 3000) pygame.time.set_timer(M_ATTACK_EVENT, 3000) game_start = False #-------- Main Program Loop ----------- while not done: #Probably would make a class just to handle #client events. #These handle the movements keys = pygame.key.get_pressed() if keys[pygame.K_h]: player.changespeed(-1, 0) if keys[pygame.K_l]: player.changespeed(1, 0) if keys[pygame.K_k]: player.changespeed(0, -1) if keys[pygame.K_j]: player.changespeed(0, 1) if keys[pygame.K_n]: player.changespeed(1, 1) if keys[pygame.K_b]: player.changespeed(-1, 1) if keys[pygame.K_y]: player.changespeed(-1, -1) if keys[pygame.K_u]: player.changespeed(1, -1) #More events, quit and attacks and stopping the player #when the button goes up. for event in pygame.event.get(): if event.type == pygame.QUIT: done = True player.check_events(event) if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: r_attack = player.ranged_attack(all_sprites_list, None, player.r_attack_images, dam_mod) m_fact.set_check_attack(r_attack) if event.type == pygame.KEYUP: if event.key == pygame.K_h: player.stop() if event.key == pygame.K_y: player.stop() if event.key == pygame.K_k: player.stop() if event.key == pygame.K_u: player.stop() if event.key == pygame.K_l: player.stop() if event.key == pygame.K_n: player.stop() if event.key == pygame.K_j: player.stop() if event.key == pygame.K_b: player.stop() #Really for testing pathfinding, pathfinding is really for monsters. if event.type == pygame.MOUSEBUTTONUP: pos = pygame.mouse.get_pos() player.follow_path(path_finder.get_path(player.get_pos(), pos), map_pix_size, pos) #Monsters follow every two seconds to cut down on pathfinding #Calculations if event.type == FOLLOW_EVENT: m_fact.monster_group_follow(player.get_pos()) pygame.time.set_timer(FOLLOW_EVENT, 2000) #Attack every second which is kind of a lot still #Otherwise player would get hurt too fast or too slow. if event.type == M_ATTACK_EVENT: m_attacks = m_fact.monsters_attack(player.get_pos()) player.set_check_attack(m_attacks) pygame.time.set_timer(M_ATTACK_EVENT, 1000) #Move the player and then check for game end or picked up item. player_pos = player.move(collid_list, all_mobiles) lost = player.damaged() m_fact.move_monsters(all_mobiles) got_item = item_fact.is_picked_up() #For now just one item and if it is picked up the player wins. if got_item: end_text = [] end_text.append( 'You Found the Scepter of Yendor and Won the Game!') end_text.append('To replay press r!') end_text.append('To quit press q!') end_text.append('To continue press Space Bar!') done = game_end(True, end_text, screen, map_tool) map_tool.map_move(0, 0) player.stop() player.ranged_item = 3 player.speed = 8 player.dam_mod = 10 elif (lost): end_text = [] end_text.append('You perished!') end_text.append('To replay press r!') end_text.append('To quit press q!') done = game_end(False, end_text, screen, map_tool) if (map_tool.map_section_change(player_pos)): area = map_tool.get_area() m_fact.gen_monsters(area) player.is_moving(map_pix_size) all_mobiles.update(None, None) if m_attacks: m_attacks.update() all_sprites_list.draw(screen) clock.tick(25) pygame.display.flip() pygame.quit()
def ai_lab_3(without_traversing_delays=True): baseTrees = 0 charCoal = 0 while charCoal < 200: workers = 0 scouts = 0 craftsmen = 0 for a in agents: if a.agentType == AgentEnum.WORKER: workers += 1 if a.agentType == AgentEnum.SCOUT: scouts += 1 if a.agentType == AgentEnum.BUILDER: craftsmen += 1 if without_traversing_delays or time() > a.timer: if a.agentType == AgentEnum.WORKER: if scouts < 3: a.timer = time() + 60 a.agentType = AgentEnum.SCOUT scouts += 1 continue elif craftsmen < 1: a.timer = time() + 120 a.agentType = AgentEnum.BUILDER craftsmen += 1 continue if lands[a.pos].trees > 0 and a.holding != ItemEnum.tree: lands[a.pos].trees -= 1 a.holding = ItemEnum.tree a.timer = time() + 30 a.pathToGoal = [] # something with pos, g, h if a.pathToGoal: a.timer = time() + pathfinding.move_cost( a.pos, a.pathToGoal[-1]) a.pos = a.pathToGoal.pop() # move to goal elif a.pos == startingPoint and len(treeTiles): if a.holding == ItemEnum.tree: baseTrees += 1 print("Trees In inventory:", baseTrees) a.holding = ItemEnum.none to_traverse = graph_to_nodes(treeTiles[0], a.agentType) a.pathToGoal = pathfinding.a_star(to_traverse, a.pos) # return to starting point else: lands[a.pos].trees -= 1 a.holding = ItemEnum.tree a.timer = time() + 30 to_traverse = graph_to_nodes(startingPoint, a.agentType) a.pathToGoal = pathfinding.a_star(to_traverse, a.pos) if a.agentType == AgentEnum.SCOUT: # something with pos, g, h if a.pathToGoal: a.timer = time() + pathfinding.move_cost( a.pos, a.pathToGoal[0]) a.pos = a.pathToGoal.pop() # move to goal elif a.pos == startingPoint: rng_undiscovered = terrain.find_scout_goal() to_traverse = graph_to_nodes(rng_undiscovered, a.agentType) a.pathToGoal = pathfinding.a_star(to_traverse, a.pos) # return to starting point else: to_traverse = graph_to_nodes(startingPoint, a.agentType) a.pathToGoal = pathfinding.a_star(to_traverse, a.pos) for n in r + ((0, 0), ): neigh = a.pos[0] + n[0], a.pos[1] + n[1] karta[neigh][0] = (karta[neigh][0]).upper() discovered[neigh] = karta[neigh] if a.agentType == AgentEnum.BUILDER: # Build a coalMill if there is none if karta[a.pos][ 0] == 'M' and baseTrees >= 10 and a.pos not in millTiles: baseTrees -= 10 millTiles.append(a.pos) a.timer = time() + 60 # if the miller is standing in the millTiles and has enough resources to smelt if a.pos in millTiles and baseTrees >= 2: baseTrees -= 2 charCoal += 1 print("charCoal:", charCoal) a.timer = time() + 30 # if len(a.pathToGoal) > 0: a.timer = time() + pathfinding.move_cost( a.pos, a.pathToGoal[-1]) a.pos = a.pathToGoal.pop() elif a.pos not in millTiles and len(millTiles) > 0: builder_goal = terrain.find_builder_goal() to_traverse = graph_to_nodes(builder_goal, AgentEnum.BUILDER) a.pathToGoal = pathfinding.a_star(to_traverse, a.pos) update_map()
def set_waypoint(self, goal): self.waypoint = goal self.path = pathfinding.a_star(self.grid, (self.loc.x, self.loc.y), (self.waypoint.x, self.waypoint.y))
start = (start_x, start_y) end = (end_x, end_y) print "\nStart: %s" % str(start) print "End: %s" % str(end) # mark the start and end nodes on the grid grid.nodes[start].value = "O" grid.nodes[end].value = "X" print grid.draw() print # use A* to find the path path = pf.a_star(grid, start, end) # print the path and the node values for coord in path: print grid.nodes[coord] # mark the path on the grid for coord in path: if (coord != start) and (coord != end): grid.nodes[coord].value = "+" # print the results on the grid if not path: print "No path found." print