conwaylife.py 1.6 KB

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