Bài viết phổ biến của tác giả
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
嗨!我正在制作一个国际象棋引擎,但 make/unmake 方法有一些问题。
我有一个 Piece 类,用于保存棋子的类型(兵、后等)和位置,还有一个 Move 类,用于保存目标方格、移动的棋子和捕获的棋子。
问题是,当我调用 makeMove 方法时,它会将棋子的位置更改为 Piece 对象内的目标方 block 。但现在,我无法使用 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 Câu trả lời
根据我的评论和 link on the Memento pattern Fred Larson 发布的内容是您可能想要执行的操作的示例实现:
class Engine(object):
định nghĩa __init__(bản thân):
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
Của bạn 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, capturepiece)
形式的元组。
关于python - 国际象棋编程的走棋和撤棋,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11873180/
Tôi là một lập trình viên xuất sắc, rất giỏi!