1

在我的国际象棋程序中,我有一个名为 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
4

1 回答 1

2

当你创建一个对象时,你就是在创建一个东西。棋盘和棋盘上的棋子都是东西。当您希望与这些事物进行交互时,您需要一种方式来实现它——或者是一个动词。

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

  • 创建代表棋盘和棋盘上所有棋子的对象。
  • 类化表示单个块运动特征的所有块的类,并覆盖特定于块的动作,例如运动。

我开始写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.
于 2012-07-29T18:56:26.410 回答