Skip to content

Instantly share code, notes, and snippets.

@minamiyama1994
Forked from utgwkk/lifegame.py
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minamiyama1994/9661915 to your computer and use it in GitHub Desktop.
Save minamiyama1994/9661915 to your computer and use it in GitHub Desktop.
import pygame, sys, random
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 = [[x for x in y] for y in cells]
clock = pygame.time.Clock()
stop = False
def get_alive(x, y):
cnt = 0
for i in range ( -1 , 2 ) :
for j in range ( -1 , 2 ) :
if i != 0 and j != 0 :
cnt += 1 if cells_swp[(y+j+height)%height][(x+i+width)%width] 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 = [[x for x in y] for y in cells]
pygame.display.flip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment