Last active
February 9, 2025 03:28
-
-
Save alankrantas/2cb9699ea3b6a04ea0f39c0b5f8dca8d to your computer and use it in GitHub Desktop.
Conway's Game of Life - using Pygame
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
''' | |
Conway's Game of Life | |
Install Pygame: | |
``` | |
pip install pygame | |
``` | |
''' | |
# game configuration | |
RULE = ((3, ), (2, 3)) # game rule: B3/S23 | |
# see: https://en.wikipedia.org/wiki/Life-like_cellular_automaton#A_selection_of_Life-like_rules | |
RAND_PCT = 25 # cell seeding chance (25%) | |
WIDTH = 100 # board width | |
HEIGHT = 50 # board height | |
DRAW_SIZE = 8 # size of a "pixel" | |
DELAY = 0.05 # cycle delay | |
# to create a Gosper glider gun instead, set to True | |
glider_gun = False | |
import random, time, gc, pygame | |
gc.enable() | |
pygame.init() | |
screen = pygame.display.set_mode([WIDTH * DRAW_SIZE, HEIGHT * DRAW_SIZE]) | |
TOTAL = WIDTH * HEIGHT | |
def init(): | |
global board, glider_gun | |
board = [0] * TOTAL | |
if not glider_gun: | |
for i in range(TOTAL): | |
if random.randint(0, (100 // RAND_PCT) - 1) == 0: | |
board[i] = 1 | |
else: | |
glider_gun = [ | |
WIDTH*1+25, | |
WIDTH*2+23, | |
WIDTH*2+25, | |
WIDTH*3+13, | |
WIDTH*3+14, | |
WIDTH*3+21, | |
WIDTH*3+22, | |
WIDTH*3+35, | |
WIDTH*3+36, | |
WIDTH*4+12, | |
WIDTH*4+16, | |
WIDTH*4+21, | |
WIDTH*4+22, | |
WIDTH*4+35, | |
WIDTH*4+36, | |
WIDTH*5+1, | |
WIDTH*5+2, | |
WIDTH*5+11, | |
WIDTH*5+17, | |
WIDTH*5+21, | |
WIDTH*5+22, | |
WIDTH*6+1, | |
WIDTH*6+2, | |
WIDTH*6+11, | |
WIDTH*6+15, | |
WIDTH*6+17, | |
WIDTH*6+18, | |
WIDTH*6+23, | |
WIDTH*6+25, | |
WIDTH*7+11, | |
WIDTH*7+17, | |
WIDTH*7+25, | |
WIDTH*8+12, | |
WIDTH*8+16, | |
WIDTH*9+13, | |
WIDTH*9+14, | |
] | |
for i in glider_gun: | |
board[i] = 1 | |
def next_gen(): | |
global board | |
buffer = [0] * TOTAL | |
for i in range(TOTAL): | |
i1 = (i - 1) if (i % WIDTH) - 1 >= 0 else (i - 1) + WIDTH | |
i3 = (i + 1) if (i % WIDTH) + 1 < WIDTH else (i + 1) - WIDTH | |
cells = board[i1] + board[i3] + \ | |
board[i1 - WIDTH] + board[i - WIDTH] + board[i3 - WIDTH] + \ | |
board[(i1 + WIDTH) % TOTAL] + board[(i + WIDTH) % TOTAL] + board[(i3 + WIDTH) % TOTAL] | |
if cells in RULE[board[i]]: | |
buffer[i] = 1 | |
pygame.draw.circle(screen, | |
(255, 255, 255) if buffer[i] else (0, 0, 0), | |
(i % WIDTH * DRAW_SIZE, i // WIDTH * DRAW_SIZE), DRAW_SIZE // 2) | |
board = buffer | |
pygame.display.flip() | |
pygame.display.set_caption(f'Conway\'s Game of Life [{sum(board)} cells]') | |
init() | |
running = True | |
while running: | |
for event in pygame.event.get(): | |
if event.type == pygame.QUIT: | |
running = False | |
next_gen() | |
time.sleep(DELAY) | |
pygame.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment