|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import random, time, copy
- WIDTH = 60
- HEIGHT = 20
- while True:
- nextCells = []
- for i in range(WIDTH):
- column = []
- for y in range(HEIGHT):
- if random.randint(0, 1):
- column.append('#')
- else:
- column.append(' ')
- nextCells.append(column)
- print('\n\n\n\n\n')
- currentCells = copy.deepcopy(nextCells)
- for y in range(HEIGHT):
- for x in range(WIDTH):
- print(currentCells[x][y], end='')
- print()
- for x in range(WIDTH):
- for y in range(HEIGHT):
- leftCoord = (x-1) % WIDTH
- rightCoord = (x+1) % WIDTH
- 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] = ''
复制代码
这个程序有点没搞明白,就是其中的%的用法那里,
leftCoord = (x-1) % WIDTH
rightCoord = (x+1) % WIDTH
aboveCoord = (y-1) % HEIGHT
belowCoord = (y+1) % HEIGHT
这几句话到底是啥意思啊?
哪位前辈给指点一下啊
本帖最后由 nahongyan1997 于 2021-6-27 17:31 编辑
是为了防止索引的时候超界的, 举个例子:
(0,0)位置的元素左边的元素是 (-1,0),可是 -1 在列表中并不存在,直接索引肯定会出错,
但是 如果如 当前位置0 x % 左边一个的位置-1 = 0,所以这样就不会出现索引越界的情况了,
这样 0 % -1 = 0
右边同理,
已知最大宽度 60
60 右边是 61
60 % 61 = 60,
完美答案
给个最佳
|
|