-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
87 lines (58 loc) · 2.04 KB
/
main.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
# 1 Any live cell with fewer than two live neighbours dies, as if by underpopulation.
# 2 Any live cell with two or three live neighbours lives on to the next generation.
# 3 Any live cell with more than three live neighbours dies, as if by overpopulation.
# 4 Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
# use "X" for alive and " " for dead
import os
import time
import random
def createMatrix():
rows = 40
columns = 150
matrix = [[random.randint(0,1) for i in range(columns)] for j in range(rows)]
for row in matrix:
print("".join(str(cell) for cell in row))
return matrix
def countNeighbours(matrix, x, y):
directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
rows = len(matrix)
columns = len(matrix[0])
liveNeighbours = 0
for dx, dy in directions:
nx = x + dx
ny = y + dy
if 0 <= nx < rows and 0 <= ny < columns:
liveNeighbours += matrix[nx][ny]
return liveNeighbours
def updateMatrix(matrix):
rows = len(matrix)
columns = len(matrix[0])
newMatrix = [[0 for i in range(columns)] for j in range(rows)]
for x in range(rows):
for y in range(columns):
liveNeighbours = countNeighbours(matrix, x, y)
if matrix[x][y] == 1:
if liveNeighbours in [2, 3]:
newMatrix[x][y] = 1
else:
newMatrix[x][y] = 0
else:
if liveNeighbours == 3:
newMatrix[x][y] = 1
else:
newMatrix[x][y] = 0
return newMatrix
def clearScreen():
os.system("clear")
def runSimulation():
matrix = createMatrix()
while True:
clearScreen()
matrix = updateMatrix(matrix)
for row in matrix:
print("".join("█" if cell else " " for cell in row))
time.sleep(0.5)
# █ ■
runSimulation()
#matrixGrl = createMatrix()
#updateMatrix(matrixGrl)