Class: ChessData::Database

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/chess_data/database.rb

Overview

Class to store a set of chess games

The usual way to create a database is directly from a filename. If your pgn file is called ‘my_games.pgn’, create a database using

Database.from_file 'my_games.pgn'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDatabase

Returns a new instance of Database.



14
15
16
# File 'lib/chess_data/database.rb', line 14

def initialize
  @games = []
end

Class Method Details

.from_file(filename, encoding: "iso-8859-1") ⇒ Object

Loads and returns a new database based on given filename.

filename

the name of a pgn file from which to load games

encoding

defaults to “iso-8859-1” (which works for TWIC files).



76
77
78
79
80
# File 'lib/chess_data/database.rb', line 76

def Database.from_file filename, encoding: "iso-8859-1"
  database = Database.new
  database.add_games_from filename, encoding: encoding
  return database
end

Instance Method Details

#<<(game) ⇒ Object

Adds a given game to the database.



19
20
21
# File 'lib/chess_data/database.rb', line 19

def << game
  @games << game
end

#[](index) ⇒ Object

Returns the game at the given index value in the database.



24
25
26
# File 'lib/chess_data/database.rb', line 24

def [] index
  @games[index]
end

#add_games_from(filename, encoding: "iso-8859-1") ⇒ Object

Add games from a specified filename to database.

filename

the name of a pgn file from which to load games

encoding

defaults to “iso-8859-1” (which works for TWIC files).



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/chess_data/database.rb', line 48

def add_games_from filename, encoding: "iso-8859-1"
  File.open filename, mode: "r", encoding: encoding do |file|
    begin
      begin
        game = Game.from_pgn file
        @games << game unless game.nil?
      rescue ArgumentError
        puts "Error in #{filename}, previous game #{@games.last.white} vs #{@games.last.black}"
        return
      end
    end until file.eof?
  end
end

#search(&block) ⇒ Object

Returns a new database based on search criteria given in the block. Each game is scanned to see if it meets the criteria. Also see Game#search.



35
36
37
38
39
40
41
42
43
# File 'lib/chess_data/database.rb', line 35

def search &block
  db = Database.new

  @games.each do |game|
    db << game if game.search(&block)
  end

  return db
end

#sizeObject

Returns the number of games in the database.



29
30
31
# File 'lib/chess_data/database.rb', line 29

def size
  @games.size
end

#to_file(filename) ⇒ Object

Save the database in PGN format to given filename. If filename exists, the games are appended to the file.



64
65
66
67
68
69
70
71
# File 'lib/chess_data/database.rb', line 64

def to_file filename
  File.open(filename, "a") do |f|
    @games.each do |game|
      game.to_pgn f
      f.puts
    end
  end
end