-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgameOfLife.py
More file actions
executable file
·81 lines (70 loc) · 2.07 KB
/
gameOfLife.py
File metadata and controls
executable file
·81 lines (70 loc) · 2.07 KB
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
80
81
import console
import sys
import time
from copy import *
from random import *
def read_seed():
#open given seed file
f = open(sys.argv[1],'r')
seed_ = f.readlines()
#manipulate to correct form
seed_ = [x for x in seed_ if not x.startswith('!')]
seed = [[0 for i in seed_[0]] for i in seed_]
for y,row in enumerate(seed_):
for x,cell in enumerate(row):
seed[y][x] = 1 if cell == 'O' else 0
return seed
def create_frame():
#create frame with all zeros
frame = [[0 for i in range(width)] for i in range(height)]
#insert seed into centre of frame
for j,y in enumerate(range(int((height-len(seed))/2),int((height+len(seed))/2))):
for i,x in enumerate(range(int((width-len(seed[0]))/2),int((width+len(seed[0]))/2))):
frame[y][x] = seed[j][i]
return frame
def is_alive(x,y):
#return state of given cell
return frame[y%height][x%width]
def check_cells(x,y):
#count number of alive cells surrounding
number = -1
for yOff in range(-1,2):
for xOff in range(-1,2):
number += is_alive(x+xOff,y+yOff)
#change state of cell depending on number of alive cells surrounding
if frame[y][x]:
if number < 2:
#any live cell with fewer than two live neighbours dies, as if caused by under-population.
new_frame[y][x] = 0
elif number < 4:
#any live cell with two or three live neighbours lives on to the next generation.
new_frame[y][x] = 1
else:
#any live cell with more than three live neighbours dies, as if by overcrowding.
new_frame[y][x] = 0
else:
if number == 2:
#any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
new_frame[y][x] = 1
#program start
width = console.WIDTH
height = console.HEIGHT-1
generation = 0
seed = read_seed()
frame = create_frame()
while True:
#print frame
for row in frame:
for cell in row:
out = '#' if cell else ' '
print(out,end='')
print()
print('Generation: '+str(generation))
#check cells using rules
new_frame = deepcopy(frame)
for y, row in enumerate(frame):
for x, cell in enumerate(row):
check_cells(x,y)
frame = new_frame
generation += 1
time.sleep(0)