最近看到一则新闻:英国全能数学家John Conway因新冠去世。读了他的简历,才知道他就是生命游戏(Game of Life)的设计者。谨以此文,向其致敬。
生命游戏其实算不上是真正的游戏,它主要是模拟细胞的繁衍迭代的过程。在游戏进行中,杂乱无序的细胞会逐渐演化出各种精致、有形的结构;这些结构往往有很好的对称性,而且每一代都在变化形状。
这个游戏的主要玩法和规则是:
定义一个二维网格,例如N*N
每个方格中都放置一个细胞,每个生命细胞只有两种状态:
“生”或“死”
整个网格的细胞在不停的迭代,每个细胞迭代后的状态由该细胞及周围8个细胞状态所决定。
在游戏最初的版本,细胞生存规则为:
当周围存活细胞少于2个时, 原来的存活状态的细胞进入死亡状态。
(死于孤独)
当周围有2个或3个存活细胞时, 网格保持原样
当周围有4个及以上存活细胞时,原来的存活细胞亦进入死亡状态。
(死于拥挤)
当周围有3个存活细胞时,空白网格变成存活细胞。
(模拟繁殖)
Excel本身就是二维的网格结构,因此特别适合模拟这个生命游戏。在这里简单的写了个代码,主要思路是:
指定一个二维区域,在其中每个单元格随机生成0或者1
利用条件格式,如果是1代表细胞存活,显示橙色
将当前的细胞存活状态存入数组
根据游戏规则进行迭代,生成迭代后的数组
把迭代后数组的值返回赋值到单元格区域
代码如下:
Option ExplicitPublic PlayGround As RangeSub Main() Dim i As Integer Set PlayGround = Range("b2:ay51") PlayGround.FormulaR1C1 = "=RANDBETWEEN(0,1)" For i = 1 To 20 Call Iteration(PlayGround) Application.Wait Now + TimeValue("00:00:01") DoEvents Application.StatusBar = i Next i MsgBox "done"End SubPrivate Sub Iteration(rng As Range) Dim r As Integer, c As Integer Dim i As Integer, j As Integer Dim m As Integer, n As Integer Dim currentGeneration Dim nextGeneration Dim LiveCellCount As Integer currentGeneration = rng.Value r = rng.Rows.Count c = rng.Columns.Count ReDim nextGeneration(1 To r, 1 To c) For i = 1 To r For j = 1 To c LiveCellCount = 0 For m = -1 To 1 For n = -1 To 1 If (m <> 0 Or n <> 0) And IsInsidePlayground(i, j, m, n, r, c) Then If currentGeneration(i + m, j + n) = 1 Then LiveCellCount = LiveCellCount + 1 End If Next n Next m Select Case LiveCellCount Case Is < 2 nextGeneration(i, j) = 0 Case 2 nextGeneration(i, j) = currentGeneration(i, j) Case 3 If currentGeneration(i, j) = 0 Then nextGeneration(i, j) = 1 If currentGeneration(i, j) = 1 Then nextGeneration(i, j) = 1 Case Is > 3 nextGeneration(i, j) = 0 End Select Next j Next i rng.Value = nextGenerationEnd SubFunction IsInsidePlayground(i As Integer, j As Integer, m As Integer, n As Integer, r As Integer, c As Integer) If (i + m >= 1) And (i + m <= r) And (j + n >= 1) And (j + n <= c) Then IsInsidePlayground = True Else IsInsidePlayground = False End IfEnd Function
运行一下,迭代20次看看:
不知道大家注意到了没有,迭代到后期,右上角有几个正方形的细胞簇,形状一直不变。
这就是这个游戏的有趣之处,细胞游戏里有很多代表性的图形,例如:
静物,也就是一旦形成此类稳定结构,迭代后的图形不会改变
你没看错,这的确是一张gif图
振荡,也就是周期为N的迭代循环
整体移动,迭代多次后虽然还能形成最初的形状,但整体位置发生了变化
根据生存规则的不同,生命游戏可以衍生出很多版本。如果有兴趣,可以到这个网址来模拟一下:https://bitstorm.org/gameoflife/
参考网址:
https://www.douban.com/note/690728776/