Class to store grid.
| 36 | |
| 37 | |
| 38 | class Grid: |
| 39 | """Class to store grid.""" |
| 40 | |
| 41 | def __init__(self, width, height) -> None: |
| 42 | """Initialise the grid with empty cells.""" |
| 43 | self._grid = [[Empty() for _ in range(width)] for _ in range(height)] |
| 44 | |
| 45 | def __str__(self) -> str: |
| 46 | """Return the string representation of the grid.""" |
| 47 | return "\n".join(["".join(row) for row in self._grid]) |
| 48 | |
| 49 | @property |
| 50 | def neurons(self) -> tuple[tuple[Neuron, tuple[int, int]]]: |
| 51 | """Return 2D tuple of Neurons.""" |
| 52 | return tuple( |
| 53 | (element, (x, y)) |
| 54 | for y, row in enumerate(self._grid) |
| 55 | for x, element in enumerate(row) |
| 56 | if isinstance(element, Neuron) |
| 57 | ) |
| 58 | |
| 59 | def set_neuron(self, x, y) -> None: |
| 60 | """Set x, y to a Neuron.""" |
| 61 | self._grid[y][x] = Neuron() |
| 62 | |
| 63 | def tick(self) -> None: |
| 64 | """Randomly kill or move all Neurons.""" |
| 65 | for neuron_data in self.neurons: |
| 66 | neuron = neuron_data[0] |
| 67 | x, y = neuron_data[1] |
| 68 | |
| 69 | if random.randint(1, 100) <= Neuron.CHANCE_OF_DEATH: |
| 70 | self._grid[y][x] = Empty() |
| 71 | continue |
| 72 | |
| 73 | direction = random.choice(list(Direction)) |
| 74 | if direction == Direction.UP: |
| 75 | y -= 1 |
| 76 | elif direction == Direction.RIGHT: |
| 77 | x += 1 |
| 78 | elif direction == Direction.DOWN: |
| 79 | y += 1 |
| 80 | elif direction == Direction.LEFT: |
| 81 | x -= 1 |
| 82 | try: |
| 83 | self._grid[y][x] = Neuron() |
| 84 | except IndexError: |
| 85 | pass |
| 86 | |
| 87 | |
| 88 | def main() -> None: |