Class: Sashite::Feen::Hands

Inherits:
Object
  • Object
show all
Defined in:
lib/sashite/feen/hands.rb

Overview

Immutable representation of pieces held in hand by each player.

Stores captured pieces that players hold in reserve, available for placement back onto the board in games that support drop mechanics (such as shogi, crazyhouse, etc.).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(first_player, second_player) ⇒ Hands

Create a new immutable Hands object.

Examples:

Empty hands

hands = Hands.new([], [])

First player has captured pieces

hands = Hands.new([pawn1, pawn2], [])

Both players have captured pieces

hands = Hands.new([rook, bishop], [pawn1, pawn2, knight])

Parameters:

  • first_player (Array)

    Pieces in first player’s hand

  • second_player (Array)

    Pieces in second player’s hand



32
33
34
35
36
37
# File 'lib/sashite/feen/hands.rb', line 32

def initialize(first_player, second_player)
  @first_player = first_player.sort_by(&:to_s).freeze
  @second_player = second_player.sort_by(&:to_s).freeze

  freeze
end

Instance Attribute Details

#first_playerArray (readonly)

Returns Array of pieces held by first player.

Returns:

  • (Array)

    Array of pieces held by first player



14
15
16
# File 'lib/sashite/feen/hands.rb', line 14

def first_player
  @first_player
end

#second_playerArray (readonly)

Returns Array of pieces held by second player.

Returns:

  • (Array)

    Array of pieces held by second player



17
18
19
# File 'lib/sashite/feen/hands.rb', line 17

def second_player
  @second_player
end

Instance Method Details

#==(other) ⇒ Boolean Also known as: eql?

Compare two hands for equality.

Parameters:

  • other (Hands)

    Another hands object

Returns:

  • (Boolean)

    True if both players’ pieces are equal



64
65
66
67
68
# File 'lib/sashite/feen/hands.rb', line 64

def ==(other)
  other.is_a?(Hands) &&
    first_player == other.first_player &&
    second_player == other.second_player
end

#empty?Boolean

Check if both hands are empty.

Examples:

hands.empty?  # => true

Returns:

  • (Boolean)

    True if neither player has pieces in hand



45
46
47
# File 'lib/sashite/feen/hands.rb', line 45

def empty?
  first_player.empty? && second_player.empty?
end

#hashInteger

Generate hash code for hands.

Returns:

  • (Integer)

    Hash code based on both players’ pieces



75
76
77
# File 'lib/sashite/feen/hands.rb', line 75

def hash
  [first_player, second_player].hash
end

#to_sString

Convert hands to their FEEN string representation.

Examples:

hands.to_s
# => "2P/p"

Returns:

  • (String)

    FEEN pieces-in-hand field



56
57
58
# File 'lib/sashite/feen/hands.rb', line 56

def to_s
  Dumper::PiecesInHand.dump(self)
end