def test_rule_3(self): """Any live cell with more than 3 live neighbors dies.""" grid = self.GRID_CLS.from_2d_seq([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 1], [0, 0, 0, 0]]) grid.tick() assert grid[Point(2, 1)] == 0 assert grid[Point(2, 2)] == 0
def test_rule_2(self): """Any live cell with 2 or 3 neighbors lives on.""" grid = self.GRID_CLS.from_2d_seq([[0, 1, 0], [0, 1, 1], [0, 0, 0]]) grid.tick() assert grid[Point(1, 0)] == 1 assert grid[Point(1, 1)] == 1 assert grid[Point(2, 1)] == 1
def from_2d_seq(cls, seq: Sequence[Sequence[Any]], **kwargs) -> "Grid": width = kwargs.get("width") or max(len(row) for row in seq) height = kwargs.get("height") or len(seq) cells = { Point(x, y) for y, row in enumerate(seq) for x, cell in enumerate(row) if cell } return Grid(width, height, cells=cells)
def from_set(cls, set_: Set[Point], **kwargs) -> "Grid": width = kwargs.get("width") or max(x for x, _ in set_) height = kwargs.get("height") or max(y for _, y in set_) return cls.from_2d_seq( [ [Point(x, y) in set_ for x in range(width)] for y in range(height) ], width=width, height=height, )
def test_rule_4(self): """Any dead cell with exactly 3 live neighbors becomes alive.""" grid = self.GRID_CLS.from_2d_seq([[0, 0, 0], [0, 0, 1], [0, 1, 1]]) grid.tick() assert grid[Point(1, 1)] == 1
def enumerate_cells(self) -> Iterator[Tuple[Point, bool]]: for y in range(self.height): for x in range(self.width): point = Point(x, y) yield point, self[point]
def enumerate_cells(self) -> Iterator[Tuple[Point, bool]]: for y, row in enumerate(self.cells): for x, cell in enumerate(row): yield Point(x, y), cell