blob: 323f42e850e68e84ac81d871a864b3cdabe40373 [file] [log] [blame]
ugurthemasterb94a2092014-01-24 08:48:10 +02001#import essential libraries
ugurthemasterb94a2092014-01-24 08:48:10 +02002import pyb
3
Damien George0c3955b2014-10-19 19:02:34 +01004lcd = pyb.LCD('x')
5lcd.light(1)
6
Damien Georgefd04bb32014-01-07 17:14:05 +00007# do 1 iteration of Conway's Game of Life
8def conway_step():
9 for x in range(128): # loop over x coordinates
10 for y in range(32): # loop over y coordinates
Ville Skyttäca16c382017-05-29 10:08:14 +030011 # count number of neighbours
Damien Georgefd04bb32014-01-07 17:14:05 +000012 num_neighbours = (lcd.get(x - 1, y - 1) +
13 lcd.get(x, y - 1) +
14 lcd.get(x + 1, y - 1) +
15 lcd.get(x - 1, y) +
16 lcd.get(x + 1, y) +
17 lcd.get(x + 1, y + 1) +
18 lcd.get(x, y + 1) +
19 lcd.get(x - 1, y + 1))
20
21 # check if the centre cell is alive or not
22 self = lcd.get(x, y)
23
24 # apply the rules of life
25 if self and not (2 <= num_neighbours <= 3):
Damien George0c3955b2014-10-19 19:02:34 +010026 lcd.pixel(x, y, 0) # not enough, or too many neighbours: cell dies
Damien Georgefd04bb32014-01-07 17:14:05 +000027 elif not self and num_neighbours == 3:
Ville Skyttäca16c382017-05-29 10:08:14 +030028 lcd.pixel(x, y, 1) # exactly 3 neighbours around an empty cell: cell is born
Damien Georgefd04bb32014-01-07 17:14:05 +000029
30# randomise the start
31def conway_rand():
Damien George0c3955b2014-10-19 19:02:34 +010032 lcd.fill(0) # clear the LCD
Damien Georgefd04bb32014-01-07 17:14:05 +000033 for x in range(128): # loop over x coordinates
34 for y in range(32): # loop over y coordinates
Damien George0c3955b2014-10-19 19:02:34 +010035 lcd.pixel(x, y, pyb.rng() & 1) # set the pixel randomly
Damien Georgefd04bb32014-01-07 17:14:05 +000036
37# loop for a certain number of frames, doing iterations of Conway's Game of Life
38def conway_go(num_frames):
39 for i in range(num_frames):
40 conway_step() # do 1 iteration
41 lcd.show() # update the LCD
Damien George0c3955b2014-10-19 19:02:34 +010042 pyb.delay(50)
Damien Georgefd04bb32014-01-07 17:14:05 +000043
Damien George0c3955b2014-10-19 19:02:34 +010044# testing
Damien Georgefd04bb32014-01-07 17:14:05 +000045conway_rand()
Damien George0c3955b2014-10-19 19:02:34 +010046conway_go(100)