Restored back and forward functionalities.
[kaya.git] / lib / ics / match_handler.rb
blob18d91445afbd1f8f4c68a45102d2c114909b8b57
1 require 'interaction/match'
2 require 'ics/icsplayer'
4 module ICS
6 # Handler for ICS games
7
8 class MatchHandler
9   include Observer
10   
11   attr_reader :matches
12   
13   def initialize(user, protocol)
14     @protocol = protocol
15     @matches = { }
16     @user = user
17     
18     protocol.add_observer(self)
19   end
20   
21   def on_creating_game(data)
22     match = Match.new(data[:game], 
23         :kind => :ics, 
24         :editable => false)
25     @matches[data[:number]] = [match, data[:icsapi]]
26   end
27   
28   def on_style12(style12)
29     match, icsapi = @matches[style12.game_number]
30     return if match == nil
31     
32     if match.started?
33       puts "match.index = #{match.index}"
34       puts "move index = #{style12.move_index}"
35       puts "current state = #{match.state}"
36       if match.index < style12.move_index
37         # last_move = icsapi.parse_verbose(style12.last_move, match.state)
38         move = match.game.serializer.new(:compact).deserialize(style12.last_move_san, match.state)
39 #         if last_move != move
40 #           warn "[server inconsistency] " +
41 #                 "SAN for last move is different from verbose notation"
42 #         end
43         if move
44           match.move(nil, move, style12.state)
45         else
46           warn "Received invalid move from ICS: #{style12.last_move_san}"
47         end
48       end
49     else
50       rel = style12.relation
51       state = style12.state
52       turns = [state.turn, state.opposite_turn(state.turn)]
53       @user.color, opponent_color =
54         if rel == Style12::Relation::MY_MOVE
55           turns
56         else
57           turns.reverse
58         end
59       opponent = ICSPlayer.new(
60         lambda {|msg| @protocol.connection.send_text(msg) },
61         opponent_color,
62         match.game.serializer.new(:compact))
63       
64       match.register(@user)
65       match.register(opponent)
66       
67       match.start(@user)
68       match.start(opponent)
69       
70       raise "couldn't start match" unless match.started?
71       
72       @user.reset(match)
73     end
74     
75     
76   end
77 end
79 end