omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / conways-game-of-life / oracle.py
| 1 | # Independent reference for "Conway's Game of Life" (Python 3, standard library only). |
| 2 | # expected.txt is this program's stdout; omc never produced it. |
| 3 | # the live cells as a set of (row, col); neighbour counts come from a Counter over all live cells |
| 4 | from collections import Counter |
| 5 | def step(live, rows, cols): |
| 6 | counts = Counter((r + dr, c + dc) for r, c in live |
| 7 | for dr in (-1, 0, 1) for dc in (-1, 0, 1) if (dr, dc) != (0, 0)) |
| 8 | return {p for p, n in counts.items() |
| 9 | if 0 <= p[0] < rows and 0 <= p[1] < cols and (n == 3 or (n == 2 and p in live))} |
| 10 | def run(live, rows, cols, gens): |
| 11 | for g in range(gens + 1): |
| 12 | print("generation", g) |
| 13 | for r in range(rows): |
| 14 | print("".join("#" if (r, c) in live else "." for c in range(cols))) |
| 15 | live = step(live, rows, cols) |
| 16 | run({(1, 0), (1, 1), (1, 2)}, 3, 3, 2) |
| 17 | print() |
| 18 | run({(0, 1), (1, 2), (2, 0), (2, 1), (2, 2)}, 8, 8, 4) |