模塊: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()
該代碼的實現策略是遍歷所有像素點,判斷每個像素點下一代的狀態,然后每個像素點狀態寫入數組,根據數組更新畫面
這個方法有點暴力,像素過多的話會大量消耗資源,很慢