Python——Pygame实现生命游戏(game of life)

时间:2022-01-27 19:07:37

模块:pygame

import pygame,sys,time,random
from pygame.locals import *


"""Color"""
WHITE   = (255,255,255)
RED     = (255,0,0)
GREEN   = (0,255,0)
"""Color"""

def Neighbor(x,y):#返回周围存活细胞数
    alive = 0
    around = ((x+1,y+1),(x+1,y),(x+1,y-1),(x-1,y),(x-1,y+1),(x-1,y-1),(x,y-1),(x,y+1),)
    for a in around:
        color = WIN.get_at(a)
        if color == RED:
            alive += 1
    return alive

def Init():
    so = 200000
    for number in range(0,so):
        pygame.draw.rect(WIN,RED,(random.randint(0,SIZE[0]),random.randint(0,SIZE[1]),1,1))
    print('so =  ',so)

def rule(i,j):
    if Neighbor(i,j) < 2:
        return False
    elif WIN.get_at((i,j)) == RED:
        if Neighbor(i,j) == 2 :
            return True
        elif Neighbor(i,j) == 3:
            return True
    elif Neighbor(i,j) > 3:
        return False
    elif Neighbor(i,j) == 3:
        return True


pygame.init()

SIZE = (800,800)
WIN = pygame.display.set_mode(SIZE)
pygame.display.set_caption("game of life")

WIN.fill(WHITE)
Init()
gen = 0
while True:
    Next_alive = []
    Next_dead = []
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)
    x = SIZE[0]
    y = SIZE[1]
    for i in range(10,x-10):
        for j in range(10,y-10):
            if rule(i,j):
                Next_alive.append((i,j))
    WIN.fill(WHITE)
    print('Alive =',len(list(set(Next_alive))))




    for x,y in list(set(Next_alive)):
        pygame.draw.rect(WIN,RED,(x,y,1,1))
    # for x,y in Next_dead:
    #     pygame.draw.rect(WIN,GREEN,(x,y,1,1))
    gen += 1
    print(gen)

    pygame.display.update()

该代码的实现策略是遍历所有像素点,判断每个像素点下一代的状态,然后每个像素点状态写入数组,根据数组更新画面

Python——Pygame实现生命游戏(game of life)

这个方法有点暴力,像素过多的话会大量消耗资源,很慢