Chess piece hierarchy design: inheritance vs type fields

前端 未结 6 768
别跟我提以往
别跟我提以往 2021-02-15 13:23

I have a base class for pieces

 class piece;

and an array containing derived objects

piece* board[8][8];

Advantag

6条回答
  •  囚心锁ツ
    2021-02-15 14:15

    I never wrote a chess program, but I'd guess the most common operations would be things like:

    • display/print the board
    • get the set of possible moves for each piece
    • sum up the values of all pieces for a board, maybe sum up some kind of "position value" that depends on the piece (rook on an open line, things like that)

    Additionally, some of the pieces have "state" (a king can only castle if it hasn't moved before, a pawn can strike in passing if the other pawn just moved two squares) that only apply to one kind of piece.

    That all screams class hierarchy to me. (Assuming you don't need bitboard-performance)

    On the other hand, it's unlikely that you will ever have to add new piece types or that you will ever be able to re-use one of the piece types in separation. i.e. extensibility and modularity is not really an issue. So if you find that some important part of your algorithm that should really be in one place is scattered over multiple piece classes - use a switch statement. Just add an abstract method tp the Piece class that returns a PieceType enum and switch on that.

提交回复
热议问题