简体   繁体   中英

How to declare chess pieces whose location causes the chess board object to update and store the piece at the given location

If I'm working on designing a simple chess game code and I've already created my board layout, I'm wondering how it is that I implement the pieces (P, p, R, r, N, n, B, b, Q, q, K, k) (capitals represent white pieces , lowercase are black pieces ) so that the ChessBoard object updates to store the piece at that inputted location?

Should I declare the pieces as instance variables? Or should I just declare them in the main?

As far as the user inputting a location that is already taken, I'm totally lost as to how to translate that into code.

I did however implement a part of the code that displays an error message if the input from the user is outside of the board range.

(this is all in java, by the way)

Any help would be greatly appreciated!! Thanks in advance! Let me know if seeing some of my code would help.

I "implemented" a chess game for a job interview a couple years ago. Each piece was an instance variable, and had a move() method that determined what the piece's legal moves were. The board contained information on where all of the pieces were located, and a piece would query the board when determining what its legal moves were (eg a pawn would query the board to see if there were any diagonally located opposing pieces that it could capture). Piece was an abstract class (and the board contained a grid of Piece objects), and Pawn , Knight , etc extended Piece .

If you need to implement en passant, then you'll probably want a separate rules engine that the pieces can query for their legal moves - the pieces would be stateless, and the rules engine would carry the state information needed to determine if pawns could capture via en passant, or if a draw were in effect due to three move repetition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM