Skip to content

Instantly share code, notes, and snippets.

@sebastius
Created April 14, 2020 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastius/6f00fc7fe3de8da6a0f79a7db5326ff9 to your computer and use it in GitHub Desktop.
Save sebastius/6f00fc7fe3de8da6a0f79a7db5326ff9 to your computer and use it in GitHub Desktop.
### Author: Sam Delaney
### Description: Game of Life
### License: MIT
### Modified by Sebastius for the SHA2017 Badge. Fixed by polyfloyd.
### Modified by Renze for the ESP32 platform firmware
import random
import paho.mqtt.client as mqtt
client =mqtt.Client('Sebastius_gol')
client.connect('test.mosquitto.org')
from time import sleep
# Clear the screen
width = 5
height = 5
cell_width = 1
cell_height = 1
grid = [[False] * height for _ in range(width)]
def seed():
global grid, width, height, cell_width, cell_height
for x in range(0, width-1):
for y in range(0, height-1):
if random.getrandbits(30) % 2 == 1:
grid[x][y] = True
else:
grid[x][y] = False
grid = [[0,0,0,0,0],[0,0,1,0,0],[0,0,0,1,0],[0,1,1,1,0],[0,0,0,0,0]]
def updateDisplay():
global grid, width, height, cell_width, cell_height
output = b''
print('\n'*2)
for y in range(0, height):
for x in range(0, width):
if grid[x][y]:
print('#', end = '')
output += b'\xFF\x00\x00'
else:
print('.', end = '')
output += b'\x00\x00\x00'
print('\n')
print(output)
client.publish("matrixflut", output, retain=True)
sleep(0.3)
def alive_neighbours(x, y, wrap):
global grid, width, height, cell_width, cell_height
if wrap:
range_func = lambda dim, size: range(dim - 1, dim + 2)
else:
range_func = lambda dim, size: range(max(0, dim - 1), min(size, dim + 2))
n = 0
for nx in range_func(x, width):
for ny in range_func(y, height):
if grid[nx % width][ny % height]:
if nx != x or ny != y:
n += 1
return n
def step():
global grid, width, height, cell_width, cell_height
changed = False
new_grid = [[False] * height for _ in range(width)]
for x in range(width):
for y in range(height):
neighbours = alive_neighbours(x, y, True)
if neighbours < 2: # Starvation
new_grid[x][y] = False
changed = True
elif neighbours > 3: # Overpopulation
new_grid[x][y] = False
changed = True
elif not grid[x][y] and neighbours == 3: # Birth
new_grid[x][y] = True
changed = True
else: # Survival
new_grid[x][y] = grid[x][y]
pass
grid = new_grid
return changed
seed()
generation = 0
while True:
generation += 1
updateDisplay()
if not step() or generation > 50:
seed()
generation = 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment