Last active
August 29, 2015 13:57
-
-
Save utgwkk/9660187 to your computer and use it in GitHub Desktop.
A Lifegame for Python (requires Pygame)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pygame, sys, random | |
from copy import deepcopy | |
pygame.init() | |
size = (800,450) | |
white = (255, 255, 255) | |
color = (30, 30, 180) | |
fps = 30 | |
screen = pygame.display.set_mode(size) | |
pygame.display.set_caption('lifegame') | |
cellsize = 8 | |
width, height = [x/cellsize for x in size] | |
cells = [[(True, False)[random.randint(0,1)] for x in xrange(width)] for y in xrange(height)] | |
cells_swp = deepcopy(cells) | |
clock = pygame.time.Clock() | |
stop = False | |
def get_alive(x, y): | |
cnt = 0 | |
for i in xrange(-1, 2): | |
for j in xrange(-1, 2): | |
if x+i==-1 or x+i==width or y+j==-1 or y+j==height or (i==0 and j==0): continue | |
cnt += 1 if cells_swp[y+j][x+i] else 0 | |
return cnt | |
while True: | |
clock.tick(fps) | |
for e in pygame.event.get(): | |
if e.type == pygame.QUIT: sys.exit() | |
elif e.type == pygame.KEYDOWN and e.key == pygame.K_SPACE: stop = not stop | |
if stop: continue | |
screen.fill(white) | |
for y in xrange(height): | |
for x in xrange(width): | |
alive = get_alive(x, y) | |
if alive == 3 and not cells_swp[y][x]: cells[y][x] = True | |
if alive <= 1 or alive >= 4: cells[y][x] = False | |
if cells[y][x]: pygame.draw.rect(screen, color, pygame.Rect(x*cellsize, y*cellsize, cellsize, cellsize)) | |
cells_swp = deepcopy(cells) | |
pygame.display.flip() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment