Class: JustChess::SquareSet
- Inherits:
-
BoardGameGrid::SquareSet
- Object
- BoardGameGrid::SquareSet
- JustChess::SquareSet
- Defined in:
- lib/just_chess/square_set.rb
Overview
Square Set
A collection of Squares with useful filtering functions
Instance Method Summary collapse
-
#find_king_for_player(player_number) ⇒ Square
Find the square occupied by the player’s king.
-
#initialize(squares:) ⇒ SquareSet
constructor
New objects can be instantiated by passing in a hash with squares.
-
#threatened_by(player_number, game_state) ⇒ SquareSet
Returns all squares threatened by the specified player.
-
#unmoved ⇒ SquareSet
Returns all squares with pieces that haven’t moved.
Constructor Details
#initialize(squares:) ⇒ SquareSet
24 25 26 27 28 29 30 31 32 |
# File 'lib/just_chess/square_set.rb', line 24 def initialize(squares: ) @squares = if squares.all? { |s| s.instance_of?(Hash) } squares.map { |s| Square.new(**s) } elsif squares.all? { |s| s.instance_of?(Square) } squares else raise ArgumentError, "all squares must have the same class" end end |
Instance Method Details
#find_king_for_player(player_number) ⇒ Square
Find the square occupied by the player’s king
Example:
# Find the square occupied by player 2's king
square_set.find_king_for_player(2)
43 44 45 |
# File 'lib/just_chess/square_set.rb', line 43 def find_king_for_player(player_number) find { |s| s.piece && s.piece.is_a?(JustChess::King) && s.occupied_by_player?(player_number) } end |
#threatened_by(player_number, game_state) ⇒ SquareSet
Returns all squares threatened by the specified player
63 64 65 66 67 68 69 |
# File 'lib/just_chess/square_set.rb', line 63 def threatened_by(player_number, game_state) _squares = occupied_by_player(player_number).map do |s| s.piece.potential_capture_squares(s, game_state).squares end.flatten.uniq self.class.new(squares: _squares) end |
#unmoved ⇒ SquareSet
Returns all squares with pieces that haven’t moved
50 51 52 |
# File 'lib/just_chess/square_set.rb', line 50 def unmoved select { |s| s.piece && s.piece.has_not_moved? } end |