Last active
March 22, 2016 21:55
-
-
Save bgola/5e90e9960fe95a0d71b8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import os, random, time, fcntl, termios, struct | |
# SETUP | |
BACKGROUND=" " | |
FILL="." | |
BUFFER = [] | |
FRAMERATE = 20 | |
# To get terminal number of lines and columns | |
def ioctl_GWINSZ(fd): | |
cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) | |
return cr | |
size = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) | |
WIDTH,HEIGHT = int(size[1]), int(size[0]) | |
def neighbours(x,y): | |
total = 0 | |
for pos in [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]: | |
try: | |
if BUFFER[y+pos[0]][x+pos[1]] == FILL: | |
total += 1 | |
except IndexError: | |
pass | |
return total | |
def draw(): | |
to_live = [] | |
to_die = [] | |
for y in range(HEIGHT): | |
for x in range(WIDTH): | |
status = neighbours(x,y) | |
if status < 2 or status > 3: | |
to_die.append((x,y)) | |
if status == 3: | |
to_live.append((x,y)) | |
while to_live: | |
x,y = to_live.pop() | |
BUFFER[y][x] = FILL | |
while to_die: | |
x,y = to_die.pop() | |
BUFFER[y][x] = BACKGROUND | |
def background(c): | |
global BACKGROUND, BUFFER | |
BACKGROUND = c | |
BUFFER = [ [ BACKGROUND for _ in range(WIDTH) ] for _ in range(HEIGHT) ] | |
def glider(x,y): | |
BUFFER[y][x+1] = FILL | |
BUFFER[y+1][x+2] = FILL | |
BUFFER[y+2][x] = FILL | |
BUFFER[y+2][x+1] = FILL | |
BUFFER[y+2][x+2] = FILL | |
# Setup the buffer | |
background(" ") | |
# Add some random gliders | |
for _ in range(100): glider(random.randint(0,WIDTH-5),random.randint(0,HEIGHT-5)) | |
try: | |
while True: | |
for line in BUFFER: | |
print("".join(line)) | |
draw() | |
time.sleep(1/FRAMERATE) | |
except KeyboardInterrupt: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment