欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-10-05 10:25:17
模块:pygame 该代码的实现策略是遍历所有像素点,判断每个像素点下一代的状态,然后每个像素点状态写入数组,根据数组更新画面 这个方法有点暴力,像素过多的话会大量消耗资源,很慢 ......

模块: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)

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