Class: ChessOpenings

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeChessOpenings

Returns a new instance of ChessOpenings.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/chess_openings.rb', line 11

def initialize
  @tree = SearchTree.new
  @list = []

  file = "/chess_openings/json_openings/openings.json"
  openings_file = File.join(File.dirname(__FILE__), file)

  openings = JSON.load(File.open(openings_file))["openings"]
  openings.each do |op|
    opening = Opening.new(op["name"], op["eco_code"], op["moves"])
    @list << opening
    @tree.insert opening.moves, opening
  end

end

Instance Attribute Details

#listObject

Returns the value of attribute list.



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

def list
  @list
end

#treeObject

Returns the value of attribute tree.



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

def tree
  @tree
end

Instance Method Details

#from_moves(moves) ⇒ Object



31
32
33
34
# File 'lib/chess_openings.rb', line 31

def from_moves(moves)
  # moves.map! { |move| move.to_s if move.is_a? Symbol }
  @tree.search moves
end

#from_pgn(file_name) ⇒ Object

Raises:

  • (LoadError)


36
37
38
39
40
41
42
43
44
# File 'lib/chess_openings.rb', line 36

def from_pgn(file_name)
  raise LoadError, "File does not exist" unless File.exist?(file_name)
  begin
    game = PGN.parse(File.read(file_name)).first
    @tree.search game.moves
  rescue
    raise InvalidPGNError, "Invalid PGN file"
  end
end

#from_string(string) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/chess_openings.rb', line 54

def from_string(string)
  array = string.split
  moves = []
  array.each do |move|
    if move.include?(".")
      next if move.end_with?(".")
      move = move.split(".").last
    end
    moves << move
  end
  @tree.search moves
end

#get_allObject



27
28
29
# File 'lib/chess_openings.rb', line 27

def get_all
  @list.dup
end

#that_start_with(moves) ⇒ Object



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

def that_start_with(moves)
  @tree.search_all_with_moves moves
end

#with_name(name) ⇒ Object



46
47
48
# File 'lib/chess_openings.rb', line 46

def with_name(name)
  @list.select { |op| op.name.downcase.include?(name.downcase) }
end