好好百科

分享有趣又有用的知识

用户工具

站点工具


侧边栏

导航菜单

python:programming:game_of_life

Game of Life

import sys
import pygame
import numpy as np
 
 
def lifes_generator(shape):
    empty = np.zeros(shape=shape, dtype=np.int8)
    lifes = np.random.randint(low=2, size=shape, dtype=np.int8)
    while True:
        yield lifes
        neighbors = empty.copy()
        neighbors[1:] += lifes[:-1]
        neighbors[:-1] += lifes[1:]
        neighbors[:, 1:] += lifes[:, :-1]
        neighbors[:, :-1] += lifes[:, 1:]
        neighbors[1:, 1:] += lifes[:-1, :-1]
        neighbors[1:, :-1] += lifes[:-1, 1:]
        neighbors[:-1, 1:] += lifes[1:, :-1]
        neighbors[:-1, :-1] += lifes[1:, 1:]
        lifes = (neighbors == 3) + (neighbors + lifes == 3)
 
 
def game_of_life(cols=100, rows=75, size=10, gb=(200, 255, 200), fg=(0, 200, 100)):
    pygame.init()
    screen = pygame.display.set_mode((size * cols, size * rows), 0, 32)
    for lifes in lifes_generator((rows, cols)):
        screen.fill(gb)
        [screen.fill(fg, (size * x, size * y, size, size))
         for y in range(rows) for x in range(cols) if lifes[y][x]]
        pygame.display.flip()
        pygame.time.wait(1)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
 
 
if __name__ == "__main__":
    game_of_life(200, 150, 5)
python/programming/game_of_life.txt · 最后更改: 2019/08/23 15:12 由 老赵