Skip to content

Instantly share code, notes, and snippets.

@ggventurini
Created April 4, 2014 18:12
Show Gist options
  • Save ggventurini/9980101 to your computer and use it in GitHub Desktop.
Save ggventurini/9980101 to your computer and use it in GitHub Desktop.

Conway's Game of Life in kivy

screen shot 2014-04-04 at 20 03 22

You will need:

  • scipy
  • numpy
  • kivy

to run this simple demo.

cogl.py

from __future__ import division

from kivy.core.window import Window
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color, Rectangle
from kivy.clock import Clock

import numpy
import scipy.ndimage

class Life(object):
    """"Think Complexity", Allen B. Downey"""
    def __init__(self, n, p=0.5, mode='wrap'):
        self.n = n
        self.mode = mode
        self.array = numpy.uint8(numpy.random.random((n, n)) < p)
        self.weights = numpy.array([[1,1,1],
                                    [1,10,1],
                                    [1,1,1]], dtype=numpy.uint8)

    def step(self):
        con = scipy.ndimage.filters.convolve(self.array,
                                             self.weights,
                                             mode=self.mode)

        boolean = (con==3) | (con==12) | (con==13)
        self.array = numpy.int8(boolean)
        return self.array

class CGOLWidget(Widget):
    def __init__(self):
        Widget.__init__(self)
        self.game_size = 50
        self.game = Life(self.game_size)
        self.tile_size = [d/self.game_size for d in Window.size]
        Clock.schedule_interval(self.update, 1/6.)

    def update(self, *args):
        a = self.game.step()
        self.canvas.clear()
        with self.canvas:
            for x in range(self.game_size):
                for y in range(self.game_size):
                    Color((not a[x, y])*255 + 0,
                          (not a[x, y])*255 + 0,
                          (not a[x, y])*255 + 0)
                    Rectangle(pos=[d*s for d, s in zip((x, y), self.tile_size)], size=self.tile_size)

class ConwaysGameofLife(App):
    def build(self):
        return CGOLWidget()

if __name__ == '__main__':
    ConwaysGameofLife().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment