如何利用 Python 实现生命游戏

2020-12-14 18:21:42 +08:00
 fanqieipnet
英国数学家约翰·何顿·康威在 1970 年发明了 the game of life,今天番茄加速就来分享下如何利用 python 实现生命游戏,规则如下:

  每个细胞有两种状态 - 存活或死亡

  每个细胞与以自身为中心的周围八格细胞产生互动

  当前细胞为存活状态时,当周围的存活细胞低于 2 个时(不包含 2 个),该细胞变成死亡状态。(模拟生命数量稀少)

  当前细胞为存活状态时,当周围有 2 个或 3 个存活细胞时,该细胞保持原样。

  当前细胞为存活状态时,当周围有超过 3 个存活细胞时,该细胞变成死亡状态。(模拟生命数量过多)

  当前细胞为死亡状态时,当周围有 3 个存活细胞时,该细胞变成存活状态。(模拟繁殖)

  拿个例子阐述上述状态,如下种子时代:

  [0, 0, 1, 0, 0]

  [0, 1, 1, 0, 0]

  [0, 0, 1, 1, 0]

  [0, 1, 1, 1, 0]

  [0, 0, 0, 0, 0]

  坐标[0,2]为一个存活的细胞,因为周围细胞个数为 2,所以繁衍后依然存活;

  坐标[1,2]的存活细胞,因为周围有 4 个存活细胞,所以繁衍后死亡;

  坐标[0,1]死亡细胞,因为周围恰好有 3 个存活细胞,所以[0,1]处出现生命,

  繁衍一代后的,完整图如下:

  [0, 1, 1, 0, 0]

  [0, 1, 0, 0, 0]

  [0, 0, 0, 0, 0]

  [0, 1, 0, 1, 0]

  [0, 0, 1, 0, 0]

  第二代:

  [0, 1, 1, 0, 0]

  [0, 1, 1, 0, 0]

  [0, 0, 1, 0, 0]

  [0, 0, 1, 0, 0]

  [0, 0, 1, 0, 0]

  ...

  能到第几代结束呢?借用 Python 模拟了生命游戏,整个代码一共 60 行。

  首先生成生命网格:

   def get_board(size, alive_cons):

   return [[1 if (i, j) in alive_cons else 0

   for j in range(size)]

   for i in range(size)]

  获得细胞的邻域:

   def get_neighbors(con):

   x, y = con

   neighbors = [(x + i, y + j)

   for i in range(-1, 2)

   for j in range(-1, 2)

   if not i == j == 0]

   return neighbors

  判断下一代是否存活:

   def is_alive_con(con, alive_cons):

   alive_neighbors = calculate_alive_neighbors(con, alive_cons)

   if (alive_neighbors == 3 or

  (alive_neighbors == 2 and con in alive_cons)):

   return True

   return False

  生成下一代完整的生命网格:

   def new_step(alive_cons):

   board = itertools.chain(*map(get_neighbors, alive_cons))

   new_board = set([con

   for con in board

   if is_alive_con(con, alive_cons)])

   return list(new_board)

  以上就是几个核心的函数,下面主函数:

   def main():

   size = 5

   board = [(0, 2), (1, 1), (1, 2), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

   print_board(get_board(size, board))

   for _ in range(10):

   board = correct_cons(size, new_step(board))

   print_board(get_board(size, board))

  终止状态:所有网格细胞状态都为 0
557 次点击
所在节点    推广
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/735378

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX