-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.py
79 lines (69 loc) · 2.62 KB
/
game.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import numpy as np
from time import sleep
from tabulate import tabulate
from os import system, name
# define the row/col lengths
GRID_ROW_LEN = 20
GRID_COL_LEN = 20
GRID_ALIVE_PROB = 0.3
# Define alive and dead, alive is 1, dead is 0
ALIVE = "x"
# Use Braille Pattern Blank Unicode Character to ensure fixed width columns in grid
DEAD = "\u2800"
def clear_screen():
# check and make call (specific to operating system in use)
# windows => 'cls' & max/linux => 'clear'
_ = system('cls' if name == 'nt' else 'clear')
# Define array of arrays for the table
def create_grid():
return [ np.random.choice([DEAD, ALIVE], size=GRID_COL_LEN, p=[1-GRID_ALIVE_PROB, GRID_ALIVE_PROB]) for _ in range(GRID_ROW_LEN) ]
# Define rules of underpopulation, overpopulation, loneliness
def count_neighbors(x, y, grid):
live_count = 0
neighbor_points = [(x-1,y-1), (x-1,y), (x-1,y+1), (x,y-1), (x,y+1), (x+1,y-1), (x+1,y), (x+1,y+1)]
for pt in neighbor_points:
try:
neighbor = grid[pt[0]][pt[1]]
if neighbor == ALIVE:
live_count += 1
except IndexError:
pass
return live_count
def check_grid(grid):
# starting new grid as all 0s
new_grid = [ np.array([DEAD] * GRID_COL_LEN) for _ in range(GRID_ROW_LEN) ]
for x in range(GRID_ROW_LEN):
for y in range(GRID_COL_LEN):
cell = grid[x][y]
n = count_neighbors(x,y, grid)
# apply rules to set all live cells for next generation
# 1. dead cell with three live neighbors is now alive
# 2. live cell with two or three live neighbors survives
# 3. live cell with less than two or more than 3 live neighbors dies
if (cell == DEAD and n == 3) or (cell == ALIVE and (n == 2 or n == 3)):
new_grid[x][y] = ALIVE
if (cell == ALIVE and (n < 2 or n > 3)):
new_grid[x][y] = DEAD
return new_grid
def print_grid(grid, gen_num):
# clear the screen first
clear_screen()
# show gen_num number
print(f"Generation: {gen_num}")
# Print: Use tabulate to pretty print the grid
print(tabulate(grid, tablefmt="heavy_grid"))
# main loop
def main():
gen_num = 0
grid = create_grid()
print_grid(grid, gen_num)
while True:
gen_num += 1
sleep(1) # pause to let the viewer see each generation of the grid
# Check current grid cells against rules and set changes to a new grid
# and update the old grid with new grid
grid = check_grid(grid)
# display the resulting grid
print_grid(grid, gen_num)
if __name__ == "__main__":
main()