Add licence and installation instructions.
[kaya.git] / lib / ics / match_handler.rb
blob385fc0deade5bbd6943b6d460059f4eafef3f491
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 require 'interaction/match'
9 require 'ics/icsplayer'
11 module ICS
13 # Handler for ICS games
14
15 class MatchHandler
16   include Observer
17   
18   attr_reader :matches
19   
20   def initialize(user, protocol)
21     @protocol = protocol
22     @matches = { }
23     @user = user
24     
25     protocol.add_observer(self)
26   end
27   
28   def on_creating_game(data)
29     match = Match.new(data[:game], 
30         :kind => :ics, 
31         :editable => false)
32     @matches[data[:number]] = [match, data]
33   end
34   
35   def on_end_game(data)
36     entry = @matches.delete(data[:game_number])
37     if entry
38       match, info = entry
39       match.close(data[:result], data[:message])
40     end
41   end
42   
43   def on_style12(style12)
44     match, match_info = @matches[style12.game_number]
45     return if match == nil
46     
47     if match.started?
48       match.update_time(style12.time)
49       if match.index < style12.move_index
50         # last_move = icsapi.parse_verbose(style12.last_move, match.state)
51         move = match.game.serializer.new(:compact).deserialize(style12.last_move_san, match.state)
52         if move
53           match.move(nil, move, :state => style12.state)
54         else
55           warn "Received invalid move from ICS: #{style12.last_move_san}"
56         end
57       end
58     else
59       rel = style12.relation
60       state = style12.state
61       turns = [state.turn, state.opposite_turn(state.turn)]
62       @user.color, opponent_color =
63         if rel == Style12::Relation::MY_MOVE
64           turns
65         else
66           turns.reverse
67         end
68       opponent = ICSPlayer.new(
69         lambda {|msg| @protocol.connection.send_text(msg) },
70         opponent_color,
71         match.game.serializer.new(:compact),
72         match_info[opponent_color][:name])
73       @user.name = match_info[@user.color][:name]
74       
75       match.register(@user)
76       match.register(opponent)
77       
78       match.start(@user)
79       match.start(opponent)
80       
81       raise "couldn't start match" unless match.started?
82       
83       @user.reset(match)
84       
85       match.update_time(style12.time)
86     end
87     
88     
89   end
90 end
92 end