Last active
March 11, 2020 20:36
-
-
Save jtiai/52c00b7f200284709ea1e3d525a92e01 to your computer and use it in GitHub Desktop.
Game of Life
This file contains 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 as pg | |
import sys | |
import collections | |
# Number of cells | |
CELL_GRID_WIDTH = 50 | |
CELL_GRID_HEIGHT = 50 | |
# Visible size of the cell | |
CELL_WIDTH = 10 | |
CELL_HEIGHT = 10 | |
pg.init() | |
screen = pg.display.set_mode((CELL_GRID_WIDTH * CELL_WIDTH, CELL_GRID_HEIGHT * CELL_HEIGHT)) | |
CELL_SURF = pg.Surface((CELL_WIDTH, CELL_HEIGHT)) | |
CELL_SURF.fill((255, 255, 255), ((0,0), (9, 9))) | |
GLIDER = [ | |
" X", | |
" X", | |
"XXX", | |
] | |
def load_initial(cells, pos, initial): | |
x, y = pos | |
for y_offset, row in enumerate(initial): | |
for x_offset, marker in enumerate(row): | |
if marker != " ": | |
cells[x + x_offset, y + y_offset] = 1 | |
def evolve(cells): | |
"""Evolves cells according to rules""" | |
# Note: Grid is "infinite" | |
new_cells = collections.defaultdict(lambda: 0) | |
for x in range(CELL_GRID_WIDTH): | |
for y in range(CELL_GRID_HEIGHT): | |
# Calculate number of neighbours | |
new_cells[x, y] += cells[x - 1, y] # left | |
new_cells[x, y] += cells[x + 1, y] # right | |
new_cells[x, y] += cells[x, y - 1] # top | |
new_cells[x, y] += cells[x, y + 1] # bottom | |
new_cells[x, y] += cells[x - 1, y - 1] # topleft | |
new_cells[x, y] += cells[x + 1, y + 1] # bottomright | |
new_cells[x, y] += cells[x + 1, y - 1] # topright | |
new_cells[x, y] += cells[x - 1, y + 1] # bottomleft | |
if new_cells[x, y] == 2 and cells[x, y]: | |
new_cells[x, y] = 1 | |
elif new_cells[x, y] == 3: | |
new_cells[x, y] = 1 | |
else: | |
new_cells[x, y] = 0 | |
return new_cells | |
def draw_cells(cells, screen): | |
rect = pg.Rect((0, 0), (CELL_WIDTH, CELL_HEIGHT)) | |
for x in range(CELL_GRID_WIDTH): | |
for y in range(CELL_GRID_HEIGHT): | |
if cells[x, y]: | |
rect.x = x * CELL_WIDTH | |
rect.y = y * CELL_HEIGHT | |
screen.blit(CELL_SURF, rect) | |
def life(cells): | |
clock = pg.time.Clock() | |
evolve_timer = 500 | |
# Main game loop | |
while True: | |
dt = clock.tick(30) | |
for event in pg.event.get(): | |
if event.type == pg.QUIT: | |
sys.exit() | |
evolve_timer -= dt | |
if evolve_timer <= 0: | |
# Evolve cells | |
evolve_timer = 1000 | |
cells = evolve(cells) | |
screen.fill((0, 0, 0)) | |
# Draw current state | |
draw_cells(cells, screen) | |
pg.display.flip() | |
if __name__ == "__main__": | |
cells = collections.defaultdict(lambda: 0) | |
load_initial(cells, (20, 20), GLIDER) | |
life(cells) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment