Example #1
0
    def run(self):
        start_node = NavNode(position=self.board.start, g=0)

        a_star = AStar(
            draw=self.gfx.draw if not self.disable_gfx else lambda _: 0,
            disable_gfx=self.disable_gfx,
            draw_every=self.draw_every,
            print_path=self.print_path
        )

        a_star.run(start_node=start_node)
Example #2
0
class mainWindow():
        times=1
        timestart=time.clock()

        def __init__(self):
                gamedata = pickle.load(open('C:/gamedata.p', 'rb'))
                blockHeights = gamedata['blockHeights']
                vis_map = get_visibility_map(blockHeights)
                self.astar = AStar(blockHeights, vis_map.tolist())
                self.start_point = (0,0)

                self.vis_map = vis_map

                blocks = np.array(self.vis_map)
                self.blocks = blocks.transpose()

                self.end_point = (40,25)

                self.root = Tkinter.Tk()
                self.frame = Tkinter.Frame(self.root, width=1024, height=768)
                self.frame.pack()
                self.canvas = Tkinter.Canvas(self.frame, width=1024,height=768)
                self.canvas.place(x=-2,y=-2)
                self.root.after(100,self.start) # INCREASE THE 0 TO SLOW IT DOWN
                self.root.mainloop()

        def start(self):
                try:
                    self.im = Image.fromarray(np.uint8(cm.gist_yarg(self.blocks)*255))

                    if self.start_point[0] < self.blocks.shape[1]-1:
                        self.start_point = (self.start_point[0]+1, self.start_point[1])

                    path = self.astar.get_path(self.start_point[0],
                                      self.start_point[1],
                                      self.end_point[0],
                                      self.end_point[1])

                    self.im.putpixel(self.start_point,(0,255,0))
                    for x in path:
                        self.im.putpixel((x[0], x[1]),(255,0,0))
                    self.im.putpixel(self.end_point,(0,0,255))

                    newy, newx = self.blocks.shape
                    scale = 8
                    self.im = self.im.resize((newx*scale, newy*scale))

                    self.photo = ImageTk.PhotoImage(image=self.im)
                    self.canvas.create_image(0,0,image=self.photo,anchor=Tkinter.NW)
                    self.root.update()
                    self.times+=1
                    if self.times%33==0:
                            print "%.02f FPS"%(self.times/(time.clock()-self.timestart))
                    self.root.after(2000,self.start)
                except Exception as e:

                    print e
                    self.root.after(10,self.start)
Example #3
0
    def get_order(self, commander, bot):


        exact_target = commander.level.findRandomFreePositionInBox((commander.game.team.flag.position - 5.0, commander.game.team.flag.position + 5.0))
        pomastar = AStar(commander.gamedata['blockHeights'], commander.twodpom)
        path = pomastar.get_path(bot.position.x,
                              bot.position.y,
                              exact_target.x,
                              exact_target.y)

        try:
            if len(path) > 10:
                exact_target = Vector2(*path[len(path)/2])
                target = commander.level.findRandomFreePositionInBox((exact_target-5.0, exact_target+5.0))
            else:
                target = commander.game.team.flag.position
            # print target
            if not target:
                raise "no target found"

        except:
            print 'couldnt convert target to vec2'
            target = flagScoreLocation = commander.game.team.flagScoreLocation



        targetMin = target - Vector2(2.0, 2.0)
        targetMax = target + Vector2(2.0, 2.0)
        goal = commander.level.findRandomFreePositionInBox([targetMin, targetMax])

        if not goal:
            return None, None

        if (goal - bot.position).length() > 8.0:
            return (orders.Charge, commander.defender, goal), {'description' : 'rushing to defend'}
        else:
            return (orders.Defend, commander.defender, (commander.middle - bot.position)), {'description' : 'defending'}
Example #4
0
    def reset_algorithm(self):
        """Resets the algorithm"""
        self.costmap_widget.canvas.freeze = True
        self.costmap[:] = 0.0
        Obstacle(3,3,3,3).draw(self.costmap)
        Obstacle(9,5,3,3).draw(self.costmap)
        Obstacle(16,4,3,3).draw(self.costmap)

        temp = self.costmap_widget.canvas.start_coord
        self.start_coord = (floor(temp[0]+0.5), floor(temp[1]+0.5))
        temp = self.costmap_widget.canvas.goal_coord
        self.goal_coord = (floor(temp[0]+0.5), floor(temp[1]+0.5))
        self.a_star = AStar(self.costmap,
                            self.start_coord,
                            self.goal_coord,
                            self.heuristic)
        self.costmap_widget.canvas.freeze = False
        self.costmap_widget.canvas.on_map_update()
Example #5
0
        def __init__(self):
                gamedata = pickle.load(open('C:/gamedata.p', 'rb'))
                blockHeights = gamedata['blockHeights']
                vis_map = get_visibility_map(blockHeights)
                self.astar = AStar(blockHeights, vis_map.tolist())
                self.start_point = (0,0)

                self.vis_map = vis_map

                blocks = np.array(self.vis_map)
                self.blocks = blocks.transpose()

                self.end_point = (40,25)

                self.root = Tkinter.Tk()
                self.frame = Tkinter.Frame(self.root, width=1024, height=768)
                self.frame.pack()
                self.canvas = Tkinter.Canvas(self.frame, width=1024,height=768)
                self.canvas.place(x=-2,y=-2)
                self.root.after(100,self.start) # INCREASE THE 0 TO SLOW IT DOWN
                self.root.mainloop()
Example #6
0
    def setup_algorithm(self):
        """Sets up the algorithm"""
        self.costmap = Costmap2D(DEFAULT_WIDTH, DEFAULT_HEIGHT,
                                 resolution=DEFAULT_RESOLUTION)
        Obstacle(3,3,3,3).draw(self.costmap)
        Obstacle(9,5,3,3).draw(self.costmap)
        Obstacle(16,4,3,3).draw(self.costmap)

        self.costmap_widget = Costmap2DWidget(self.costmap,
                                              parent=self, 
                                              show_goal=False,
                                              show_colorbar=True)
        self.costmap_widget.canvas.show_start = True
        self.costmap_widget.canvas.show_goal = True
        temp = self.costmap_widget.canvas.start_coord
        self.start_coord = (floor(temp[0]+0.5), floor(temp[1]+0.5))
        temp = self.costmap_widget.canvas.goal_coord
        self.goal_coord = (floor(temp[0]+0.5), floor(temp[1]+0.5))
        self.a_star = AStar(self.costmap,
                            self.start_coord,
                            self.goal_coord,
                            self.heuristic)
Example #7
0
#!/usr/bin/python

from a_star import AStar
import time

a_star = AStar()

a_star.leds(0,0,0)
time.sleep(0.3)
a_star.leds(1,0,0)
time.sleep(0.3)
a_star.leds(1,1,0)
time.sleep(0.3)
a_star.leds(0,1,1)
time.sleep(0.3)
a_star.leds(0,0,1)
time.sleep(0.3)
a_star.leds(0,0,0)
time.sleep(0.3)
a_star.leds(0,0,1)
time.sleep(0.3)
a_star.leds(0,1,1)
time.sleep(0.3)
a_star.leds(1,1,0)
time.sleep(0.3)
a_star.leds(1,0,0)
time.sleep(0.3)
a_star.leds(0,0,0)
			return (rand_x,rand_y)



gridValues = [[0 for y in range(GRID_HEIGHT)] for x in range(GRID_WIDTH)]
currentRobotPositions = [(1,1,),(5,20),(10,40)]
numRobots = len(currentRobotPositions)

for r in range(0,numRobots):
	fillRobotSpace(gridValues,currentRobotPositions[r],ROBOT_SIZE,r+4)

insertObtsacles(40, gridValues, OBSTACLE_SIZE, AStar.OBSTACLE_VAL)
goalPos = insertFinishPt(AStar.FINISH_PT_VAL, gridValues,FINISH_PT_SIZE)


aStarProb = AStar(gridValues,currentRobotPositions[0],goalPos,ROBOT_SIZE)

NUM_STEPS = 10
NUM_ITERATIONS = 12

for i in range(0,NUM_ITERATIONS):
	for r in range(0,numRobots):
		if(currentRobotPositions[r] != None):
			aStarProb.robotStartPos = currentRobotPositions[r]
			aStarProb.robotId = r + 4
			directions = aStarProb.getDirectionsToGoal()
			#print directions
			nextPos = aStarProb.fillGridWithDirections(directions,NUM_STEPS,gridValues)
			#print nextPos
			currentRobotPositions[r] = nextPos
Example #9
0
from a_star import AStar
a_star = AStar()
print(a_star.analog_read(2))
# Copyright Pololu Corporation.  For more information, see https://www.pololu.com/
from a_star import AStar

a_star = AStar()

a_star.play_notes("o4l16ceg>c8")
Example #11
0
from a_star import AStar
a_star = AStar()
print(a_star.read_battery_millivolts())
Example #12
0
class AStarAlgorithmWidget(AlgorithmWidget):
    def __init__(self, parent=None):
        self.heuristic = naive
        AlgorithmWidget.__init__(self, "A* Algorithm", parent)
        self.combo_box = QtGui.QComboBox(parent)
        self.combo_box.addItems(["naive", 'manhattan', 'crow'])
        self.combo_box.currentIndexChanged.connect(self.select_heuristic)
        self.buttons.append(self.combo_box)
        self.pack_buttons()

    def select_heuristic(self, index):
        if index == 0:
            self.heuristic = naive
        elif index == 1:
            self.heuristic = manhattan
        elif index == 2:
            self.heuristic = crow
        self.a_star.heuristic_cost_estimate = self.heuristic

    def setup_algorithm(self):
        """Sets up the algorithm"""
        self.costmap = Costmap2D(DEFAULT_WIDTH, DEFAULT_HEIGHT,
                                 resolution=DEFAULT_RESOLUTION)
        Obstacle(3,3,3,3).draw(self.costmap)
        Obstacle(9,5,3,3).draw(self.costmap)
        Obstacle(16,4,3,3).draw(self.costmap)

        self.costmap_widget = Costmap2DWidget(self.costmap,
                                              parent=self, 
                                              show_goal=False,
                                              show_colorbar=True)
        self.costmap_widget.canvas.show_start = True
        self.costmap_widget.canvas.show_goal = True
        temp = self.costmap_widget.canvas.start_coord
        self.start_coord = (floor(temp[0]+0.5), floor(temp[1]+0.5))
        temp = self.costmap_widget.canvas.goal_coord
        self.goal_coord = (floor(temp[0]+0.5), floor(temp[1]+0.5))
        self.a_star = AStar(self.costmap,
                            self.start_coord,
                            self.goal_coord,
                            self.heuristic)

    def step_solution(self):
        """Steps the solution"""
        # self.costmap_widget.canvas.freeze = True
        # count = 0
        # while count < 25:
        #     count += 1
        #     result = self.a_star.step_solution()
        #     if result == False:
        #         self.costmap_widget.canvas.freeze = False
        #         self.costmap_widget.canvas.on_map_update()
        #         return result
        # self.costmap_widget.canvas.freeze = False
        # self.costmap_widget.canvas.on_map_update()
        # return True
        return self.a_star.step_solution()

    def reset_algorithm(self):
        """Resets the algorithm"""
        self.costmap_widget.canvas.freeze = True
        self.costmap[:] = 0.0
        Obstacle(3,3,3,3).draw(self.costmap)
        Obstacle(9,5,3,3).draw(self.costmap)
        Obstacle(16,4,3,3).draw(self.costmap)

        temp = self.costmap_widget.canvas.start_coord
        self.start_coord = (floor(temp[0]+0.5), floor(temp[1]+0.5))
        temp = self.costmap_widget.canvas.goal_coord
        self.goal_coord = (floor(temp[0]+0.5), floor(temp[1]+0.5))
        self.a_star = AStar(self.costmap,
                            self.start_coord,
                            self.goal_coord,
                            self.heuristic)
        self.costmap_widget.canvas.freeze = False
        self.costmap_widget.canvas.on_map_update()
Example #13
0
def main(args):

    # initialize pygame
    pygame.init()

    # set screen size of phone or desktop window.  Adjust to your phone
    screen = pygame.display.set_mode((1024, 768))
    pygame.display.set_caption("Use keyboard arrow keys or mouse.  Press TEST to toggle overlay")
    

    # game framerate.  Higher number is faster
    FPS = 40

    # change the file names to your player graphic and map file
    player_image_file = "img/direction_24px.png"
    map_file = "maps/mega_map.json"

    # change to False (with capital F) to turn off red squares over
    # collision rectangles
    TESTING = True

    # Loading Paths (complete paths to all sections and from section start to parking slots)     
    filename = "maps/paths.json"
    path = []
    paths = loader.json_to_dict(filename)
    a_star = AStar(filename)
#    print a_star

    #initialize json loader, build tileset list, load player graphic
    initial = json_loader.Initialize(screen, TESTING, map_file, player_image_file, paths, 80)

    # initialize position of player when game first starts
    initial_position = (-4574,-4837)  
    map = json_loader.Map(initial, initial_position)
    map.move(initial_position[0], initial_position[1])
    #map.move_to_tile([146,153])

    # handle events such as keyboard / touchscreen presses
    event = json_loader.Event(initial)
    clock = pygame.time.Clock()

    # Generating pathfile 
    if args.generate_path:
        pathfile = open("path"+ str(random.randint(1,100)), 'w')
        new_path = []

    sections = paths["sections"]
    section = sections[0]

    slot = -1    
    new_car = 0
    [x,y] = [0,0]


    students = 10
#    path =  a_star.a_star(a_star.graph,"Caseta Policia")[0]
    

    while True:
        event.update()
    
        if event.direction == "start" and not path:
            #new_car = random.randint(1,10)  
            map.player.change_car_image("img/car_24px_"+str(students)+".png")
            astar =  a_star.a_star(a_star.graph,"Residencias 1")
            path = astar[0]
            a_star.rebuild_graph(astar[1])
            #slot += 1
            #path = [x for x in section["path_from_start"]]
            #path +=  section["slots"][slot]["path_from_section_start"]
            #path.reverse()   
       
        if path:
            move = path.pop()
            map.move_to_tile(move)
            time.sleep(.1)
            event.direction = "car_moving"
            if not path:
                map.change_tile(move, 3, students-1)
                map.player.change_car_image("img/direction_24px.png")
                event.direction = "stop"  
                students = students - 1
        map.update(event.direction)
        
        event.direction = "stop"  

        # Path file helper
        if args.generate_path:
            if x != map.mapx or y != map.mapy:        
                 tile = [map.player.position[0], map.player.position[1]]
                 if tile not in new_path:
                     new_path.append(tile)
                     pathfile.write(str(tile)+",")
            x = map.mapx
            y = map.mapy 
       
  
        map.display(screen)
        clock.tick(FPS)
        pygame.display.update()
        event.update() 
    def cover_xytable(self):
        total_distance = 0

        flood_covered = [[False for y in col] for col in self.rockpoint]

        # return all manhattan neighbors
        def get_neighbors(loc):
            xx, yy = loc
            return filter(self.is_in_bounds, [
                    (xx - 1, yy),
                    (xx, yy - 1),
                    (xx + 1, yy),
                    (xx, yy + 1),
                    ])


        S         = [(self.radius + 1, self.radius + 1)]        # start at 10,10 for funsies
        self.path = [(self.radius + 1, self.radius + 1, True)]  # mark path as exploratory
        current_location = None
        while 0 < len(S):
            new_loc = S.pop()
            (x, y) = new_loc
            if current_location is not None:
                (x0, y0) = current_location

                # don't do all this twice
                if flood_covered[x][y]: continue
                flood_covered[x][y] = True

                # set up the path planner, from the new point back to the current point
                # AStar(cost_fn, is_goal_fn, h_fn, successors_fn)
                cost_fn = lambda _, __  : 1
                h_fn = lambda (x, y) : abs(x - x0) + abs(y - y0) # manhattan distance
                is_goal_fn = lambda path : path == current_location
                successors_fn = lambda node : [n
                                               for n in get_neighbors(node)
                                               if (self.is_visited(n)
                                                   or n == current_location
                                                   or n == new_loc)]

                path_planner = AStar(cost_fn, is_goal_fn, h_fn, successors_fn, self.hack_draw_planned_path)

                # steps to get us to new location
                current_to_new_location = path_planner.solve(new_loc)
                if current_to_new_location is None:
                    self.draw_pathplan_failure(current_location, new_loc)
                    raise AssertionError("Couldn't go from " + str(current_location) + " to " + str(new_loc))


                # actually visit points
                total_distance += len(current_to_new_location) - 2
                self.path += [(xx, yy, False) for (xx, yy) in current_to_new_location[1:-1]]


            current_location = self.path[-1][:2]

            # only get neighbors of points with no displacement... otherwise dead end
            if not self.visit_point(x, y): continue

            # we've arrived
            current_location = new_loc
            total_distance += 1

            # add new neighbors to the list of places we need to check
            for neighbor in get_neighbors(new_loc):
                xx, yy = neighbor
                if not flood_covered[xx][yy]:
                    if self.is_ball_contained(xx, yy):
                        S.append(neighbor)

        print "Total distance is", total_distance,
        print "which has % efficiency", round(100.0 * len(self.get_visited_list()) / total_distance, 1)
Example #15
0
from a_star import AStar
a_star = AStar()
a_star.play("v10l8cg>cgc")