class ChessOpenings
Class responsible for searching for chess Openings
Attributes
Public Class Methods
# 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
Public Instance Methods
Get all openings available
@return [Array] Array with all the Openings possible
# File lib/chess_openings.rb, line 27 def all @list.dup end
Get Opening
from FEN string
@param [String] fen_string FEN formatted String @return [Opening] Opening
that was used in the game of the FEN String
# File lib/chess_openings.rb, line 92 def from_fen(fen_string) fen = PGN::FEN.new(fen_string) move_number = (fen.fullmove.to_i - 1) * 2 final_list = @tree.get_moves_in_depth(move_number) final_list.select { |op| op.to_fen == fen_string }.first end
Get Opening
from a PGN file
@param [String] file_name String with the path to the PGN file @return [Opening] Opening
that was used in the PGN game @raise [InvalidPGNError] Path points to invalid PGN file @raise [LoadError] Path points to non existent file
# File lib/chess_openings.rb, line 45 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.map(&:notation) rescue raise InvalidPGNError, 'Invalid PGN file' end end
Get Opening
from a PGN formatted String
@param [String] string String in PGN format @return [Opening] Opening
that was used in PGN formatted String
# File lib/chess_openings.rb, line 75 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
Search all Openings that start with the moves in the argument
@param [Array] moves Moves to be searched for @return [Array] Array with all Openings that start with the moves provided
# File lib/chess_openings.rb, line 67 def that_start_with(moves) @tree.search_all_with_moves moves end
Search Openings by name
@param [String] name String with the name to search for @return [Array] Array with all the Openings found
# File lib/chess_openings.rb, line 59 def with_name(name) @list.select { |op| op.name.downcase.include?(name.downcase) } end
Private Instance Methods
# File lib/chess_openings.rb, line 101 def to_s @tree.to_s end