Skip to content

Instantly share code, notes, and snippets.

@abstractart
Created June 29, 2021 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abstractart/29922872ea2f2f10456b17cec623d9f2 to your computer and use it in GitHub Desktop.
Save abstractart/29922872ea2f2f10456b17cec623d9f2 to your computer and use it in GitHub Desktop.
from random import randint
from time import sleep
from copy import deepcopy
import os
LIFE = 1
DEATH = 0
def main():
cols, rows = 7, 7
area = [[0 for i in range(cols)] for j in range(rows)]
glider(area, cols, rows)
start(area, rows, cols)
def glider(area, rows, cols):
x, y = randint(0, rows - 1), randint(0, cols - 1)
area[x][y] = LIFE
area[(x + 1) % rows][(y + 1) % cols] = LIFE
area[(x + 1) % rows][(y + 2) % cols] = LIFE
area[(x + 2) % rows][y] = LIFE
area[(x + 2) % rows][y + 1] = LIFE
area[(x + 2) % rows][y + 1] = LIFE
def start(area, rows, cols):
interval = 0.5
while(True):
printArea(area)
newArea = deepcopy(area)
for i in range(rows):
for j in range(cols):
newArea[i][j] = nextState(i, j, area, rows, cols)
area = newArea
sleep(interval)
def nextState(i, j, area, rows, cols):
total = (
area[(i - 1) % rows][(j - 1) % cols] +
area[(i - 1) % rows][j] +
area[(i - 1) % rows][(j + 1) % cols] +
area[i][(j + 1) % cols] +
area[(i + 1) % rows][(j + 1) % cols] +
area[(i + 1) % rows][j] +
area[(i + 1) % rows][(j - 1) % cols] +
area[i][(j - 1) % cols]
)
if area[i][j] == LIFE:
if total > 3 or total < 2:
return DEATH
elif area[i][j] == DEATH:
if total == 3:
return LIFE
return area[i][j]
def printArea(area):
os.system('clear')
print('\n'.join([''.join([char(cell) for cell in row]) for row in area]))
def char(n):
if n == LIFE: return '*'
return '-'
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment