0

Board 类有一个 s 的 8x8 2D 数组Piece,所以我显然可以使用 Board 类移动一块,board.move(piece1, 3, left)例如,但是我无法简单地告诉块移动,比如piece1.move(3, left),因为它没有办法了解有关棋盘的任何信息(没有将其作为参数传递),因此它无法将自身移动到特定索引,或者知道一块是否已经占据了该索引,或者是否被告知移动到边界之外的数组。

4

2 回答 2

3

You have other objects which haven't been modeled yet, such as a Game and a Player. Let's take a step back and think about the responsibilities of each of these models:

  • Piece: A Piece is pretty minimal. It knows what it is, which color it is, that's probably about it.
  • Board: Also fairly minimal. It knows what its squares are.
  • Game: This is probably the most complex component. It knows the rules of the game. (After all, if you ever want to change the rules of the game then you shouldn't have to also change the Board or the Piece, right?) It knows which Pieces make up a complete game set. It knows which moves each Piece can make. It knows where any given Piece is on the Board at any given time.
  • Player: The Player interacts with the Game. It will tell the Game that it wants to perform a given action on a Piece. The Game will allow or deny that action, and modify the state of the Game (Check, Mate, Stalemate, other Player's turn, etc.) based on that action. (Again, the Pieces and the Board don't care about these states.)

If the Game object becomes bloated and unwieldy, it can probably be broken into pieces and exist mostly as a composite object. You can have a MoveList of possible moves for a given set of rules, for example. The Game is composed of it, but doesn't need to internally contain it.

The more I think about it, the more I think that Board and Piece are set apart as really "dumb" objects in this domain. They're not even really entities, just value objects. One piece which has the exact same attributes as another piece is essentially interchangeable with that other piece. (If you lose a Black Bishop you can replace it with another Black Bishop and not have any adverse effect on the experience.) The domain might work more fluidly if these two are treated as immutable data structures instead of models.

(It's also worth noting that the same Board can be re-used by other Games with entirely different sets of Pieces.)

As an exercise, I recommend following Robert Martin's Bowling Game Kata. You'll be surprised how much effort you can put into modeling a game domain only to have it turn out to be a lot simpler when you consider the actual tests to validate the domain. We can academically think about these chess models all day long, but coming up with a few tests to validate the game can emerge a simpler design.

于 2012-10-01T00:28:01.173 回答
2

一块,就其本身而言,不知道它恰好放置在哪里(并且可能不需要知道)。Board因此,需要调用方法来移动一块并没有错。

于 2012-10-01T00:20:06.760 回答