Board 类有一个 s 的 8x8 2D 数组Piece
,所以我显然可以使用 Board 类移动一块,board.move(piece1, 3, left)
例如,但是我无法简单地告诉块移动,比如piece1.move(3, left)
,因为它没有办法了解有关棋盘的任何信息(没有将其作为参数传递),因此它无法将自身移动到特定索引,或者知道一块是否已经占据了该索引,或者是否被告知移动到边界之外的数组。
2 回答
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 thePiece
, right?) It knows whichPieces
make up a complete game set. It knows which moves eachPiece
can make. It knows where any givenPiece
is on theBoard
at any given time. - Player: The
Player
interacts with theGame
. It will tell theGame
that it wants to perform a given action on aPiece
. TheGame
will allow or deny that action, and modify the state of theGame
(Check, Mate, Stalemate, otherPlayer
's turn, etc.) based on that action. (Again, thePieces
and theBoard
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 Piece
s.)
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.
一块,就其本身而言,不知道它恰好放置在哪里(并且可能不需要知道)。Board
因此,需要调用方法来移动一块并没有错。