好好百科

分享有趣又有用的知识

用户工具

站点工具


侧边栏

导航菜单

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)

不使用numpy

import sys
import copy
import random
import pygame
 
CELL, EMPTY = 1, 0
SIZE, COLS, ROWS = 10, 100, 60
BODY = 0, 200, 100
SKIN = 0, 100, 50
BACKGROUND = 200, 255, 200
SPEED = 10
 
pygame.init()
screen = pygame.display.set_mode((SIZE * COLS + 1, SIZE * ROWS + 1), 0, 32)
pygame.display.set_caption('Life')
# 随机生成第一代生命
lifes = [[random.choice((CELL, EMPTY)) for _ in range(COLS)] for _ in range(ROWS)]
while True:
    screen.fill(BACKGROUND)
    space = [[0] * COLS for i in range(ROWS)]
    """放置下一代生命的空间"""
    for x in range(COLS):
        for y in range(ROWS):
            neighbors = sum(lifes[i][j] for i in (y - 1, y, y + 1) for j in (x - 1, x, x + 1)
                            if (0 <= i < ROWS) and (0 <= j < COLS)) - lifes[y][x]
            if (lifes[y][x] + neighbors == 3) or neighbors == 3:
                space[y][x] = CELL
                screen.fill(BODY, (SIZE * x, SIZE * y, SIZE, SIZE))
                pygame.draw.rect(screen, SKIN, (SIZE * x, SIZE * y, SIZE + 1, SIZE + 1), 1)
    lifes = copy.deepcopy(space)
    pygame.display.flip()
    # pygame.time.wait(1000 // SPEED)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
python/programming/game_of_life.txt · 最后更改: 2019/12/12 18:11 由 老赵