Class: Opening

Inherits:
Object
  • Object
show all
Defined in:
lib/chess_openings/opening.rb

Overview

Class that represents a chess Opening

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, eco_code, moves) ⇒ Opening

Returns a new instance of Opening



9
10
11
12
13
# File 'lib/chess_openings/opening.rb', line 9

def initialize(name, eco_code, moves)
  @name = name
  @eco_code = eco_code
  @moves = moves.map! { |move| move.is_a?(String)? move.to_sym : move }
end

Instance Attribute Details

#eco_codeObject

Returns the value of attribute eco_code



7
8
9
# File 'lib/chess_openings/opening.rb', line 7

def eco_code
  @eco_code
end

#movesObject

Returns the value of attribute moves



7
8
9
# File 'lib/chess_openings/opening.rb', line 7

def moves
  @moves
end

#nameObject

Returns the value of attribute name



7
8
9
# File 'lib/chess_openings/opening.rb', line 7

def name
  @name
end

Instance Method Details

#==(other) ⇒ Boolean

Compares two Openings

Parameters:

  • other (Opening)

    Opening to be compared

Returns:

  • (Boolean)

    True if both Openings have the same values, false otherwise



33
34
35
# File 'lib/chess_openings/opening.rb', line 33

def ==(other)
  @name == other.name && @eco_code == other.eco_code && @moves == other.moves
end

#to_fenString

Returns FEN formatted String representation of the Opening

Returns:

  • (String)

    String that represents a game where Opening was used



61
62
63
64
# File 'lib/chess_openings/opening.rb', line 61

def to_fen
  moves = ChessOpeningsHelper.moves_as_strings(@moves)
  PGN::Game.new(moves).fen_list.last
end

#to_hHash

Hash representation of Opening

Returns:

  • (Hash)

    Hash that represents an Opening



25
26
27
# File 'lib/chess_openings/opening.rb', line 25

def to_h
  { 'name' => @name, 'eco_code' => @eco_code, 'moves' => @moves }
end

#to_pgnString

Returns PGN formatted String of the Opening

Returns:

  • (String)

    String that represents a game where Opening was used



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/chess_openings/opening.rb', line 40

def to_pgn
  result = ""
  index = 1
  @moves.each do |move|

    if index.odd?
      result += "#{(index / 2.0).ceil}.#{move}"
    elsif index.even? && @moves.size != index
      result += " #{move} "
    else
      result += " #{move}"
    end

    index += 1
  end
  return result
end

#to_sString

String representation of Opening

Returns:

  • (String)

    String that represents an Opening



18
19
20
# File 'lib/chess_openings/opening.rb', line 18

def to_s
  "#{@eco_code}: #{@name}\n#{@moves}"
end