Class: JustCheckers::SquareSet

Inherits:
BoardGameGrid::SquareSet
  • Object
show all
Defined in:
lib/just_checkers/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
JustCheckers::SquareSet.new({
  squares: [
    { x: 1, y: 0, piece: { player_number: 1, king: false }}
  ]
})

Parameters:

  • squares (Array<Square,Hash>) (defaults to: [])

    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_checkers/square_set.rb', line 24

def initialize(squares: [])
  @squares = if squares.all? { |element| element.instance_of?(Hash) }
    squares.map { |args| JustCheckers::Square.new(**args) }
  elsif squares.all? { |element| element.instance_of?(JustCheckers::Square) }
    squares
  else
    raise ArgumentError, "all squares must have the same class"
  end
end

Instance Method Details

#in_direction_of(piece, square) ⇒ SquareSet

Find squares in the direction of the piece from the square If the piece is normal, it returns squares in front of it. If the piece is king, it returns all squares.

Example:

# Get all squares in the direction of the piece.
square_set.in_direction_of(piece, square)

Parameters:

  • piece (Piece)

    the piece in question.

  • square (Square)

    the square the piece is on.

Returns:



49
50
51
52
53
# File 'lib/just_checkers/square_set.rb', line 49

def in_direction_of(piece, square)
  select do |s|
    piece.king? || BoardGameGrid::Vector.new(square, s).direction.y == piece.direction
  end
end

#occupied_by(player_number) ⇒ SquareSet

Takes a player number and returns all squares occupied by the player

Parameters:

  • player_number (Fixnum)

    the player’s number.

Returns:



71
72
73
# File 'lib/just_checkers/square_set.rb', line 71

def occupied_by(player_number)
  select { |s| s.piece && s.piece.player_number == player_number }
end

#occupied_by_opponent_of(player_number) ⇒ SquareSet

Takes a player number and returns all squares occupied by the opponent of the player

Parameters:

  • player_number (Fixnum)

    the player’s number.

Returns:



61
62
63
# File 'lib/just_checkers/square_set.rb', line 61

def occupied_by_opponent_of(player_number)
  select { |s| s.piece && s.piece.player_number != player_number }
end