国际象棋程序OO设计

时间:2012-07-29 18:32:17

标签: python oop chess

在我的国际象棋程序中,我有一个名为Move的课程。它存放了拍摄和放置的地方。这件作品是什么,拍摄的作品是什么。

问题是,为了获取被移动和捕获的片段,我将整个Board对象传递给__init__方法。所以IMO似乎应该将所有Move类方法存储到Board类中,它也有一个方法可以获得给定方块上的那个。

我刚刚开始学习OO,所以对此有一些建议,也许更一般的设计决策非常感谢。

这是我觉得最好省略的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

1 个答案:

答案 0 :(得分:2)

创建对象时,您正在创建事物。板子和板子上的碎片都是东西。如果您希望与这些内容进行交互,则需要方式来执行此操作 - 或动词。

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

  • 创建代表董事会和董事会所有部分的对象。
  • Subclass代表单件运动特征的所有部分的类,以及override特定于片段的动作,例如移动。

我从编写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.