1

私のチェス プログラムには、Move というクラスがあります。ピースがどこに置かれたかを保存します。何がピースで、何がキャプチャされたのか。

問題は、移動してキャプチャしたピースを取得するために、Board オブジェクト全体を __init__ メソッドに渡すことです。したがって、IMO では、Move クラスのすべてのメソッドを Board クラスに格納する必要があるように思われます。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 に答える