Beispiel #1
0
 def test_find_path(self):
     path = pathfinding.find_path(self.board_grid, self.node_a, self.node_g)
     self.assertEqual([
         self.node_a, self.node_b, self.node_d, self.node_e, self.node_f,
         self.node_g
     ], path)
     self.board_grid.insert_path(path)
Beispiel #2
0
def find_food(board, board_grid, head):
    food_paths = []
    # Run pathfinding algorithm on every food point and pick the shortest one
    for food in board["food"]:
        path = pathfinding.find_path(board_grid, board_grid.grid[head["y"]][head["x"]],
                                     board_grid.grid[food["y"]][food["x"]])
        if path is not None:
            food_paths.append(path)

    board_grid.insert_paths(food_paths)

    print(f"Current certainty after food:")
    board_grid.printGridCertainty()
    def move_to(self, tk_event):
        ''' Sets a path to follow to the given destination coordinates '''

        click_coords = (tk_event.x // self.tile_width,
                        tk_event.y // self.tile_height)

        self.dest_path = pathfinding.find_path(
            self.game_map.get_node((self.x_coord, self.y_coord)),
            self.game_map.get_node(click_coords), self.game_map)

        self.game_map.set_dest_node(click_coords)

        # Resest random path counter
        self.random_path_counter = 0
Beispiel #4
0
async def update_player(player):
    player.spawn_timer -= 1
    if player.target is not None and player.spawn_timer <= 0:
        player.spawn_timer = entities.SPAWN_INTERVAL

        castle = castles[player.name]
        enemy_castle = castles[player.target]

        # TODO: find optimal side to spawn on given target
        spawn_x = castle.x
        spawn_y = castle.y + 2

        minion = entities.Entity(spawn_x, spawn_y, "minion", player.name)
        board_add_entity(minion)
        path = pathfinding.find_path((spawn_x, spawn_y),
                                     (enemy_castle.x, enemy_castle.y),
                                     is_obstructed)
        minions[minion.uid] = path[1:]

        await broadcast_message('entity_created', minion.to_list())
Beispiel #5
0
    lines.append(line)


def find_pos(pos):
    for row, line in enumerate(lines):
        if pos in line:
            return line.index(pos), row


def passable(src, dst):
    return lines[dst[1]][dst[0]] != '#'


checkpoints = []
for c in input:
    if c.isdigit() and c != '0':
        checkpoints.append(find_pos(c))

find_path = lru_cache()(find_path)
route_lenths = []
for route in itertools.permutations(checkpoints):
    pos = find_pos('0')
    route_length = 0
    route = list(route) + [pos]
    for checkpoint in route:
        route_length += len(find_path(pos, checkpoint, passable)) - 1
        pos = checkpoint
    route_lenths.append(route_length)

print(min(route_lenths))
Beispiel #6
0
for line in input.split('\n')[2:]:
    node = Node(line)
    nodes[node.x, node.y] = node

width = max(nodes.values(), key=lambda node: node.x).x + 1
height = max(nodes.values(), key=lambda node: node.y).y + 1
empty_node = [node for node in nodes.values() if node.used == 0][0]

goal = width - 1, 0
next_goal = None


def passable(src, dst):
    if dst[0] < 0 or dst[1] < 0 or dst[0] >= width or dst[1] >= height:
        return False
    if dst == goal and src != next_goal:
        return False
    if nodes[dst].size < nodes[src].used:
        return False
    return True


goal_path = find_path(goal, (0, 0), passable)
empty = empty_node.x, empty_node.y
move_count = 0
for goal, next_goal in zip(goal_path, goal_path[1:]):
    path = find_path(empty, goal, passable)
    empty = goal
    move_count += len(path) - 1
print(move_count)
    def _update(self):
        ''' Updates the player's state, moving the character along a path if it has one '''

        if len(self.dest_path) != 0 and not self.moving:
            self.current_dest = self.dest_path.pop()

            if self.current_dest.is_passable():
                self.moving = True
                self.recalc_counter += 1

            else:
                if len(self.dest_path) != 0:
                    self.dest_path = pathfinding.find_path(
                        self.game_map.get_node(self.get_position()),
                        self.dest_path.popleft(), self.game_map)

                else:
                    self.current_dest = self.game_map.get_node(
                        self.get_position())

                self.recalc_counter = 0

        elif self.moving:
            # Move NE
            if self.x < self.current_dest.get_x() * self.tile_width + (self.tile_width // 2) - self.size * self.tile_width // 2 and \
            self.y > self.current_dest.get_y() * self.tile_height + (self.tile_height // 2) - self.size * self.tile_height // 2:
                self.x_offset += self.speed * self.tile_width
                self.y_offset -= self.speed * self.tile_height

            # Move NW
            elif self.x > self.current_dest.get_x() * self.tile_width + (self.tile_width // 2) - self.size * self.tile_width // 2 and \
            self.y > self.current_dest.get_y() * self.tile_height + (self.tile_height // 2) - self.size * self.tile_height // 2:
                self.x_offset -= self.speed * self.tile_width
                self.y_offset -= self.speed * self.tile_height

            # Move SE
            elif self.x < self.current_dest.get_x() * self.tile_width + (self.tile_width // 2) - self.size * self.tile_width // 2 and \
            self.y < self.current_dest.get_y() * self.tile_height + (self.tile_height // 2) - self.size * self.tile_height // 2:
                self.x_offset += self.speed * self.tile_width
                self.y_offset += self.speed * self.tile_height

            # Move SW
            elif self.x > self.current_dest.get_x() * self.tile_width + (self.tile_width // 2) - self.size * self.tile_width // 2 // 2 and \
            self.y < self.current_dest.get_y() * self.tile_height + (self.tile_height // 2) - self.size * self.tile_height // 2:
                self.x_offset -= self.speed * self.tile_width
                self.y_offset += self.speed * self.tile_height

            # Move E
            elif self.x < self.current_dest.get_x() * self.tile_width + (
                    self.tile_width // 2) - self.size * self.tile_width // 2:
                self.x_offset += self.speed * self.tile_width

            # Move W
            elif self.x > self.current_dest.get_x() * self.tile_width + (
                    self.tile_width // 2) - self.size * self.tile_width // 2:
                self.x_offset -= self.speed * self.tile_width

            # Move S
            elif self.y < self.current_dest.get_y() * self.tile_height + (
                    self.tile_height // 2) - self.size * self.tile_height // 2:
                self.y_offset += self.speed * self.tile_height

            # Move N
            elif self.y > self.current_dest.get_y() * self.tile_height + (
                    self.tile_height // 2) - self.size * self.tile_height // 2:
                self.y_offset -= self.speed * self.tile_height

            if (abs(self.current_dest.get_x() * self.tile_width +
                    (self.tile_width // 2) - self.size * self.tile_width // 2 -
                    self.x) <= (self.speed * self.tile_width)
                    and abs(self.current_dest.get_y() * self.tile_height +
                            (self.tile_height // 2) -
                            self.size * self.tile_height // 2 - self.y) <=
                (self.speed * self.tile_height)):

                self.x_offset = 0
                self.y_offset = 0

                self.moving = False

                self.x_coord = self.current_dest.get_x()
                self.y_coord = self.current_dest.get_y()

                if self.recalc_counter == self.RECALC_COUNT:
                    self.recalc_counter = 0
                    if len(self.dest_path) != 0:
                        self.dest_path = pathfinding.find_path(
                            self.game_map.get_node(self.get_position()),
                            self.dest_path.popleft(), self.game_map)

        else:
            self.recalc_counter = 0
Beispiel #8
0
import os

from graphics import draw_map
from grid import Grid
from pathfinding import find_path, ALGORITHMS


if __name__ == "__main__":
    dir_name = os.getcwd()
    for filename in os.listdir(os.path.join(dir_name, 'boards')):
        for algorithm in ALGORITHMS:
            grid = Grid(os.path.join(dir_name, 'boards', filename))

            image_name = filename.replace('.txt', '-{}.png'.format(algorithm))
            image_path = os.path.join(dir_name, "report", "img", image_name)

            draw_map(grid, image_path, *find_path(grid, algorithm))
            print "Wrote {}".format(image_name)
Beispiel #9
0
draw_everything()

# main game loop
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif (event.type == MOUSEBUTTONDOWN) and game_state is not RUNNING:
            if event.button == 1:
                mouse_x, mouse_y = event.pos
                for button in buttons:
                    if (button.square.x <= mouse_x <= button.square.x2) and (
                            button.square.y <= mouse_y <= button.square.y2):
                        path = find_path(map_tiles, map_tiles[0][0])
                        if game_state is BUILD_TOWER:
                            game_state = BUILD_WALLS
                        elif game_state is BUILD_WALLS:
                            game_state = RUNNING
                for row in map_tiles:
                    for tile in row:
                        if (tile.square.x <= mouse_x <= tile.square.x2) and (
                                tile.square.y <= mouse_y <= tile.square.y2):
                            if game_state is BUILD_WALLS:
                                if tile.typeTyle == FLOOR:
                                    tile.change_type(WALL)
                                else:
                                    tile.change_type(FLOOR)
                            elif game_state is BUILD_TOWER:
                                if tower:
Beispiel #10
0
import os

from graphics import draw_map
from grid import Grid
from pathfinding import find_path, ALGORITHMS

if __name__ == "__main__":
    dir_name = os.getcwd()
    for filename in os.listdir(os.path.join(dir_name, 'boards')):
        for algorithm in ALGORITHMS:
            grid = Grid(os.path.join(dir_name, 'boards', filename))

            image_name = filename.replace('.txt', '-{}.png'.format(algorithm))
            image_path = os.path.join(dir_name, "report", "img", image_name)

            draw_map(grid, image_path, *find_path(grid, algorithm))
            print "Wrote {}".format(image_name)
Beispiel #11
0
import os

from GUI import draw_map
from board import Board
from pathfinding import find_path, ALGORITHMS


if __name__ == "__main__":
    dir_name = os.getcwd()
    for filename in os.listdir(os.path.join(dir_name, "boards")):
        for algorithm in ALGORITHMS:
            board = Board(os.path.join(dir_name, "boards", filename))

            image_name = filename.replace(".txt", "-{}.png".format(algorithm))
            image_path = os.path.join(dir_name, "report", "img", image_name)

            draw_map(board, image_path, *find_path(board, algorithm))
            print "Wrote {}".format(image_name)
Beispiel #12
0
def recalculate_minion_paths():
    for minion_id in minions.keys():
        start = minions[minion_id][0]
        end = minions[minion_id][-1]
        path = pathfinding.find_path(start, end, is_obstructed)
        minions[minion_id] = path
Beispiel #13
0
    def update(self, dt):
        tile = self._world.tiles[self.current_location]
        if self.current_location == self.orders:
            done = True
            if tile.type in DIGGABLE_TYPES:
                done = tile.work_on(dt, TileType.GROUND)
            elif tile.type == TileType.GROUND:
                done = tile.work_on(dt, TileType.ROAD)
            elif tile.type == TileType.WATER:
                done = tile.work_on(dt, TileType.WATER)

            if done:
                self.orders = None
            return

        # If we're tracking a resource, try to pick it up
        elif isinstance(
                self.orders, Resource
        ) and self.current_location == self.orders.location and not self.inventory:
            self._world.resources.remove(self.orders)
            self.inventory = self.orders
            self.path = find_path(self._world, self.current_location,
                                  self._world.base.location)
            if not self.path:
                self.orders = None
                self.inventory = None
                print("We lost a resource forever")
            return

        # Deposit items into the base
        elif self.inventory and self.current_location == self._world.base.location:
            self._world.base.add_item(self.inventory)
            self.inventory = None
            self.orders = None
            return

        # If idle, look for something to do
        if not self.path and not self.orders:
            if self._world.orders:
                # TODO: Prioritize orders by proximity and priority level
                tile = self._world.orders.pop()
                self.path = find_path(self._world, self.current_location, tile)
                if not self.path:
                    self._world.orders.add(tile)
                else:
                    self.orders = tile
            # Try to get a resource
            elif self._world.resources:
                other_orders = {
                    w.orders
                    for w in self._world.workers if w is not self
                }
                targets = [
                    w for w in self._world.resources if w not in other_orders
                ]
                if targets:
                    res = targets[0]
                    self.path = find_path(self._world, self.current_location,
                                          (res.x // 16, res.y // 16))
                    self.orders = res
            return
        elif not self.path and self.orders:
            print("Uh oh, orders were", self.orders)
            self.orders = None
            return

        # Otherwise, just follow the path
        dx = self.path[0][0] * 16 - self.x
        dy = self.path[0][1] * 16 - self.y
        speed = self.speed / TILE_COSTS[tile.type]
        if self.current_location == self.path[0]:
            self.path.pop(0)
            self.update(dt)  # recurse
            return
        # Movement
        elif abs(dx) >= 1 and abs(dx) > abs(dy):
            self.x += speed * math.copysign(1, dx) * dt
        elif abs(dy) >= 1 and abs(dy) > abs(dx):
            self.y += speed * math.copysign(1, dy) * dt

        # If there's an inventory, move it too
        if self.inventory:
            self.inventory.x = self.x
            self.inventory.y = self.y