Beispiel #1
0
    def __init__(self, environment=None):
        """sets up details about the red rectangle as well as variables for A.I. behavior"""
        super(RedAiPilot, self).__init__("red_ai_pilot", environment)
        self.bot = Bot()
        # set the rectangle's color
        self.bot.image.fill(RED)
        # set the starting position
        self.bot.rect.x = RECTANGLE_STARTING_X
        self.bot.rect.y = RECTANGLE_STARTING_Y
        # place the coordinates of our rectangle in a tuple to update the game manager
        self.red_coordinate = (self.bot.rect.x, self.bot.rect.y)
        self.rect = self.bot.rect

        # these coordinates tell the agent how far away the blue player is
        self.blue_coordinate = None
        self.distance_from_blue_player = 0
        self.current_position = 0

        self.path_course = []
        self.path_found = False
        self.next_node_coordinates = None

        # variables for A.I. behavior
        self.winning = False

        self.current_behavior = PilotAgentBehavior.FINDING_PATH
        self.pathfinder = Pathfinder()
Beispiel #2
0
    def exec(self, state):
        self.game = Game(state)
        self.pathfinder = Pathfinder(self.game)

        # Choix d'un nouveau client
        if self.customer is None:
            print("Selecting customer")
            _, self.customer_loc = self.pathfinder.get_closest_customer(
                get_hero_pos(self.game))
            self.customer = get_customer_by_pos(self.customer_loc, self.game)

        if (self.num_death >= 5) and (self.min_heal <= 45):
            self.min_heal += 5
            self.num_death = 0

        destination = self.next_state()

        self.hero_health = get_hero_life(self.game)
        self.hero_calories = get_our_hero(self.game).calories

        # Reset de mort et check de healing
        if self.hero_health == 0:
            self.num_death += 1
            self.next_state = self.init
        elif (self.hero_calories > 30) and (self.hero_health < self.min_heal):
            if self.next_state != self.heal:
                self.state_before_heal = self.next_state
            self.next_state = self.heal

        return destination
Beispiel #3
0
def main():

    pg.init()

    resolution = (1200, 900)
    window = pg.display.set_mode(resolution, pg.DOUBLEBUF | pg.RESIZABLE)
    pg.display.set_caption("pathfinder")

    map = Terrain(8, 11, 100)
    # format (y, x)
    map.set_target([1, 6])
    pawn = Pathfinder([6, 6], map.grid)

    clock = pg.time.Clock()
    run_flag = True

    while run_flag:
        clock.tick(20)

        for event in pg.event.get():
            if event.type == pg.QUIT:
                run_flag = False
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_w:
                    map.add_block_manually(pg.mouse.get_pos())
                if event.key == pg.K_e:
                    map.set_target_manually(pg.mouse.get_pos())
                if event.key == pg.K_q:
                    map.free_block_manually(pg.mouse.get_pos())

        window.fill((120, 120, 120))
        map.draw(window)
        pg.display.update()

        pawn.make_move(map.grid, window, map)
Beispiel #4
0
    def __init__(self,
                 arduino=None,
                 android=None,
                 fakeRun=False,
                 fakeMap=None,
                 stepsPerSec=1,
                 **kwargs):
        """ 
        Constructor. Accepts attributes as kwargs.
            
        Args:
            fakeRun: set True if running simulation. Remember to give fake map as input. I.e: fakeMap = fakemap
            fakeMap: set simulation map. If left empty, creates an empty arena.
            pos: a 15x20 array. Contains None, 0 or 1 as values.
            orientation: Centre of 3x3 start area. Default = [1,1]
            map: Map object. Refer to Map.py
            sensors: Sensors object. Refer to sensors.py
            coordinator: Coordinator object. Refer to coordinator.py
        """
        if fakeRun:
            self.fakeRun = True

            from sensors_fake import Sensors
            self.sensors = Sensors(self, fakeMap)  #fake sensors for simulation
            self.coordinator.fakeRun = True
            self.coordinator.stepsPerSec = stepsPerSec
            self.imagefinder = Imagefinder(fakeRun=True)
        elif arduino is None:
            raise Exception("Real run requires arduino to be present")
        elif android is None:
            raise Exception("Real run requires arduino to be present")
        else:
            from sensors import Sensors
            self.android = android
            self.sensors = Sensors(self, arduino)
            self.coordinator.arduino = arduino
            self.imagefinder = Imagefinder()

        #update map
        self.updatemap()
        goalTiles = [  #set goal as explored
            [12, 19],
            [13, 19],
            [14, 19],
            [12, 18],
            [13, 18],
            [14, 18],
            [12, 17],
            [13, 17],
            [14, 17],
        ]
        valuelist = [0] * len(goalTiles)
        self.map.setTiles(goalTiles, valuelist)

        #initialise pathfinder
        self.pathfinder = Pathfinder(self.map)

        #initialise explorer
        self.explorer = Explorer(self)
Beispiel #5
0
 def __init__(self):
     super().__init__()
     # Из cfg.txt считывается рабочая директория,
     # за пределы которой выйти будет нельзя
     with open('cfg.txt') as f:
         root = f.readline()
     # Создается объект, преобразующий ввод в полноценные пути
     # Он получает на вход рут, и вернет код ошибки, если его покинуть
     self.pathfinder = Pathfinder(root)
Beispiel #6
0
    def __init__(self):
        bot_name = "Swarming"
        self.game = hlt.Game(bot_name)
        logging.info("Starting bot {}".format(bot_name))

        self.pathfinder = Pathfinder()
        self.info = Info()
        self.ai = AI(self.info, self.pathfinder)

        self.game_map = None
Beispiel #7
0
    def __init__(self, environment=None):
        """sets up details about the red rectangle as well as variables for A.I. behavior"""
        super(NEO, self).__init__("neo", environment)

        # the bot object represents NEO's physical body
        # it performs the tasks as directed by the body part classes below
        self.bot = Bot()
        # set the bot's image and angle
        self.bot.image = pygame.Surface([16, 16])
        self.bot.image = pygame.transform.scale(pygame.image.load('Neo.png'),
                                                (25, 25))
        self.original_image = self.bot.image.copy()
        self.angle = 90
        # set the starting position
        self.bot.rect.x = NEO_STARTING_X
        self.bot.rect.y = NEO_STARTING_Y
        # place the coordinates of our rectangle in a tuple to update the game manager
        self.red_coordinate = (self.bot.rect.x, self.bot.rect.y)
        self.rect = self.bot.rect

        # these different body part classes help modularize the various functions NEO performs
        self.eyes = Eyes()
        self.hands = Hands()
        self.legs = Legs()
        self.memory = Memory()
        self.memory.create_object_memory()
        # self.mouth = Mouth()
        # self.ears = Ears()
        self.wernicke_area = Wernicke_Area()

        self.current_object = None

        # these coordinates tell the agent how far away the object is
        self.object_coordinates = None
        self.distance_from_object = 0
        self.current_position = 0

        self.path_course = []
        self.path_found = False
        self.next_node_coordinates = None

        # variables for A.I. behavior
        self.inspecting = False
        self.detected_objects = []
        self.uninspected_objects = []

        self.current_behavior = BEHAVIOR_STATE.SCANNING
        self.pathfinder = Pathfinder()
        self.running_training = True

        #search variables
        self.rotating_counter = 0
        self.location_coordinates = self.ask("memory", "location_coordinates")

        self.sql_statement = None
Beispiel #8
0
    def __init__(self):
        # INIT PYGAME
        pygame.init()
        pygame.display.set_caption("A* demo")
        pygame.font.init()

        self.font = pygame.font.SysFont("roboto", 25)
        self.is_running = False
        self.started = False
        self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
        self.pencil = BlockType.WALL
        self.board = Board(WINDOW_WIDTH, WINDOW_HEIGHT - 120, BLOCK_SIZE)
        self.finder = Pathfinder(self.board)
Beispiel #9
0
 def __init__(self, id, pos, app):
     Tank.__init__(self, id, pos, app)
     self.path = None
     self.dest = (10,10)
     self.idest = None
     self.rot_dest = None
     self.rotation_signum = 0
     self.driving_signum = 0
     self.previous_state = None
     self.pathfinder = Pathfinder(self.is_valid_cell)
     dx, dy = self.dest
     dcell = self.app.current_map.get_at_pixel(dx, dy)
     x,y = self.position
     cell = self.app.current_map.get_at_pixel(x, y)
     self.pathfinder.setupPath(cell.i, cell.j, dcell.i, dcell.j)
Beispiel #10
0
    def createboard(self, predefinedboard, uselastdata):
        """
        Create board and prepares paths if not prepared.

        :param predefinedboard: Array of sprites
        :param uselastdata: Bool value determining if paths have already been calculated.
        :return: nothing
        """
        Board(predefinedboard, self.systems, self.elements, self.tile_size)
        start = int(round(time.time() * 1000))
        if not uselastdata:
            self.last_data = Pathfinder(predefinedboard)
            self.last_data.prepareallstepsforshortestpaths()
            print("Pathfinder time: ", int(round(time.time() * 1000)) - start)
        self.systems[AiMovementSystem.NAME].register(self.last_data)
        self.elements.append(self.last_data)
    def __init__(self, window, algorithm):
        self.window = window
        self.score = 0
        self.snake = [Snake(window.display, (WIDTH/2, HEIGHT/2))]
        self.apple = Apple(window.display, self.snake)

        # make graph
        self.graph = Environment(self.snake, self.apple)

        # init search algorithm
        self.algorithm = Pathfinder(
            self.snake[0].relative_pos, self.apple.relative_pos, self.graph, algorithm)

        # Run loop
        self.loop()

        self.window.quit()
Beispiel #12
0
    def test_astar_intercardinal_search(self):
        map = [
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
            [0, 0, 1, 0, 0, 0, 0, 0, 2, 0],
            [0, 0, 1, 1, 1, 0, 0, 2, 0, 0],
            [0, 0, 0, 1, 1, 0, 2, 0, 0, 2],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 2],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        ]

        # Make it walkable only on tiles with a 2
        walkable = lambda v: v != 2

        # We need to annotate the clearance on the grid for later use in our pathfindings
        grid = Grid(map).annotate(walkable)
        finder = Pathfinder(astar.search)

        agent_characteristics = AgentCharacteristics(walkable=walkable, clearance=2)

        path = finder.get_path(
            grid,
            (0, 0),
            (8, 8),
            agent_characteristics=agent_characteristics,
            heuristic=cardinal_intercardinal,
        )

        X = "x"
        marked_map = [
            [X, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, X, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 0, X, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, X, 0, 0, 0, 0, 0, 0],
            [0, 0, 1, 0, X, 0, 0, 0, 2, 0],
            [0, 0, 1, 1, X, 0, 0, 2, 0, 0],
            [0, 0, 0, 1, 1, X, 2, 0, 0, 2],
            [0, 0, 0, 0, 1, 0, X, X, 0, 2],
            [0, 0, 0, 0, 0, 0, 0, 0, X, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        ]

        self._assert_the_resulting_path_nodes_should_be_like(marked_map, path)
Beispiel #13
0
    def test_do_a_search_smaller_corridor(self):
        map = [
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 2, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 2, 0, 1, 0, 0, 0, 0, 0, 0],
            [0, 2, 1, 0, 0, 0, 0, 0, 2, 0],
            [0, 2, 1, 1, 1, 0, 0, 2, 0, 0],
            [0, 2, 0, 1, 1, 0, 2, 0, 0, 2],
            [0, 2, 0, 0, 1, 0, 0, 0, 0, 2],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        ]

        walkable = lambda v: v != 2

        grid = Grid(map).annotate(walkable)
        finder = Pathfinder(astar.search)

        startx, starty = 0, 0
        endx, endy = 0, 8
        agent_characteristics = AgentCharacteristics(walkable=walkable, clearance=2)

        path = finder.get_path(
            grid,
            (startx, starty),
            (endx, endy),
            agent_characteristics,
            heuristic=heuristics.diagonal,
        )

        X = "x"
        marked_map = [
            [X, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, X, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 2, X, 0, 0, 0, 0, 0, 0, 0],
            [0, 2, X, 1, 0, 0, 0, 0, 0, 0],
            [0, 2, X, 0, 0, 0, 0, 0, 2, 0],
            [0, 2, X, 1, 1, 0, 0, 2, 0, 0],
            [0, 2, X, 1, 1, 0, 2, 0, 0, 2],
            [0, 2, X, 0, 1, 0, 0, 0, 0, 2],
            [X, X, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        ]

        self._assert_the_resulting_path_nodes_should_be_like(marked_map, path)
Beispiel #14
0
    def test_astar_large_map(self, datadir):
        # Make it walkable only if
        walkable = lambda v: v != 2

        map = (datadir / "large_map_hard.map").read_text()
        map = map.replace("@", "2").replace("T", "1").replace(".", "0")

        grid = Grid(map).annotate(walkable)
        finder = Pathfinder(astar.search)

        agent_characteristics = AgentCharacteristics(walkable=walkable, clearance=2)
        finder.get_path(
            grid,
            (0, 0),
            (8, 8),
            agent_characteristics,
            heuristic=cardinal_intercardinal,
        )
Beispiel #15
0
    def test_paths(self):
        """ Confirms each waypoint is reachable """

        for z in range(self.dim_z+1):
            # Create the graph, impediments are walls(0) and locked doors(L)

            imp = []

            this_floor = [None for y in range(self.dim_y)]
            for y in range(self.dim_y):
                this_floor[y]=[None for x in range(self.dim_x)]
                for x in range(self.dim_x):
                    this_floor[y][x]=self.grid[x,y,z][0]

            graph = GraphGrid(this_floor)

            # Default impediments are wall(0) and locked doors(L)
            imp=[(a,b) for a,b,c in self.grid if self.grid[a,b,z][0] in [0,'0','L']]

            # Set the list of impassable points
            graph.impassable = imp

            # Set the floor start and end points
            start,end = self.find_path_ends(z)

            self.logger.info('[*] Testing the path from {} to {}'.format(start,
                                                                         end))

            # Initialize the path tester, as a_star for best path
            path_tester=Pathfinder(Pathfinder.gb_first)
            path_tester.g = graph
            path_tester.start = start[:2]
            path_tester.dest = end[:2]
            path = path_tester.execute()

            if not path:
                self.logger.error("Invalid pathfinding algorithm")
            else:
                for (x,y) in path:
                    val=path[x,y]
                    if val is not None:
                        if self.grid[x,y,z][0] not in ['U','D','S','E']:
                            self.grid[val[0],val[1],z][1]=[color.WHITE_ON_BLUE]
Beispiel #16
0
    def test_astar_all_heuristics_should_return_a_similar_path(self, all_heuristics):
        map = [
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
            [0, 0, 1, 0, 0, 0, 0, 0, 2, 0],
            [0, 0, 1, 1, 1, 0, 0, 2, 0, 0],
            [0, 0, 0, 1, 1, 0, 2, 0, 0, 2],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 2],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        ]

        walkable = lambda v: v != 2

        grid = Grid(map).annotate(walkable)
        finder = Pathfinder(astar.search)

        startx, starty = 0, 0
        endx, endy = 8, 8

        paths = []

        agent_characteristics = AgentCharacteristics(walkable=walkable, clearance=2)
        for heuristic in all_heuristics:
            paths.append(
                finder.get_path(
                    grid,
                    (startx, starty),
                    (endx, endy),
                    agent_characteristics,
                    heuristic=heuristic,
                )
            )

        num_nodes = len(paths[0].nodes)
        assert all(len(path.nodes) == num_nodes for path in paths)
Beispiel #17
0
def find_path():
    if request.method == 'POST':
        pathfinder = Pathfinder(host='localhost', port='5436', database='postgres',
                                user='******', password='******')
        data = json.loads(request.data.decode('ascii'))

        start = data['viewparams']['start']
        end = data['viewparams']['end']
        time_limit = data['time']  # hours
        distance_limit = data['distance']  # km

        time_start = time.time()
        # Uruchomienie procedury podstawowej - procedura RUN
        pathfinder.run(start, end, distance_limit * 1000, time_limit)
        time_end = time.time()
        print('Total time (in minutes): {}'.format((time_end - time_start)/60.0))
        print('Number of locations: {}'.format(len(pathfinder.locations)))
        print('Additional len left: {}'.format(pathfinder.additional_len))
        print('Additional time left: {}'.format(pathfinder.additional_time))

        # Sprawdzenie, czy zostalo wykorzystane co najmniej 80% dodatkowych kilometrow
        if pathfinder.additional_len / float(distance_limit * 1000) <= 0.2 or pathfinder.additional_len <= 2000:
            ret = {
                'key_points': pathfinder.locations,
                'route': pathfinder.routes
            }
            return jsonify(ret)

        # Let's try again
        print('Trying one more time')

        locations_backup = pathfinder.locations
        routes_backup = pathfinder.routes

        time_start = time.time()
        # Uruchomienie procedury wyjatkowej - procedura RUN_WITH_FIRST_RANDOM
        pathfinder.run_with_first_random(start, end, distance_limit * 1000, time_limit)
        time_end = time.time()
        print('Total time (in minutes): {}'.format((time_end - time_start)/60.0))
        print('Number of locations: {}'.format(len(pathfinder.locations)))
        print('Additional len left: {}'.format(pathfinder.additional_len))
        print('Additional time left: {}'.format(pathfinder.additional_time))

        if len(pathfinder.locations) > len(locations_backup):
            ret = {
                'key_points': pathfinder.locations,
                'route': pathfinder.routes
            }
            return jsonify(ret)
        else:
            ret = {
                'key_points': locations_backup,
                'route': routes_backup
            }
            return jsonify(ret)
Beispiel #18
0
async def run_async_2():
    with timewith("async"):
        grid = Grid(map)
        finder = Pathfinder(astar.search, heuristic=cardinal_intercardinal)
        grid.annotate(walkable)
        get_path_async = async_wrap(finder.get_path)

        # Compute all the paths serially
        computed_paths = []
        tasks = []
        for start, end in paths:
            tasks.append(
                get_path_async(start[0], start[1], end[0], end[1], agent_size))

        await aio.gather(*tasks)

    assert len(computed_paths) == len(paths)
Beispiel #19
0
 def __init__(self, cutDiameter, mowerLength, turnRadius, centerDistance, length, width, startingIndex):
     self.client = MongoClient()
     self.db = self.client.backyardbarber
     self.collection = self.db.schedules
     self.finder = Pathfinder(cutDiameter, mowerLength, turnRadius, centerDistance, length, width)
     self.cutDiameter = cutDiameter
     self.mowerLength = mowerLength
     self.turnRadius = turnRadius
     self.centerDistance = centerDistance
     self.length = length
     self.width = width
     self.pathBuilt = (self.db.path.find().count > 0)
     if Controller.coms is None:
         Controller.coms = Communications(0)
     if Controller.running is None:
         Controller.running = False
     if Controller.controller is None:
         Controller.controller = self
Beispiel #20
0
    def __init__(self, game_map, ships):
        self.game_map = game_map
        self.id = min(ships)
        self.ships = ships

        self.vel_x = 0
        self.vel_y = 0
        self.magnitude = 0
        self.angle = 0

        self.target = None

        self.formation = 'ender'
        self.focus = None
        self.radius = None

        self.pathfinder = Pathfinder()

        self.position_modifier = []
        if self.formation == 'ender':
            self.inner_ring_distance = 0.5 * 2 + SQUADRON_SPREAD
            self.outer_ring_distance = 0.5 * 4 + SQUADRON_SPREAD * 2

            self.position_modifier.append((0, 0))
            for angle in range(0, 360, 60):
                self.position_modifier.append(
                    (self.inner_ring_distance, angle))
            for angle in range(0, 360, 30):
                self.position_modifier.append(
                    (self.outer_ring_distance, angle))

            self.max_size = 19

        if self.formation == '3':
            self.distance_between_ships = 0.5 * 2 + SQUADRON_SPREAD
            self.max_size = 3

        for ship in self.ships:
            self.game_map.get_me().get_ship(ship).in_squadron = True

        self.distance_between_ships = 0.5 * 2 + SQUADRON_SPREAD

        self.update_position()
        self.x, self.y = self.get_center_point(self.ships)
Beispiel #21
0
    def __init__(self, width, height, tile_side_length):
        self.start_tile = None
        self.finish_tile = None
        self.width = width
        self.height = height
        self.tiles = [height * [0] for _ in range(width)]
        self.tiles_unordered = []
        self.tile_images = pygame.sprite.Group()

        for x in range(width):
            for y in range(height):
                self.tiles[x][y] = Tile(x * tile_side_length,
                                        y * tile_side_length, tile_side_length)

        for col in self.tiles:
            for tile in col:
                self.tile_images.add(tile.sprite)
                self.tiles_unordered += [tile]

        self.establish_connections()

        self.pathfinder = Pathfinder(self.tiles_unordered, self.start_tile,
                                     self.finish_tile)
Beispiel #22
0
    def test_paths(self):
        """ Confirms each waypoint is reachable """

        for z in range(self.dim_z + 1):
            # Create the graph, impediments are walls(0) and locked doors(L)

            imp = []

            this_floor = [None for y in range(self.dim_y)]
            for y in range(self.dim_y):
                this_floor[y] = [None for x in range(self.dim_x)]
                for x in range(self.dim_x):
                    this_floor[y][x] = self.grid[x, y, z][0]

            graph = GraphGrid(this_floor)

            # Default impediments are wall(0) and locked doors(L)
            imp = [(a, b) for a, b, c in self.grid
                   if self.grid[a, b, z][0] in [0, '0', 'L']]

            # Set the list of impassable points
            graph.impassable = imp

            # Set the floor start and end points
            start, end = self.find_path_ends(z)

            self.logger.info('[*] Testing the path from {} to {}'.format(
                start, end))

            # Initialize the path tester, as a_star for best path
            path_tester = Pathfinder(Pathfinder.gb_first)
            path_tester.g = graph
            path_tester.start = start[:2]
            path_tester.dest = end[:2]
            path = path_tester.execute()

            if not path:
                self.logger.error("Invalid pathfinding algorithm")
            else:
                for (x, y) in path:
                    val = path[x, y]
                    if val is not None:
                        if self.grid[x, y, z][0] not in ['U', 'D', 'S', 'E']:
                            self.grid[val[0], val[1],
                                      z][1] = [color.WHITE_ON_BLUE]
Beispiel #23
0
class NEO(Agent):
    """Controls the behaviors of the NEO bot

    NEO has four main tasks:
    1. scan the room for new objects,
    2. approach discovered objects,
    3. inspect objects and gather info about their attributes,
    4. accept queries from the user to test its memory of objects.

    NEO performs these tasks by using the various body part classes located in the neo_body directory. This NEO
    class essentially serves as the 'brain' class and passes commands to all other body parts as needed. NEO and every
    body part class are subclasses of the Agent class, which allows them to safely share info with each other using
    Agent Oriented Programming methods. This allows us to easily add new parts or replace parts altogether."""
    def __init__(self, environment=None):
        """sets up details about the red rectangle as well as variables for A.I. behavior"""
        super(NEO, self).__init__("neo", environment)

        # the bot object represents NEO's physical body
        # it performs the tasks as directed by the body part classes below
        self.bot = Bot()
        # set the bot's image and angle
        self.bot.image = pygame.Surface([16, 16])
        self.bot.image = pygame.transform.scale(pygame.image.load('Neo.png'),
                                                (25, 25))
        self.original_image = self.bot.image.copy()
        self.angle = 90
        # set the starting position
        self.bot.rect.x = NEO_STARTING_X
        self.bot.rect.y = NEO_STARTING_Y
        # place the coordinates of our rectangle in a tuple to update the game manager
        self.red_coordinate = (self.bot.rect.x, self.bot.rect.y)
        self.rect = self.bot.rect

        # these different body part classes help modularize the various functions NEO performs
        self.eyes = Eyes()
        self.hands = Hands()
        self.legs = Legs()
        self.memory = Memory()
        self.memory.create_object_memory()
        # self.mouth = Mouth()
        # self.ears = Ears()
        self.wernicke_area = Wernicke_Area()

        self.current_object = None

        # these coordinates tell the agent how far away the object is
        self.object_coordinates = None
        self.distance_from_object = 0
        self.current_position = 0

        self.path_course = []
        self.path_found = False
        self.next_node_coordinates = None

        # variables for A.I. behavior
        self.inspecting = False
        self.detected_objects = []
        self.uninspected_objects = []

        self.current_behavior = BEHAVIOR_STATE.SCANNING
        self.pathfinder = Pathfinder()
        self.running_training = True

        #search variables
        self.rotating_counter = 0
        self.location_coordinates = self.ask("memory", "location_coordinates")

        self.sql_statement = None

    def act_out_decision(self):
        pass

    def check_distance_from_object(self):
        self.update_coordinates()
        self.distance_from_object = \
            abs(self.object_coordinates[0] - self.red_coordinate[0]) + \
            abs(self.object_coordinates[1] - self.red_coordinate[1])

    def determine_behavior(self):
        if self.inspecting:
            self.current_behavior = BEHAVIOR_STATE.INSPECTING
        elif self.uninspected_objects and not self.path_found:
            self.current_behavior = BEHAVIOR_STATE.PATH_FINDING
            self.current_object = self.uninspected_objects[0]
        elif self.path_found:
            self.current_behavior = BEHAVIOR_STATE.APPROACHING
        else:
            self.current_behavior = BEHAVIOR_STATE.SCANNING

    def determine_object_position(self):
        """"used to determine which direction the red player should turn to face object"""
        if self.red_coordinate[0] + MARGIN >= self.object_coordinates[
                0] >= MARGIN - self.red_coordinate[0]:
            # red player is above blue player
            if self.red_coordinate[1] < self.object_coordinates[1] - MARGIN:
                self.current_position = PilotCurrentPosition.ABOVE

            # red player is below blue player
            elif self.red_coordinate[1] > self.object_coordinates[1] + MARGIN:
                self.current_position = PilotCurrentPosition.BELOW
            # red player is right of blue
            elif self.red_coordinate[0] > self.object_coordinates[0]:
                self.current_position = PilotCurrentPosition.RIGHT
            # red player is left of blue
            elif self.red_coordinate[0] < self.object_coordinates[0]:
                self.current_position = PilotCurrentPosition.LEFT

    def filter_detected_objects(self):
        """Decides whether detected objects(currently just 1 at a time) have been inspected before"""
        for obj in self.detected_objects:
            self.sql_statement = "SELECT * FROM objects WHERE object_x_pos = " + str(obj.x) + \
                " AND object_y_pos = " + str(obj.y)
            self.memory.recall_objects()
            if self.ask("memory", "short_term_memory"):
                self.detected_objects.remove(obj)
            else:
                self.uninspected_objects += [obj]
                self.detected_objects.remove(obj)

    def find_next_node(self):
        """finds the closest node in our path and removes nodes once they are reached"""
        if not (1 <= abs(self.rect.centerx - self.next_node_coordinates[0]) or
                1 <= abs(self.rect.centery - self.next_node_coordinates[1])):
            self.path_course.pop(0)
            if self.path_course:
                self.next_node_coordinates = (self.path_course[0].x,
                                              self.path_course[0].y)

    def is_healthy(self):
        return self.hit_points > 50

    def make_decision(self):
        """Acts out decisions based on the current behavior state"""
        if not self.running_training:
            self.filter_detected_objects()
            self.determine_behavior()
            if self.current_behavior == BEHAVIOR_STATE.SCANNING:
                self.legs.rotate()
                self.angle = self.ask("legs", "angle")
                self.eyes.scan_room()
                # _thread.start_new_thread(self.mouth.speak, ("Scanning Room",))
            elif self.current_behavior == BEHAVIOR_STATE.PATH_FINDING:
                self.path_course = self.pathfinder.find_path(
                    self.object_coordinates)
                self.path_found = True
                self.next_node_coordinates = (self.path_course[0].x,
                                              self.path_course[0].y)
            elif self.current_behavior == BEHAVIOR_STATE.APPROACHING:
                if not self.path_course:
                    self.path_found = False
                    self.inspecting = True
                    return
                self.find_next_node()
                self.move_to_next_node()
            elif self.current_behavior == BEHAVIOR_STATE.INSPECTING:
                # if not self.mouth.inspection_message_spoken:
                #     self.mouth.stopSentence()
                #     _thread.start_new_thread(self.mouth.speak, ("Inspecting Object",))
                #     self.mouth.inspection_message_spoken = True
                self.eyes.look_at_object()
                self.hands.pick_up_object()
                self.memory.memorize()
                self.inspecting = False
                self.uninspected_objects.remove(self.current_object)
                self.current_object = None
        else:
            self.run_training()

    def move_to_next_node(self):
        """tells the bot which direction to move to reach the next node in its path"""
        if self.next_node_coordinates[0] < self.rect.centerx:
            self.bot.move(-2, 0)
        elif self.next_node_coordinates[0] > self.rect.centerx:
            self.bot.move(2, 0)

        # up and down
        if self.next_node_coordinates[1] < self.rect.centery:
            self.bot.move(0, -2)
        elif self.next_node_coordinates[1] > self.rect.centery:
            self.bot.move(0, 2)

    # def rotate(self): Use the one in legs.py instead
    #     self.angle += .5
    #     key = pygame.key.get_pressed()
    #     if key[pygame.K_LEFT]:
    #         self.angle += 4
    #     if key[pygame.K_RIGHT]:
    #         self.angle -= 4
    #     # self.angle += 2
    #     self.angle %= 360
    #     self.bot.angle_facing = self.angle
    #     self.bot.update_dx_dy()
    #
    #     rect_center = self.bot.image.get_rect()
    #     self.bot.image = pygame.transform.rotozoom(self.original_image, self.angle, 1)
    #     rot_rect = rect_center.copy()
    #     rot_rect.center = self.bot.image.get_rect().center
    #     self.bot.image = self.bot.image.subsurface(rot_rect).copy()

    def run_training(self):
        if self.current_behavior != BEHAVIOR_STATE.PATH_FINDING:
            key = pygame.key.get_pressed()
            if key[pygame.K_LEFT]:
                self.legs.walk(-2, 0)
            if key[pygame.K_RIGHT]:
                self.legs.walk(2, 0)
            if key[pygame.K_UP]:
                self.legs.walk(0, -2)
            if key[pygame.K_DOWN]:
                self.legs.walk(0, 2)

            if key[pygame.K_SPACE]:
                location_name = input("Enter a name for this location:")
                self.memory.save_location(location_name)
            if key[pygame.K_c]:
                command = input("Enter a command to run")
                self.wernicke_area.parse_command(command)
                # location_coordinates = self.ask("wernicke_area", "location_coordinates")
                self.update_coordinates()
                self.current_behavior = self.ask("wernicke_area",
                                                 "next_behavior")
                self.current_behavior = BEHAVIOR_STATE(7)
                # to do: add division between tasks
                # self.path_course = self.pathfinder.find_path(location_coordinates)
                # self.current_behavior = BEHAVIOR_STATE.PATH_FINDING
                # print(self.path_course)
        elif self.current_behavior == BEHAVIOR_STATE.PATH_FINDING:
            if not self.path_course:
                self.path_found = False
                self.current_behavior = BEHAVIOR_STATE.TRAINING
                return
            else:
                self.next_node_coordinates = (self.path_course[0].x,
                                              self.path_course[0].y)
                self.find_next_node()
                self.move_to_next_node()

    def search_for(self):

        self.legs.rotate()
        self.rotating_counter += 1
        self.angle = self.ask("legs", "angle")
        if self.rotating_counter > 360:
            self.rotating_counter = 0
            self.current_behavior = BEHAVIOR_STATE.SWITCHING_ROOMS
        else:
            self.eyes.scan_room()
            self.current_behavior = BEHAVIOR_STATE.SEARCHING

    def update_search(self):
        if self.current_behavior == BEHAVIOR_STATE.SEARCHING:
            self.search_for()
        elif self.current_behavior == BEHAVIOR_STATE.SWITCHING_ROOMS:
            self.go_to_room()

    def go_to_room(self):
        if self.path_course is None:
            self.path_course = self.pathfinder.find_path(
                self.location_coordinates[0])
            self.location_coordinates.pop(0)
        else:
            self.next_node_coordinates = (self.path_course[0].x,
                                          self.path_course[0].y)
            self.move_to_next_node()

    def setup_bot_map(self):
        self.bot.wall_list = self.environment.get_object("wall_list")

    def shoot(self):
        if self.bot.reloaded():
            bullet_list = self.environment.get_object("bullet_list")
            if self.current_position == PilotCurrentPosition.LEFT:
                bullet_list.add(self.bot.shoot_right())
            elif self.current_position == PilotCurrentPosition.RIGHT:
                bullet_list.add(self.bot.shoot_left())
            elif self.current_position == PilotCurrentPosition.ABOVE:
                bullet_list.add(self.bot.shoot_down())
            elif self.current_position == PilotCurrentPosition.BELOW:
                bullet_list.add(self.bot.shoot_up())

    def update_coordinates(self):
        self.red_coordinate = (self.rect.x, self.rect.y)
Beispiel #24
0
import socket
import json
from pathfinder import Pathfinder
import time

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("172.16.17.26", 8090))
server.listen(1)
robot = Pathfinder()
client, addr = server.accept()
client.settimeout(2)
try:
    while True:
        msg = client.recv(1024)
        if msg == "quit":
            break
        else:
            try:
                msg = json.loads(msg)
                robot.move(msg['x'], msg['y'], msg['w'],)
            except ValueError:
                pass
except socket.timeout:
    print("timeout error")
    robot.move(0,0,0)
except socket.error:
    print("socket error occured: ")
    robot.move(0,0,0)
server.close()
Beispiel #25
0
class Controller():
    coms = None
    running = None
    controller = None
    
    def __init__(self, cutDiameter, mowerLength, turnRadius, centerDistance, length, width, startingIndex):
        self.client = MongoClient()
        self.db = self.client.backyardbarber
        self.collection = self.db.schedules
        self.finder = Pathfinder(cutDiameter, mowerLength, turnRadius, centerDistance, length, width)
        self.cutDiameter = cutDiameter
        self.mowerLength = mowerLength
        self.turnRadius = turnRadius
        self.centerDistance = centerDistance
        self.length = length
        self.width = width
        self.pathBuilt = (self.db.path.find().count > 0)
        if Controller.coms is None:
            Controller.coms = Communications(0)
        if Controller.running is None:
            Controller.running = False
        if Controller.controller is None:
            Controller.controller = self
        
    def buildPath(self):
        self.finder.buildBasePath()
        self.pathBuilt = True
        
    def startMower(self):
        if self.pathBuilt == False:
            self.buildPath()
        if Controller.running == False:
            Controller.coms.run()
            Controller.running = True
        # tell node that we started
        
    def interrupt(self, message, terminate):
        Controller.coms.interrupt(message, terminate)
        Controller.running = False
        
    def schedule(self):
        cron = CronTab()
        for schedule in self.collection.find():
            job  = cron.new(command='python /backyarbarber/python/controller.py startMower')
            min = schedule["time"]["minute"]
            hour = schedule["time"]["hour"]
            days = schedule["days"]
            dayString = ""
            if days["Sunday"]:
                dayString += ",0"
            elif days["Monday"]:
                dayString += ",1"
            elif days["Tuesday"]:
                dayString += ",2"
            elif days["Wednesday"]:
                dayString += ",3"
            elif days["Thursday"]:
                dayString += ",4"
            elif days["Friday"]:
                dayString += ",5"
            elif days["Saturay"]:
                dayString += ",6"
            if dayString[0] == ',':
                dayString = dayString[1:]
            job.minute.on(min)
            job.hour.on(hour)
            job.days.on(dayString)
            job.enable()
Beispiel #26
0
class SimpleBot(Bot):
    def __init__(self):
        self.customer = None
        self.customer_loc = None
        self.game = None
        self.next_state = self.init
        self.state_before_heal = self.init
        self.fries_loc = None
        self.burger_loc = None
        self.drink_loc = None
        self.pathfinder = None
        self.min_heal = 30
        self.num_death = 0
        self.hero_health = 100
        self.hero_calories = 0

    def init(self):
        self.next_state = self.get_fries
        self.state_before_heal = self.get_fries
        self.customer = None
        self.customer_loc = None
        self.fries_loc = None
        self.drink_loc = None
        self.pathfinder = None

        return 'Stay'

    def exec(self, state):
        self.game = Game(state)
        self.pathfinder = Pathfinder(self.game)

        # Choix d'un nouveau client
        if self.customer is None:
            print("Selecting customer")
            _, self.customer_loc = self.pathfinder.get_closest_customer(
                get_hero_pos(self.game))
            self.customer = get_customer_by_pos(self.customer_loc, self.game)

        if (self.num_death >= 5) and (self.min_heal <= 45):
            self.min_heal += 5
            self.num_death = 0

        destination = self.next_state()

        self.hero_health = get_hero_life(self.game)
        self.hero_calories = get_our_hero(self.game).calories

        # Reset de mort et check de healing
        if self.hero_health == 0:
            self.num_death += 1
            self.next_state = self.init
        elif (self.hero_calories > 30) and (self.hero_health < self.min_heal):
            if self.next_state != self.heal:
                self.state_before_heal = self.next_state
            self.next_state = self.heal

        return destination

    def get_fries(self):

        if self.fries_loc is None:
            print("Choosing new fries")
            fries_tile, self.fries_loc = self.pathfinder.get_closest_fries(
                get_hero_pos(self.game))

        client_fries = self.customer.french_fries
        hero_fries = get_hero_fries(self.game)

        direction = get_direction(self.game, self.fries_loc)
        hero_loc = get_hero_pos(self.game)

        if self.pathfinder.get_distance(self.fries_loc, hero_loc) <= 1:
            print("Fries acquired")
            self.fries_loc = None

        if hero_fries >= client_fries:
            self.next_state = self.get_burgers
        else:
            self.next_state = self.get_fries

        return direction

    def get_burgers(self):

        if self.burger_loc is None:
            print("Choosing new burger")
            burger_tile, self.burger_loc = \
                self.pathfinder.get_closest_burger(get_hero_pos(self.game))

        client_burgers = self.customer.burger
        hero_burgers = get_hero_burgers(self.game)
        hero_loc = get_hero_pos(self.game)

        direction = get_direction(self.game, self.burger_loc)

        if self.pathfinder.get_distance(self.burger_loc, hero_loc) <= 1:
            print("Burger acquired")
            self.burger_loc = None

        if hero_burgers >= client_burgers:
            if get_hero_fries(self.game) >= self.customer.french_fries:
                self.next_state = self.goto_customer
            else:
                self.next_state = self.get_fries
        else:
            self.next_state = self.get_burgers

        return direction

    def heal(self):
        # Check si on a les calories pour guerir
        if self.hero_calories <= 30:
            self.next_state = self.state_before_heal
            return 'STAY'

        hero_loc = get_hero_pos(self.game)
        if self.drink_loc is None:
            drink_tile, self.drink_loc = self.pathfinder.get_closest_drink(
                hero_loc)
        direction = get_direction(self.game, self.drink_loc)

        print("Healing time! drink pos: {}".format(self.drink_loc))
        if (self.pathfinder.get_distance(self.drink_loc, hero_loc) <= 1) \
                or (self.hero_health == 100):
            print("drink acquired")
            self.drink_loc = None
            self.min_heal -= (100 - self.hero_health)
            if self.min_heal < 30:
                self.min_heal = 30
            self.next_state = self.state_before_heal

        return direction

    def goto_customer(self):
        direction = get_direction(self.game, self.customer_loc)
        hero_loc = get_hero_pos(self.game)
        if self.pathfinder.get_distance(self.customer_loc, hero_loc) <= 1:
            self.customer = None
            self.customer_loc = None
            self.next_state = self.get_fries

        return direction

    def opportunity(self):
        direction = self.check_for_opportunity('Stay')

        # Transition d'etat
        if get_hero_fries(self.game) < self.customer.french_fries:
            self.next_state = self.get_fries
        elif get_hero_burgers(self.game):
            self.next_state = self.get_burgers
        else:
            self.next_state = self.goto_customer

        # Retourne mouvement
        if direction:
            return direction
        else:
            return 'Stay'

    def check_for_opportunity(self, direction):
        cardinal_directions = ['WEST', 'EAST', 'NORTH', 'SOUTH']
        hero_loc = get_hero_pos(self.game)

        for dir in cardinal_directions:
            destination = self.game.board.to(hero_loc, direction)
            row, col = destination
            tile = self.game.board.tiles[row][col]

            print("Direction choisi: {} -- opportunite: {}".format(
                type(direction), type(dir)))
            if direction != dir and (isinstance(tile, FriesTile)
                                     or isinstance(tile, BurgerTile)):

                owner_id = tile.hero_id
                if owner_id == '-':
                    owner_id = '-1'
                if int(owner_id) != get_our_hero_id(self.game):
                    return dir
Beispiel #27
0
def main() -> None:
    drawing = """
#####
#..E#
#...#
#...#
#S#.#
#.#.#
#####
""".strip()
    maze = Maze(drawing)
    #
    pf = Pathfinder(maze)
    # pf.show()
    start = Point(x=1, y=4)
    end = Point(x=3, y=1)
    pf.set_start_point(start)
    pf.set_end_point(end)
    # pf.show_maze_with_distance_values()
    pf.start_bfs_discovery()
    pf.show_maze_with_distance_values()
    path = pf.find_shortest_path()
    print(path)
Beispiel #28
0
class RedAiPilot(Agent):
    """Controls the behaviors of the red rectangle in the game

    RedAiPilot's decisions are based on its current_behavior state. The state is determined by the conditions of its
    environment. A full list of behaviors can be found at the bottom of the red_ai_pilot module in the
    PilotAgentBehavior class."""
    def __init__(self, environment=None):
        """sets up details about the red rectangle as well as variables for A.I. behavior"""
        super(RedAiPilot, self).__init__("red_ai_pilot", environment)
        self.bot = Bot()
        # set the rectangle's color
        self.bot.image.fill(RED)
        # set the starting position
        self.bot.rect.x = RECTANGLE_STARTING_X
        self.bot.rect.y = RECTANGLE_STARTING_Y
        # place the coordinates of our rectangle in a tuple to update the game manager
        self.red_coordinate = (self.bot.rect.x, self.bot.rect.y)
        self.rect = self.bot.rect

        # these coordinates tell the agent how far away the blue player is
        self.blue_coordinate = None
        self.distance_from_blue_player = 0
        self.current_position = 0

        self.path_course = []
        self.path_found = False
        self.next_node_coordinates = None

        # variables for A.I. behavior
        self.winning = False

        self.current_behavior = PilotAgentBehavior.FINDING_PATH
        self.pathfinder = Pathfinder()

    def act_out_decision(self):
        if self.current_behavior == PilotAgentBehavior.FINDING_PATH:
            self.path_course = self.pathfinder.find_path(self.blue_coordinate)
            self.path_found = True
            self.next_node_coordinates = (self.path_course[0].x,
                                          self.path_course[0].y)
        if self.current_behavior == PilotAgentBehavior.CHASING:
            if not self.path_course:
                self.path_found = False
                return
            self.find_next_node()
            self.move_to_next_node()
        if self.current_behavior is PilotAgentBehavior.SHOOTING:
            self.determine_enemy_position()
            self.shoot()

    def check_distance_from_opponent(self):
        self.update_coordinates()
        self.distance_from_blue_player = \
            abs(self.blue_coordinate[0] - self.red_coordinate[0]) + abs(self.blue_coordinate[1] - self.red_coordinate[1])

    def determine_behavior(self):
        self.check_distance_from_opponent()
        if self.distance_from_blue_player > 100 and self.bot.hit_points > 50:
            if not self.path_found:
                self.current_behavior = PilotAgentBehavior.FINDING_PATH
            else:
                self.current_behavior = PilotAgentBehavior.CHASING
        elif self.bot.hit_points > 50:
            self.current_behavior = PilotAgentBehavior.SHOOTING
        else:
            self.current_behavior = PilotAgentBehavior.FLEEING

    def determine_enemy_position(self):
        if self.red_coordinate[0] + MARGIN >= self.blue_coordinate[
                0] >= MARGIN - self.red_coordinate[0]:
            # red player is above blue player
            if self.red_coordinate[1] < self.blue_coordinate[1] - MARGIN:
                self.current_position = PilotCurrentPosition.ABOVE

            # red player is below blue player
            elif self.red_coordinate[1] > self.blue_coordinate[1] + MARGIN:
                self.current_position = PilotCurrentPosition.BELOW

            elif self.red_coordinate[0] > self.blue_coordinate[0]:
                self.current_position = PilotCurrentPosition.RIGHT

            elif self.red_coordinate[0] < self.blue_coordinate[0]:
                self.current_position = PilotCurrentPosition.LEFT

    def find_next_node(self):
        if not (1 <= abs(self.rect.centerx - self.next_node_coordinates[0]) or
                1 <= abs(self.rect.centery - self.next_node_coordinates[1])):
            self.path_course.pop(0)
            if self.path_course:
                self.next_node_coordinates = (self.path_course[0].x,
                                              self.path_course[0].y)

    def is_healthy(self):
        return self.hit_points > 50

    def make_decision(self):
        self.determine_behavior()
        self.act_out_decision()

    def move_to_next_node(self):

        if self.next_node_coordinates[0] < self.rect.centerx:
            self.bot.move(-2, 0)
        elif self.next_node_coordinates[0] > self.rect.centerx:
            self.bot.move(2, 0)

        # up and down
        if self.next_node_coordinates[1] < self.rect.centery:
            self.bot.move(0, -2)
        elif self.next_node_coordinates[1] > self.rect.centery:
            self.bot.move(0, 2)

    def setup_bot_map(self):
        self.bot.wall_list = self.environment.get_object("wall_list")

    def shoot(self):
        if self.bot.reloaded():
            bullet_list = self.environment.get_object("bullet_list")
            if self.current_position == PilotCurrentPosition.LEFT:
                bullet_list.add(self.bot.shoot_right())
            elif self.current_position == PilotCurrentPosition.RIGHT:
                bullet_list.add(self.bot.shoot_left())
            elif self.current_position == PilotCurrentPosition.ABOVE:
                bullet_list.add(self.bot.shoot_down())
            elif self.current_position == PilotCurrentPosition.BELOW:
                bullet_list.add(self.bot.shoot_up())

    def update_coordinates(self):
        self.red_coordinate = (self.rect.x, self.rect.y)
        self.blue_coordinate = self.ask("blue_player_pilot", "blue_coordinate")
Beispiel #29
0
def run_async():
    map = [
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
        [0, 0, 1, 0, 0, 0, 0, 0, 2, 0],
        [0, 0, 1, 1, 1, 0, 0, 2, 0, 0],
        [0, 0, 0, 1, 1, 0, 2, 0, 0, 2],
        [0, 0, 0, 0, 1, 0, 0, 0, 0, 2],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    ]

    walkable = lambda v: v != 2

    paths = [
        ((0, 0), (8, 8)),
        ((0, 0), (3, 5)),
        ((1, 0), (1, 8)),
        ((0, 0), (8, 8)),
        ((0, 0), (8, 8)),
        ((0, 0), (8, 8)),
        ((0, 0), (8, 8)),
        ((0, 0), (8, 8)),
        ((0, 0), (8, 8)),
        ((0, 0), (8, 8)),
        ((0, 0), (8, 8)),
        ((0, 0), (8, 8)),
        ((0, 0), (8, 8)),
        ((0, 0), (8, 8)),
    ] * 100
    agent_size = 2

    with timewith():
        grid = Grid(map)
        finder = Pathfinder(astar.search, heuristic=cardinal_intercardinal)
        grid.annotate(walkable)

        # Compute all the paths serially
        computed_paths = []
        for start, end in paths:
            computed_paths.append(
                finder.get_path(start[0], start[1], end[0], end[1],
                                agent_size))

    assert len(computed_paths) == len(paths)

    # Multithreaded version. It should take almost the same as the previous one (or more due to overhead of threads)
    # since computing the path is a purely CPU bound operation.
    # Node: The options IS NOT threadsafe
    class PathFinderLocal(threading.local):
        def __init__(self):
            print("Initializing local")
            local_grid = Grid(map)
            local_grid.annotate(walkable)
            self.finder = Pathfinder(astar.search,
                                     heuristic=cardinal_intercardinal)

    local_finder = PathFinderLocal()

    with timewith():
        with ThreadPoolExecutor(max_workers=5) as executor:

            def _(path_to_do):
                return local_finder.finder.get_path(
                    path_to_do[0][0],
                    path_to_do[0][1],
                    path_to_do[1][0],
                    path_to_do[1][1],
                    agent_size,
                )

            computed_paths = executor.map(_, paths)

    assert len(list(computed_paths)) == len(paths)
Beispiel #30
0
 def __init__(self):
     print("Initializing local")
     local_grid = Grid(map)
     local_grid.annotate(walkable)
     self.finder = Pathfinder(astar.search,
                              heuristic=cardinal_intercardinal)
Beispiel #31
0
class FileManager(cmd.Cmd):
    def __init__(self):
        super().__init__()
        # Из cfg.txt считывается рабочая директория,
        # за пределы которой выйти будет нельзя
        with open('cfg.txt') as f:
            root = f.readline()
        # Создается объект, преобразующий ввод в полноценные пути
        # Он получает на вход рут, и вернет код ошибки, если его покинуть
        self.pathfinder = Pathfinder(root)

    # Приветствие при запуске
    intro = 'Welcome to Fima file manager.   Type help or ? to list commands.\n'
    # Приглашение к вводу
    prompt = '(Fima) '

    # Метод, предварительно обрабатывающий ввод
    def precmd(self, line):
        # Если ввод - это просьба о помощи, она просто передается дальше
        if line[:4] == 'help' or line[0] == '?':
            return line
        # Если другая команда - из аргументов делаются абсолютные пути
        # Таким образом проверяется, не пытается ли пользователь
        # выйти за границы своих возможностей
        args = line.split(' ')
        try:
            args = args[0] + ' ' + ' '.join(map(self.pathfinder.make_path, args[1:]))
        except EnvironmentError:
            # Когда pathfinder возвращает код ошибки, пользовательский ввод
            # превращается в команду, вызывающую сообщение о отсутствии прав доступа
            return 'oos'
        else:
            return args

    def do_oos(self, arg):
        'Punishes you for leaving a root tree'
        print('Access denied!')

    def do_pwd(self, arg):
        'Print working directory: pwd'
        print(self.pathfinder.working_directory)

    def do_lsd(self, arg):
        'List of all files and directories in current directory:\n\tlsd'
        print('\n'.join(list_dir(self.pathfinder.working_directory)))

    def do_chd(self, destination):
        'Change working directory:\n\tchd myDir'
        print(self.pathfinder.change_wd(destination))

    def do_crd(self, name):
        'Create a new directory:\n\tcrd myDir'
        print(create_dir(name))

    def do_rmd(self, name):
        'Remove a directory:\n\trmd myDir'
        print(remove_dir(name))

    def do_crf(self, name):
        'Create a new file:\n\tcrf myFile'
        print(create_file(name))

    def do_rmf(self, name):
        'Remove a file:\n\trmf myFile'
        print(remove_file(name))

    def do_wtf(self, arg):
        'Write to file:\n\twtf myFile'
        print(write_to_file(arg))

    def do_rdf(self, arg):
        'Read a file:\n\trdf myFile'
        print(read_file(arg))

    def do_cpf(self, args):
        'Copy a file:\n\tcpf srcFile destFile'
        print(copy_file(*args.split(' ')))

    def do_mvf(self, args):
        'Move a file:\n\tmvf srcFile destFile'
        print(move_file(*args.split(' ')))

    def do_exit(self, arg):
        'Exit file manager:\n\texit'
        print('Thank you for using Fima')
        return True
Beispiel #32
0
import pygame
import sys
import random

from map import Map
from visualiser import Visualiser
from pathfinder import Pathfinder

map = Map()
map.loadData()

visualiser = Visualiser("Inlupp 2 - Visualiser", map.getWidth(),
                        map.getHeight())
visualiser.setMap(map)

pathfinder = Pathfinder(visualiser, map)
pathfinder.findCheapestPath()

visualiser.runLoop()
Beispiel #33
0
from map import Map, load_map
from pathfinder import Pathfinder

map_40 = load_map()
start = 8
goal = 27
pathfinder = Pathfinder(map_40, start, goal)
path = pathfinder.path

map_40.draw(path)