Is square (r, c) attacked by a piece of the given color?
(board, r, c, by_white: bool)
| 44 | |
| 45 | |
| 46 | def _attacked(board, r, c, by_white: bool) -> bool: |
| 47 | """Is square (r, c) attacked by a piece of the given color?""" |
| 48 | # pawns |
| 49 | pr = 1 if by_white else -1 # white pawns attack from row r+1 (below), moving up |
| 50 | for dc in (-1, 1): |
| 51 | ar, ac = r + pr, c + dc |
| 52 | if 0 <= ar < 8 and 0 <= ac < 8: |
| 53 | p = board[ar][ac] |
| 54 | if p and _white(p) == by_white and p.upper() == "P": |
| 55 | return True |
| 56 | for dr, dc in KNIGHT: |
| 57 | ar, ac = r + dr, c + dc |
| 58 | if 0 <= ar < 8 and 0 <= ac < 8: |
| 59 | p = board[ar][ac] |
| 60 | if p and _white(p) == by_white and p.upper() == "N": |
| 61 | return True |
| 62 | for dr, dc in KING: |
| 63 | ar, ac = r + dr, c + dc |
| 64 | if 0 <= ar < 8 and 0 <= ac < 8: |
| 65 | p = board[ar][ac] |
| 66 | if p and _white(p) == by_white and p.upper() == "K": |
| 67 | return True |
| 68 | for dirs, kinds in ((BISHOP, "BQ"), (ROOK, "RQ")): |
| 69 | for dr, dc in dirs: |
| 70 | ar, ac = r + dr, c + dc |
| 71 | while 0 <= ar < 8 and 0 <= ac < 8: |
| 72 | p = board[ar][ac] |
| 73 | if p: |
| 74 | if _white(p) == by_white and p.upper() in kinds: |
| 75 | return True |
| 76 | break |
| 77 | ar, ac = ar + dr, ac + dc |
| 78 | return False |
| 79 | |
| 80 | |
| 81 | def _king(board, white: bool): |