def __init__(self): self.path_finder = PathFinder() self.food_orders = {} self.food_targets = set() self.explore_orders = {} self.attaking_orders = {} self.food_gathering_ants = [] self.enemy_hills = [] self.water = set() self.prox_dest = set() self.times_stats = {'food':2, 'unseen':5, 'enemy_hill':5, 'attack_hill':10} self.fifth_turn = -1 self.first_turn = True self.rose = ['n','e','s','w'] self.not_spawned_ants = 0 # visibles spaces around hills self.neighbourhood = {} # spaces with permanent ants, around hills self.hill_defending_locations = {} self.hill_exitway = {} self.hill_shield = {}
def process(v): subp.Popen("cls", shell=True) if v != 3: filename = filedialog.askopenfilename(initialdir = "./", title = "Seleccione input", filetypes = (("Archivo de lista de adyacencia","*.al"), ("Todos los archivos", "*"))) if v == 0: #subp.Popen("cls", shell=True) #subp.Popen("\"PathFinder\PathFinder.py\" " + filename, shell=True) PF.run(filename) if v == 1: #subp.Popen("cls", shell=True) #subp.Popen("\"WarshallFinder\WarshallFinder.py\" " + filename, shell=True) WF.run(filename) if v == 2: #subp.Popen("cls", shell=True) #subp.Popen("MCB\MCB.py" + filename) MCB.run(filename) if v == 3: filename = filedialog.askopenfilename(initialdir = "./BF/", title = "Seleccione input", filetypes = (("Archivos de valores delimitados por comas","*.csv"), ("Todos los archivos", "*"))) #subp.Popen("cls", shell=True) #subp.Popen("\"BF\BF.py\" " + filename, shell=True) BF.run(filename)
def __init__(self, bzrc, tank_index): self.bzrc = bzrc self.obstacles = self.bzrc.get_obstacles() self.tank_index = tank_index self.G_FROB = 0.90 self.R_FROB = 0.1 self.path = [] self.has_path = False self.has_flag = False self.path_finder = PathFinder(self.bzrc, self.tank_index)
def main(): cols, rows = 10, 10 screen = Screen(500, 500, rows) screen.show() screen.makeGrid() grid = [[Spot(screen, i, j) for j in range(0, rows)] for i in range(0, cols)] for i in range(0, cols): for j in range(0, rows): grid[i][j].addNeigbors(grid, cols, rows) start = grid[0][0] start.obstacle = False stop = grid[cols - 1][rows - 1] stop.obstacle = False pathFinder = PathFinder(grid, start, stop) while True: for event in pygame.event.get(): if (event.type == pygame.QUIT): screen.close() result = pathFinder.findPath() pathFinder.showOpenSet() pathFinder.showPath() screen.update()
def main(): # Process CLI arguments. try: execname, host, port = sys.argv except ValueError: execname = sys.argv[0] print >>sys.stderr, '%s: incorrect number of arguments' % execname print >>sys.stderr, 'usage: %s hostname port' % sys.argv[0] sys.exit(-1) # Connect. # bzrc = BZRC(host, int(port), debug=True) bzrc = BZRC(host, int(port)) path_finder = PathFinder(bzrc, 0) remove_old_plot_files() ### Depth First Search Visualizations ### path = path_finder.get_depth_first_search_path() plot_single(path, bzrc.get_obstacles(), '../plots/dfs_plots/dfs.png') snapshots = path_finder.search_snapshots plot_snapshots(snapshots, "../plots/dfs_plots/dfs", bzrc.get_obstacles()) ### Breadth First Search Visualizations ### path = path_finder.get_breadth_first_search_path() plot_single(path, bzrc.get_obstacles(), '../plots/bfs_plots/bfs.png') snapshots = path_finder.search_snapshots plot_snapshots(snapshots, "../plots/bfs_plots/bfs", bzrc.get_obstacles()) ### A* Visualizations ### path = path_finder.get_a_star_path() plot_single(path, bzrc.get_obstacles(), '../plots/a_star_plots/a_star.png') snapshots = path_finder.search_snapshots plot_snapshots(snapshots, "../plots/a_star_plots/a_star", bzrc.get_obstacles()) print("finished") bzrc.close()
def __init__(self, clock, dungeon, locale_id): self.clock = clock self.dungeon = dungeon self.path_finder = PathFinder(dungeon) self.locale_id = locale_id self.queue = PriorityQueue() self.factions = {} self.playing = True self.dungeon_expire = self.clock.max_locale_time self.char_id = 'DM' self.placement_locations = { 'ne': [], 'e': [], 'se': [], 'nw': [], 'w': [], 'sw': [], } self.init_placement_locations() self.clock.set_local_time(locale_id=locale_id, locale_time=0)
def draw_graph(self): pos = nx.spring_layout(self.graph) # print(self.color_graph()) nx.draw_networkx_nodes(self.graph, pos=pos, node_size=700) # hamilton = Hamilton(self) # is_hamilton_cycle = hamilton.is_hamilton_cycle() # # if is_hamilton_cycle: # nx.draw_networkx_edges(self.graph, pos, edgelist=hamilton.visited_edges, width=6) # edge_labels = self.get_edge_dict_with_property('placement') # nx.draw_networkx_edge_labels(self.graph, pos=pos, edge_labels=edge_labels) nx.draw_networkx_edges(self.graph, pos) if not self.are_all_weights_equal(): edge_labels = self.get_edge_dict_with_property('weight') nx.draw_networkx_edge_labels(self.graph, pos=pos, edge_labels=edge_labels) nx.draw_networkx_labels(self.graph, pos) # eulerian = Eulerian(self.graph) # # if eulerian.is_eulerian_circuit(): # plt.suptitle('Is an Euler\'s circuit.', color='green') # else: # plt.suptitle('Is not an Euler\'s circuit.', color='red') # # eulerian.eulerian_circuit(0) # print('Critical edges: ' + str(self.get_critical_edges())) pathFinder = PathFinder(self, list(self.get_nodes())[0]) print(pathFinder.get_shortest_path_to_node(3)) # print(pathFinder.get_shortest_path_to_all_nodes_using_weights()) plt.axis('off') plt.show()
def __init__(self): # Must come before pygame.init() self.sounds = Sounds() self._clock = pygame.time.Clock() pygame.init() pygame.display.set_mode( (1, 1)) # temporarily initialise display so bitmaps can be loaded pygame.display.set_caption("Pacman") self.graphics = Graphics(self) self._img_Background = self.graphics.loadImage("backgrounds", "1.gif") # create the pacman self.player = Player(self) # create a path_finder object self.path = PathFinder() # create ghost objects self.ghosts = {} for i in range(0, 6, 1): # remember, ghost[4] is the blue, vulnerable ghost self.ghosts[i] = Ghost(self, i) # create piece of fruit self.fruit = Fruit(self) self.tileID = {} # gives tile ID (when the name is known) self.tileIDImage = {} # gives tile image (when the ID# is known) # create game and level objects and load first level self.game = Game(self) self.level = Level(self) self.level.loadLevel(self.game.getLevelNum()) self.graphics.initDisplay() # initialise the joystick if pygame.joystick.get_count() > 0: if JS_DEVNUM < pygame.joystick.get_count(): self._js = pygame.joystick.Joystick(JS_DEVNUM) else: self._js = pygame.joystick.Joystick(0) self._js.init() else: self._js = None
def __choose__qCard(self): date = datetime.date month = date.month if month == 12: if randrange(1, 2) == 1: finder = PathFinder("Questions.txt") infile = open(finder.getPath()) qCards = infile.readlines() CardNo = randrange(0, len(qCards)) self.__qCard = qCards[CardNo] else: finder = PathFinder("Holiday Expansion Questions.txt") infile = open(finder.getPath()) qCards = infile.readlines() CardNo = randrange(0, len(qCards)) self.__qCard = qCards[CardNo] else: finder = PathFinder("Questions.txt") infile = open(finder.getPath()) qCards = infile.readlines() CardNo = randrange(0, len(qCards)) self.__qCard = qCards[CardNo]
def GenerateObstacle(self): self.obstacle_point.append( PathFinder.Point(self.size // 2, self.size // 2)) self.obstacle_point.append( PathFinder.Point(self.size // 2, self.size // 2 - 1)) # Generate an obstacle in the middle for i in range(self.size // 2 - self.size // 3, self.size // 2): self.obstacle_point.append(PathFinder.Point(i, self.size - i)) self.obstacle_point.append(PathFinder.Point(i, self.size - i - 1)) self.obstacle_point.append(PathFinder.Point(self.size - i, i)) self.obstacle_point.append(PathFinder.Point(self.size - i, i - 1))
def __getAnswerCard(): date = datetime.date month = date.month if month == 12: if randrange(1, 2) == 1: finder = PathFinder("Answers.txt") infile = open(finder.getPath()) aCards = infile.readlines() CardNo = randrange(0, len(aCards)) __aCard = aCards[CardNo] else: finder = PathFinder("Holiday Expansion Answers.txt") infile = open(finder.getPath()) aCards = infile.readlines() CardNo = randrange(0, len(aCards)) __aCard = aCards[CardNo] else: finder = PathFinder("Answers.txt") infile = open(finder.getPath()) aCards = infile.readlines() CardNo = randrange(0, len(aCards)) __aCard = aCards[CardNo] return __aCard
def start(self): rospy.wait_for_service("apriltags_info") try: info_query = rospy.ServiceProxy("apriltags_info", apriltags_info) resp = info_query() for i in range(len(resp.polygons)): # A polygon (access points using poly.points) poly = resp.polygons[i] # The polygon's id (just an integer, 0 is goal, all else is bad) t_id = resp.ids[i] polyPoints = [] for point in poly.points: polyPoints.append(Point(point.x, point.y)) self.world.addTag(PolyField(t_id, polyPoints)) self.world.createFields() PathFinder(self.world) except Exception, e: print "Exception: " + str(e)
from PathFinder import PathFinder pathFinder = PathFinder() pathFinder.clustering( )
class MyBot: def __init__(self): self.path_finder = PathFinder() self.food_orders = {} self.food_targets = set() self.explore_orders = {} self.attaking_orders = {} self.food_gathering_ants = [] self.enemy_hills = [] self.water = set() self.prox_dest = set() self.times_stats = {'food':2, 'unseen':5, 'enemy_hill':5, 'attack_hill':10} self.fifth_turn = -1 self.first_turn = True self.rose = ['n','e','s','w'] self.not_spawned_ants = 0 # visibles spaces around hills self.neighbourhood = {} # spaces with permanent ants, around hills self.hill_defending_locations = {} self.hill_exitway = {} self.hill_shield = {} def do_setup(self, ants): self.rows = ants.rows self.cols = ants.cols #random.seed(ants.player_seed) #self.explore_map = ExploreMap(self.rows, self.cols, 3, ants.viewradius2) #self.explore_map = DiffusionMap.DiffusionMap(self.rows, self.cols, ants.viewradius2) self.explore_map = SimpleExploreMap(self.rows, self.cols) # precalculate squares around an ant, of radius sqrt(rad2) def get_pre_radius(rad2): offsets = [] mx = int(sqrt(rad2)) for d_row in range(-mx,mx+1): for d_col in range(-mx,mx+1): d = d_row**2 + d_col**2 if d <= rad2: offsets.append(( d_row%self.rows-self.rows, d_col%self.cols-self.cols )) return offsets extra_rad = 0 # attack_rad*2 + extra_rad attack_rad2 = int(4*ants.attackradius2+(extra_rad**2)+4*extra_rad*sqrt(ants.attackradius2)) extra_rad = -1 # attack_rad + extra_rad defend_rad2 = int(ants.attackradius2+(extra_rad**2)+2*extra_rad*sqrt(ants.attackradius2)) self.ant_view_area = get_pre_radius(ants.viewradius2) self.ant_attack_area = get_pre_radius(attack_rad2) self.ant_defend_area = get_pre_radius(defend_rad2) self.food_rad = get_pre_radius(ants.spawnradius2) def do_turn(self, ants): self.ants = ants self.fifth_turn = (self.fifth_turn +1)%5 time_left = ants.time_remaining # track all moves, prevent collisions and prevent stepping on my own hills self.prox_dest = set(ants.my_hills()) self.water.update(ants.water()) free_ants = ants.my_ants()[:] initial_n_ants = len(free_ants) if self.first_turn: #self.explore_map = WaveFrontMap(self.rows, self.cols, ants.my_hills()[0], ants.viewradius2) self.not_spawned_ants = initial_n_ants self.set_hills_areas() self.first_turn = False self.explore_map.update(ants) self.detect_enemy_hills() self.check_razed_hills(free_ants) if time_left() < 10: return self.maintain_ants_at_defending_location(initial_n_ants, free_ants) self.defend_my_hills(free_ants) if time_left() < 10: return self.fight(free_ants) if time_left() < 20: return self.unblock_own_hill(initial_n_ants, free_ants) self.continue_with_attaking_orders(free_ants) self.continue_with_food_orders(free_ants) if time_left() < 10: return self.find_close_food(free_ants, time_left, 1) self.attack_enemy_hills(free_ants, time_left, 2) if time_left() < 25: return #self.continue_with_explore_orders(free_ants) #if self.fifth_turn == 4: # print("time left before explore: "+str(time_left())) self.explore2(free_ants, time_left, 3) if time_left() < 20: return self.check_collected_food() #if self.fifth_turn == 4: # print("time left: "+str(time_left())) ############################################################################################### ############### Helper Functions ############################################################## ############################################################################################### # receive set of obstacles # return function giving possible moves using these obstacles def possible_moves(self, obstacles): def temp(loc): d = self.ants.destination rose = self.rose moves = [ loc for loc in [ d(loc, direction) for direction in rose ] if loc not in obstacles ] return moves return temp def do_move_direction(self, loc, direction, free_ants): new_loc = self.ants.destination(loc, direction) if(self.ants.unoccupied(new_loc) and new_loc not in self.prox_dest): self.ants.issue_order((loc, direction)) self.prox_dest.add(new_loc) free_ants.remove(loc) if loc in self.ants.my_hills(): self.not_spawned_ants-=1 return True else: return False def do_move_location(self, loc, dest, free_ants): directions = self.ants.direction(loc, dest) for direction in directions: if self.do_move_direction(loc, direction, free_ants): return True return False def get_radius(self, loc, area): a_row, a_col = loc return set([ ((a_row+v_row)%self.rows, (a_col+v_col)%self.cols) for v_row, v_col in area]) def get_full_shield(self, hill): # .sss. # sssss # ssHss # sssss # .sss. h_row, h_col = hill shield = set([ (row%self.rows, col%self.cols) for row in range(h_row-2, h_row+2) for col in range(h_col-2, h_col+2) ]) shield.remove(hill) shield.difference_update(self.water) shield.difference_update(set([((h_row+2)%self.rows, (h_col+2)%self.cols), ((h_row+2)%self.rows, (h_col-2)%self.cols), ((h_row-2)%self.rows, (h_col-2)%self.cols), ((h_row-2)%self.rows, (h_col+2)%self.cols)])) d = self.ants.euclidian_distance dist = [ (d(loc,hill), loc) for loc in shield ] dist.sort() return dist def get_inner_shield(self, hill): # ..... # .sss. # .sHs. # .sss. # ..... h_row, h_col = hill shield = set([ (row%self.rows, col%self.cols) for row in range(h_row-1, h_row+1) for col in range(h_col-1, h_col+1) ]) shield.difference_update(self.water) shield.remove(hill) d = self.ants.euclidian_distance dist = [ (d(loc,hill), loc) for loc in shield ] dist.sort() return dist def get_inner_odd_shield(self, hill): # ..... # ..s.. # .sHs. # ..s.. # ..... h_row, h_col = hill shield = set([ ((h_row-1)%self.rows, (h_col)%self.cols), ((h_row)%self.rows, (h_col+1)%self.cols), ((h_row+1)%self.rows, (h_col)%self.cols), ((h_row)%self.rows, (h_col-1)%self.cols) ]) shield.difference_update(self.water) d = self.ants.euclidian_distance dist = [ (d(loc,hill), loc) for loc in shield ] dist.sort() return dist def get_inner_even_shield(self, hill): # ..... # .s.s. # ..H.. # .s.s. # ..... h_row, h_col = hill return set([(h_row+1,h_col+1), (h_row-1,h_col-1), (h_row-1,h_col+1), (h_row+1,h_col-1)]) - self.water def get_outer_shield(self, hill): # .sss. # s...s # s.H.s # s...s # .sss. h_row, h_col = hill shield = set([ ((h_row-2)%self.rows, (h_col-1)%self.cols), ((h_row-2)%self.rows, (h_col)%self.cols), ((h_row-2)%self.rows, (h_col+1)%self.cols), ((h_row-1)%self.rows, (h_col-2)%self.cols), ((h_row-1)%self.rows, (h_col+2)%self.cols), ((h_row)%self.rows, (h_col-2)%self.cols), ((h_row)%self.rows, (h_col+2)%self.cols), ((h_row+1)%self.rows, (h_col-2)%self.cols), ((h_row+1)%self.rows, (h_col+2)%self.cols), ((h_row+2)%self.rows, (h_col-1)%self.cols), ((h_row+2)%self.rows, (h_col)%self.cols), ((h_row+2)%self.rows, (h_col+1)%self.cols) ]) shield.difference_update(self.water) d = self.ants.euclidian_distance dist = [ (d(loc,hill), loc) for loc in shield ] dist.sort() return dist def get_exit_ways(self, hill): h_row, h_col = hill potencial_exit_ways = [((h_row+1,h_col), 's'), ((h_row-1,h_col), 'n'), ((h_row,h_col+1), 'e'), ((h_row,h_col-1), 'w')] exit_ways = [] for loc, direction in potencial_exit_ways: if loc not in self.water: next_loc = self.ants.destination(loc, direction) if next_loc not in self.water: exit_ways.append((loc, direction)) if len(exit_ways) > 0: return exit_ways else: return potencial_exit_ways ############################################################################################### ############### Action Functions ############################################################## ############################################################################################### def check_razed_hills(self, free_ants): for enemy_hill in self.enemy_hills[:]: if enemy_hill in free_ants: self.enemy_hills.remove(enemy_hill) def detect_enemy_hills(self): for hill_loc, hill_owner in self.ants.enemy_hills(): if hill_loc not in self.enemy_hills: self.enemy_hills.append(hill_loc) def set_hills_areas(self): for hill in self.ants.my_hills(): self.neighbourhood[hill] = self.get_radius(hill, self.ant_view_area) - self.water self.hill_defending_locations[hill] = self.get_inner_even_shield(hill) self.hill_exitway[hill] = self.get_exit_ways(hill) self.hill_shield[hill] = {} #self.hill_shield[hill]['full'] = self.get_full_shield(hill) self.hill_shield[hill]['inner'] = self.get_inner_shield(hill) self.hill_shield[hill]['outer'] = self.get_outer_shield(hill) def maintain_ants_at_defending_location(self, initial_n_ants, free_ants): my_hills = self.ants.my_hills() ants_per_hill = initial_n_ants/(len(my_hills)+1) if ants_per_hill > 6: n_expected_ants = 4 elif ants_per_hill > 3: n_expected_ants = 2 elif ants_per_hill > 1: n_expected_ants = 1 else: n_expected_ants = 0 for hill in my_hills: n_defending_ants = 0 for defend_loc in self.hill_defending_locations[hill]: if n_defending_ants >= n_expected_ants: break n_defending_ants+=1 if defend_loc in free_ants: # if there is an ant, stay there free_ants.remove(defend_loc) self.prox_dest.add(defend_loc) else: paths = self.path_finder.BFS(defend_loc, free_ants, self.possible_moves(self.water), backward=True) for path in paths: self.do_move_location(path['source'], path['path'][path['source']], free_ants) def unblock_own_hill(self, initial_n_ants, free_ants): my_hills = self.ants.my_hills() if initial_n_ants > (15 * len(my_hills)): ideal_def = int(initial_n_ants * 0.10) else: ideal_def = 0 for hill in my_hills: for loc, direction in self.hill_exitway[hill]: if loc in free_ants: self.do_move_direction(loc, direction, free_ants) if hill in free_ants: if self.not_spawned_ants >= ideal_def: for direction in self.rose: if self.do_move_direction(hill, direction, free_ants): break else: free_ants.remove(hill) def check_collected_food(self): for food in self.ants.food(): close_ants = self.get_radius(food, self.food_rad) & self.prox_dest if len(close_ants) > 0: self.not_spawned_ants+=1 def continue_with_attaking_orders(self, free_ants): # orders_format: (hill_loc, path) new_orders = {} for ant_loc in free_ants[:]: if ant_loc in self.attaking_orders and self.attaking_orders[ant_loc][0] in self.enemy_hills: new_loc = self.attaking_orders[ant_loc][1][ant_loc] self.do_move_location(ant_loc, new_loc, free_ants) new_orders[new_loc] = self.attaking_orders[ant_loc] self.attaking_orders = new_orders def continue_with_food_orders(self, free_ants): # orders_format: (food_loc, path) foods = self.ants.food() new_orders = {} for ant_loc in self.food_gathering_ants[:]: # if ant is still alive and if food still exist, go for it if ant_loc in free_ants and self.food_orders[ant_loc][0] in foods: new_loc = self.food_orders[ant_loc][1][ant_loc] if self.do_move_location(ant_loc, new_loc, free_ants) and new_loc == self.food_orders[ant_loc][0]: self.food_targets.remove(new_loc) # discard collected food new_orders[new_loc] = self.food_orders[ant_loc] self.food_orders = new_orders self.food_gathering_ants = self.food_orders.keys() def continue_with_explore_orders(self, free_ants): # orders_format: (dest_loc, path) new_orders = {} for ant_loc in free_ants[:]: if ant_loc in self.explore_orders and ant_loc != self.explore_orders[ant_loc][0]: new_loc = self.explore_orders[ant_loc][1][ant_loc] if self.do_move_location(ant_loc, new_loc, free_ants): new_orders[new_loc] = self.explore_orders[ant_loc] self.explore_orders = new_orders def find_close_food(self, free_ants, time_left, stat_update_turn): #if self.fifth_turn == stat_update_turn: # ini = time.time() # ~1ms/ant foods = set(self.ants.food()) possible_moves = self.possible_moves(self.water) #if time_left()-self.times_stats['food'] > 20: for ant_loc in free_ants[:]: paths = self.path_finder.BFS(ant_loc, foods-self.food_targets, possible_moves) for path in paths: if self.do_move_location(ant_loc, path['path'][ant_loc], free_ants): self.food_targets.add(path['goal']) self.food_orders[path['path'][ant_loc]] = (path['goal'], path['path']) self.food_gathering_ants.append(path['path'][ant_loc]) # if self.fifth_turn == stat_update_turn: # self.times_stats['food'] = int(1000*(time.time()-ini))+2 def find_close_food2(self, free_ants, time_left, stat_update_turn): foods = set(self.ants.food()) - self.food_targets possible_moves = self.possible_moves(self.water) for food_loc in foods: paths = self.path_finder.BFS(food_loc, free_ants, possible_moves, max_cost=15, backward=True) for path in paths: if self.do_move_location(path['source'], path['path'][path['source']], free_ants): self.food_targets.add(food_loc) self.food_orders[path['path'][path['source']]] = (food_loc, path['path']) self.food_gathering_ants.append(path['path'][path['source']]) def attack_enemy_hills(self, free_ants, time_left, stat_update_turn): if self.fifth_turn == stat_update_turn: #num = len(free_ants)+1 ini = time.time() possible_moves = self.possible_moves(self.water) if time_left()-self.times_stats['attack_hill'] > 20: for hill_loc in self.enemy_hills: paths = self.path_finder.BFS(hill_loc, set(free_ants), possible_moves, num=30, max_cost=40, backward=True) for path in paths: if path['source'] in free_ants and self.do_move_location(path['source'], path['path'][path['source']], free_ants): self.attaking_orders[path['path'][path['source']]] = (hill_loc, path['path']) if self.fifth_turn == stat_update_turn: self.times_stats['attack_hill'] = int(1000*(time.time()-ini))+2#/num +2 def explore(self, free_ants, time_left, stat_update_turn): #if self.fifth_turn == stat_update_turn: num = len(free_ants)+1 ini = time.time() possible_moves = self.possible_moves(self.water) for ant_loc in free_ants[:]: if time_left()-self.times_stats['unseen'] < 20: break # new_locs = self.explore_map.get_higher_locs(ant_loc) # for val, loc in new_locs: # if self.do_move_location(ant_loc, loc, free_ants): # break new_locs = self.explore_map.all_val_locs(ant_loc) for val, locs in new_locs: break2 = False paths = self.path_finder.BFS(ant_loc, set(locs), possible_moves, num=15, max_cost=15) for path in paths: #if ant_loc not in path['path']: # sys.stdout.flush() # sys.exit() try: if self.do_move_location(ant_loc, path['path'][ant_loc], free_ants): self.explore_orders[path['path'][ant_loc]] = (path['goal'], path['path']) break2 = True break except KeyError, e: pass #print(path) #print(ant_loc) if break2: break #if self.fifth_turn == stat_update_turn: self.times_stats['unseen'] = int(1000*(time.time()-ini))/num +2
from MapManager import MapManager from PathFinder import PathFinder MapMgr = MapManager() PF = PathFinder() mandatory_tasks = ['push_top','push_mid','push_bot'] addictional_tasks = ['take_rune','def_top','def_mid','def_bot'] task_queue = [] if !task_queue: task = mandatory_tasks[0] task_queue.append(task) current_task = task_queue.pick() if current_task == 'push_top': MapMgr.blockArea(MapMgr.top_blocks) #add top part of map to blocked area PF.goTo(MapMgr.home) #go to the home location destination = MapMgr.getPushPoint('top') #get point where to go to
class PathAgent(object): def __init__(self, bzrc, tank_index): self.bzrc = bzrc self.obstacles = self.bzrc.get_obstacles() self.tank_index = tank_index self.G_FROB = 0.90 self.R_FROB = 0.1 self.path = [] self.has_path = False self.has_flag = False self.path_finder = PathFinder(self.bzrc, self.tank_index) def tick(self, time_diff): self.commands = [] tank = self.bzrc.get_mytanks()[self.tank_index] # if our tank is dead, invalidate its path and we're done if tank.status == "dead": self.has_path = False return # if the tank picks up the flag, recalculate path if not self.has_flag and not tank.flag =='-': self.has_path = False self.has_flag = True if not self.has_path: # get the path by choosing from DFS, BFS, A*, etc. print "updating visibility graph for tank", self.tank_index self.path_finder.update_visibility_graph(self.tank_index) print "calculating path for tank", self.tank_index self.path = self.path_finder.get_path() self.has_path = True if not len(self.path) == 0: dist_from_next = math.sqrt((tank.x - self.path[0][0]) ** 2 + (tank.y - self.path[0][1]) **2) next_point = self.path[0] if dist_from_next < 25: self.path.remove(self.path[0]) self.traverse_path(next_point, tank) else: self.has_path = False return def traverse_path(self, next_point, tank): forces = [] x_force = 0 y_force = 0 forces.append(self.calculate_goal_force(next_point, tank)) forces.append(self.calculate_random_force(tank)) for force in forces: x_force += force[0] y_force += force[1] self.move(x_force, y_force, tank) def calculate_goal_force(self, goal, tank): x_force = min(goal[0] - tank.x, 200) y_force = min(goal[1] - tank.y, 200) output = [x_force * self.G_FROB, y_force * self.G_FROB] return output def calculate_random_force(self, tank): return [random.randint(-10, 10) * self.R_FROB, random.randint(-10, 10) * self.R_FROB] def move(self, x_force, y_force, tank): magnitude = math.sqrt(x_force ** 2 + y_force ** 2)/20 targetAngle = math.atan2(y_force, x_force) # randomly shoot should_shoot = False if random.random() < .05: should_shoot = True command = Command(self.tank_index, magnitude, self.calculate_angvel(tank, targetAngle), should_shoot) self.commands.append(command) if self.commands: self.bzrc.do_commands(self.commands) def calculate_angvel(self, tank, targetAngle): targetAngle = self.two_pi_normalize(targetAngle) current = self.two_pi_normalize(tank.angle) output = self.normalize_angle(targetAngle - current) return output def normalize_angle(self, angle): """Make any angle be between +/- pi.""" angle -= 2 * math.pi * int (angle / (2 * math.pi)) if angle <= -math.pi: angle += 2 * math.pi elif angle > math.pi: angle -= 2 * math.pi return angle def two_pi_normalize(self, angle): """Make any angle between 0 to 2pi.""" angle += 2 * math.pi return angle % (2 * math.pi)
import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from PathFinder import RandomMap, PathFinder plt.figure(figsize=(6, 6)) graph = RandomMap.RandomMap(size=50) ax = plt.gca() ax.set_xlim([0, graph.size]) ax.set_ylim([0, graph.size]) for i in range(graph.size): for j in range(graph.size): if graph.IsObstacle(PathFinder.Point(i, j)): rec = Rectangle((i, j), width=1, height=1, color='gray') ax.add_patch(rec) else: rec = Rectangle((i, j), width=1, height=1, edgecolor='gray', facecolor='w') ax.add_patch(rec) rec = Rectangle((0, 0), width=1, height=1, facecolor='b') ax.add_patch(rec) rec = Rectangle((graph.size - 1, graph.size - 1), width=1,
def __init__(self): self.rose = ['n','e','s','w'] self.water = set() self.path_finder = PathFinder()
def run(self): """ Starts the maze solving process. This method blocks until the maze has been solved, but will call update_callback on a regular basis to allow the UI to be updated. """ self._stopped = False self._finished = False if self.fixed_image_path is None: camera = cv2.VideoCapture(self.camera_index) retval, self._current_image = camera.read() if not retval: raise IOError("Failed to read initial image from camera.") else: self._current_image = cv2.imread(self.fixed_image_path) # Run initial image processing mazenodes = MazeNodes(self._current_image, self.end_colour_lower, self.end_colour_upper, self.start_colour_lower, self.start_colour_upper, self.play_colour_lower, self.play_colour_upper, self.debug) mazenodes.runProcessing() nodes = mazenodes.nodes start_node = mazenodes.start end_node = mazenodes.end # Start and end nodes not necessarily on grid with other nodes, must find # their neighbours separately img.findRegionCenterNeighbours(start_node, nodes, mazenodes.x_div_len, mazenodes.y_div_len) img.findRegionCenterNeighbours(end_node, nodes, mazenodes.x_div_len, mazenodes.y_div_len) # Find path through maze pathfinder = PathFinder(nodes, start_node, end_node) self._path = pathfinder.findPath() self._end_x, self._end_y = end_node.coordinates if self.debug: img.drawResults(self._current_image, nodes, self._path, start_node, end_node) if not self.fixed_image_path is None: # Debug: draw result of pathfinding img.drawResults(self._current_image, nodes, self._path, start_node, end_node) else: # Live ball tracking ball_finder = FindBall(mazenodes.start_lower, mazenodes.start_upper, mazenodes.filt_close, mazenodes.filt_open) planner = BallPathPlanner(self._path) with ServoConnection(port=self.serial_port) as conn: # Get "flat" x and y positions of servos over serial connection try: flat_x = conn.get_x_val() flat_y = conn.get_y_val() except SerialException: flat_x = conn.get_x_val() flat_y = conn.get_y_val() while not planner.isFinished(): if self._stopped: break start_time = time.clock() # Get current image of maze retval, self._current_image = camera.read() if not retval: raise IOError("Failed to read image from camera.") # Find ball, its acceleration, and where its currently trying to get to self._ball_x, self._ball_y = ball_finder.findBall( self._current_image) self._acc_x, self._acc_y = planner.getAcceleration( self._ball_x, self._ball_y) self._target_coords = planner.get_target_pos() try: # Determine how to tilt the board next to acheive desired acceleraton and direction new_x_acc = max( -1 * MAX_ACC, min(MAX_ACC, self._acc_x * ACC_MULTIPLIER + flat_x)) new_y_acc = max( -1 * MAX_ACC, min(MAX_ACC, self._acc_y * ACC_MULTIPLIER + flat_y)) # Send command for x servo over serial conn.set_x_val(int(new_x_acc)) self._ser_results.append(1) time.sleep(0.001) # Send command for y servo over serial conn.set_y_val(int(new_y_acc)) self._ser_results.append(1) except SerialException as ex: print ex self._ser_results.append(0) self.update_callback(self) time.sleep( max(1.0 / FRAMERATE - (time.clock() - start_time), 0)) self._finished = planner.isFinished() # Release camera camera.release()
from Repository import Repository from PathFinder import PathFinder from Service import Service from UI import UI repository = Repository("ll\\tsp.txt", "ll\\tsp_solution.txt") pathFinder = PathFinder(repository) service = Service(pathFinder) ui = UI(service) ui.start()
import sys sys.path.append("View") sys.path.append("PathAlgorithms") sys.path.append("Images") sys.path.append("Common") from PathFinder import PathFinder if __name__ == "__main__": pathFinder = PathFinder(); pathFinder.bestSearch()
self.start_index = start_node self.end_index = end_node self.memory = {} for row in self.board: for node in row: self.memory[node] = float('inf') self.memory[start_node] = 0 def execute(self): pass def run(self): pass def find_distance(self): pass def find_adjacent_nodes(self): pass if __name__ == "__main__": WINDOW_RES = (301, 301) NODE_SIZE = 20 program = PathFinder(WINDOW_RES, NODE_SIZE) program.run()
screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE | DOUBLEBUF, 32) screen.fill((0,0,0)) pygame.display.set_caption("PathFinder - v1.0 @ ShannonXu") #init font uiFont = pygame.font.SysFont("arial", 20) # path finder init gridMap = GM(31,56) # map drawer mapDrawer = MD(pygame, screen, SCREEN_SIZE, gridMap) #path finder pathFinder = PF() pathFinder.setMapDrawer(mapDrawer) #maze maker mazeMaker = MM() gridMap.setMazeMaker(mazeMaker) # rts sim rtss = RTSS() rtss.setMapDrawer(mapDrawer) lastTime = time.time() while True: currTime = time.time() update(screen, uiFont, int(round(currTime * 1000)) - int(round(lastTime * 1000))) lastTime = currTime
startNode = Node.Node() endNode = Node.Node() for n in nodes: if nodes.get(n).start: startNode = nodes.get(n) if nodes.get(n).end: endNode = nodes.get(n) imgpro.findRegionCenterNeighbours(startNode, nodes, mn.x_div_len, mn.y_div_len) imgpro.findRegionCenterNeighbours(endNode, nodes, mn.x_div_len, mn.y_div_len) pf = PathFinder(nodes, startNode, endNode) path = pf.findPath() planner = bpp.BallPathPlanner(path) planner.speed = 400 ballsim = BallSimulator(startNode.coordinates[0], startNode.coordinates[1]) while not planner.isFinished(): start = time.clock() x, y = ballsim.getBallPos() cv2.circle(image, (int(x), int(y)), 8, BALL_COLOUR) acc = planner.getAcceleration(x, y) ballsim.setAcceleration(acc[0], acc[1]) time.sleep(max(0.03 - (time.clock() - start), 0))
(3, 11, 12), (3, 18, 19), (3, 24, 25), (3, 31, 36), (4, 3, 12), (4, 22, 25), (5, 11, 12), (5, 18, 25), (6, 11, 32), (7, 16, 19), (7, 27, 33), (8, 3, 22), (8, 30, 31), (9, 10, 15), (9, 30, 32), (10, 13, 15), (10, 24, 32), (11, 13, 19), (11, 24, 25), (12, 9, 15), (12, 24, 30), (13, 24, 25), (14, 8, 25), (15, 0, 9), (15, 15, 30), (16, 0, 1)) START = (16, 0) STARTNEIGHBOORS = {"left": False, "right": False, "front": True, "back": False} END = (3, 35) ENDNEIGHBOORS = {"left": True, "right": False, "front": False, "back": False} maze = Maze(WALL, PATH, WENTPATH, PATHTUPLE, START, END) graph = Graph(maze) pathFinder = PathFinder(graph, START, END) mario = {"show": "@", "loc": START} def display(): for i in range(maze.size[0]): tempr = "" for j in range(maze.size[1]): tempr = tempr + maze.maze[i, j] + " " print(tempr) def takeStep(y, x): maze.maze[mario["loc"]] = WENTPATH maze.maze[y, x] = mario["show"]
def main(screen): clock = pygame.time.Clock() main_menu = MainMenu() dirty_drawing = DirtyDrawing() dirty_drawing.world_window_is_dirty = True dirty_drawing.world_window_redraw = True map_loader = MapLoader(MapData, dirty_drawing, NPC, Intent) map_data = map_loader.load_default_map() passable_tiles = map_data.passable_tiles path_finder = PathFinder(passable_tiles) floor_s = pygame.Surface((1280, 840)) pathfinder_screen_s = floor_s.copy() pathfinder_screen_s.set_colorkey(colorBlack) intent = Intent() hero = Hero("dg_classm32_swordHero.gif", Intent(), Inventory()) if not map_data.tile_occupied((1, 1)): map_data.charLayer[(1, 1)] = hero hero.move(1, 1) hero.inventory.add_item(Weapon("Knuckles +1Fat")) message_log = MessageLog(defaultFont, dirty_drawing) message_log.position = (screen.get_size()[0] - message_log.render.get_size()[0], 0) # Temporary. Combat is on at the start in_combat = False entities_in_combat = [] for entity in map_data.charLayer.values(): entities_in_combat.append(entity) reaction_order = [] new_event = pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="start") pygame.event.post(new_event) screen.fill(colorBlack) update_game_window = True # MAINLOOP-------------------------- while 1: clock.tick(40) hero.intent.type = 0 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYUP: if event.key == pygame.K_SPACE: hero.intent.type = intent.WAIT elif event.key == pygame.K_UP or event.key == pygame.K_KP8: hero.intent.type = intent.MOVE hero.intent.direction = (0, -1) elif event.key == pygame.K_DOWN or event.key == pygame.K_KP2: hero.intent.type = intent.MOVE hero.intent.direction = (0, 1) elif event.key == pygame.K_LEFT or event.key == pygame.K_KP4: hero.intent.type = intent.MOVE hero.intent.direction = (-1, 0) elif event.key == pygame.K_RIGHT or event.key == pygame.K_KP6: hero.intent.type = intent.MOVE hero.intent.direction = (1, 0) elif event.key == pygame.K_KP7: hero.intent.type = intent.MOVE hero.intent.direction = (-1, -1) elif event.key == pygame.K_KP9: hero.intent.type = intent.MOVE hero.intent.direction = (1, -1) elif event.key == pygame.K_KP3: hero.intent.type = intent.MOVE hero.intent.direction = (1, 1) elif event.key == pygame.K_KP1: hero.intent.type = intent.MOVE hero.intent.direction = (-1, 1) elif event.key == pygame.K_KP_PLUS: npc = add_monster_to_random_position( map_data, NPC("dg_monster132_thug.gif", Intent()), dirty_drawing ) entities_in_combat.append(npc) update_game_window = True elif event.key == pygame.K_KP_MINUS: pygame.event.post(pygame.event.Event(pygame.USEREVENT, subtype="menu")) if event.type == pygame.USEREVENT: if event.subtype is "combat": if event.combat_situation == "start": in_combat = True reaction_order = roll_reactions(entities_in_combat) creature_in_turn = reaction_order[0] message_log.newline("RR") if event.combat_situation == "first_turn": creature_in_turn = reaction_order[0] if creature_in_turn == hero: message_log.newline("You start") else: message_log.newline("{} starts".format(reaction_order[0].name)) if event.combat_situation == "turn_change": try: reaction_order.remove(creature_in_turn) except ValueError: print "{} not in reaction order.".format(creature_in_turn) try: creature_in_turn = reaction_order[0] if creature_in_turn == hero: message_log.newline("Your turn.") else: message_log.newline("{}'s turn.".format(reaction_order[0].name)) except IndexError: creature_in_turn = None pygame.event.post( pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="end_of_phase") ) update_game_window = True if event.combat_situation == "end_of_phase": if in_combat: reaction_order = roll_reactions(entities_in_combat) creature_in_turn = None message_log.newline("EOP- RR") pygame.event.post( pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="first_turn") ) if event.combat_situation == "end": in_combat = False elif event.subtype is "menu": main_menu.open_menu(screen) if in_combat is True: if isinstance(creature_in_turn, Hero): hero_makes_decision = hero_turn(hero, map_data, message_log) if hero_makes_decision: pygame.event.post( pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="turn_change") ) if hero.intent.type is intent.MOVE: map_data.attempt_move("char", hero.positionOnMap, direction=hero.intent.direction) hero.move(*hero.intent.direction) elif hero.intent.type is intent.ATTACK: handle_attack( hero, hero.intent.target, message_log, map_data, dirty_drawing, entities_in_combat, reaction_order, ) elif hero.intent.type == intent.WAIT: pass else: raise "No Hero intention_:{}".format(hero.intent.type) elif isinstance(creature_in_turn, NPC): npc = creature_in_turn path = path_finder.find_path_between_points(npc.positionOnMap, hero.positionOnMap, pathfinder_screen_s) if path == "No route found": pass if len(path) == 1: handle_attack(npc, hero, message_log, map_data, dirty_drawing, entities_in_combat, reaction_order) pygame.event.post( pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="turn_change") ) else: move_success = map_data.attempt_move("char", npc.positionOnMap, destination=path[1]) if move_success is True: # npc.move(*npc.intent.direction) npc.set_position(*path[1]) pygame.event.post( pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="turn_change") ) elif isinstance(move_success, NPC): npc.intent = Intent.WAIT pygame.event.post( pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="turn_change") ) else: print "ERRORROROREREERRROR" enable_pathfinder_screen = True if enable_pathfinder_screen == True: dirty_drawing.world_window_redraw = True floor_s, update_game_window, screen = dirty_drawing.draw( map_data, floor_s, update_game_window, screen, message_log, pathfinder_screen_s ) pygame.display.flip()
class DungeonMaster(object): def __init__(self, clock, dungeon, locale_id): self.clock = clock self.dungeon = dungeon self.path_finder = PathFinder(dungeon) self.locale_id = locale_id self.queue = PriorityQueue() self.factions = {} self.playing = True self.dungeon_expire = self.clock.max_locale_time self.char_id = 'DM' self.placement_locations = { 'ne': [], 'e': [], 'se': [], 'nw': [], 'w': [], 'sw': [], } self.init_placement_locations() self.clock.set_local_time(locale_id=locale_id, locale_time=0) def init_placement_locations(self): center = self.dungeon.get_hex(x=0, y=0, z=0) ring_1 = self.dungeon.ring(center, self.dungeon.map_radius - 1) ring_2 = self.dungeon.ring(center, self.dungeon.map_radius) rings = ring_1 + ring_2 high = self.dungeon.map_radius - 1 low = 1 for point in rings: x = abs(point.x) y = abs(point.y) z = abs(point.z) if x >= high and y > low and y < high: if point.x < 0: self.placement_locations['w'].append(point) else: self.placement_locations['e'].append(point) elif y >= high and x > low and x < high: if point.y < 0: self.placement_locations['se'].append(point) else: self.placement_locations['nw'].append(point) elif z >= high and x > low and x < high: if point.z < 0: self.placement_locations['ne'].append(point) else: self.placement_locations['sw'].append(point) def run_dungeon(self): while self.is_playing(): self.run() def run(self): char = self.next_char() self.increment_time() while self.get_time() < char.gcd: self.increment_time() self.activate_char(char) def is_playing(self): if self.get_time() > self.dungeon_expire: self.playing = False elif len(self.factions) <= 1: self.playing = False else: self.playing = True return self.playing def add_char(self, member, faction='dm', edge='dm', insert_time=0): if faction == 'dm': faction = self if faction.faction_id not in self.factions.keys(): self.factions[faction.faction_id] = [] if insert_time == 0: insert_time = self.get_time() + member.get_stat('initiative') self.factions[faction.faction_id].append(member) self.queue.put(member, insert_time) member.dm = self faction.place_char(member, self.get_placement_locations(edge)) def remove_char(self, member): faction_id = member.faction.faction_id self.factions[faction_id].remove(member) if len(self.factions[faction_id]) == 0: self.factions.pop(faction_id, None) def next_char(self): return self.queue.get() def get_time(self): return self.clock.get_locale_time(self.locale_id) def increment_time(self): self.clock.increment_locale_time(self.locale_id) def activate_char(self, char): priority = char.activate() if char.health > 0: self.queue.put(char, priority) def get_placement_locations(self, edge): sides = ['ne', 'e', 'se', 'sw', 'w', 'nw'] if edge in sides: return self.placement_locations[edge] def get_adjacent_enemies(self, requestor): hexes = self.dungeon.neighbors(requestor.dungeon_hex) return self.get_enemies(requestor, hexes) def get_nearby_enemies(self, requestor, radius=2): hexes = self.dungeon.spiral(requestor.dungeon_hex, radius) return self.get_enemies(requestor, hexes) def get_enemies(self, requestor, hexes): enemies = [] for dungeon_hex in hexes: if dungeon_hex is None: next elif dungeon_hex.character is None: next elif dungeon_hex.character.faction != requestor.faction: enemies.append(dungeon_hex.character) return enemies def get_nearest_enemy(self, requestor): enemies = [] min_dist = requestor.sight_range closest = None for faction in self.factions.keys(): if faction != requestor.faction.faction_id: for member in self.factions[faction]: enemies.append(member) for enemy in enemies: current = self.distance(requestor, enemy) if current < min_dist: min_dist = current closest = enemy requestor.target_enemy = enemy requestor.distance_to_enemy = min_dist return closest def distance(self, actor, target): return self.dungeon.distance(actor.dungeon_hex, target.dungeon_hex) def move_char_along_path(self, actor, source, dest, distance): path = self.path_finder.find_path( start=source, goal=dest, ) if (len(path) - 1) < distance: distance = (len(path) - 1) actor.move(path[distance])
from PathFinder import PathFinder triangle_blocks = [[(1, 8), (1, 2), (1, 4)], [(5, 4), (2, 1), (8, 1)], [(9, 8), (6, 5), (9, 2)], [(2, 9), (5, 6), (8, 9)]] PF = PathFinder() print PF.inTriangle((2, 5), ((1, 8), (1, 2), (4, 5)))
def main(screen): # -----------Debug------------ enable_pathfinder_screen = False # Draws the found pathfinder path # ---------------------------- clock = pygame.time.Clock() floor_s = pygame.Surface((10 * 64, 20 * 64)) world_s = pygame.Surface((10 * 64, 20 * 64)) pathfinder_screen_s = floor_s.copy() pathfinder_screen_s.set_colorkey(colorBlack) pathfinding_screen_reset = False sword_surface = resource_loader.load_sprite('sword') main_menu = MainMenu() map_loader = MapLoader(MapData, NPC, Intent) map_data = map_loader.load_default_map() path_finder = PathFinder(map_data.passable_tiles) dirty_drawing = DirtyDrawing() dirty_drawing.prepare_floor(floor_s, map_data.get_texture_layer) dirty_drawing.issue_world_surface_redraw() intent = Intent() hero = Hero(surface=resource_loader.load_sprite('hero'), intent_instance=Intent(), inventory_instance=Inventory()) if not map_data.tile_occupied((1, 1)): map_data.set_character_on_map(hero, (1, 1)) hero.move(1, 1) new_weapon = Weapon(generate_item_name('sword')) print hero.inventory hero.inventory.add_item(new_weapon) camera = Camera(starting_position=hero.positionOnMap, viewport_size=(10, 10)) camera.set_viewport_boundaries((0, 0), map_data.mapBoundaries) message_log = MessageLog(defaultFont) message_log.position = (screen.get_size()[0] - message_log.render.get_size()[0], 0) # Temporary. Combat is on at the start in_combat = False entities_in_combat = [] for entity in map_data.get_characters_on_map: entities_in_combat.append(entity) reaction_order = [] creature_in_turn = None new_event = pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="start") pygame.event.post(new_event) screen.fill(colorBlack) new_sword = Weapon(generate_item_name(), surface=sword_surface) map_data.set_item_on_map(new_sword, (3, 4)) # MAINLOOP-------------------------- while 1: clock.tick(40) hero.intent.type = 0 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYUP: if event.key == pygame.K_SPACE: hero.intent.type = intent.WAIT elif event.key == pygame.K_UP or event.key == pygame.K_KP8: hero.intent.type = intent.MOVE hero.intent.direction = (0, -1) elif event.key == pygame.K_DOWN or event.key == pygame.K_KP2: hero.intent.type = intent.MOVE hero.intent.direction = (0, 1) elif event.key == pygame.K_LEFT or event.key == pygame.K_KP4: hero.intent.type = intent.MOVE hero.intent.direction = (-1, 0) elif event.key == pygame.K_RIGHT or event.key == pygame.K_KP6: hero.intent.type = intent.MOVE hero.intent.direction = (1, 0) elif event.key == pygame.K_KP7: hero.intent.type = intent.MOVE hero.intent.direction = (-1, -1) elif event.key == pygame.K_KP9: hero.intent.type = intent.MOVE hero.intent.direction = (1, -1) elif event.key == pygame.K_KP3: hero.intent.type = intent.MOVE hero.intent.direction = (1, 1) elif event.key == pygame.K_KP1: hero.intent.type = intent.MOVE hero.intent.direction = (-1, 1) elif event.key == pygame.K_KP_PLUS: npc = add_monster_to_random_position(map_data, NPC(resource_loader.load_sprite('thug'), Intent(), Inventory())) entities_in_combat.append(npc) elif event.key == pygame.K_KP_MINUS: pygame.event.post(pygame.event.Event(pygame.USEREVENT, subtype="menu")) elif event.key == pygame.K_i: message_log.newline("-----Inventory:-----") for item in hero.inventory.get_items: assert isinstance(item, Item) message_log.newline(item.name) elif event.key == pygame.K_COMMA: pick_up_item(hero, map_data) if event.type == pygame.USEREVENT: if event.subtype is "combat": if event.combat_situation == 'start': in_combat = True reaction_order = Dice.roll_reactions(entities_in_combat) message_log.newline('RR') pygame.event.post(pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation='first_turn')) if event.combat_situation == 'first_turn': creature_in_turn = reaction_order[0] if creature_in_turn == hero: message_log.newline("You start") else: message_log.newline('{} starts'.format(reaction_order[0].name)) if event.combat_situation == 'turn_change': try: reaction_order.remove(creature_in_turn) except ValueError: print '{} not in reaction order.'.format(creature_in_turn) try: creature_in_turn = reaction_order[0] if creature_in_turn == hero: message_log.newline("Your turn.") else: message_log.newline("{}'s turn.".format(reaction_order[0].name)) except IndexError: creature_in_turn = None pygame.event.post(pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation='end_of_phase')) if event.combat_situation == "end_of_phase" and in_combat: reaction_order = Dice.roll_reactions(entities_in_combat) creature_in_turn = None message_log.newline('EOP- RR') pathfinding_screen_reset = True pygame.event.post(pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation='first_turn')) if event.combat_situation == "end": in_combat = False elif event.subtype is 'menu': main_menu.open_menu(screen) if in_combat is True: if isinstance(creature_in_turn, Hero): hero_makes_decision = hero_turn(hero, map_data, message_log) if hero_makes_decision: pygame.event.post(pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="turn_change")) if hero.intent.type is intent.MOVE: map_data.attempt_move("char", hero.positionOnMap, direction=hero.intent.direction) hero.move(*hero.intent.direction) elif hero.intent.type is intent.ATTACK: handle_attack(hero, hero.intent.target, message_log, map_data, entities_in_combat, reaction_order, sword_surface=sword_surface) elif hero.intent.type == intent.WAIT: pass else: raise "No Hero intention_:{}".format(hero.intent.type) elif isinstance(creature_in_turn, NPC): npc = creature_in_turn path = path_finder.find_path_between_points(npc.positionOnMap, hero.positionOnMap) if enable_pathfinder_screen == True: if pathfinding_screen_reset == True: pathfinder_screen_s.fill(colorBlack) pathfinding_screen_reset = False draw_pathfinder_path(pathfinder_screen_s, path) if path == 'path not found': pygame.event.post(pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="turn_change")) else: move_success = map_data.attempt_move("char", npc.positionOnMap, destination=path[1]) if move_success is True: # npc.move(*npc.intent.direction) npc.set_position(path[1]) pygame.event.post(pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="turn_change")) elif isinstance(move_success, NPC): npc.intent = Intent.WAIT pygame.event.post(pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="turn_change")) elif isinstance(move_success, Hero): handle_attack(npc, hero, message_log, map_data, entities_in_combat, reaction_order) pygame.event.post(pygame.event.Event(pygame.USEREVENT, subtype="combat", combat_situation="turn_change")) else: print "ERRORROROREREERRROR" camera.set_tile_position(hero.positionOnMap) if enable_pathfinder_screen: dirty_drawing.issue_world_surface_redraw() dirty_drawing.draw(screen, world_s, camera, floor_s, map_data) if message_log.get_is_dirty is True: dirty_drawing.draw_message_log(screen, message_log) if enable_pathfinder_screen: pass # dirty_drawing.draw_pathfinder_screen(screen, pathfinder_screen_s) pygame.display.flip()
class PathAgent(object): def __init__(self, bzrc, tank_index): self.bzrc = bzrc self.obstacles = self.bzrc.get_obstacles() self.tank_index = tank_index self.G_FROB = 0.90 self.R_FROB = 0.1 self.path = [] self.has_path = False self.has_flag = False self.path_finder = PathFinder(self.bzrc, self.tank_index) def tick(self, time_diff): self.commands = [] tank = self.bzrc.get_mytanks()[self.tank_index] # if our tank is dead, invalidate its path and we're done if tank.status == "dead": self.has_path = False return # if the tank picks up the flag, recalculate path if not self.has_flag and not tank.flag == '-': self.has_path = False self.has_flag = True if not self.has_path: # get the path by choosing from DFS, BFS, A*, etc. print "updating visibility graph for tank", self.tank_index self.path_finder.update_visibility_graph(self.tank_index) print "calculating path for tank", self.tank_index self.path = self.path_finder.get_path() self.has_path = True if not len(self.path) == 0: dist_from_next = math.sqrt((tank.x - self.path[0][0])**2 + (tank.y - self.path[0][1])**2) next_point = self.path[0] if dist_from_next < 25: self.path.remove(self.path[0]) self.traverse_path(next_point, tank) else: self.has_path = False return def traverse_path(self, next_point, tank): forces = [] x_force = 0 y_force = 0 forces.append(self.calculate_goal_force(next_point, tank)) forces.append(self.calculate_random_force(tank)) for force in forces: x_force += force[0] y_force += force[1] self.move(x_force, y_force, tank) def calculate_goal_force(self, goal, tank): x_force = min(goal[0] - tank.x, 200) y_force = min(goal[1] - tank.y, 200) output = [x_force * self.G_FROB, y_force * self.G_FROB] return output def calculate_random_force(self, tank): return [ random.randint(-10, 10) * self.R_FROB, random.randint(-10, 10) * self.R_FROB ] def move(self, x_force, y_force, tank): magnitude = math.sqrt(x_force**2 + y_force**2) / 20 targetAngle = math.atan2(y_force, x_force) # randomly shoot should_shoot = False if random.random() < .05: should_shoot = True command = Command(self.tank_index, magnitude, self.calculate_angvel(tank, targetAngle), should_shoot) self.commands.append(command) if self.commands: self.bzrc.do_commands(self.commands) def calculate_angvel(self, tank, targetAngle): targetAngle = self.two_pi_normalize(targetAngle) current = self.two_pi_normalize(tank.angle) output = self.normalize_angle(targetAngle - current) return output def normalize_angle(self, angle): """Make any angle be between +/- pi.""" angle -= 2 * math.pi * int(angle / (2 * math.pi)) if angle <= -math.pi: angle += 2 * math.pi elif angle > math.pi: angle -= 2 * math.pi return angle def two_pi_normalize(self, angle): """Make any angle between 0 to 2pi.""" angle += 2 * math.pi return angle % (2 * math.pi)