-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconway.py
More file actions
55 lines (48 loc) · 1.74 KB
/
conway.py
File metadata and controls
55 lines (48 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'''
Conway's Game Of Life for the micro:bit
Press button A or tap the micro:bit to generate a fresh layout.
'''
import microbit
arena1 = bytearray(7 * 7)
arena2 = bytearray(7 * 7)
def show():
for y in range(5):
for x in range(5):
microbit.display.image.set_pixel(x, y, arena1[8 + y * 7 + x])
# do 1 iteration of Conway's Game of Life
def conway_step():
global arena1, arena2
for i in range(5 * 5): # loop over pixels
i = 8 + (i // 5) * 7 + i % 5
# count number of neigbours
num_neighbours = (arena1[i - 8] +
arena1[i - 7] +
arena1[i - 6] +
arena1[i - 1] +
arena1[i + 1] +
arena1[i + 6] +
arena1[i + 7] +
arena1[i + 8])
# check if the centre cell is alive or not
self = arena1[i]
# apply the rules of life
if self and not (2 <= num_neighbours <= 3):
arena2[i] = 0 # not enough, or too many neighbours: cell dies
elif not self and num_neighbours == 3:
arena2[i] = 1 # exactly 3 neigbours around an empty cell: cell is born
else:
arena2[i] = self # stay as-is
# swap the buffers (arena1 is now the new one to display)
arena1, arena2 = arena2, arena1
while True:
# randomise the start
for i in range(5 * 5): # loop over pixels
i = 8 + (i // 5) * 7 + i % 5
arena1[i] = microbit.random(2) # set the pixel randomly
show()
microbit.sleep(1) # need to yield to update accelerometer (not ideal...)
# loop while button a is not pressed
while not microbit.button_a.is_pressed() and microbit.accelerometer.get_z() < -800:
conway_step()
show()
microbit.sleep(150)