Skip to content

Instantly share code, notes, and snippets.

@ali1234
Created March 11, 2018 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ali1234/6b019867d61c1ac2d916ca10ec720d2a to your computer and use it in GitHub Desktop.
Save ali1234/6b019867d61c1ac2d916ca10ec720d2a to your computer and use it in GitHub Desktop.
PySDL2 Life Demo
import sys
import sdl2
import sdl2.ext
import numpy as np
class Life(object):
def __init__(self, height, width):
self.width = width
self.height = height
self.buf = np.random.randint(0, 255, (self.height+2, self.width), dtype=np.uint8) == 0
def __call__(self):
self.buf = np.roll(self.buf, -1, axis=0)
self.buf[-1] = np.random.randint(0, 3, (1, self.width), dtype=np.uint8) == 0
hneighbours = np.roll(self.buf, 1, axis=0)*1 + self.buf*1 + np.roll(self.buf, -1, axis=0)*1
neighbours = np.roll(hneighbours, 1, axis=1)*1 + hneighbours*1 + np.roll(hneighbours, -1, axis=1)*1 - self.buf
self.buf = self.buf & (neighbours > 1) & (neighbours < 4)
self.buf = self.buf | (neighbours == 3)
return self.buf[2:][:,:,np.newaxis] * np.array([[[255, 255, 255, 255]]])
def run():
sdl2.ext.init()
window = sdl2.ext.Window("Life", size=(800, 600))
window.show()
life = Life(*window.size)
surfarray = sdl2.ext.pixels3d(window.get_surface())
running = True
while running:
events = sdl2.ext.get_events()
for event in events:
if event.type == sdl2.SDL_QUIT:
running = False
break
surfarray[:] = life()
window.refresh()
return 0
if __name__ == "__main__":
sys.exit(run())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment