Parse castling in verbose notation.
[kaya.git] / lib / plugins / ics / lib / icsapi.rb
blob18b5e92fa235054c42d74c9784d4a63474653198
1 # Copyright (c) 2009 Paolo Capriotti <p.capriotti@gmail.com>
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
8 module ICS
10 class ICSApi
11   PIECES = {
12     'r' => :rook,
13     'n' => :knight,
14     'b' => :bishop,
15     'q' => :queen,
16     'k' => :king,
17     'p' => :pawn }
19   def initialize(game)
20     @game = game
21   end
23   def new_state(opts)
24     state = @game.state.new
25     state.turn = opts[:turn]
26     state.en_passant_square = 
27       if opts[:en_passant] != -1
28         Point.new(opts[:en_passant], 
29                   state.turn == :white ? 
30                   state.board.size.y - 3 : 2)
31       end
32     state.castling_rights.cancel_king(:white) unless opts[:wk_castling]
33     state.castling_rights.cancel_queen(:white) unless opts[:wq_castling]
34     state.castling_rights.cancel_king(:black) unless opts[:bk_castling]
35     state.castling_rights.cancel_queen(:black) unless opts[:bq_castling]
36     state
37   end
39   def new_piece(p)
40     return nil if p == '-'
41     color = p =~ /[a-z]/ ? :black : :white
42     type = PIECES[p.downcase]
43     @game.piece.new(color, type)
44   end
45   
46   def parse_last_move(str, turn)      
47     if str =~ /.*\/(.*)-(.*)$/
48       src, dst = [$1, $2].map do |c| 
49         Point.from_coord(c, @game.size.y, :strict => true)
50       end
51       @game.move.new(src, dst)
52     elsif str.downcase == "o-o-o"
53       src = Point.new(4, turn == :white ? 7 : 0)
54       dst = Point.new(2, turn == :white ? 7 : 0)
55       @game.move.new(src, dst)
56     elsif str.downcase == "o-o"
57       src = Point.new(4, turn == :white ? 7 : 0)
58       dst = Point.new(6, turn == :white ? 7 : 0)
59       @game.move.new(src, dst)
60     end
61   end
62   
63   def same_state(state1, state2)
64     state1.board == state2.board &&
65     state1.turn == state2.turn
66   end
67   
68   def amend_state(state1, state2)
69     state1.dup.tap do |result|
70       result.board = state2.board.dup
71       result.turn = state2.turn
72     end
73   end
74 end
76 end