python - 国际象棋程序OO设计

标签 python oop chess

在我的国际象棋程序中,我有一个名为 Move 的类。它存储了工件被取出和放置的位置。这是什么棋子以及被捕获的棋子是什么。

问题是,为了获取被移动和捕获的棋子,我将整个 Board 对象传递给 __init__ 方法。因此,在我看来,我似乎应该将所有 Move 类方法存储到 Board 类,该类也有一个方法可以获取给定方 block 上的棋子。

我刚刚开始学习面向对象,因此非常感谢有关此的一些建议,也许还有一些更通用的设计决策。

这是我认为最好省略的 Move 类?

class Move(object):

    def __init__(self, from_square, to_square, board):
        """ Set up some move infromation variables. """
        self.from_square = from_square
        self.to_square = to_square
        self.moved = board.getPiece(from_square)
        self.captured = board.getPiece(to_square)

    def getFromSquare(self):
        """ Returns the square the piece is taken from. """
        return self.from_square

    def getToSquare(self):
        """ Returns the square the piece is put. """
        return self.to_square

    def getMovedPiece(self):
        """ Returns the piece that is moved. """
        return self.moved

    def getCapturedPiece(self):
        """ Returns the piece that is captured. """
        return self.captured

最佳答案

当您创建一个对象时,您正在创建一个事物。棋盘和棋盘上的棋子都是东西。当您希望与这些事物交互时,您需要一种方式来做到这一点 - 或一个动词。

这仅作为建议方法,以避免使用 Move 类。我打算做什么:

  • 创建代表棋盘和棋盘上所有棋子的对象。
  • Subclass代表单个 block 运动特征的所有 block 的类,以及 override特定于片段的 Action ,例如移动。

我从编写Board开始;您可以稍后决定如何表示位置。

class Board:
    def __init__(self):
         self.board = [['-' for i in xrange(8)] for j in xrange(8)]
    # You would have to add logic for placing objects on the board from here.

class Piece:
    def __init__(self, name):
         self.name = name
    def move(self, from, to):
         # You would have to add logic for movement.
    def capture(self, from, to):
         # You would have to add logic for capturing.
         # It's not the same as moving all the time, though.

class Pawn(Piece):
    def __init__(self, name=""):
        Piece.__init__(self, name)
    def move(self, from, to):
        # A rule if it's on a starting block it can move two, otherwise one.
    def capture(self, from, to):
        # Pawns capture diagonal, or via en passant.

关于python - 国际象棋程序OO设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11711860/

相关文章:

python - 根据值删除 Pandas 中的 DataFrame 列

c++ - C++ 中的对象内存布局及其结构如何依赖于大多数平台

c++ - 检查下一步是否将死

python - 极小极大函数内国际象棋移动生成的转置表

python - 如何在Python中找到满足条件(最大和最小阈值)的所有可能组合?

python - python eval() 中的有效语句是什么?

python - Python 中的简单线程示例

oop - Lua 和对象生成

flash - 访问 AS3 中的 Document 类

Python minimax函数中的深度复制