Module: PGN::Attack

Defined in:
lib/pgn/attack.rb

Overview

Attack is the single source of truth for square-attack queries on a Board. It factors the private attack logic that Notation previously duplicated, so Position (and other consumers) can ask "is this square attacked?" and "which squares attack this square?".

Squares are 0x88 indices (see Board); on-board when (idx & 0x88).zero?. color is 'w' or 'b'.

Constant Summary collapse

BISHOP_DIRS =
[-15, 15, -17, 17].freeze
ROOK_DIRS =
[-1, 1, -16, 16].freeze

Class Method Summary collapse

Class Method Details

.attacked?(board, target, color) ⇒ Boolean

Whether target (a 0x88 index) is attacked by any color piece.

Returns:

  • (Boolean)


27
28
29
# File 'lib/pgn/attack.rb', line 27

def self.attacked?(board, target, color)
  attackers(board, target, color).any?
end

.attackers(board, target, color) ⇒ Object

The algebraic squares of every color piece on board that attacks target (a 0x88 index), in no particular order.



33
34
35
36
37
38
# File 'lib/pgn/attack.rb', line 33

def self.attackers(board, target, color)
  pawn_attackers(board, target, color) +
    knight_attackers(board, target, color) +
    king_attackers(board, target, color) +
    slider_attackers(board, target, color)
end

.king_idx(board, color) ⇒ Object

The 0x88 index of the color king on board, or nil if absent.



16
17
18
19
20
21
22
23
24
# File 'lib/pgn/attack.rb', line 16

def self.king_idx(board, color)
  king = color == 'w' ? 'K' : 'k'
  (0...128).each do |idx|
    next if idx.anybits?(0x88)

    return idx if board.at_index(idx) == king
  end
  nil
end