Sha256: 3cf3497e7956220f5e7019e4010c551e26d4b60e4121508caeb5c15a1d63ba1b

Contents?: true

Size: 1.55 KB

Versions: 10

Compression:

Stored size: 1.55 KB

Contents

module BoardAnalysis
  # This is the total material evaluation (pieces value put together)
  # when a player keeps just a king, a queen and a few pieces, indicating
  # that the game is now in its last stage (endgame):
  LAST_STAND_PIECES_VALUE = 21_500

  def in_check?(color)
    king_position = find_king(color)

    enemy_pieces(color).each do |piece|
      return true if piece.available_moves.include?(king_position)
    end

    false
  end

  def find_king(color)
    king_location = pieces.find do |piece|
      piece.color == color && piece.is_a?(King)
    end

    king_location&.location
  end

  def checkmate?(color)
    return false unless in_check?(color)

    friendly_pieces(color).all? { |piece| piece.safe_moves.empty? }
  end

  def no_king?(color)
    find_king(color).nil?
  end

  def pieces
    matrix.flatten.reject { |position| position.is_a?(EmptySquare) }
  end

  def friendly_pieces(color)
    pieces.select { |piece| piece.color == color }
  end

  def enemy_pieces(color)
    pieces.reject { |piece| piece.color == color }
  end

  def count(type, color)
    friendly_pieces(color).select { |piece| piece.instance_of?(type) }.size
  end

  def promoted_pawns(color)
    friendly_pieces(color).select do |piece|
      piece.is_a?(Pawn) && piece.promoted?
    end.size
  end

  def end_game?
    (count(Queen, :white).zero? && count(Queen, :black).zero?) ||
      (last_stand?(:white) || last_stand?(:black))
  end

  def last_stand?(color)
    count(Queen, color).positive? &&
      friendly_pieces(color).map(&:value).sum <= LAST_STAND_PIECES_VALUE
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
sapphire-chess-1.1.7 lib/sapphire-chess/board/board_analysis.rb
sapphire-chess-1.1.6 lib/sapphire-chess/board/board_analysis.rb
sapphire-chess-1.1.5 lib/sapphire-chess/board/board_analysis.rb
sapphire-chess-1.1.4 lib/sapphire-chess/board/board_analysis.rb
sapphire-chess-1.1.3 lib/sapphire-chess/board/board_analysis.rb
sapphire-chess-1.1.2 lib/sapphire-chess/board/board_analysis.rb
sapphire-chess-1.1.1 lib/sapphire-chess/board/board_analysis.rb
sapphire-chess-1.1.0 lib/sapphire-chess/board/board_analysis.rb
sapphire-chess-1.0.1 lib/sapphire-chess/board/board_analysis.rb
sapphire-chess-1.0.0 lib/sapphire-chess/board/board_analysis.rb