如何制作特定(可变)对象的深拷贝?

How to make deep copy of a specific(mutable) object?

我正在尝试制作国际象棋引擎。

def botmove(board):
  legal=list(board.legal_moves)#needed because --->TypeError: 'LegalMoveGenerator' object is not subscriptable
  boardhalfmove=board.pop()
  choosemove(board,boardhalfmove, legal)
  print("Computer moves:",move)
  movepiece(move,board)

然而,我运行陷入了一个错误:

Traceback (most recent call last):
  File "main.py", line 32, in <module>
    botmove(board)
  File "/home/runner/chess-engine-goal-3minimax/move.py", line 70, in botmove
    choosemove(board,boardhalfmove, legal)
  File "/home/runner/chess-engine-goal-3minimax/move.py", line 49, in choosemove
    movepiece(str(i),board)
  File "/home/runner/chess-engine-goal-3minimax/move.py", line 4, in movepiece
    moveinput = str(board.push_san(movestr))
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/chess/__init__.py", line 3003, in push_san
    move = self.parse_san(san)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/chess/__init__.py", line 2970, in parse_san
    move = self.find_move(square(from_file, from_rank), to_square, promotion)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/chess/__init__.py", line 2272, in find_move
    raise ValueError(f"no matching legal move for {move.uci()} ({SQUARE_NAMES[from_square]} -> {SQUARE_NAMES[to_square]}) in {self.fen()}")
ValueError: no matching legal move for g8h6 (g8 -> h6) in rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1

这不好,尤其是 legal move 部分。我追溯了错误的根源:

boardhalfmove=board.pop()

我知道 Python 古怪的可变性,虽然我知道我可以复制这样的列表:

secondlist=list[:]#makes a copy

type(board) returns<class 'chess.Board'>.
如何完整复制 board?
提前致谢。

通常,Python 有一个名为 'copy' 的库,它实现了基本对象的深度复制。尝试使用 from copy import deepcopy 并覆盖 Board 的 __eq__ 函数。

有关详细信息,请查看 How can I create a copy of an object in Python?