Skip to content

Instantly share code, notes, and snippets.

@dbechrd
Created September 18, 2024 19:13
Show Gist options
  • Save dbechrd/b92d96b89fe3e5d86091a980a2e1079b to your computer and use it in GitHub Desktop.
Save dbechrd/b92d96b89fe3e5d86091a980a2e1079b to your computer and use it in GitHub Desktop.
# Copyright 2022 Ben Groves & Dan Bechard @ Avvir.io
# MIT License
import os
import time
import random
from copy import deepcopy
def create_board(size):
board = [[0] * size for i in range(size)]
return board
def create_glider(board, x, y):
assert(len(board) >= 3)
board[y + 0][x] = 0; board[y + 0][x + 1] = 1; board[y + 0][x + 2] = 0
board[y + 1][x] = 0; board[y + 1][x + 1] = 0; board[y + 1][x + 2] = 1
board[y + 2][x] = 1; board[y + 2][x + 1] = 1; board[y + 2][x + 2] = 1
return board
def simulate_cell(cell, live_neighbors):
new_cell = cell
if cell == 1 and (live_neighbors < 2 or live_neighbors > 3):
new_cell = 0
elif cell == 0 and live_neighbors == 3:
new_cell = 1
return new_cell
def simulate(board):
assert(len(board) > 0)
assert(len(board) == len(board[0]))
new_board = deepcopy(board)
# For each cell in board
for y in range(0, len(board)):
for x in range(0, len(board)):
# TODO(dlb): Separate out into cell_live_neighbor_count and test
# For each neighbor of this cell
live_neighbors = 0
for y2 in range(y - 1, y + 2):
for x2 in range(x - 1, x + 2):
if y2 < 0: y2 += len(board)
if x2 < 0: x2 += len(board)
y2 %= len(board)
x2 %= len(board)
if (y2 != y or x2 != x) and board[y2][x2] == 1:
live_neighbors += 1
new_board[y][x] = simulate_cell(board[y][x], live_neighbors)
return new_board
def clear():
os.system('clear')
def create_starfield(size):
starfield = [[0] * size for i in range(size)]
for y in range(0, size):
for x in range(0, size):
starfield[y][x] = random.randint(1, 20) == 20
return starfield
def display(board, starfield, starfield_offset):
clear()
for y in range(0, len(board)):
for x in range(0, len(board)):
star_y = (y + starfield_offset) % len(board)
star_x = (x + starfield_offset) % len(board)
star = starfield[star_y][star_x]
cell = board[y][x]
print('■ ' if cell else ('* ' if star else ' '), end='')
print('')
if __name__ == "__main__":
board_size = 32
board = create_board(board_size)
create_glider(board,
random.randint(1, len(board) - 3),
random.randint(1, len(board) - 3)
)
starfield = create_starfield(board_size)
delay = 0.05
display(board, starfield, 0)
time.sleep(delay)
frame = 0
while True:
if frame % 50 == 0:
create_glider(board,
random.randint(1, len(board) - 3),
random.randint(1, len(board) - 3)
)
board = simulate(board)
display(board, starfield, frame % len(board))
time.sleep(delay)
frame += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment