import random, time, copy import matplotlib.pyplot as plt from matplotlib.pyplot import MultipleLocator from matplotlib.animation import FuncAnimation # 设置画布dpi和大小 fig = plt.figure(dpi=100, figsize=(6, 6)) # 画布边缘设置颜色 fig.patch.set_facecolor('yellow') # 设置透明度 fig.patch.set_alpha(0.5) ax = fig.add_subplot(111) # 设置背景颜色 ax.patch.set_facecolor('yellow') # 设置透明度 ax.patch.set_alpha(1) # 隐藏坐标轴 plt.axis('off') WIDTH = 100 HEIGHT = 100 scatter1 = plt.scatter([], []) def init(): # x轴范围设置 plt.xlim(0, 100) # y轴范围设置 plt.ylim(0, 100) # 有x轴刻度线间隔 x_major_locator = MultipleLocator(20) # y轴刻度线间隔 y_major_locator = MultipleLocator(20) ax.yaxis.set_major_locator(y_major_locator) ax.xaxis.set_major_locator(x_major_locator) plt.title("Conway") return scatter1, nextCells = [] for x in range(WIDTH): colum = [] for y in range(HEIGHT): if random.randint(0, 1) == 0: colum.append('#') else: colum.append('*') nextCells.append(colum) def update(frame): print("\n\n\n") xaxis = [] yaxis = [] currentCells = copy.deepcopy(nextCells) for y in range(HEIGHT): for x in range(WIDTH): if currentCells[x][y] == '#': xaxis.append(x) yaxis.append(y) scatter1 = plt.scatter(xaxis, yaxis, color='purple', s=10, marker='+',alpha=1) 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] = '#' #print((x, y), '生存') elif currentCells[x][y] == '*' and numNeighbors == 3: nextCells[x][y] = '#' #print((x, y), '生存') else: nextCells[x][y] = '*' #print((x,y),'死亡') return scatter1, ani = FuncAnimation(fig , update , init_func=init , frames=200 , interval=90 , blit=True ) plt.show()
Conway(Python)
最新推荐文章于 2024-09-15 22:31:42 发布