Exemplo n.º 1
0
def test_alive_cell_with_fewer_fewer_2_neighbours_dies():
    cell = Cell(Cell.ALIVE)
    live_neighbours = 1

    cell.evolve(live_neighbours)

    assert cell.status == Cell.DEAD
Exemplo n.º 2
0
def run(window_size):
    pygame.init()
    cells = {}
    camera = Camera(window_size, cells)
    Cell.static_init(camera, cells)
    simulation = Simulation(camera, cells)
    clock = pygame.time.Clock()
    debug_mode = False

    while True:
        dt = clock.tick(FPS) / 1000
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return
                elif event.key == pygame.K_F1:
                    debug_mode = not debug_mode
            camera.process_event(event)
            simulation.process_event(event)
        camera.update(dt)
        simulation.update(dt)
        camera.draw()
        if debug_mode:
            show_debug_info(camera, simulation, clock.get_fps())
        pygame.display.flip()
Exemplo n.º 3
0
def test_alive_cell_with_3_neighbours_keep_alive():
    cell = Cell(Cell.ALIVE)
    live_neighbours = 3

    cell.evolve(live_neighbours)

    assert cell.status == Cell.ALIVE
Exemplo n.º 4
0
def test_dead_cell_with_3_neighbours_change_to_live():
    cell = Cell(Cell.DEAD)
    live_neighbours = 3

    cell.evolve(live_neighbours)

    assert cell.status == Cell.ALIVE
Exemplo n.º 5
0
def test_dead_cell_with_2_neighbours_keep_dead():
    cell = Cell(Cell.DEAD)
    live_neighbours = 2

    cell.evolve(live_neighbours)

    assert cell.status == Cell.DEAD
Exemplo n.º 6
0
    def set_size(self, x, y):
        """Set map size.

        Args:
            - x - x size
            - y - y size

        """
        assert (0 < x and 0 < y)
        self.x = x
        self.y = y
        coord_x = START_COORD + 5
        coord_y = START_COORD
        for i in range(0, x):
            list = []
            for j in range(0, y):
                if i % 2 == 1 and j == y - 1:
                    continue
                cell = Cell(i, j, "")
                cell.create_vis_cell((coord_x, coord_y), self)
                coord_x = coord_x + cell.vis_cell.x_size() * 3 // 2
                list.append(cell)
            if i % 2 == 0:
                coord_x = START_COORD * 2 // 3 + 9 + list[0].vis_cell.x_size()
            else:
                coord_x = START_COORD + 5
            coord_y = coord_y + list[0].vis_cell.y_size() // 2
            self.cells.append(list)
Exemplo n.º 7
0
def test_alive_cell_with_more_than_3_neighbours_dies():
    cell = Cell(Cell.ALIVE)
    live_neighbours = 4

    cell.evolve(live_neighbours)

    assert cell.status == Cell.DEAD
Exemplo n.º 8
0
 def get_near_neighbours(self, cell: Cell) -> list:
     valid_near_neighbours_list = list()
     for dx in [-1, 0, 1]:
         for dy in [-1, 0, 1]:
             c = Cell(cell.get_cord_x() + dx, int(cell.get_cord_y() + dy))
             if c != cell:
                 valid_near_neighbours_list.append(c)
     return valid_near_neighbours_list
Exemplo n.º 9
0
    def test_cell_with_two_neighbours_lives_in_next_iteration(self):
        self.expected_matrix[0][1] = '*'
        self.board.init_board(4, 4)
        self.board.game.add_cell(Cell(0, 0))
        self.board.game.add_cell(Cell(0, 1))
        self.board.game.add_cell(Cell(0, 2))

        self.board.game.get_next_iteration()
        self.assertListEqual(self.expected_matrix, self.board.display_board())
Exemplo n.º 10
0
    def test_should_turn_dead_when_a_live_cell_have_2_alive_neighbour(self):
        # given
        cell = Cell(True)
        number_of_alive_neighbour = 1

        # when
        cell.next(number_of_alive_neighbour)

        # then
        self.assertFalse(cell.state)
Exemplo n.º 11
0
    def test_should_turn_alive_when_a_cell_have_3_alive_neighbour(self):
        # given
        cell = Cell(False)
        number_of_alive_neighbour = 3

        # when
        cell.next(number_of_alive_neighbour)

        # then
        self.assertTrue(cell.state)
Exemplo n.º 12
0
    def test_should_keep_dead_when_a_dead_cell_have_2_alive_neighbour(self):
        # given
        cell = Cell(False)

        number_of_alive_neighbour = 2

        # when
        cell.next(number_of_alive_neighbour)

        # then
        self.assertFalse(cell.state)
Exemplo n.º 13
0
    def test_should_keep_alive_when_a_alive_cell_have_2_alive_neighbour(self):
        # given
        cell = Cell(True)

        number_of_alive_neighbour = 2

        # when
        cell.next(number_of_alive_neighbour)

        # then
        self.assertTrue(cell.state)
Exemplo n.º 14
0
def makeArrayFromPhoto():
    img = cv2.imread('src/img/final_map.png')
    res = cv2.resize(img, dsize=(120, 60), interpolation=cv2.INTER_CUBIC)
    newmap = np.empty((120, 60), dtype=object)
    for i in range(120):
        for j in range(60):
            if (j > 50):
                newmap[i][j] = Cell(SEA)
            elif np.all(res[j][i] <= [255, 218, 180]) and np.all(
                    res[j][i] >= [255, 218, 150]):
                newmap[i][j] = Cell(SEA)
            else:
                newmap[i][j] = Cell(LAND)

    return newmap
Exemplo n.º 15
0
 def set_state(self, state):
     if not isinstance(state, list):
         raise TypeError()
     elif len(state) != self._height and any(
             len(row) != self._width for row in state):
         raise ValueError()
     self._cells = [[Cell(st) for st in row] for row in state]
Exemplo n.º 16
0
    def main(self, cell_width: int) -> None:
        # Initial setup
        logger.info("Starting game")

        self.cols = floor(self.width / cell_width)
        self.rows = floor(self.height / cell_width)

        self.cells = []
        for row in range(self.rows):
            for col in range(self.cols):
                self.cells.append(Cell(self.screen, row, col))

        self.current_cell = self.cells[0]

        self.stack = []

        # Main game loop
        while self.running:
            self.current_cell.visited = True
            neighbor = self.current_cell.check_neighbors(self.cells)

            if neighbor:
                neighbor.visited = True

                self.stack.append(self.current_cell)

                neighbor.remove_wall(self.current_cell)
                self.current_cell = neighbor
            elif len(self.stack) > 0:
                self.current_cell = self.stack.pop()

            self.update_screen()
Exemplo n.º 17
0
    def init_cells(self, prob=0.3):
        self.cells = []
        for y in range(self.height):
            self.cells.append([Cell(np.random.choice([0, 1], p=[prob, 1 - prob])) for _ in range(self.width)])

        # set neighborhood cell
        for y in range(self.height):
            for x in range(self.width):
                if y - 1 > 0:
                    # 左上
                    if x - 1 >= 0:
                        self.cells[y][x].neighbor_cells.append(self.cells[y - 1][x - 1])
                    # 右上
                    if x + 1 < self.width:
                        self.cells[y][x].neighbor_cells.append(self.cells[y - 1][x + 1])
                    # 真上
                    self.cells[y][x].neighbor_cells.append(self.cells[y - 1][x])
                if y + 1 < self.height:
                    # 左下
                    if x - 1 >= 0:
                        self.cells[y][x].neighbor_cells.append(self.cells[y + 1][x - 1])
                    # 右下
                    if x + 1 < self.width:
                        self.cells[y][x].neighbor_cells.append(self.cells[y + 1][x + 1])
                    # 真下
                    self.cells[y][x].neighbor_cells.append(self.cells[y + 1][x])
                # 右
                if x + 1 < self.width:
                    self.cells[y][x].neighbor_cells.append(self.cells[y][x + 1])
                # 左
                if x - 1 >= 0:
                    self.cells[y][x].neighbor_cells.append(self.cells[y][x - 1])
Exemplo n.º 18
0
 def __init__(self, width, height, init_state=None):
     self._width = width
     self._height = height
     self._cells = [[Cell(True) for x in range(width)]
                    for y in range(height)]
     if init_state is not None:
         self.set_state(init_state)
     self._time = 0
 def __init__(self, width, height):
     self.width = width
     self.height = height
     #create a list the length of the height parameter
     #filled with a list the length of the width parameter containing a cell
     self.cells = list(
         map(lambda row: list(map(lambda cell: Cell(), range(height))),
             range(width)))
Exemplo n.º 20
0
 def from_file(self, lines):
     """Creating treasure map as list 5 by 5 from file"""
     for i in range(5):
         line = lines[i].split()
         row = list(map(int, line))
         if validate(row):
             self.grid[i] = [Cell(value) for value in row]
         else:
             input("Error: your file has incorrect values. For exit press Enter")
Exemplo n.º 21
0
 def __init__(self,
              sizeX,
              sizeY,
              p=50,
              starting_point=None,
              roadcolor=None,
              carcolor=None,
              sidecolor=None,
              nonecolor=None,
              slowcolor=None,
              prioritycolor=None,
              startingcolor=None,
              entriescolor=None,
              exitscolor=None):
     if roadcolor is None:
         roadcolor = np.array([125, 125, 125], dtype=np.uint8)
     if carcolor is None:
         carcolor = np.array([0, 255, 0], dtype=np.uint8)
     if sidecolor is None:
         sidecolor = np.array([0, 0, 0], dtype=np.uint8)
     if nonecolor is None:
         nonecolor = np.array([255, 255, 255], dtype=np.uint8)
     if slowcolor is None:
         slowcolor = np.array([255, 0, 0], dtype=np.uint8)
     if prioritycolor is None:
         prioritycolor = np.array([150, 150, 90], dtype=np.uint8)
     if startingcolor is None:
         startingcolor = np.array([255, 150, 90], dtype=np.uint8)
     if entriescolor is None:
         entriescolor = np.array([250, 150, 250], dtype=np.uint8)
     if exitscolor is None:
         exitscolor = np.array([90, 250, 250], dtype=np.uint8)
     self.cellmap = np.array(
         [list(Cell() for _ in range(sizeX)) for _ in range(sizeY)])
     self.colormap = np.array(np.full([sizeY, sizeX, 3], 255),
                              dtype=np.uint8)
     self.cars = []
     self.trafficLights = []
     self.probabilityOfTurn = p
     self.roadcolor = roadcolor
     self.carcolor = carcolor
     self.sidecolor = sidecolor
     self.nonecolor = nonecolor
     self.slowcolor = slowcolor
     self.prioritycolor = prioritycolor
     self.startingcolor = startingcolor
     self.entriescolor = entriescolor
     self.exitscolor = exitscolor
     self.slow_cars = 0
     self.max_slow_cars = 0
     self.currentIteration = 0
     if starting_point is None:
         self.starting_point = []
     self.dt_string = ""
     self.car_distances = None
     self.flow_flags = []
     self.intensities = []
Exemplo n.º 22
0
 def from_keyboard(self):
     """Creating treasure map as list 5 by 5 from keyboard"""
     counter = 0
     while counter < 5:
         line = input()
         line = line.strip().split()
         row = list(map(int, line))
         if validate(row):
             self.grid[counter] = [Cell(value) for value in row]
             counter += 1
Exemplo n.º 23
0
 def move(self):
     self.update()
     self.correct()
     self.tail.insert(0, Cell(self.x, self.y, 'src/zet.png'))
     while len(self.tail) > self.length:
         self.tail.pop()
     count = 0
     for each_cell in self.tail:
         count += 1
         each_cell.number = count
Exemplo n.º 24
0
    def generate_grid(self):
        grid = list()

        # Place a Cell object at each location in the grid
        for i in range(self.num_rows):
            grid.append(list())

            for j in range(self.num_cols):
                grid[i].append(Cell(i, j))

        return grid
Exemplo n.º 25
0
    def test_ctor(self):
        """Make sure that the constructor values are getting properly set."""

        cell = Cell(2, 2)
        self.assertEqual(cell.row, 2)
        self.assertEqual(cell.col, 2)
        self.assertEqual(cell.visited, False)
        self.assertEqual(cell.active, False)
        self.assertEqual(cell.is_entry_exit, None)
        self.assertEqual(cell.walls, {"top": True, "right": True, "bottom": True, "left": True})
        self.assertEqual(cell.neighbours, list())
Exemplo n.º 26
0
    def generate_grid(self):
        """Function that creates a 2D grid of Cell objects to be the maze."""
        grid = list()

        for i in range(self.num_rows):
            grid.append(list())

            for j in range(self.num_cols):
                grid[i].append(Cell(i, j))

        return grid
Exemplo n.º 27
0
 def process_mouse_press(self):
     if self.camera.mouse_grid_position != self.last_changed_cell_position:
         self.last_changed_cell_position = self.camera.mouse_grid_position
         selected_cell = self.cells.get(self.camera.mouse_grid_position,
                                        None)
         erase_mode = pygame.key.get_mods() & pygame.KMOD_CTRL
         if selected_cell is None:
             if not erase_mode:
                 self.cells[self.camera.mouse_grid_position] = Cell(
                     self.camera)
         else:
             if erase_mode:
                 selected_cell.delete()
             else:
                 selected_cell.increment_state()
Exemplo n.º 28
0
 def clean_board(self):
     for cell in self._cells:
         cnt = 0
         for path in self.paths:
             if cell.coord not in path:
                 cnt += 1
         if cnt == len(self.paths):
             x, y = cell.coord['x'], cell.coord['y']
             flag = True  # checking portal
             for st in self._start:
                 if x == st['x'] and y == st['y']:
                     flag = False
             if flag:
                 self._cells[x * len(self.BOARD_CELLS[0]) + y] = Cell(
                     0, {
                         'x': x,
                         'y': y
                     })
                 self._marked_board[x][y] = 0
Exemplo n.º 29
0
    def generate_grid(self):
        """Function that creates a 2D grid of Cell objects. This can be thought of as a
        maze without any paths carved out

        Return:
            A list with Cell objects at each position

        """

        # Create an empty list
        grid = list()

        # Place a Cell object at each location in the grid
        for i in range(self.num_rows):
            grid.append(list())

            for j in range(self.num_cols):
                grid[i].append(Cell(i, j))

        return grid
Exemplo n.º 30
0
    def _parse_board(self):
        i = 0
        for row in self.BOARD_CELLS:
            j = 0
            for cell in row:
                if cell == 5000:
                    self._Castle = Castle(cell, {'x': i, 'y': j})
                    self._cells.append(self._Castle)
                    self._end['x'] = i
                    self._end['y'] = j

                elif cell == 2:
                    tw = Tower(cell, {'x': i, 'y': j})
                    self._towers.append(tw)
                else:
                    if cell == -5000:
                        self._start.append({'x': i, 'y': j})
                    cl = Cell(cell, {'x': i, 'y': j})
                    self._cells.append(cl)
                j += 1
            i += 1