Class: JustChess::SquareSet

Inherits:
BoardGameGrid::SquareSet
  • Object
show all
Defined in:
lib/just_chess/square_set.rb

Overview

Square Set

A collection of Squares with useful filtering functions

Instance Method Summary collapse

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 Set
JustChess::SquareSet.new({
  squares: [
    { x: 1, y: 0, piece: { player_number: 1, direction: 1, king: false }}
  ]
})

Parameters:

  • squares (Array<Square,Hash>)

    An array of squares, each with x and y co-ordinates and a piece.



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)

Parameters:

  • player_number (Fixnum)

    the number of the player

Returns:



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

Parameters:

  • player_number (Fixnum)

    the player’s number.

  • game_state (GameState)

    the current game state.

Returns:



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

#unmovedSquareSet

Returns all squares with pieces that haven’t moved

Returns:



50
51
52
# File 'lib/just_chess/square_set.rb', line 50

def unmoved
  select { |s| s.piece && s.piece.has_not_moved? }
end