cellauto.py

Created by vef03715

Created on June 27, 2021

1.44 KB


from kandinsky import *
from time import *

GRID_W = 21
GRID_H = 21

generation = 0

class Cell:
  def __init__(self,r,c,on=0):
    self.c = c
    self.r = r
    self.on = on

  def display(self):
    x=8
    y=8
    if self.on == 1:
      fill_rect(x+SZ*self.r, y+SZ*self.c, SZ, SZ,'black')
    else:
      fill_rect(x+SZ*self.r, y+SZ*self.c, SZ, SZ,'white')

  def checkNeighbors(self):
    neighbs = 0
    if self.on == 1: return 1
    for dr,dc in [[-1,0], [1,0], [0,-1],[0,1]]:
      try:
        if cellList[self.r + dr][self.c + dc].on == 1:
          neighbs += 1
      except IndexError:
        continue
    if neighbs in [1,4]:
      return 1
    else:
      return 0

def setup():
  global SZ, cellList
  width=200
  SZ = width // GRID_W + 1
  cellList = createCellList()

def draw():
  global generation,cellList
  while True:
    cellList = update(cellList)
    for row in cellList:
      for cell in row:
        cell.display()
    generation += 1
    if generation == 16:
      break
    sleep(0.5)

def update(cellList):
  newList = []
  for r,row in enumerate(cellList):
    newList.append([])
    for c,cell in enumerate(row):
      newList[r].append(Cell(r,c,cell.checkNeighbors()))
  return newList[::]
        
def createCellList():
  newList=[]
  for j in range(GRID_H): 
    newList.append([])
    for i in range(GRID_W):
      newList [j].append(Cell(i,j,0))
  newList [GRID_H//2][GRID_W//2].on = 1 
  return newList

setup()
draw()

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.