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


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

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

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

  • 相关阅读:
    [程序员代码面试指南]栈和队列-单调栈结构(单调栈)
    快学Scala第一部分
    Add Digits
    Nim Game
    将分布式中多台节点的日志信息集中到一个节点上
    Eclipse调试的一些小技巧
    Maven的常用命令
    Eclipse插件本地扩展安装
    Spark应用程序的运行框架
    Spark运行各个时间段的解释
  • 原文地址:https://www.cnblogs.com/zxingwork/p/10531151.html
Copyright © 2020-2023  润新知