random-grid.py (1252B)
1 import pygame, sys 2 import random 3 from pygame.locals import * 4 5 pygame.init() 6 7 RED = (255,0,0) 8 BLACK = (0, 0, 0) 9 WHITE = (255, 255, 255) 10 11 Y=5 12 X=5 13 14 WIDTH = 500 15 HEIGHT = 500 16 17 DISPLAY = pygame.display.set_mode((WIDTH, HEIGHT)) 18 pygame.display.set_caption('Hello World!') 19 20 21 22 grid = [ 23 [0,0,0,0,0], 24 [0,1,1,0,0], 25 [0,1,1,0,0], 26 [0,0,0,1,0], 27 [1,0,0,0,0] 28 ] 29 30 def simulate(prior): 31 neighbors = prior.copy() 32 33 for y in range(len(prior)): 34 for x in range(len(prior[y])): 35 neighbors[y][x] = random.randint(0,2) 36 37 return neighbors 38 39 40 def drawGrid(): 41 blockSize = int(WIDTH / len(grid)) 42 for x in range(0, WIDTH, blockSize): 43 for y in range(0, HEIGHT, blockSize): 44 if grid[int(x / blockSize)][int(y / blockSize)] == 1: 45 rect = pygame.Rect(x, y, blockSize, blockSize) 46 pygame.draw.rect(DISPLAY, WHITE, rect) 47 else: 48 rect = pygame.Rect(x, y, blockSize, blockSize) 49 pygame.draw.rect(DISPLAY, WHITE, rect, 1) 50 51 52 53 while True: 54 for event in pygame.event.get(): 55 if event.type == QUIT: 56 pygame.quit() 57 sys.exit() 58 59 grid = simulate(grid) 60 DISPLAY.fill(BLACK) 61 drawGrid() 62 pygame.display.update() 63