File: conwaylife.py

package info (click to toggle)
giac 1.9.0.93%2Bdfsg2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 117,732 kB
  • sloc: cpp: 404,272; ansic: 205,462; python: 30,548; javascript: 28,788; makefile: 17,997; yacc: 2,690; lex: 2,464; sh: 705; perl: 314; lisp: 216; asm: 62; java: 41; xml: 36; sed: 16; csh: 7; pascal: 6
file content (46 lines) | stat: -rw-r--r-- 1,598 bytes parent folder | download | duplicates (3)
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
#import essential libraries
import pyb

lcd = pyb.LCD('x')
lcd.light(1)

# do 1 iteration of Conway's Game of Life
def conway_step():
    for x in range(128):        # loop over x coordinates
        for y in range(32):     # loop over y coordinates
            # count number of neighbours
            num_neighbours = (lcd.get(x - 1, y - 1) +
                lcd.get(x, y - 1) +
                lcd.get(x + 1, y - 1) +
                lcd.get(x - 1, y) +
                lcd.get(x + 1, y) +
                lcd.get(x + 1, y + 1) +
                lcd.get(x, y + 1) +
                lcd.get(x - 1, y + 1))

            # check if the centre cell is alive or not
            self = lcd.get(x, y)

            # apply the rules of life
            if self and not (2 <= num_neighbours <= 3):
                lcd.pixel(x, y, 0) # not enough, or too many neighbours: cell dies
            elif not self and num_neighbours == 3:
                lcd.pixel(x, y, 1)   # exactly 3 neighbours around an empty cell: cell is born

# randomise the start
def conway_rand():
    lcd.fill(0)                 # clear the LCD
    for x in range(128):        # loop over x coordinates
        for y in range(32):     # loop over y coordinates
            lcd.pixel(x, y, pyb.rng() & 1)   # set the pixel randomly

# loop for a certain number of frames, doing iterations of Conway's Game of Life
def conway_go(num_frames):
    for i in range(num_frames):
        conway_step()           # do 1 iteration
        lcd.show()              # update the LCD
        pyb.delay(50)

# testing
conway_rand()
conway_go(100)