gpt4 book ai didi

python - 生命游戏 : How to keep track of active cells

转载 作者:行者123 更新时间:2023-12-02 07:04:13 25 4
gpt4 key购买 nike

现在我已经阅读了其他 stackoverflow 生命游戏问题,并且还贪婪地进行了 Google 搜索。我知道如何为我的生命游戏的 Python 实现做些什么。我想跟踪网格中的事件单元格。问题是我不知道该如何编码。
这是我的想法,但除此之外我有点无计可施:

  • 维护一个由事件单元格坐标元组组成的 ActiveCell 列表
    死了还是活了。
  • 计算下一代时,只需迭代ActiveCell列表,计算cell状态并检查状态是否改变。
  • 如果状态发生变化,则将所有当前单元邻居添加到列表中
  • 如果不是,请从列表中删除该单元格
  • 现在的问题是:(“.”--> 其他单元格)
    B C D<br/>
    . A .<br/>
    . . .

    如果 A 满足 3),则添加 B、C、D
    那么如果B对于3)也返回true,这意味着它将再次添加A,C(重复)

我考虑过使用 OrderedSet 或其他东西来处理顺序并避免重复。但我仍然遇到这些问题。我只需要一个方向。

最佳答案

不知道它是否对您有帮助,但这是生命游戏的快速草图,带有 activecells 字典:

from itertools import product

def show(board):
for row in board:
print " ".join(row)

def init(N):
board = []
for x in range(N):
board.append([])
for y in range(N):
board[x].append(".");
return board

def create_plane(board):
board[2][0] = "x"
board[2][1] = "x"
board[2][2] = "x"
board[1][2] = "x"
board[0][1] = "x"

def neighbors(i, j, N):
g1 = {x for x in product([1, 0, -1], repeat=2) if x != (0, 0)}
g2 = {(i + di, j + dj) for di, dj in g1}
return [(x, y) for x, y in g2 if x >= 0 and x < N and y >= 0 and y < N]

def live(board):
N = len(board)
acells = {}
for i in range(N):
for j in range(N):
if board[i][j] == "x":
for (x, y) in neighbors(i, j, N):
if (x, y) not in acells: acells[(x, y)] = board[x][y]

while True:
print "-" * 2 * N, len(acells), "cells to check"
show(board)
raw_input("Press any key...")
for c in acells.keys():
a = len([x for x in neighbors(c[0], c[1], N) if board[x[0]][x[1]] == "x"])
cur = board[c[0]][c[1]]
if a == 0:
del acells[c] # if no live cells around, remove from active
elif cur == "x" and a not in (2, 3):
acells[c] = "." # if alive and not 2 or 3 neighbors - dead
elif cur == "." and a == 3:
acells[c] = "x" # if dead and 3 neighbors - alive
for x in neighbors(c[0], c[1], N): # add all neighbors of new born
if x not in acells: acells[x] = board[x[0]][x[1]]

for c in acells:
board[c[0]][c[1]] = acells[c]

N = 7
board = init(N)
create_plane(board)

live(board)

关于python - 生命游戏 : How to keep track of active cells,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17897988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com