game-of-life.py (2048B)
1 import pygame 2 import random 3 import pygame.locals 4 import sys 5 6 7 grid_size = int(sys.argv[1]) 8 living = int(sys.argv[2]) 9 10 11 pygame.init() 12 13 WIDTH = 1500 14 HEIGHT = 1500 15 16 WHITE = (255,255,255) 17 BLACK = (0,0,0) 18 19 DISPLAY = pygame.display.set_mode((WIDTH,HEIGHT), pygame.RESIZABLE) 20 21 22 def simulate(prior): 23 result = [row[:] for row in prior] 24 25 count = 0 26 27 for y in range(len(prior)): 28 for x in range(len(prior[y])): 29 neighbors = 0 30 for dx in range(-1,2): 31 for dy in range(-1,2): 32 if dx == 0 and dy == 0: 33 continue 34 if dx + x < 0 or dx + x >= len(prior[y]): 35 continue 36 if dy + y < 0 or dy + y >= len(prior): 37 continue 38 neighbors += prior[dy+y][dx+x] 39 is_alive = prior[y][x] 40 if neighbors == 3 or (is_alive and neighbors == 2): 41 result[y][x] = 1 42 count += 1 43 else: 44 # this is a copy of input... 45 result[y][x] = 0 46 47 return result 48 49 50 def drawGrid(g): 51 blockSize = int(WIDTH / len(g)) 52 for y in range(0, WIDTH, blockSize): 53 for x in range(0, HEIGHT, blockSize): 54 if g[int(y / blockSize)][int(x / blockSize)] == 1: 55 rect = pygame.Rect(x, y, blockSize, blockSize) 56 pygame.draw.rect(DISPLAY, WHITE, rect) 57 else: 58 rect = pygame.Rect(x, y, blockSize, blockSize) 59 pygame.draw.rect(DISPLAY, BLACK, rect) 60 61 62 grid = [[0] * grid_size for _ in range(grid_size)] 63 64 def seed(grid): 65 for i in range(0,living): 66 rnd_y = random.randint(0,len(grid) - 1) 67 rnd_x = random.randint(0,len(grid[0]) - 1) 68 grid[rnd_y][rnd_x] = 1 69 70 seed(grid) 71 72 while True: 73 for event in pygame.event.get(): 74 if event.type == pygame.locals.QUIT: 75 pygame.quit() 76 exit() 77 78 grid = simulate(grid) 79 80 DISPLAY.fill(BLACK) 81 drawGrid(grid) 82 pygame.display.update()