2 Star 0 Fork 0

mirrors_beltoforion/recreational_mathematics_with_python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
game_of_life.py 2.32 KB
一键复制 编辑 原始数据 按行查看 历史
import pygame
import numpy as np
col_about_to_die = (200, 200, 225)
col_alive = (255, 255, 215)
col_background = (10, 10, 40)
col_grid = (30, 30, 60)
def update(surface, cur, sz):
nxt = np.zeros((cur.shape[0], cur.shape[1]))
for r, c in np.ndindex(cur.shape):
num_alive = np.sum(cur[r-1:r+2, c-1:c+2]) - cur[r, c]
if cur[r, c] == 1 and num_alive < 2 or num_alive > 3:
col = col_about_to_die
elif (cur[r, c] == 1 and 2 <= num_alive <= 3) or (cur[r, c] == 0 and num_alive == 3):
nxt[r, c] = 1
col = col_alive
col = col if cur[r, c] == 1 else col_background
pygame.draw.rect(surface, col, (c*sz, r*sz, sz-1, sz-1))
return nxt
def init(dimx, dimy):
cells = np.zeros((dimy, dimx))
pattern = np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0],
[1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[1,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]);
pos = (3,3)
cells[pos[0]:pos[0]+pattern.shape[0], pos[1]:pos[1]+pattern.shape[1]] = pattern
return cells
def main(dimx, dimy, cellsize):
pygame.init()
surface = pygame.display.set_mode((dimx * cellsize, dimy * cellsize))
pygame.display.set_caption("John Conway's Game of Life")
cells = init(dimx, dimy)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
surface.fill(col_grid)
cells = update(surface, cells, cellsize)
pygame.display.update()
if __name__ == "__main__":
main(100, 70, 8)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/mirrors_beltoforion/recreational_mathematics_with_python.git
git@gitee.com:mirrors_beltoforion/recreational_mathematics_with_python.git
mirrors_beltoforion
recreational_mathematics_with_python
recreational_mathematics_with_python
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385