from machine import Pin, SPI
import max7219
from time import sleep
import random

spi = SPI(0,sck=Pin(2),mosi=Pin(3))
cs = Pin(5, Pin.OUT)

display = max7219.Matrix8x8(spi, cs, 1)

display.brightness(10)

conway = [[0]*8]*8

def step(conway):
  new_matrix = [[0]*8]*8
  
  for x in range(8):
    for y in range(8):
      dx = [-1, 0, 1, -1, 1, -1, 0, 1]
      dy = [1, 1, 1, 0, 0, -1, -1, -1]
      neigh = 0
      for t in range(8):
        if x + dx[t] >= 0 and x + dx[t] < 8 and y + dy[t] >= 0 and y + dy[t]:
          neigh += conway[x + dx[t]][y + dy[t]]
      
      if conway[x][y] == 1:
        if neigh != 3 and neigh != 4:
          new_matrix[x][y] = 0
        else:
          new_matrix[x][y] = 1
      else:
        if neigh == 3:
          new_matrix[x][y] = 1
        else:
          new_matrix[x][y] = 0
  return new_matrix

def show_board(display, conway):
  for x in range(8):
    for y in range(8):
      display.pixel(x, y)

for x in range(8):
  for y in range(8):
    conway[x][y] = random.randint(0, 1)

c=0

while True:
    display.fill(0)
    step(conway)
    show_board(display, conway)
    c += 1
    sleep(1)
    print(c, "hello")

