注解

此笔记本可在此处下载: Scientific_Python_Tutorial.ipynb

代码作者:Ludovic Charleux ludovic.charleux@univ-smb.fr

科学 Python 教程:生命游戏编码(GOL)

图像0

第1部分:引言

入门读物

什么是gol?

只要不需要玩家,高尔夫就不是真正的游戏。它是在棋盘上玩的,就像网格一样 细胞 存在于两种状态: 死亡(0)活的(1) .细胞的状态在每一个 step 根据两条规则: * 这个 生存规则 :在戈尔,如果一个活的细胞在它的邻居中有2或3个活的细胞,它就活下来,否则它就死了。 * 这个 出生规则:(b) :如果一个细胞在它的邻居中有3个活细胞,它就活了。

请不要犹豫尝试现有的在线模拟器,了解游戏的工作原理:https://bitstorm.org/gameoflife/

第2部分:计算活着的邻居

在这一部分中,您将学习如何计算每个单元周围的邻居数。

%matplotlib nbagg
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import animation, rc, cm
rc('animation', html='html5')

我们可以很容易地用 numpy

cells = np.random.randint(2, size = (5, 5))
cells
array([[1, 1, 1, 0, 1],
       [1, 1, 1, 1, 1],
       [0, 1, 0, 0, 0],
       [1, 0, 0, 1, 0],
       [0, 1, 1, 1, 0]])
plt.figure()
plt.imshow(cells, cmap = cm.gray)
plt.colorbar()
plt.show()
<IPython.core.display.Javascript object>

现在,您需要找到一种方法来计算每个单元周围居住(1)个邻居的数量。

提示: * 尝试几种方法,确定哪种方法最适合你, * 使用 numpy 切片可以帮上忙, * 边界条件很重要。

邻居计数可以存储在如下矩阵中:

neighbors = np.zeros_like(cells)
neighbors
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])

##第2部分:创建类

既然您掌握了邻居计数,现在是时候创建一个类来管理单元计数的演化了。GOL类胚胎如下:

class GoL:
    """
    A game of life class.
    """

    def __init__(self, cells):
        self.cells = np.array(cells)

    def __repr__(self):
        return "<GoL with {0} cells>".format(self.cells.size)

    def count_living_neighbors(self):
        """
        Counts the number of living neighbors of each cell.
        """
        # to be completed.
        return

    def step(self):
        """
        make an evolution step forward.
        """
        # to be completed.
        return


g = GoL(cells)
g
<GoL with 25 cells>

第3部分:动画工作

现在,是时候让你的作品充满活力了。为此,可以使用以下代码的修改版本来设置随机图像的动画:

class RandomImage:
    """
    Creates a random image.
    """
    def __init__(self, size = (5,5), depth = 8):
        self.size = size
        self.depth = depth
        self.evolve()

    def evolve(self):
        """
        Randomizes the image
        """
        self.image = np.random.randint(self.depth, size = self.size)

ri = RandomImage( size = (50, 50))

def updatefig(*args):
    ri.evolve()
    im.set_array(ri.image)
    return im,


fig, ax = plt.subplots()
ax.axis('off')
im = plt.imshow(ri.image, interpolation = "nearest", cmap = cm.gray, animated=True)
anim = animation.FuncAnimation(fig, updatefig, frames=40, interval=50, blit=True)
#plt.show()
plt.close()
anim
<IPython.core.display.Javascript object>

第4部分:其他规则

高尔夫只是一套规则 B3/S23 在更广泛的群体中 Life-like cellular automatons : https://en.wikipedia.org/wiki/Life-like_细胞自动机

修改您的工作以便能够模拟其他规则。