"""life2DEBUG.py!""" import collections import random from turtle import * global newLifeColor, colorIndex, justDied, justBorn, livingCells XY_MAX = 300 BOX_SIZE = 15 BOARD_SIDE = 2 * (XY_MAX + BOX_SIZE) LOOP_TIMER = 10 DEAD_COLOR = 'black' XY_INIT = 300 CHOICE = [1, 1, 1, 0, 0] RANDOM_SEEDS_INDEX = 2 RANDOM_SEEDS = [ None, 127, 131, '37', '13', '5', '29', '87', '101', 'remaining seeds yet to be tested:'] NEW_LIFE_COLORS = ['white', 'red', 'green', 'orange', 'blue', 'gray', 'purple', 'yellow', 'chocolate'] Cell = collections.namedtuple('Cell', ['x', 'y']) livingCells = set() justBorn = set() justDied = set() colorIndex = 0 newLifeColor = NEW_LIFE_COLORS[colorIndex] loopCount = 0 def myInitialize(): random.seed(a=RANDOM_SEEDS[RANDOM_SEEDS_INDEX], version=2) for x in range(-XY_MAX, XY_MAX, BOX_SIZE): for y in range(-XY_MAX, XY_MAX, BOX_SIZE): if (-XY_INIT <= x <= XY_INIT and -XY_INIT <= y <= XY_INIT): if random.choice(CHOICE): justBorn.add(Cell(x, y)) livingCells.add(Cell(x, y)) else: justDied.add(Cell(x, y)) else: justDied.add(Cell(x, y)) def myComputeOneStep(): global newLifeColor, colorIndex, justDied, justBorn, livingCells justBorn.clear() justDied.clear() deadNeighbors = {} for p in livingCells: count = -1 for h in [-BOX_SIZE, 0, BOX_SIZE]: for v in [-BOX_SIZE, 0, BOX_SIZE]: q = Cell(p.x + h, p.y + v) if q in livingCells: count += 1 elif XY_MAX > q.x > -XY_MAX and XY_MAX > q.y > -XY_MAX: deadNeighbors[q] = (deadNeighbors.get(q, 0) + 1) if count < 2 or count > 3: justDied.add(p) for p in justDied: livingCells.remove(p) for p, count in deadNeighbors.items(): if count == 3: justBorn.add(p) livingCells.add(p) colorIndex = (colorIndex + 1) % len(NEW_LIFE_COLORS) newLifeColor = NEW_LIFE_COLORS[colorIndex] def draw(): myDrawCells() update() myComputeOneStep() ontimer(draw, LOOP_TIMER) def myDrawCells(): color(DEAD_COLOR) for p in justDied: mySquare(p.x, p.y, BOX_SIZE) color(newLifeColor) for p in justBorn: mySquare(p.x, p.y, BOX_SIZE) def mySquare(x, y, size): up() goto(x, y) down() begin_fill() forward(size) left(90) forward(size) left(90) forward(size) left(90) forward(size) left(90) end_fill() setup(BOARD_SIDE, BOARD_SIDE, None, None) hideturtle() tracer(False) clear() myInitialize() draw() done()