国际象棋节目制作和取消移动

时间:2012-08-08 21:07:09

标签: python chess

嗨!我正在制作一个国际象棋引擎,我对make / unmake方法有一些问题。

我有一个Piece类,它包含类型(pawn,queen等等)和片段的位置以及一个Move类,它包含目标方块,移动的片段和捕获的片段。

问题是,当我调用makeMove方法时,它会将Piece的位置更改为Piece对象内的目标方块。但是现在,我无法使用Move对象调用unmakeMove,因为现在我没有关于移动来自哪里的信息,因为我刚刚更改了该块的位置。你会如何解决这个问题?

非常感谢!

class Board:
# Previous methods omitted. 

    def makeMove(self, move, player):
        """ Makes a move on the board and changes Piece object. Returns None. """
        self.moved_piece = move.getPiece()
        self.captured_piece = move.getCapturedPiece(self)

        if self.captured_piece:  # Remove captured piece from player's piece dict. 
            player.removePiece(self.captured_piece)

        self.setPiece(move.getTargetSquare(), self.moved_piece)  # Set moved piece on target square.
        self.setPiece(self.moved_piece.getPosition(), EMPTY)  # Make the origin square empty.
        self.moved_piece.changePosition(move.getTargetSquare())  # Change piece object's position.

    def unmakeMove(self, move, player):
        """ Unmakes a move. Returns None. """
        self.moved_piece = move.getPiece()
        self.captured_piece = move.getCapturedPiece(self)

        self.setPiece(self.moved_piece.getPosition(), captured_piece)  # Set captured piece or empty square to target square.
        # Set piece to original square. HOW !?

1 个答案:

答案 0 :(得分:2)

根据我的评论和Fred Larson发布的link on the Memento pattern,以下是您可能想要做的示例实现:

class Engine(object):
    def __init__(self):
        self.board = Board()
        self.move_list = []

    def make_move(self, from, to):
        #board.makeMove returns a "memento object".
        self.move_list.append(board.makeMove(from, to))
        ...

    def undo_move(self):
        board.undo(self.move_list.pop())
    ...
    ...

让我们说你有这个结构的移动对象:

class Move(object):
    def __init__(self, from_coords, to_coords, capture=None):
        self.from = from_coords
        self.to = to_coords
        self.capture = capture

你是Board对象会实现以下方法:

class Board(object):
    ...
    def make_move(self, from_coords, to_coords):
        #move logic here
        return Move(from_coords, to_coords, capturedPiece)

    def undo_move(self, move_object):
        self.make_move(move_object.to_coords, move_object.from_coords)
        self.uncapture(move_object.capture, move_object.to_coords)

显然,上面的代码只是概念性的。实际实现将取决于代码的其余部分的结构。

注意:我为Move对象使用了一个类,因为属性访问是明确且易于理解的。实际上,像这样基本的对象可能只是(from, to, capturedpiece)形式的元组。