Class: ChessGame

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

Overview

ChessGame takes a listener in its constructor and creates a Board. The method ChessGame#read_moves reads game data. Calling ChessGame#play moves the pieces, which in turn sends messages to the listener so it can react.

Instance Method Summary collapse

Constructor Details

#initialize(listener = GameListener.new) ⇒ ChessGame

Returns a new instance of ChessGame.



10
11
12
# File 'lib/bangkok/chessgame.rb', line 10

def initialize(listener = GameListener.new)
  @listener = listener
end

Instance Method Details

#play(io) ⇒ Object

Writes a MIDI file.



42
43
44
45
46
47
# File 'lib/bangkok/chessgame.rb', line 42

def play(io)
  @listener.start_game(io)
  board = Board.new(@listener)
  @moves.each { | move | board.apply(move) }
  @listener.end_game
end

#read(io) ⇒ Object

Read the chess game. Set player names and return a string containing the chess moves (“1. f4 Nf6 2. Nf3 c5…”).



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/bangkok/chessgame.rb', line 26

def read(io)
  game_text = ''
  io.each { | line |
    line.chomp!
    case line
    when /\[(.*)\]/           # New games starting (if multi-game file)
    when /^\s*$/
    else
      game_text << ' '
      game_text << line
    end
  }
  game_text
end

#read_moves(io) ⇒ Object

Read the chess game and turn it into Moves.



15
16
17
18
19
20
21
22
# File 'lib/bangkok/chessgame.rb', line 15

def read_moves(io)
  game_text = read(io)
  @moves = []
  game_text.scan(/\d+\.\s+(\S+)\s+(\S+)/).each { | white, black |
    @moves << Move.new(:white, white)
    @moves << Move.new(:black, black) unless black == '1-0' || black == '0-1'
  }
end