Class: JustXiangqi::SquareSet
- Inherits:
-
BoardGameGrid::SquareSet
- Object
- BoardGameGrid::SquareSet
- JustXiangqi::SquareSet
- Defined in:
- lib/just_xiangqi/square_set.rb
Overview
Square Set
A collection of Squares with useful filtering functions
Instance Method Summary collapse
-
#find_jiang_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.
Constructor Details
#initialize(squares:) ⇒ SquareSet
New objects can be instantiated by passing in a hash with squares. They can be square objects or hashes.
Example:
# Instantiates a new Square Sete
JustXiangqi::SquareSet.new({
squares: [
{ id: '1', x: 0, y: 0, piece: { id: 1, player_number: 1, type: 'zu' } }
]
})
24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/just_xiangqi/square_set.rb', line 24 def initialize(squares: ) @squares = if squares.instance_of?(Array) 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 else raise ArgumentError, "squares must be an array" end end |
Instance Method Details
#find_jiang_for_player(player_number) ⇒ Square
Find the square occupied by the player’s king
Example:
# Find the square occupied by player 2's jiang
square_est.find_jiang_for_player(2)
47 48 49 |
# File 'lib/just_xiangqi/square_set.rb', line 47 def find_jiang_for_player(player_number) find { |s| s.piece && s.piece.is_a?(JustXiangqi::Jiang) && s.occupied_by_player?(player_number) } end |
#threatened_by(player_number, game_state) ⇒ SquareSet
Returns all squares threatened by the specified player
60 61 62 63 64 65 66 |
# File 'lib/just_xiangqi/square_set.rb', line 60 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 |