Method: ChessRB::Position#mate?

Defined in:
lib/chess_rb/position.rb

#mate?Boolean

Returns if the current position is checkmate, false otherwise

Returns:

  • (Boolean)


126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/chess_rb/position.rb', line 126

def mate?
  return false if !check?

  t = turn().upcase
  king_vector = Vector[*(squares_with([t + 'K'])[0])]

  around_vectors = [[1, 0], [0, 1], [-1, 0], [0, -1], [1, 1], [-1, 1],
    [1, -1], [-1, -1]]
  around_vectors.each do |v|
    v = Vector[*v]
    current_square = (king_vector + v).to_a
    if !self.class.valid_square?(current_square) ||
      piece_on(current_square).color == t

      next
    else
      undo_code = piece_on(current_square).code
      move(king_vector.to_a, current_square)
      if !check?
        undo(king_vector.to_a, current_square, undo_code)
        return false
      end
      undo(king_vector.to_a, current_square, undo_code)
    end
  end

  return true
end