#!/usr/bin/env python3
# life - Conway's Game of Life in the terminal for a few generations
# Usage: life [-g GENERATIONS] [--pattern glider|blinker|random|pulsar] [--seed N]
import argparse, random, sys, time

PATTERNS = {
 "blinker": [(0, 0), (1, 0), (2, 0)],
 "glider": [(1, 0), (2, 1), (0, 2), (1, 2), (2, 2)],
 "pulsar": [(2, 0), (3, 0), (4, 0), (8, 0), (9, 0), (10, 0),
            (0, 2), (5, 2), (7, 2), (12, 2), (0, 3), (5, 3), (7, 3), (12, 3),
            (0, 4), (5, 4), (7, 4), (12, 4), (2, 5), (3, 5), (4, 5), (8, 5), (9, 5), (10, 5),
            (2, 7), (3, 7), (4, 7), (8, 7), (9, 7), (10, 7),
            (0, 8), (5, 8), (7, 8), (12, 8), (0, 9), (5, 9), (7, 9), (12, 9),
            (0, 10), (5, 10), (7, 10), (12, 10), (2, 12), (3, 12), (4, 12), (8, 12), (9, 12), (10, 12)],
 "toad": [(1, 0), (2, 0), (3, 0), (0, 1), (1, 1), (2, 1)],
 "beacon": [(0, 0), (1, 0), (0, 1), (3, 2), (2, 3), (3, 3)],
}

def step(live):
    from collections import Counter
    counts = Counter()
    for x, y in live:
        for dx in (-1, 0, 1):
            for dy in (-1, 0, 1):
                if dx or dy:
                    counts[(x + dx, y + dy)] += 1
    return {c for c, n in counts.items() if n == 3 or (n == 2 and c in live)}

def render(live, w, h, ox=0, oy=0):
    lines = []
    for y in range(h):
        lines.append("".join("█" if (x + ox, y + oy) in live else "·" for x in range(w)))
    return "\n".join(lines)

def run(pattern, generations, w, h, seed=None, delay=0.0, animate=False):
    if pattern == "random":
        rng = random.Random(seed)
        live = {(x, y) for x in range(w) for y in range(h) if rng.random() < 0.25}
        ox = oy = 0
    else:
        cells = PATTERNS[pattern]
        ox = (w - (max(x for x, _ in cells) + 1)) // 2
        oy = (h - (max(y for _, y in cells) + 1)) // 2
        live = {(x + ox, y + oy) for x, y in cells}
    for gen in range(generations + 1):
        if animate:
            print("\033[2J\033[H", end="")
        print(f"Generation {gen}  (alive: {len(live)})")
        print(render(live, w, h))
        if gen < generations:
            live = step(live)
            if delay:
                time.sleep(delay)
    return live

def selftest():
    # Blinker oscillates with period 2
    b = {(1, 0), (1, 1), (1, 2)}
    assert step(step(b)) == b
    assert step(b) == {(0, 1), (1, 1), (2, 1)}
    # Block is stable
    block = {(0, 0), (1, 0), (0, 1), (1, 1)}
    assert step(block) == block
    # Glider moves: after 4 steps it has shifted by (1,1) with same shape
    g = {(1, 0), (2, 1), (0, 2), (1, 2), (2, 2)}
    cur = g
    for _ in range(4):
        cur = step(cur)
    assert cur == {(x + 1, y + 1) for x, y in g}, cur
    run("glider", 3, 20, 10)
    print("life selftest OK")

def main():
    p = argparse.ArgumentParser(description="Conway's Game of Life in the terminal for a few generations.")
    p.add_argument("-g", "--generations", type=int, default=10, help="generations to run (default 10)")
    p.add_argument("--pattern", default="glider", choices=list(PATTERNS) + ["random"], help="starting pattern")
    p.add_argument("-w", "--width", type=int, default=30, help="board width (default 30)")
    p.add_argument("--height", type=int, default=15, help="board height (default 15)")
    p.add_argument("--seed", type=int, default=None, help="seed for the random pattern")
    p.add_argument("--delay", type=float, default=0.2, help="seconds between generations (0 to disable)")
    p.add_argument("--animate", action="store_true", help="clear the screen between generations")
    p.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
    a = p.parse_args()
    if a.selftest:
        selftest(); return 0
    run(a.pattern, a.generations, a.width, a.height, a.seed, a.delay, a.animate)
    return 0

if __name__ == "__main__":
    sys.exit(main())
