Skip to content

Instantly share code, notes, and snippets.

@NaPs
Created April 11, 2009 17:10
Show Gist options
  • Select an option

  • Save NaPs/93633 to your computer and use it in GitHub Desktop.

Select an option

Save NaPs/93633 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
#coding=utf8
import os
import sys
import copy
from random import randint
import pygame; pygame.init()
from pygame.locals import *
try:
import psyco
psyco.full()
except:
pass
def case2pxl(x, y, case_size=5):
''' Return a Rect which is the position of case. '''
return pygame.Rect((x*(case_size+1)+1, y*(case_size+1)+1), (case_size, case_size))
def get_case(x, y, x_len=100, y_len=100):
return (x % x_len, y % y_len)
def get_neighbors(x, y, x_len=100, y_len=100):
x, y = get_case(x, y, x_len=100, y_len=100)
neighbors = (
get_case(x, y-1), # top
get_case(x+1, y-1), # top right
get_case(x+1, y), # right
get_case(x+1, y+1), # bottom right
get_case(x, y+1), # bottom
get_case(x-1, y+1), # bottom left
get_case(x-1, y), # left
get_case(x-1, y-1), # top right
)
return neighbors
def generate_iteration(old_map):
x_len = len(old_map[0])
y_len = len(old_map)
map = copy.deepcopy(old_map)
for x in xrange(x_len):
for y in xrange(y_len):
neighbors = get_neighbors(x, y, x_len=x_len, y_len=y_len)
alives = len([True for n_x, n_y in neighbors if old_map[n_x][n_y]])
if alives == 3:
map[x][y] = True
elif alives == 2:
pass # no nothing
else:
map[x][y] = False
return map
def create_empty_grid(map_size=(100, 100)):
return [[False]*map_size[0]]*map_size[1]
def main(map_size=(200, 200), case_size=1):
screen_size = [x*case_size+x+1 for x in map_size]
screen = pygame.display.set_mode(screen_size)
# Background is a grid
background = pygame.Surface(screen_size)
background.fill((255, 255, 255))
background.convert()
# Drawing the grid
for x in range(0, screen_size[0], case_size + 1):
pygame.draw.line(background, (0, 0, 0), (x, 0), (x, screen_size[1]))
for x in range(0, screen_size[1], case_size + 1):
pygame.draw.line(background, (0, 0, 0), (0, x), (screen_size[0], x))
clock = pygame.time.Clock()
old_map = [[bool(randint(0, 1)) for x in xrange(map_size[0])] for y in xrange(map_size[1])]
while 0xBeef:
clock.tick(10)
screen.blit(background, background.get_rect())
map = generate_iteration(old_map)
# Draw the map
x_len = len(map[0])
y_len = len(map)
for x in xrange(x_len):
for y in xrange(y_len):
if map[x][y]:
screen.fill((0,0,0), case2pxl(x, y, case_size=case_size))
old_map = map
pygame.display.flip()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment