Skip to content

Instantly share code, notes, and snippets.

@Byteflux
Created July 16, 2021 01:03
Show Gist options
  • Save Byteflux/bdc4eddeeb74b30e76a758d3587f2d8c to your computer and use it in GitHub Desktop.
Save Byteflux/bdc4eddeeb74b30e76a758d3587f2d8c to your computer and use it in GitHub Desktop.
Conway's Game of Life (in Python)
#!/usr/bin/env python3
"""Conway's Game of Life"""
STEPS = 100
STEPS_PER_SECOND = 3
# Pulsar
SEED = ('0 0 0 0 0 0 0 0 0 0 0 0 0 0 0',
'0 0 0 1 1 1 0 0 0 1 1 1 0 0 0',
'0 0 0 0 0 0 0 0 0 0 0 0 0 0 0',
'0 1 0 0 0 0 1 0 1 0 0 0 0 1 0',
'0 1 0 0 0 0 1 0 1 0 0 0 0 1 0',
'0 1 0 0 0 0 1 0 1 0 0 0 0 1 0',
'0 0 0 1 1 1 0 0 0 1 1 1 0 0 0',
'0 0 0 0 0 0 0 0 0 0 0 0 0 0 0',
'0 0 0 1 1 1 0 0 0 1 1 1 0 0 0',
'0 1 0 0 0 0 1 0 1 0 0 0 0 1 0',
'0 1 0 0 0 0 1 0 1 0 0 0 0 1 0',
'0 1 0 0 0 0 1 0 1 0 0 0 0 1 0',
'0 0 0 0 0 0 0 0 0 0 0 0 0 0 0',
'0 0 0 1 1 1 0 0 0 1 1 1 0 0 0',
'0 0 0 0 0 0 0 0 0 0 0 0 0 0 0')
if __name__ == '__main__':
import time
board = []
for row in SEED:
board.append([int(c) for c in row if c in ('0', '1')])
width = len(board[0])
height = len(board)
step_duration = 1 / STEPS_PER_SECOND
for step in range(1, STEPS + 1):
start_time = time.time()
# clear previously written lines
if step > 1:
print('\033[F\033[K' * height, end='')
for row in board:
for cell in row:
style = '37;42' if cell else '32;40'
print(f'\033[0;{style}m {cell} ', end='')
print('\033[0m')
# don't calculate next generation on last step
if step == STEPS:
break
next = []
for y in range(height):
row = []
next.append(row)
for x in range(width):
neighbors = 0
for rel_y in range(-1, 2):
nb_y = rel_y + y
if nb_y >= 0 and nb_y < height:
for rel_x in range(-1, 2):
if rel_y == 0 and rel_x == 0:
continue
nb_x = rel_x + x
if nb_x >= 0 and nb_x < width and board[nb_y][nb_x]:
neighbors += 1
if neighbors == 3:
row.append(1)
elif neighbors < 2 or neighbors > 3:
row.append(0)
else:
row.append(board[y][x])
board = next
# sleep for remainder of step duration
remaining_time = step_duration - (time.time() - start_time)
if remaining_time > 0:
time.sleep(remaining_time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment