-
Notifications
You must be signed in to change notification settings - Fork 0
/
life.py
60 lines (53 loc) · 1.31 KB
/
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
import random
def init_life(numRows, numCols):
world = []
for r in range(numRows):
row = []
for c in range(numCols):
row.append(random.randint(0, 1))
world.append(row)
return world
def print_world(world):
for r in range(len(world)):
for c in range(len(world[r])):
if world[r][c]:
print '*'
else:
print ' '
print
def next_life(world, targetRow, targetCol):
numLiveNeighbours = 0
numRows = len(world)
numCols = len(world[0])
for r in range(targetRow - 1, targetRow + 2):
for c in range(targetCol - 1, targetCol + 2):
actualRow = r % numRows
actualCol = c % numCols
if (r != targetRow or c != targetCol) and world[actualRow][actualCol]:
numLiveNeighbours += 1
if world[targetRow][targetCol]:
if numLiveNeighbours == 2 or numLiveNeighbours == 3:
return 1
else:
return 0
else:
if numLiveNeighbours == 3:
return 1
else:
return 0
def life(world):
newWorld = []
numRows = len(world)
numCols = len(world[0])
for r in range(numRows):
newWorld.append([0]*numCols)
for r in range(numRows):
for c in range(numCols):
newWorld[r][c] = next_life(world, r, c)
return newWorld
world = init_life(5, 8)
print_world(world)
for x in range(10):
world = life(world)
print_world(world)
print'-----------------'