MCPcopy Index your code
hub / github.com/coding-parrot/chess-engine / attackingKing

Method attackingKing

src/main/java/game/Board.java:354–396  ·  view source on GitHub ↗
(Piece king)

Source from the content-addressed store, hash-verified

352 }
353
354 private Set<Piece> attackingKing(Piece king) {
355 final HashSet<Piece> attackers = new HashSet<>();
356 final int kingRow = king.position.row, kingCol = king.position.col;
357 final Color color = king.color;
358 for (int rowDiff = -1; rowDiff <= 1; rowDiff++) {
359 for (int colDiff = -1; colDiff <= 1; colDiff++) {
360 if (!(rowDiff == 0 && colDiff == 0) && attackers.size() < 2) {
361 final PieceType type = rowDiff == 0 || colDiff == 0 ? PieceType.ROOK : PieceType.BISHOP;
362 for (int row = kingRow + rowDiff, col = kingCol + colDiff; Utils.withinBoardLimits(row, col); row = row + rowDiff, col = col + colDiff) {
363 if (!isEmpty(row, col)) {
364 final Piece piece = getPiece(row, col);
365 if (piece.color != color && (piece.sameType(PieceType.QUEEN) || piece.sameType(type))) {
366 attackers.add(piece);
367 }
368 break;
369 }
370 }
371 }
372 }
373 }
374 if (attackers.size() < 2) {
375 final int pawnAttackRow = color == Color.BLACK ? kingRow - 1 : kingRow + 1;
376 if (pawnAttackRow >= 0 && pawnAttackRow < 8) {
377 final Piece leftPawn = kingCol > 0 ? getPiece(pawnAttackRow, kingCol - 1) : null;
378 final Piece rightPawn = kingCol < 7 ? getPiece(pawnAttackRow, kingCol + 1) : null;
379 if (rightPawn != null && rightPawn.sameType(PieceType.PAWN) && rightPawn.color != king.color) {
380 attackers.add(rightPawn);
381 } else if (leftPawn != null && leftPawn.sameType(PieceType.PAWN) && leftPawn.color != king.color) {
382 attackers.add(leftPawn);
383 }
384 }
385 for (int i = 0; i < Knight.diff.length && attackers.size() < 2; i++) {
386 final int row = kingRow + Knight.diff[i][0], col = kingCol + Knight.diff[i][1];
387 if (Utils.withinBoardLimits(row, col)) {
388 final Piece piece = getPiece(row, col);
389 if (piece != null && piece.sameType(PieceType.KNIGHT) && piece.color != king.color) {
390 attackers.add(piece);
391 }
392 }
393 }
394 }
395 return attackers;
396 }
397
398 private void updateHashForRemove(Piece piece) {
399 zobristHash ^= zobrist[piece.pieceType.ordinal()][piece.color.ordinal()][(piece.position.row << 3) + piece.position.col];

Callers 1

getLegalMovesMethod · 0.95

Calls 4

withinBoardLimitsMethod · 0.95
isEmptyMethod · 0.95
getPieceMethod · 0.95
sameTypeMethod · 0.95

Tested by

no test coverage detected