summaryrefslogtreecommitdiffstatshomepage
path: root/examples/conwaylife.py
diff options
context:
space:
mode:
authorJohn R. Lenton <jlenton@gmail.com>2014-01-07 18:01:08 +0000
committerJohn R. Lenton <jlenton@gmail.com>2014-01-07 18:01:08 +0000
commit270112f7312f724e46ae34649dfce3ec43b697e0 (patch)
treed7438ae877350aede062d8ac7e62e52ab35cb018 /examples/conwaylife.py
parentc06763a0207dde7f2060f7b1670a0b99298a01f8 (diff)
parentfd04bb3bacf5dbc4d79c04a49520e3e81abb7352 (diff)
downloadmicropython-270112f7312f724e46ae34649dfce3ec43b697e0.tar.gz
micropython-270112f7312f724e46ae34649dfce3ec43b697e0.zip
Merge remote-tracking branch 'upstream/master' into listsort. Lots of conflict fun.
Conflicts: py/obj.h py/objbool.c py/objboundmeth.c py/objcell.c py/objclass.c py/objclosure.c py/objcomplex.c py/objdict.c py/objexcept.c py/objfun.c py/objgenerator.c py/objinstance.c py/objmodule.c py/objrange.c py/objset.c py/objslice.c
Diffstat (limited to 'examples/conwaylife.py')
-rw-r--r--examples/conwaylife.py43
1 files changed, 43 insertions, 0 deletions
diff --git a/examples/conwaylife.py b/examples/conwaylife.py
new file mode 100644
index 0000000000..fb62ce69e8
--- /dev/null
+++ b/examples/conwaylife.py
@@ -0,0 +1,43 @@
+# 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 neigbours
+ 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.reset(x, y) # not enough, or too many neighbours: cell dies
+ elif not self and num_neighbours == 3:
+ lcd.set(x, y) # exactly 3 neigbours around an empty cell: cell is born
+
+# randomise the start
+def conway_rand():
+ lcd.clear() # clear the LCD
+ for x in range(128): # loop over x coordinates
+ for y in range(32): # loop over y coordinates
+ if pyb.rand() & 1: # get a 1-bit random number
+ lcd.set(x, y) # 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
+
+# PC testing
+import lcd
+import pyb
+lcd = lcd.LCD(128, 32)
+conway_rand()
+conway_go(100)