Created
April 22, 2015 13:22
-
-
Save fjkz/d07e123cc29360fa01f3 to your computer and use it in GitHub Desktop.
1D cellular automaton in terminal
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
#!/bin/python3 | |
from termcolor import colored | |
import os | |
import random | |
import sys | |
import time | |
def black_or_white(cell): | |
if cell > 0: | |
return colored(' ', 'white', attrs=['reverse']) | |
else: | |
return ' ' | |
def evolute(cells, wolfram_code): | |
n = len(cells) | |
new_cells = [None for _ in range(n)] | |
for i in range(n): | |
cl = cells[i - 1 if i > 1 else n - 1] | |
c = cells[i] | |
cr = cells[i + 1 if i < n - 1 else 0] | |
ccc = cl << 2 | c << 1 | cr | |
for j in range(8): | |
if ccc == j: | |
new_cells[i] = (wolfram_code >> j) & 1 | |
break | |
return new_cells | |
def get_term_width(): | |
_height, width = os.popen('stty size', 'r').read().split() | |
return int(width) | |
if __name__ == '__main__': | |
code = int(sys.argv[1]) | |
width = get_term_width()//2 | |
cells = [random.randint(0,1) for _ in range(width)] | |
while True: | |
for c in cells: | |
print(black_or_white(c), end='') | |
else: | |
print('') | |
cells = evolute(cells, code) | |
time.sleep(0.5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment