class PGN::Game

{PGN::Game} holds all of the information about a game. It is either the result of parsing a PGN file, or created by hand.

A {PGN::Game} has an interactive {#play} method, and can also return a list of positions in {PGN::Position} format or FEN.

@!attribute tags

@return [Hash<String, String>] metadata about the game
@example
  game.tags #=> {"White" => "Kasparov", "Black" => "Deep Blue"}

@!attribute moves

@return [Array<String>] a list of the moves in standard algebraic
  notation
@example
  game.moves #=> ["e4", "c5", "Nf3", "d6", "d4", "cxd4"]

@!attribute result

@return [String] the outcome of the game
@example
  game.result #=> "1-0"

Constants

EXIT
LEFT

Attributes

moves[RW]
result[RW]
tags[RW]

Public Class Methods

new(moves, tags = nil, result = nil) click to toggle source

@param moves [Array<String>] a list of moves in SAN @param tags [Hash<String, String>] metadata about the game @param result [String] the outcome of the game

# File lib/pgn/game.rb, line 63
def initialize(moves, tags = nil, result = nil)
  self.moves  = moves
  self.tags   = tags
  self.result = result
end

Public Instance Methods

fen_list() click to toggle source

@return [Array<String>] list of the fen representations of the positions

# File lib/pgn/game.rb, line 108
def fen_list
  self.positions.map {|p| p.to_fen.inspect }
end
moves=(moves) click to toggle source

@param moves [Array<String>] a list of moves in SAN

Standardize castling moves to use O's instead of 0's

# File lib/pgn/game.rb, line 73
def moves=(moves)
  @moves = moves.map do |m|
    if m.is_a? String
      MoveText.new(m.gsub("0", "O"))
    else
      MoveText.new(m.notation.gsub("0", "O"), m.annotation, m.comment, m.variations)
    end
  end
end
play() click to toggle source

Interactively step through the game

Use d to move forward, a to move backward, and +^C+ to exit.

# File lib/pgn/game.rb, line 116
def play
  index = 0
  hist = Array.new(3, "")

  loop do
    puts "\e[H\e[2J"
    puts self.positions[index].inspect
    hist[0..2] = (hist[1..2] << STDIN.getch)

    case hist.join
    when LEFT
      index -= 1 if index > 0
    when RIGHT
      index += 1 if index < self.moves.length
    when EXIT
      break
    end
  end
end
positions() click to toggle source

@return [Array<PGN::Position>] list of the {PGN::Position}s in the game

# File lib/pgn/game.rb, line 93
def positions
  @positions ||= begin
    position = starting_position
    arr = [position]
    self.moves.each do |move|
      new_pos = position.move(move.notation)
      arr << new_pos
      position = new_pos
    end
    arr
  end
end
starting_position() click to toggle source
# File lib/pgn/game.rb, line 83
def starting_position
  @starting_position ||= if fen = (self.tags && self.tags['FEN'])
                           PGN::FEN.new(fen).to_position
                         else 
                           PGN::Position.start 
                         end 
end