conways-game-of-life-on-neo.../code.py
arofarn 30b80c1b92 Cleaner living neighbour counter
Add presets : BLOOM and FROG
2020-04-16 23:27:33 +02:00

107 lines
3.1 KiB
Python

import time
import board
import busio
from adafruit_neotrellis.neotrellis import NeoTrellis
from adafruit_neotrellis.multitrellis import MultiTrellis
from neotrellism4 import NeoTrellisM4
import adafruit_adxl34x
import conway # Some functions are in an .mpy module for performance
# Starting point:
# * VOID, GLIDER, BEATING_HEART, BLOOM, FROG
# * RANDOM_UNIVERSE(percentage)
universe = conway.GLIDER
# Create the i2c object for the trellis
I2C = busio.I2C(board.SCL, board.SDA)
# Create the trellis. This is for a 2x2 array of TrellisM4 (first row) with
# 2 Neotrellis (second row).
#
# [ NeoM4_left | NeoM4_right ]
# neotrellis0 | neotrellis1
trellim4_left = NeoTrellisM4()
trellim4_right = NeoTrellisM4(left_part=trellim4_left)
trelli = [[trellim4_left, trellim4_right],
[NeoTrellis(I2C, False, addr=0x2F), NeoTrellis(I2C, False, addr=0x2E)]]
trellis = MultiTrellis(trelli)
I2C_ACCEL = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
accelerometer = adafruit_adxl34x.ADXL343(I2C_ACCEL)
accelerometer.enable_motion_detection(threshold=conway.ACCEL_THRESHOLD)
#this will be called when button events are received
def genesis_callback(xcoord, ycoord, edge):
#turn the LED on when a rising edge is detected
if edge == NeoTrellis.EDGE_RISING:
universe[xcoord][ycoord] = not(universe[xcoord][ycoord])
if universe[xcoord][ycoord]:
trellis.color(xcoord, ycoord, conway.ON)
else:
trellis.color(xcoord, ycoord, conway.OFF)
conway.draw_universe(trellis, universe)
def evo_callback(xcoord, ycoord, edge):
pass
# Init. all the keys for Genesis
for x in range(8):
for y in range(8):
#activate rising edge events on all keys
trellis.activate_key(x, y, NeoTrellis.EDGE_RISING)
trellis.set_callback(x, y, genesis_callback)
trellis.sync()
conway.draw_universe(trellis, universe)
# Genesis
while not(accelerometer.events["motion"]):
#the trellis can only be read every 17 millisecons or so
trellis.sync()
time.sleep(.02)
print("The end of Genesis, time to evolve...")
# Init. all the keys for Evolution
for x in range(8):
for y in range(8):
#activate rising edge events on all keys
trellis.activate_key(x, y, NeoTrellis.EDGE_RISING)
trellis.set_callback(x, y, evo_callback)
trellis.sync()
conway.draw_universe(trellis, universe)
generation = 0
#Evolution
while True:
new_universe = [[False for x in range(8)] for y in range(8)]
ext_universe = conway.extend_universe(universe)
for x in range(8):
for y in range(8):
n = conway.living_neighbour_count(x, y, ext_universe)
if n == 3:
new_universe[x][y] = True
# print(x, y, n, "alive")
elif n == 2 and universe[x][y]:
new_universe[x][y] = True
# print(x, y, n, "still alive")
else:
new_universe[x][y] = False
# print(x, y, n, "dead")
generation += 1
print(generation)
universe = new_universe.copy()
conway.draw_universe(trellis, universe)