Python3 实现简单的生命游戏

生命游戏是英国数学家约翰·何顿·康威在1970年发明的细胞自动机

生命游戏原理

细胞自动机(又称元胞自动机),名字虽然很深奥,但是它的行为却是非常美妙的。所有这些怎样实现的呢?我们可以把计算机中的宇宙想象成是一堆方格子构成的封闭空间,尺寸为N的空间就有NN个格子。而每一个格子都可以看成是一个生命体,每个生命都有生和死两种状态,如果该格子生就显示蓝色,死则显示白色。每一个格子旁边都有邻居格子存在,如果我们把33的9个格子构成的正方形看成一个基本单位的话,那么这个正方形中心的格子的邻居就是它旁边的8个格子。
每个格子的生死遵循下面的原则:
1. 如果一个细胞周围有3个细胞为生(一个细胞周围共有8个细胞),则该细胞为生(即该细胞若原先为死,则转为生,若原先为生,则保持不变) 。
2. 如果一个细胞周围有2个细胞为生,则该细胞的生死状态保持不变;
3. 在其它情况下,该细胞为死(即该细胞若原先为生,则转为死,若原先为死,则保持不变)

转自生命游戏百度百科

代码实现

需要导入 numpy,pygame 两个包

import numpy as np
import pygame

X_DOT=50
Y_DOT=50
DOT_PX=20
np.random.seed(100)
source_a=np.random.randint(0,2,(X_DOT,Y_DOT))
copy_a=np.copy(source_a)

def has_counts(a, x, y):
    counts = 0

    # 考虑更多因素
    if x > X_DOT:
        x = X_DOT - 1  # 直接抛异常
    if y > Y_DOT:
        y = Y_DOT - 1
	
    if (x > 0) and (y > 0) and a[x - 1, y - 1]:
        counts += 1  # counts = counts+1
    if (x > 0) and a[x - 1, y]:
        counts += 1
    if (x > 0) and (y + 1 < Y_DOT) and a[x - 1, y + 1]:
        counts += 1
    if (y > 0) and a[x, y - 1]:
        counts += 1
    if (y + 1 < Y_DOT) and a[x, y + 1]:
        counts += 1
    if (y > 0) and (x + 1 < X_DOT) and a[x + 1, y - 1]: 
        counts += 1
    if (x + 1 < X_DOT) and a[x + 1, y]:
        counts += 1
    if (y + 1 < Y_DOT) and (x + 1 < X_DOT) and a[x + 1, y + 1]:
        counts += 1

    return counts

def live_or_die(life_counts,x,y,a):
	‘’‘函数判断生命的状态’‘’
    if life_counts ==3:
        return 1
    elif life_counts ==2:
        return a[x,y]
    else:
        return 0
def next_a(source_a):
    for x in range(X_DOT):
        for y in range(Y_DOT):
            copy_a[x,y] = live_or_die(has_counts(source_a,x,y),x,y,source_a)
    return copy_a


def main():
	‘’‘用pygame生成界面’‘’
    pygame.init()
    pygame.display.set_caption('生命游戏')
    screen = pygame.display.set_mode((DOT_PX * X_DOT, DOT_PX * Y_DOT))
    running = True
    global source_a
    while running:
        screen.fill((255,255,255))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        for x in range(X_DOT):
            for y in range(Y_DOT):
                if source_a[x,y]:
                    screen.fill((0,0,225),(y*DOT_PX,x*DOT_PX,DOT_PX,DOT_PX))
                    pygame.draw.rect(screen,(0,255,0),(y*DOT_PX,x*DOT_PX,DOT_PX,DOT_PX),2)

        pygame.display.update()
        next_a(source_a)
        source_a=copy_a
        pygame.time.wait(500)

if __name__ == '__main__':
    main()

运行的结果:
Python3 实现简单的生命游戏

相关文章: