Chess program OO design

In my chess program, I have a class called Move. It stores where the piece was taken and put. What was the piece and what was the piece captured.

The problem is though, in order to get the piece that was moved and captured, I pass the whole Board object to the __init__ method. And so IMO it seems like I should store all the Move class methods to the Board class instead, which too has a method that get's the piece on a given square.

I'm just beginning to learn OO, so some advice regarding this, and maybe some more general design decision is much appreciated.

Here's the Move class that I feel might better be omitted?

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

When you create an object, you are creating a thing. The board and the pieces on the board are things. When you wish to interact with these things, you require a way to do it - or a verb.

This is only intended as a suggested approach, to avoid the use of a Move class. What I intend to do:

  • Create objects that represent the board and all pieces on the board.
  • Subclass the class that represents all pieces for individual piece motion characteristics, and override piece-specific actions, such as movement.
  • I begin with writing the Board ; you can decide how to represent the locations later.

    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.
    
    链接地址: http://www.djcxy.com/p/84608.html

    上一篇: 在wxpython中建模一个国际象棋棋盘

    下一篇: 国际象棋程序OO设计