From 373e160962c0e6c2c422edd4cd2face92b969cee Mon Sep 17 00:00:00 2001 From: informaniac Date: Thu, 22 Dec 2016 00:34:03 +0100 Subject: [PATCH] conways game of life random bml generator --- gameOfLife.py | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 gameOfLife.py diff --git a/gameOfLife.py b/gameOfLife.py new file mode 100644 index 0000000..eb5964c --- /dev/null +++ b/gameOfLife.py @@ -0,0 +1,91 @@ +import sys +import ast +import time as t +import random as r +import blup.animation +import blup.frame +import writebml + +r.seed() + +WIDTH = 22 +HEIGHT = 16 + +COLOR_DEPTH = 256 +COLORS = 3 +DELAY = 300 + +DEAD = 0 +DEADCOLOR = (0,0,0) +ALIVE = 1 +ALIVECOLOR = (0,255,0) + +dimension = blup.frame.FrameDimension(WIDTH, HEIGHT, COLOR_DEPTH, COLORS) +animation = blup.animation.Animation(dimension) + +def generateRandomGameBoard(): + gameBoard = [] + for i in range(HEIGHT): + xCoordinates = [] + for j in range(WIDTH): + xCoordinates.append(r.randint(0, 1)) + gameBoard.append(xCoordinates) + return gameBoard + +def get_neighbors(x, y): + for rowNumber in range(y-1, y+2): + if 0 <= rowNumber < HEIGHT: + for colNumber in range(x-1, x+2): + if 0 <= colNumber < WIDTH: + if not (y==rowNumber and x==colNumber): + yield gameBoard[rowNumber][colNumber] + +if len(sys.argv) == 1: + gameBoard = generateRandomGameBoard() + gameBoardIsSanitized = True +elif len(sys.argv) != 2: + print("check args. found "+str(len(sys.argv))) + exit() + +if not gameBoardIsSanitized: + gameBoard = ast.literal_eval(sys.argv[1]) + + if len(gameBoard) != HEIGHT: + print("len(gameBoard) != "+str(HEIGHT)+". counted "+str(len(gameBoard))) + exit() + + for i in gameBoard: + if len(i) != WIDTH: + print("len(rows) != "+str(WIDTH)+". counted "+str(len(i))) + exit() + +for frame in range(500): + # construct frame + newframe = blup.animation.AnimationFrame(dimension, DELAY) + for rowIndex in range(HEIGHT): + for colIndex in range(WIDTH): + cellStatus = gameBoard[rowIndex][colIndex] + if cellStatus == ALIVE: + newframe.setPixel(colIndex, rowIndex, ALIVECOLOR) + else: + newframe.setPixel(colIndex, rowIndex, DEADCOLOR) + animation.addFrame(newframe) + + # calculate next step + gameBoardNextStep = [] + for rowIndex in range(HEIGHT): + newRow = [] + for colIndex in range(WIDTH): + neighborList = list(get_neighbors(colIndex, rowIndex)) + aliveNeighbors = neighborList.count(1) + if aliveNeighbors < 2: + newRow.append(DEAD) + elif aliveNeighbors == 2: + newRow.append(gameBoard[rowIndex][colIndex]) + elif aliveNeighbors == 3: + newRow.append(ALIVE) + elif aliveNeighbors >= 4: + newRow.append(DEAD) + gameBoardNextStep.append(newRow) + gameBoard = gameBoardNextStep +writebml.writeBml(animation, '/home/pi/animations/gameOfLife.bml')