Skip to content

Instantly share code, notes, and snippets.

@kitroed
Created June 10, 2014 03:01
Show Gist options
  • Save kitroed/5b6a038bd589ca771318 to your computer and use it in GitHub Desktop.
Save kitroed/5b6a038bd589ca771318 to your computer and use it in GitHub Desktop.
r/dailyprogrammer [6/2/2014] Challenge #165 [Easy] ASCII Game of Life
import os
import time
# global vars
iterations = 0
x = 0
y = 0
grid = []
# function to check life/death
def check_life(x_loc, y_loc, grid):
count = 0
# add up all the neighboring 8 cells
# upper left
count += grid[(x_loc - 1) % x][(y_loc + 1) % y]
# above
count += grid[(x_loc) % x][(y_loc + 1) % y]
# upper right
count += grid[(x_loc + 1) % x][(y_loc + 1) % y]
# left
count += grid[(x_loc - 1) % x][(y_loc) % y]
# right
count += grid[(x_loc + 1) % x][(y_loc) % y]
# lower left
count += grid[(x_loc - 1) % x][(y_loc - 1) % y]
# below
count += grid[(x_loc) % x][(y_loc - 1) % y]
# lower right
count += grid[(x_loc + 1) % x][(y_loc - 1) % y]
if grid[x_loc][y_loc] == 0 and count == 3:
return 1
elif grid[x_loc][y_loc] == 1 and count < 2:
return 0
elif grid[x_loc][y_loc] == 1 and count > 3:
return 0
else:
return grid[x_loc][y_loc]
def display_grid(grid_to_display):
for row in grid_to_display:
for item in row:
print('.' if item == 0 else '#', end='')
print()
# load grid
input_data = open('easy165data')
line_number = 0
first_line = True
for line in input_data:
if first_line:
# first line, load the numbers
iterations = int(line.split()[0])
x = int(line.split()[1])
y = int(line.split()[2])
# intitlize the height (lines) of the grid
grid = [[] for i in range(y)]
first_line = False
else:
for char in line:
if char == '#':
grid[line_number].append(1)
elif char == '.':
grid[line_number].append(0)
line_number += 1
input_data.close()
# grid loaded, loop through, inserting into next grid
for run in range(1, iterations + 1):
# clear screen for output
os.system('cls' if os.name == 'nt' else 'clear')
next_grid = [[] for i in range(y)]
for rownum in range(y):
for cellnum in range(x):
next_grid[rownum].append(check_life(rownum, cellnum, grid))
grid = next_grid
print("Pass #%d" % run)
display_grid(grid)
time.sleep(1)
32 17 17
.................
.................
....###...###....
.................
..#....#.#....#..
..#....#.#....#..
..#....#.#....#..
....###...###....
.................
....###...###....
..#....#.#....#..
..#....#.#....#..
..#....#.#....#..
.................
....###...###....
.................
.................
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment