Last active
May 16, 2023 18:11
-
-
Save aidenfoxivey/a2991b6e2b147dcd186e9994a3ebe7ec to your computer and use it in GitHub Desktop.
Conway's 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
# Teon Brooks, Aiden Fox Ivey 2023 | |
import os | |
import time | |
# Any live cell with two or three live neighbours survives. | |
# Any dead cell with three live neighbours becomes a live cell. | |
# All other live cells die in the next generation. Similarly, all other dead cells stay dead. | |
def display(board): | |
for i in range(0,len(board)): | |
print("_",end="") | |
print() | |
for row_num in range(0, len(board)): | |
print("|", end="") | |
for col_num in range(0, len(board)): | |
val = board[row_num][col_num] | |
if val == 0: | |
print(end=" ") | |
else: | |
print("1", end=" ") | |
# print(board[row_num][col_num], end=" ") | |
print("|", end="") | |
print() | |
for i in range(0,len(board)): | |
print("_",end="") | |
print() | |
def count_alive_neighbours(board, i, j): | |
neighbour_count = 0 | |
for k in [-1, 0, 1]: | |
for l in [-1, 0, 1]: | |
if k == 0 and l == 0: | |
continue | |
foo = i + k | |
bar = j + l | |
if foo >= len(board) or foo < 0: | |
continue | |
if bar >= len(board) or bar < 0: | |
continue | |
if board[foo][bar]: | |
assert (not (k == 0 and l == 0)) | |
assert (k != 0 or l != 0) | |
neighbour_count += 1 | |
return neighbour_count | |
def evolve(board): | |
updates = [] | |
for i in range(0, len(board)): | |
for j in range(0, len(board)): | |
cell = board[i][j] | |
neighbours = count_alive_neighbours(board, i, j) | |
if cell == 0: | |
if neighbours == 3: | |
updates.append((i, j, 1)) | |
continue | |
elif cell == 1: | |
if not (neighbours in [2, 3]): | |
updates.append((i, j, 0)) | |
continue | |
else: | |
print("What happened????") | |
exit(1) | |
for update in updates: | |
i, j, val = update | |
board[i][j] = val | |
def main(): | |
SIZE = os.get_terminal_size().lines | |
board = [[0] * SIZE for i in range(SIZE)] | |
for i in range(1, 4): | |
board[2][i] = 1 | |
board[1][4] = 1 | |
board[0][3] = 1 | |
# for i in range(SIZE-4, SIZE-1): | |
# board[2][i] = 1 | |
# board[1][SIZE-1] = 1 | |
# board[0][SIZE-2] = 1 | |
# display(board) | |
# return 0 | |
length = 100 | |
for i in range(1, length): | |
display(board) | |
evolve(board) | |
time.sleep(0.2) | |
if i != (length-1): | |
os.system("clear") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment