栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

用python实现细胞自动机(康威生命游戏)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用python实现细胞自动机(康威生命游戏)

 英国数学家约翰·何顿·康威在1970年发明了细胞自动机,它属于一种仿真程序,通过设定一些基本的规则来模拟和显示的图像的自我进化,看起来颇似生命的出生和繁衍过程,故称为“生命游戏”。

完成效果

用到的第三方库

pygame

基本规则

康威生命游戏在网格上进行,有填充的网格代表有生命,或理解成一个细胞,游戏规则只有四条:

1 当周围仅有1个或没有存活细胞时, 原来的存活细胞进入死亡状态。(细胞过于稀少)

2 当周围有2个或3个存活细胞时, 网格保持原样。

3 当周围有4个及以上存活细胞时,原来的存活细胞亦进入死亡状态。(细胞过于拥挤)

4 当周围有3个存活细胞时,空白网格变成存活细胞。(繁殖新细胞)

代码实现

首先定义两个常量,来代表一个细胞(网格)的生或空白的状态:

ALIVE = (124, 252, 0)  # 绿色
EMPTY = (0, 0, 0)      # 黑色

我这里直接用颜色的RGB表示法来代表这两种状态,因为在后面的展示中,ALIVE状态将用绿色表示,EMPTY状态用黑色表示。

下面几个变量是pygame里用到的参数

SCREEN_WIDHT = 600
SCREEN_HEIGHT = 600
X = 100   # X方向的网格数量
Y = 100   # Y方向的网格数量
CELL_WIDTH = SCREEN_WIDHT / X
CELL_HEIGHT = SCREEN_HEIGHT / Y

现在来定义一个细胞,也就是一个网格:

import pygame
from pygame.locals import *


class Cell:
    '''单个细胞'''
    def __init__(self, x, y):
        self.state = EMPTY
        self.rect = Rect(x * CELL_WIDTH, y * CELL_HEIGHT, 
                         CELL_WIDTH, CELL_HEIGHT)

    def draw(self, screen):
        pygame.draw.rect(screen, self.state, self.rect)

 接下来定义整个网格:

class Grid:
    def __init__(self, X, Y):
        self.X = X
        self.Y = Y
        self.rows = []
        for y in range(Y):
            self.rows.append([])
            for x in range(X):
                self.rows[y].append(Cell(x, y))

    def get_state(self, y, x):
        return self.rows[y % self.Y][x % self.X].state

    def set_state(self, y, x, state):
        self.rows[y % self.Y][x % self.X].state = state

    def draw(self, screen):
        for row in self.rows:
            for cell in row:
                cell.draw(screen)

以下两个模块级函数用于实现生命游戏的逻辑:

def count_neighbors(y, x, get_state):
    n_ = get_state(y - 1, x + 0)  # North
    ne = get_state(y - 1, x + 1)  # Northeast
    e_ = get_state(y + 0, x + 1)  # East
    se = get_state(y + 1, x + 1)  # Southeast
    s_ = get_state(y + 1, x + 0)  # South
    sw = get_state(y + 1, x - 1)  # Southwest
    w_ = get_state(y + 0, x - 1)  # West
    nw = get_state(y - 1, x - 1)  # Northwest
    neighbor_states = [n_, ne, e_, se, s_, sw, w_, nw]
    count = 0
    for state in neighbor_states:
        if state == ALIVE:
            count += 1
    return count

def next_state(state, neighbors):
    if state == ALIVE:
        if neighbors < 2:
            return EMPTY
        elif neighbors > 3:
            return EMPTY
    else:
        if neighbors == 3:
            return ALIVE
    return state

下面两个模块级函数为设置单个细胞和整个网格的新状态

def step_cell(y, x, get_state, set_state):
    state = get_state(y, x)
    neighbors = count_neighbors(y, x, get_state)
    new_state = next_state(state, neighbors)
    set_state(y, x, new_state)

def simulate(grid):
    new_grid = Grid(grid.X, grid.Y)
    for y in range(grid.Y):
        for x in range(grid.X):
            step_cell(y, x, grid.get_state, new_grid.set_state)
    return new_grid

主体代码已经完毕,下面开始测试:

if __name__ == "__main__":
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDHT, SCREEN_HEIGHT))
    pygame.display.set_caption('Game Of Live')
    framerate = pygame.time.Clock()

    # 设定一个初始状态
    grid = Grid(X, Y)
    grid.set_state(2, 4, ALIVE)
    grid.set_state(2, 2, ALIVE)
    grid.set_state(3, 3, ALIVE)
    grid.set_state(3, 4, ALIVE)
    grid.set_state(4, 4, ALIVE)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        grid.draw(screen)
        grid = simulate(grid)

        pygame.display.update()
        framerate.tick(10)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1030192.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号