Created
February 10, 2019 15:50
-
-
Save davipatti/66da1cfe389d9d35812f401fba142856 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sense_hat import SenseHat | |
from functools import reduce | |
from operator import add | |
import random | |
i = 51, 160, 44 | |
o = 178, 223, 138 | |
rows = 8 | |
cols = 8 | |
class GameOfLife(): | |
def __init__(self): | |
# Array that stores alive / dead | |
self.a = [[False for r in range(rows)] for c in range(cols)] | |
self.count = [[None for r in range(rows)] for c in range(cols)] | |
def random_seed(self, k=10): | |
""" | |
Args: | |
k (int): Number of cells to set alive. | |
""" | |
for seed in random.sample(range(rows * cols), k): | |
i = seed // rows | |
j = seed % cols | |
self.a[i][j] = True | |
@property | |
def flat(self): | |
return reduce(add, self.a) | |
@property | |
def pixels(self): | |
return [i if c else o for c in self.flat] | |
def count_neighbours(self): | |
"""Updates self.counts""" | |
for i, j in zip(range(rows), range(cols)): | |
l = (i - 1) % rows | |
r = (i + 1) % rows | |
u = (j - 1) % cols | |
d = (j + 1) % cols | |
self.count[i][j] = self.a[l][j] + self.a[r][j] + \ | |
self.a[i][d] + self.a[i][u] + \ | |
self.a[l][d] + self.a[l][u] + \ | |
self.a[r][d] + self.a[r][u] | |
def rules(self): | |
"""Update array. | |
- Cells with <2 live neighbours die. | |
- Cells with 2 or 3 neighbours live. | |
- Cells with >3 neighbours die. | |
- Any dead cell with three live neighbours becomes live. | |
""" | |
for i, j in zip(range(rows), range(cols)): | |
if self.a[i][j]: | |
if self.count[i][j] < 2: | |
self.a[i][j] = False | |
elif self.count[i][j] < 4: | |
self.a[i][j] = True | |
else: | |
self.a[i][j] = False | |
else: | |
if self.count[i][j] == 3: | |
self.a[i][j] = True | |
if __name__ == "__main__": | |
sense = SenseHat() | |
sense.set_imu_config(False, False, True) # Accel only | |
gol = GameOfLife() | |
gol.random_seed(10) | |
while True: | |
sleep(0.1) | |
gol.count_neighbours() | |
gol.rules() | |
sense.set_pixels(gol.pixels) | |
shake = max(sense.accel_raw.values()) | |
if shake > 10: | |
gol.random_seed(int(shake)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment