@@ -138,6 +138,77 @@ public Position getEnPassantTarget() {
138138 return enPassantTarget ;
139139 }
140140
141+ public boolean isKingInCheck (Color color ){
142+ Position kingPos = findKing (color );
143+ if (kingPos == null ){
144+ return false ;
145+ }
146+ Color opponent = getOpposite (color );
147+ for (int r = 0 ; r < board .length ; r ++){
148+ for (int c = 0 ; c < board [r ].length ; c ++){
149+ ChessPiece piece = board [r ][c ];
150+ if (piece .color () == opponent ){
151+ Position [] moves = getValidMoves (new Position (r ,c ));
152+ for (Position pos : moves ){
153+ if (pos .row == kingPos .row && pos .col == kingPos .col ){
154+ return true ;
155+ }
156+ }
157+ }
158+ }
159+ }
160+ return false ;
161+ }
162+
163+ public boolean isCheckmate (Color color ){
164+ if (!isKingInCheck (color )){
165+ return false ;
166+ }
167+ for (int r = 0 ; r < board .length ; r ++){
168+ for (int c = 0 ; c < board [r ].length ; c ++){
169+ if (board [r ][c ].color () == color ){
170+ Position from = new Position (r ,c );
171+ Position [] moves = getValidMoves (from );
172+ for (Position to : moves ){
173+ ChessPiece captured = simulateMove (from , to );
174+ boolean stillCheck = isKingInCheck (color );
175+ undoMove (from , to , captured );
176+ if (!stillCheck ){
177+ return false ;
178+ }
179+ }
180+ }
181+ }
182+ }
183+ return true ;
184+ }
185+
186+ private ChessPiece simulateMove (Position from , Position to ){
187+ ChessPiece moving = board [from .row ][from .col ];
188+ ChessPiece captured = board [to .row ][to .col ];
189+ board [to .row ][to .col ] = moving ;
190+ board [from .row ][from .col ] = emptySpace ;
191+ return captured ;
192+ }
193+
194+ private void undoMove (Position from , Position to , ChessPiece captured ){
195+ ChessPiece moving = board [to .row ][to .col ];
196+ board [from .row ][from .col ] = moving ;
197+ board [to .row ][to .col ] = captured ;
198+ }
199+
200+ private Position findKing (Color color ){
201+ for (int r = 0 ; r < board .length ; r ++){
202+ for (int c = 0 ; c < board [r ].length ; c ++){
203+ ChessPiece piece = board [r ][c ];
204+ if (piece .type () == ChessPieceType .King && piece .color () == color ){
205+ return new Position (r ,c );
206+ }
207+ }
208+ }
209+ return null ;
210+ }
211+
141212 private boolean isValidPromotionType (ChessPieceType type ) {
142213 return type == ChessPieceType .Queen ||
143214 type == ChessPieceType .Rock ||
0 commit comments