Example #1
0
 def test_neighbours_origin(self):
     maze = Maze()
     length = randint(1, 10)
     maze.set_board([[Cell(i, j, False) for i in range(length)]
                     for j in range(length)])
     neighbours_to_origin = maze.get_cell_neighbours(0, 0)
     self.assertEqual(2, len(neighbours_to_origin))
Example #2
0
 def test_neighbours_center(self):
     maze = Maze()
     length = randint(1, 10)
     maze.set_board([[Cell(i, j, False) for i in range(length)]
                     for j in range(length)])
     neighbours_to_center = maze.get_cell_neighbours(1, 1)
     self.assertEqual(4, len(neighbours_to_center))
Example #3
0
 def test_get_status_GENERATING(self):
     maze = Maze()
     length = randint(1, 10)
     maze.set_board([[Cell(i, j, False) for i in range(length)]
                     for j in range(length)])
     maze.set_track({maze.get_cell(0, 0): []})
     maze.set_cell_value(0, 0, True)
     self.assertEqual(MazeStatus.GENERATING, maze.get_status())
Example #4
0
def main():
    print("URL:{}".format(url))
    with grpc.insecure_channel(url) as channel:
        stub = maze_pb2_grpc.MazeStub(channel)
        response = stub.Gen(maze_pb2.GenRequest(w=97, h=45))
        print(response.field)
        m = Maze(response.field)
        m.renderMaze('maze.svg')
Example #5
0
    def create_maze(self):
        allPoints = [(x, y) for x in range(self.size)
                     for y in range(self.size)]
        sampled = random.sample(allPoints, self.num_of_obstacles + 2)
        start = sampled[0]
        destination = sampled[1]
        obstacles = sampled[2:]

        self.maze = Maze(size=self.size,
                         start=start,
                         destination=destination,
                         obstacles=obstacles)
Example #6
0
 def test_get_status_READY(self):
     maze = Maze()
     length = randint(1, 10)
     maze.set_board([[Cell(i, j, True) for i in range(length)]
                     for j in range(length)])
     maze.set_track({maze.get_cell(0, 0): []})
     self.assertEqual(MazeStatus.READY, maze.get_status())
Example #7
0
 def test_break_wall(self):
     maze = Maze(width=2, height=1)
     self.assertSetEqual(maze.paths(0, 0), set())
     self.assertSetEqual(maze.paths(1, 0), set())
     maze.break_wall(0, 0, Compass.EAST)
     self.assertSetEqual(maze.paths(0, 0), {Compass.EAST})
     print(maze.paths(1, 0))
     self.assertSetEqual(maze.paths(1, 0), {Compass.WEST})
Example #8
0
def main(WIDTH, HEIGHT, SEARCHERS, RESCUERS, targets=5):
    manager = mp.Manager()
    searchm = manager.list()
    rescuem = manager.list()
    mazem = manager.list()
    comq = mp.Queue()

    m = Maze(WIDTH, HEIGHT, targets)
    print (type(mazem), type(m.maze))
    mazem[:] = m.maze
    m.maze = mazem
    display = GNUI(WIDTH, HEIGHT, "Map")
    display2 = GNUI(WIDTH, HEIGHT, "Maze")

    display.update(m.getMaze(), [])

    db = DatabaseAgent("[email protected]", "secret")
    db.width = WIDTH
    db.height = HEIGHT
    time.sleep(1)
    db.start()
    time.sleep(1)

    searchers = mp.Process(target=searchmanager, args=(SEARCHERS, searchm, comq, m))
    rescuers = mp.Process(target=rescuemanager, args=(RESCUERS, rescuem, comq, m))
    pf = mp.Process(target=pathmanager, args=(comq,))
    mothership = mp.Process(target=mothermanager, args=(comq,))

    pf.start()
    mothership.start()
    searchers.start()
    rescuers.start()

    try:
        for i in range(100000):
            display.update(db.map.getMap(), list(searchm), list(rescuem))
            display2.update(m.getMaze(), list(searchm), list(rescuem))
            time.sleep(0.1)

            if isReady(db.map.getMap(), rescuem):
                print ("FINISHED!")
                break
    except KeyboardInterrupt:
        pass
    except Exception, ex:
        print traceback.format_exc()
Example #9
0
    def generate(self, dim):
        maze = Maze(dim)

        x = randrange(dim)
        y = randrange(dim)
        logging.debug("Chose (%s, %s) as initial cell", x, y)

        stack = [(x, y)]
        maze.get(x, y).visited = True

        self.initbar(dim*dim)
        i = 0
        while len(stack) > 0:
            cursearch = stack[-1]
            randdirs = Direction.randdirs()

            foundnext = False
            for dir in randdirs: # search for a new cell to explore
                candidate = maze.getbydir(cursearch[0], cursearch[1], dir)
                if candidate is not None and not candidate.visited: # new explorable cell found
                    maze.connect(cursearch[0], cursearch[1], dir) # create path between current and new cell
                    candidate.visited = True # set new node as visited
                    stack.append((candidate.x, candidate.y))# set new cell as next explorable node
                    foundnext = True
                    i += 1
                    self.updatebar(i)
                    break
            if not foundnext:
                stack.pop()
        # set all cells as unvisited
        for x in range(dim):
            for y in range(dim):
                maze.get(x, y).visited = False
        self.finishbar()
        return maze
Example #10
0
def path_finder(maze):
    maze = maze.split('\n')
    maze = Maze(maze)
    G = maze.get_graph_from_maze()

    color = {i: "white" for i in G.keys()}
    pred = {i: None for i in G.keys()}
    cc = {i: None for i in G.keys()}
    cc_num = [0]
    dfs(G, color, pred, cc, cc_num)

    start_idx = 0
    exit_idx = maze.n * maze.m - 1

    if start_idx not in G.keys() or exit_idx not in G.keys():
        return False
    elif cc[start_idx] != cc[exit_idx]:
        return False
    else:
        return True
Example #11
0
    def __init__(self):
        pygame.init()

        self.is_dog = False
        self.screen = pygame.display.set_mode(self.size)
        self.screen.fill(BACKGROUND_COLOR)
        self.clock = Clock()

        self.tiles = Tiles()

        self.generator = MazeGenerator(MAZE_WIDTH, MAZE_HEIGHT)
        self.maze = Maze(self.tiles)

        self.mouse_tile, *self.mouse_recs = self.tiles.mice
        self.game_state = GameState(self.tiles)

        self.clear_tiles = list()
        self.mouse = None
        self.cats = None
        self.dog = None
        self.cheese = None
        self.bones = None

        self.level = 0
Example #12
0
    def generate(self, dim):
        maze = Maze(dim)

        x = randrange(dim)
        y = randrange(dim)
        logging.debug("Chose (%s, %s) as initial cell", x, y)

        explorablenodes =[(x, y)]
        maze.get(x, y).visited = True

        self.initbar(dim*dim)
        i = 0
        while len(explorablenodes) > 0:
            cursearch = explorablenodes[randrange(len(explorablenodes))]
            randdirs = Direction.randdirs()

            foundNext = False
            for dir in randdirs: # search for a new cell to explore
                candidate = maze.getbydir(cursearch[0], cursearch[1], dir)
                if candidate is not None and not candidate.visited:
                    maze.connect(cursearch[0], cursearch[1], dir)
                    candidate.visited = True
                    if maze.explorables(candidate.x, candidate.y) > 0:
                        explorablenodes.append((candidate.x, candidate.y))
                    foundNext = True
                    i += 1
                    self.updatebar(i)
                    break
            if not foundNext:
                explorablenodes.remove(cursearch)
        # set all cells as unvisited
        for x in range(dim):
            for y in range(dim):
                maze.get(x, y).visited = False
        self.finishbar()
        return maze
Example #13
0
from maze.maze import Maze
from gnui.gnui import GNUI
from agents.search import SearchAgent
from agents.db import DatabaseAgent
from agents.mothership import Mothership
from agents.pathfinder import PathFinder
from agents.display import DisplayAgent
from agents.rescuer import RescueAgent

WIDTH  = 32
HEIGHT = 16
SEARCHERS = range(3)
RESCUERS  = range(3)

if __name__ == "__main__":
    m = Maze(WIDTH, HEIGHT)
    display = GNUI(WIDTH, HEIGHT)

    display.update(m.getMaze(), [])

    da = DisplayAgent("[email protected]", "secret")
    da.start()

    try:
        print "Starting searchers"
        search = [SearchAgent("search{}@127.0.0.1".format(i), "secret")
                for i in SEARCHERS]
        for s in search:
            s.setMaze(m)
        print "Starting rescuers"
        rescue = [RescueAgent("rescue{}@127.0.0.1".format(i), "secret")
Example #14
0
 def test_maze_has_2x2_center(self):
     maze = Maze(width=6, height=6)
     self.assertSetEqual(maze.paths(2, 2), {Compass.SOUTH, Compass.EAST})
     self.assertSetEqual(maze.paths(3, 2), {Compass.SOUTH, Compass.WEST})
     self.assertSetEqual(maze.paths(3, 3), {Compass.NORTH, Compass.WEST})
     self.assertSetEqual(maze.paths(2, 3), {Compass.NORTH, Compass.EAST})
Example #15
0
 def test_maze_paths(self):
     maze = Maze(width=1, height=1)
     maze._grid[0][0] = Compass.NORTH | Compass.WEST
     self.assertEqual(maze.paths(0, 0), {Compass.SOUTH, Compass.EAST})
Example #16
0
from maze.maze import Maze
from gnui.gnui import GNUI
from map.map import Map
from astar.astar import Astar

import numpy as np

import time

originalMap = Maze(32, 16)
display = GNUI(32, 16)
pathPlanner = Astar()

print originalMap.getData(1, 1)

print np.array(originalMap.getMaze())


display.update(originalMap.getMaze(), [(1, 1)])


time.sleep(2)
Example #17
0
 def setUp(self) -> None:
     grid = np.array([[], []])
     self.maze = Maze(grid, (0, 0), (10, 12))
     self.solver = MazeSolver(self.maze)
     pass
Example #18
0
 def test_init(self):
     maze = Maze(2)
     self.assertEqual(maze.dim, 2)
     self.assertEqual(maze.grid.shape, (3, 3))
Example #19
0
import os
from maze.maze import Maze

if __name__ == "__main__":
    os.system('cls')
    maze = Maze(25, 10, 6)
Example #20
0
 def test_connect_east(self):
     maze = Maze(2)
     maze.connect(0, 0, Direction.EAST)
     self.assertEqual(maze.get(0, 0).walls[Direction.EAST], False)
     self.assertEqual(maze.get(1, 0).walls[Direction.WEST], False)
Example #21
0
 def test_get(self):
     maze = Maze(2)
     maze.grid[1, 0].visited = True
     self.assertEqual(maze.get(0, 0).visited, False)
     self.assertEqual(maze.get(1, 0).visited, True)
Example #22
0
class MazeBuilderWithRandomStart(Builder):
    """
    Builder getting the maze as input and setting the starting and finishing points, initializing the board of the maze
    and building the maze.
    """
    def __init__(self):
        self._maze = Maze()

    @property
    def maze(self):
        return self._maze

    def init_board(self, width, height):
        if width < 1 or height < 1:
            raise MazeBuilderException(
                "Width and Height must be superior to 1")
        self._maze.set_board([[Cell(i, j, False) for i in range(width)]
                              for j in range(height)])
        self._maze.set_start(randint(0, width - 1), randint(0, height - 1))

    def build(self):
        """
        The maze is built according to the following principle: for each point a random neighbour is selected and stored.
        While all points have not been seen, we continue. When we arrive to a point having all its neighbours selected,
        we get back to the most recent point having unseen neighbours. The finish point is selected randomly among
        these points
        :return: Map all cells with their natural children in the maze
        """
        parcours = []
        possible_finishes = []
        current_cell = self._maze.get_start()
        self._maze.set_cell_value(current_cell.x, current_cell.y, True)
        start_time = time.time()
        parcours.append(current_cell)
        track = self._maze.get_track()
        while self._maze.get_status() != MazeStatus.READY:
            current_cell_neighbours = self._maze.get_cell_neighbours(
                current_cell.x, current_cell.y)
            if len(current_cell_neighbours) > 0:
                direction, selected_neighbour = choice(
                    list(current_cell_neighbours.items()))
                self._maze.set_cell_value(selected_neighbour.x,
                                          selected_neighbour.y, True)
                possible_track_from_cell = track.get(current_cell, [])
                possible_track_from_cell.append(selected_neighbour)
                track[current_cell] = possible_track_from_cell
                current_cell.next.append(direction)
                current_cell = selected_neighbour
                parcours.append(current_cell)
            else:
                if parcours:
                    current_cell = parcours.pop()
                    possible_finishes.append(current_cell)
                    if not self._maze.get_finish():
                        self._maze.set_finish(current_cell.x, current_cell.y)
        if parcours and not self._maze.get_finish():
            pop_item = parcours.pop()
            possible_finishes.append(pop_item)
        selected_finish = choice(possible_finishes)
        self._maze.set_finish(selected_finish.x, selected_finish.y)
        print("Maze generated in --- %s seconds ---" %
              (time.time() - start_time))
        self._maze.set_track(track)
        self._maze.display_with_graph()
        return track
Example #23
0
 def __init__(self):
     self._maze = Maze()
Example #24
0
class genetic_runner:
    def __init__(self, size, num_of_obstacles=0):
        self.num_of_obstacles = num_of_obstacles
        self.size = size
        self.create_maze()
        self.generation_min = []
        self.generation_avg = []
        self.generation_max = []
        self.fitness_dict = {}

    def create_maze(self):
        allPoints = [(x, y) for x in range(self.size)
                     for y in range(self.size)]
        sampled = random.sample(allPoints, self.num_of_obstacles + 2)
        start = sampled[0]
        destination = sampled[1]
        obstacles = sampled[2:]

        self.maze = Maze(size=self.size,
                         start=start,
                         destination=destination,
                         obstacles=obstacles)

    def run(self):
        result = self.run_generations()
        return result

    def fitness_value(self, chromosome):
        stats = self.maze.walk_maze(chromosome)[0]
        cost = stats.steps * STEP_COST + \
               REPEAT_COST * stats.repeats + \
               stats.disFromDest ** DISTANCE_LEFT_EXPONENTIAL + \
               (0 if stats.disFromDest == 0 else UNSOLVED_COST)

        return 1 / cost

    def crossover(self, p1, p2):
        crossover_point = random.randint(0, CHROMOSOME_SIZE)
        return (p1[:crossover_point] + p2[crossover_point:],
                p2[:crossover_point] + p1[crossover_point:])

    def mutate(self, chromosome):
        mutate_point = random.randint(0, CHROMOSOME_SIZE - 1)
        mutation = chromosome[:mutate_point] + random_gene(
        ) + chromosome[mutate_point + 1:]
        return mutation

    def generate_generation(self, population, fitness_array):
        total_fitness = sum(fitness_array)
        roulette_array = [fitness / total_fitness for fitness in fitness_array]
        next_population = population[:ELITE_COUNT]

        while len(next_population) < POPULATION_IN_GENERATION:
            c1, c2 = npr.choice(population, 2, p=roulette_array)
            if random.random() < CROSSOVER_PCT:
                c1, c2 = self.crossover(c1, c2)

            if random.random() < MUTATE_PCT:
                c1, c2 = self.mutate(c1), self.mutate(c2)

            next_population.extend([c1, c2])

        # next_population, next_fitness_array = self.create_fitness_array_and_sort_population(population)
        self.update_fitness_dict(next_population)
        next_population.sort(key=lambda x: self.fitness_dict[x], reverse=True)
        next_fitness_array = [self.fitness_dict[x] for x in next_population]
        return (next_population, next_fitness_array)

    def run_generations(self):
        population, fitness_array = self.initiate_population()
        self.data_tracking(population, fitness_array)

        for generation in range(GENERATIONS_NUM):
            population, fitness_array = self.generate_generation(
                population, fitness_array)
            self.data_tracking(population, fitness_array)

            if self.check_if_convergence():
                break

        return population[0]

    def check_if_convergence(self):
        if len(self.generation_max) <= CONVERGENCE_GENERATIONS:
            return False
        else:
            last_generations_max = self.generation_max[
                -CONVERGENCE_GENERATIONS:]
            firstMax = last_generations_max[0]
            for mx in last_generations_max:
                if mx != firstMax:
                    return False

            return True

    def initiate_population(self):
        population = random_population()
        self.update_fitness_dict(population)
        fitness_array = [self.fitness_dict[x] for x in population]
        return (population, fitness_array)

    def data_tracking(self, generation, fitness_array):
        print(generation[0])
        self.generation_max.append(fitness_array[0])
        self.generation_avg.append(avg(fitness_array))
        self.generation_min.append(fitness_array[POPULATION_IN_GENERATION - 1])

    def update_fitness_dict(self, population):
        for chromosome in population:
            if chromosome not in self.fitness_dict:
                self.fitness_dict[chromosome] = self.fitness_value(chromosome)

    def showGraphs(self):
        # plotting the line 1 points
        plt.plot(self.generation_min, label="minimum fitness")
        plt.plot(self.generation_avg, label="average fitness")
        plt.plot(self.generation_max, label="maximum fitness")
        plt.xlabel('x - generation number')
        plt.ylabel('y - fitness')
        plt.title(
            'fitness of chromosomes in {} generations'.format(GENERATIONS_NUM))
        plt.legend()
        plt.figure()
Example #25
0
 def test_maze_dimensions(self):
     maze = Maze(width=3, height=2)
     self.assertEqual(len(maze._grid), 2)
     self.assertEqual(len(maze._grid[0]), 3)
Example #26
0
 def test_connect_south(self):
     maze = Maze(2)
     maze.connect(0, 0, Direction.SOUTH)
     self.assertEqual(maze.get(0, 0).walls[Direction.SOUTH], False)
     self.assertEqual(maze.get(0, 1).walls[Direction.NORTH], False)
Example #27
0
class MazeGame:
    play_game: bool
    maze: Maze
    mouse: Optional[Mouse]
    dog: Optional[Dog]
    cats: Optional[Cats]
    cheese: Optional[ItemGroup]
    bones: Optional[ItemGroup]

    game_state: GameState
    tiles: Tiles
    generator: MazeGenerator
    map: MazeMap
    mouse_tile: Surface
    mouse_recs: Tuple[Rect]

    size = BOARD_WIDTH, BOARD_HEIGHT
    background = Color(156, 102, 47)
    screen: Surface
    clock: Clock

    level: int
    is_dog: bool
    clear_tiles: List[Rect]

    def __init__(self):
        pygame.init()

        self.is_dog = False
        self.screen = pygame.display.set_mode(self.size)
        self.screen.fill(BACKGROUND_COLOR)
        self.clock = Clock()

        self.tiles = Tiles()

        self.generator = MazeGenerator(MAZE_WIDTH, MAZE_HEIGHT)
        self.maze = Maze(self.tiles)

        self.mouse_tile, *self.mouse_recs = self.tiles.mice
        self.game_state = GameState(self.tiles)

        self.clear_tiles = list()
        self.mouse = None
        self.cats = None
        self.dog = None
        self.cheese = None
        self.bones = None

        self.level = 0

    def title_screen(self):
        pass

    def new_level(self):
        self.level += 1
        self.map = self.generator.get_maze()
        self.maze.new_maze(self.map)

        if self.mouse is None:
            self.mouse = Mouse(self.map, self.tiles.mice, TheMouse)
        else:
            self.mouse.critter_reset(self.map)

        if self.cheese is None:
            self.cheese = ItemGroup(self.game_state, self.map, self.tiles.cheese, 1, 0)
        if self.bones is None:
            self.bones = ItemGroup(self.game_state, self.map, self.tiles.bone, 5, 1)
        if self.cats is None:
            self.cats = Cats(self.tiles, self.map, self.mouse)

        exclude_list = [Point(1, 1)]
        self.cheese.new_game(exclude_list, 50)
        self.bones.new_game(exclude_list, 6 + (4 * self.level))
        self.cats.reset(exclude_list, 5 + (5 * self.level))
        self.level = 0

    def title_loop(self):
        return True

    def game_over_loop(self):
        pass

    def game_loop(self):
        self.new_level()
        self.game_state.new_game()
        dog_counter = 0
        flash_counter = 0
        self.play_game = True
        while self.play_game:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

            if self.is_dog:
                dog_counter -= 1
                if dog_counter <= 0:
                    self.mouse.exit_dog(*self.dog.deactivate())

            keys = pygame.key.get_pressed()
            if self.is_dog:
                if keys[pygame.K_UP]:
                    self.mouse.move_up(self.map)
                elif keys[pygame.K_LEFT]:
                    self.mouse.move_left(self.map)
                elif keys[pygame.K_RIGHT]:
                    self.mouse.move_right(self.map)
                elif keys[pygame.K_DOWN]:
                    self.mouse.move_down(self.map)
            else:
                if keys[pygame.K_UP]:
                    self.mouse.move_up(self.map)
                elif keys[pygame.K_LEFT]:
                    self.mouse.move_left(self.map)
                elif keys[pygame.K_RIGHT]:
                    self.mouse.move_right(self.map)
                elif keys[pygame.K_DOWN]:
                    self.mouse.move_down(self.map)
                elif keys[pygame.K_SPACE]:
                    if self.game_state.bones > 0:
                        self.activate_dog()

            # Update mouse - returns False if mouse got ate

            self.update()
            self.screen.fill(BACKGROUND_COLOR)
            self.clear_critter_tiles()
            self.draw()

            pygame.display.flip()
            self.clock.tick(40)

            if len(self.cheese) == 0:
                self.new_level()
                self.game_state.bones.value = 0

    def update(self):
        self.clear_tiles.clear()
        if self.is_dog:
            try:
                self.dog.update(self.clear_tiles)
            except DogBlew:
                # Pop the dog - switch back to mouse and lose a life
                self.is_dog = False
                self.mouse.sprite.kill()
        else:
            if not self.mouse.update(self.clear_tiles):
                if self.next_mouse():
                    self.mouse.critter_reset(self.map)
                else:
                    self.play_game = False  # Game Over
        self.cheese.update(self.mouse.sprite)
        self.bones.update(self.mouse.sprite)
        self.cats.update(self.clear_tiles)

    def clear_critter_tiles(self):
        for tile in self.clear_tiles:
            self.maze.surface.blit(self.tiles.ground, tile)

    def draw(self):
        self.cheese.draw(self.maze.surface)
        self.bones.draw(self.maze.surface)
        self.mouse.draw(self.maze.surface)
        self.cats.draw(self.maze.surface)
        self.maze.draw(self.screen, Rect(0, 32, 32, 32), self.mouse.get_location())
        self.game_state.draw(self.screen, Rect(0, 0, HEAD_WIDTH, HEAD_HEIGHT))

    def maze_run(self):
        while self.title_loop():
            self.game_loop()
            self.game_over_loop()

    def next_mouse(self):
        self.game_state.lives -= 1
        return self.game_state.lives > 0

    def activate_dog(self):
        pass
Example #28
0
 def test_get_status_INIT(self):
     maze = Maze()
     length = randint(1, 10)
     maze.set_board([[Cell(i, j, False) for i in range(length)]
                     for j in range(length)])
     self.assertEqual(MazeStatus.INIT, maze.get_status())