1 # Conway's Game of Life
2 import random, time, copy
3 WIDTH = 60
4 HEIGHT = 20
5
6 # Create a list of list for the cells:
7 nextCells = []
8 for x in range(WIDTH):
9 column = [] # Create a new column.
10 for y in range(HEIGHT):
11 if random.randint(0, 1) == 0: #0\1两个整数中随机取一个
12 column.append('#') # Add a living cell.
13 else:
14 column.append(' ') # Add a dead cell.
15 nextCells.append(column) # nextCells is a list of column lists.
16
17 while True: # Main program loop.
18 print('\n\n\n\n\n') # Separate each step with newlines.
19 currentCells = copy.deepcopy(nextCells)#深度拷贝
20
21 # Print currentCells on the screen:
22 for y in range(HEIGHT):
23 for x in range(WIDTH):
24 print(currentCells[x][y], end='') # Print the # or space “end不换行
25 print() # Print a newline at the end of the row.
26
27 # Calculate the next step's cells based on current step's cells:
28 for x in range(WIDTH):
29 for y in range(HEIGHT):
30 # Get neighboring coordinates:
31 # `% WIDTH` ensures leftCoord is always between 0 and WIDTH - 1,巧妙简化边界
32 leftCoord = (x - 1) % WIDTH
33 rightCoord = (x + 1) % WIDTH
34 aboveCoord = (y - 1) % HEIGHT
35 belowCoord = (y + 1) % HEIGHT
36
37 # Count number of living neighbors:
38 numNeighbors = 0
39 if currentCells[leftCoord][aboveCoord] == '#':
40 numNeighbors += 1 # Top-left neighbor is alive.
41 if currentCells[x][aboveCoord] == '#':
42 numNeighbors += 1 # Top neighbor is alive.
43 if currentCells[rightCoord][aboveCoord] == '#':
44 numNeighbors += 1 # Top-right neighbor is alive.
45 if currentCells[leftCoord][y] == '#':
46 numNeighbors += 1 # Left neighbor is alive.
47 if currentCells[rightCoord][y] == '#':
48 numNeighbors += 1 # Right neighbor is alive.
49 if currentCells[leftCoord][belowCoord] == '#':
50 numNeighbors += 1 # Bottom-left neighbor is alive.
51 if currentCells[x][belowCoord] == '#':
52 numNeighbors += 1 # Bottom neighbor is alive.
53 if currentCells[rightCoord][belowCoord] == '#':
54 numNeighbors += 1 # Bottom-right neighbor is alive.
55
56 # Set cell based on Conway's Game of Life rules:
57 if currentCells[x][y] == '#' and (numNeighbors == 2 or
58 numNeighbors == 3):
59 # Living cells with 2 or 3 neighbors stay alive:
60 nextCells[x][y] = '#'
61 elif currentCells[x][y] == ' ' and numNeighbors == 3:
62 # Dead cells with 3 neighbors become alive:
63 nextCells[x][y] = '#'
64 else:
65 # Everything else dies or stays dead:
66 nextCells[x][y] = ' '
67 time.sleep(1) # Add a 1-second pause to reduce flickering.