|
| 1 | +# do 1 iteration of Conway's Game of Life |
| 2 | +def conway_step(): |
| 3 | + for x in range(128): # loop over x coordinates |
| 4 | + for y in range(32): # loop over y coordinates |
| 5 | + # count number of neigbours |
| 6 | + num_neighbours = (lcd.get(x - 1, y - 1) + |
| 7 | + lcd.get(x, y - 1) + |
| 8 | + lcd.get(x + 1, y - 1) + |
| 9 | + lcd.get(x - 1, y) + |
| 10 | + lcd.get(x + 1, y) + |
| 11 | + lcd.get(x + 1, y + 1) + |
| 12 | + lcd.get(x, y + 1) + |
| 13 | + lcd.get(x - 1, y + 1)) |
| 14 | + |
| 15 | + # check if the centre cell is alive or not |
| 16 | + self = lcd.get(x, y) |
| 17 | + |
| 18 | + # apply the rules of life |
| 19 | + if self and not (2 <= num_neighbours <= 3): |
| 20 | + lcd.reset(x, y) # not enough, or too many neighbours: cell dies |
| 21 | + elif not self and num_neighbours == 3: |
| 22 | + lcd.set(x, y) # exactly 3 neigbours around an empty cell: cell is born |
| 23 | + |
| 24 | +# randomise the start |
| 25 | +def conway_rand(): |
| 26 | + lcd.clear() # clear the LCD |
| 27 | + for x in range(128): # loop over x coordinates |
| 28 | + for y in range(32): # loop over y coordinates |
| 29 | + if pyb.rand() & 1: # get a 1-bit random number |
| 30 | + lcd.set(x, y) # set the pixel randomly |
| 31 | + |
| 32 | +# loop for a certain number of frames, doing iterations of Conway's Game of Life |
| 33 | +def conway_go(num_frames): |
| 34 | + for i in range(num_frames): |
| 35 | + conway_step() # do 1 iteration |
| 36 | + lcd.show() # update the LCD |
| 37 | + |
| 38 | +# PC testing |
| 39 | +import lcd |
| 40 | +import pyb |
| 41 | +lcd = lcd.LCD(128, 32) |
| 42 | +conway_rand() |
| 43 | +conway_go(100) |
0 commit comments