Created
December 10, 2021 21:29
-
-
Save paveldedik/0796adc424632b3972ef9a6fea59e61a to your computer and use it in GitHub Desktop.
Game of Life in terminal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
How to run: | |
$ python gof.py & | |
$ watch -n 0.1 cat epoch.txt | |
""" | |
import time | |
import random | |
from array import array | |
class GameOfLife: | |
def __init__(self, cols=10, rows=10): | |
self._cols = cols | |
self._rows = rows | |
self._matrix = self._generate() | |
def _generate(self): | |
matrix = [] | |
for _ in range(self._cols): | |
row = array("b", [bool(random.getrandbits(1)) for _ in range(self._rows)]) | |
matrix.append(row) | |
return matrix | |
def _get_number_of_neighbours(self, pos_i, pos_j): | |
number_of_neighbours = 0 | |
for i in range(pos_i - 1, pos_i + 2): | |
for j in range(pos_j - 1, pos_j + 2): | |
if i == pos_i and j == pos_j: | |
continue | |
if i < 0: | |
i += self._cols | |
if j < 0: | |
j += self._rows | |
if i > 7: | |
i -= self._cols | |
if j > 7: | |
j -= self._rows | |
number_of_neighbours += self._matrix[i][j] | |
return number_of_neighbours | |
def _determine_liveness(self, on, num_neighbours): | |
if on: | |
if num_neighbours < 2: | |
return False | |
if 2 <= num_neighbours <= 3: | |
return True | |
if num_neighbours > 3: | |
return False | |
return num_neighbours == 3 | |
def regenerate(self): | |
self._matrix = self._generate() | |
def run_epoch(self): | |
new_matrix = [array("b", [False] * self._rows) for _ in range(self._cols)] | |
for i, row in enumerate(self._matrix): | |
for j, on in enumerate(row): | |
num_neighbours = self._get_number_of_neighbours(i, j) | |
new_matrix[i][j] = self._determine_liveness(on, num_neighbours) | |
self._matrix = new_matrix | |
def write(self): | |
with open("epoch.txt", encoding="utf-8", mode="w") as fd: | |
fd.write( | |
"".join( | |
("".join(("◼" if row else " ") for row in rows) + "\n") | |
for rows in self._matrix | |
) | |
) | |
gof = GameOfLife(100, 200) | |
while True: | |
gof.write() | |
gof.run_epoch() | |
time.sleep(0.1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment