身份测试人生游戏

identity test game of life

我正在 python 中编写康威的游戏代码。我的代码是这样的:

def update_board(board: list[list[int]]) -> list[list[int]]:
    rows = len(board)
    cols = len(board[0])
    count = 0
    copy_board = deepcopy(board)
    indx = [-1, -1, -1, 0, 0, 1, 1, 1]
    indy = [-1, 0, 1, -1, 1, -1, 0, 1]
    for i in range(rows):
        for j in range(cols):
            for k, value in enumerate(indx):
                if check(i + value, j + indy[k], rows,
                         cols) and copy_board[i + indx[k]][j + indy[k]]:
                    count += 1
            # Apply the rule to each cell
            if count < 2 or count > 3:
                board[i][j] = 0
            elif count == 3:
                board[i][j] = 1
            # Reset the count for the next cell
            count = 0
    return board

需通过身份测试:

def test_is_not_identity() -> None:
   """Test board update is not done in place."""
   board = [[0 for _ in range(4)] for _ in range(4)]
   assert board is not update_board(board)

和剧照测试(我不知道它做了什么):

def test_stills(name: str, proto: str) -> None:
    """Test still lifes."""
    board = parse_board(proto)
    assert board == update_board(deepcopy(board)), name

虽然我原地更新了板子,但还是没有通过,所以我不明白。

您应该 return copy_board 而不是 board。也 moodify copy_booard 而不是 board 本身

def update_board(board: list[list[int]]) -> list[list[int]]:
    rows = len(board)
    cols = len(board[0])
    count = 0
    copy_board = deepcopy(board)
    indx = [-1, -1, -1, 0, 0, 1, 1, 1]
    indy = [-1, 0, 1, -1, 1, -1, 0, 1]
    for i in range(rows):
        for j in range(cols):
            for k, value in enumerate(indx):
                if check(i + value, j + indy[k], rows,
                         cols) and board[i + indx[k]][j + indy[k]]:
                    count += 1
            # Apply the rule to each cell
            if count < 2 or count > 3:
                copy_board[i][j] = 0
            elif count == 3:
                copy_board[i][j] = 1
            # Reset the count for the next cell
            count = 0
    return copy_board