#导入所需模块
import time
import random
import copy
WIDE = 60
HEIGHT = 20
nextCells = []
for x in range(WIDE):
column = []
for y in range(HEIGHT):
if random.randint(0,1) == 0:
column.append('#')
else:
column.append('')
nextCells.append(column)
#让他们有50%生存机会
while True:
print('\n\n\n\n\n')
print('\033c', end='')
currentCells = copy.deepcopy(nextCells)
for y in range(HEIGHT):
for x in range (WIDE):
print(currentCells[x],[y],end = '')
print()
#用currentCell来计算nextCells中的细胞
for x in range(WIDE):
for y in range(HEIGHT):
leftCoord = (x - 1) % WIDE
rightCoord = (x + 1) % WIDE
aboveCoord = (y - 1) % HEIGHT
belowCoord = (y + 1) % HEIGHT
numNeighbors = 0
#取模他上下左右的令居
if currentCells[leftCoord][aboveCoord] == '#':
numNeighbors += 1
if currentCells[x][aboveCoord] == '#':
numNeighbors += 1
if currentCells[rightCoord][aboveCoord] == '#':
numNeighbors += 1
if currentCells[leftCoord][y] == '#':
numNeighbors += 1
if currentCells[rightCoord][y] == '#':
numNeighbors += 1
if currentCells[leftCoord][belowCoord] == '#':
numNeighbors += 1
if currentCells[x][belowCoord] == '#':
numNeighbors += 1
if currentCells[rightCoord][belowCoord] =='#':
numNeighbors += 1
if currentCells[x][y]=='#' and (numNeighbors == 2 or numNeighbors == 3):
nextCells[x][y] = '#'
elif currentCells[x][y] == ' ' and numNeighbors == 3:
nextCells[x][y]
else:
nextCells[x][y] = ''
#判定是否存活
time.sleep(1)
Pyton conway生存游戏--代码参考
最新推荐文章于 2024-10-07 20:05:17 发布