-
Notifications
You must be signed in to change notification settings - Fork 0
/
Conway_Game_Life.py
142 lines (99 loc) · 2.8 KB
/
Conway_Game_Life.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# Rafsanjani Muhammod
# Problem : Conway's Game of Life
from math import *
from numpy import *
from pandas import *
def isValid(row, column):
if (row >= 1 and row <= 9) and (column >= 1 and column <= 9):
return True
else:
return False
def adjacent(box, row, column):
if box[row, column] == 1:
C = 0
else:
C = 1
i = row - 1
while i <= row + 1:
j = column - 1
while j <= column + 1:
if isValid(i, j):
if box[i, j] == 1:
C = C + 1
j = j + 1
i = i + 1
return C - 1
def calculation(box, reserved):
for i in range(1, 10, 1):
for j in range(1, 10, 1):
C = adjacent(box, i, j)
if box[i, j] == 1:
# print("({}, {}), C = {}".format(i, j, C))
if (C == 2) or (C == 3):
reserved[i, j] = 1 # Remain population
elif C < 2:
reserved[i, j] = 0 # Under population
elif C > 3:
reserved[i, j] = 0 # Over population
else:
# print("({}, {}), C = {}".format(i, j, C))
if C == 3:
reserved[i, j] = 1 # Reproduction
return reserved
def isDead(myArray):
for i in range(1, 10, 1):
for j in range(1, 10, 1):
if myArray[i, j] != 0:
return False
return True
def isHappy(pre, next):
for i in range(1, 10, 1):
for j in range(1, 10, 1):
if pre[i, j] != next[i, j]:
return False
return True
def display(myArray):
for column in range(1, 10, 1):
if column == 1:
print(" ", column, end="")
else:
if column == 2:
print("", column, end=" ")
else:
print(column, end=" ")
print()
for i in range(1, 10, 1):
print(i, end=" : ")
for j in range(1, 10, 1):
print(myArray[i, j], end=" ")
print()
print()
def main():
box = zeros([10, 10], dtype=int)
box[4, 5] = 1
box[5, 5] = 1
box[5, 6] = 1
box[6, 4] = 1
box[6, 6] = 1
pre = zeros([10, 10], dtype=int)
next = zeros([10, 10], dtype=int)
pre[:, :] = box[:, :]
next[:, :] = box[:, :]
print("Generation # 0 :")
display(box)
C = 1
while True:
next = calculation(pre, next)
print("Generation # {} :".format(C))
display(next)
if isDead(next):
print("Dead ! at generation : {}".format(C-1))
break
else:
if isHappy(pre, next):
print("Happy ! at generation : {}".format(C-1))
break
pre[:,:] = next[:,:]
C = C + 1
if __name__ == '__main__':
main()