OSDN Git Service

3a86c960ef17c23d4e39103f3cc4568117bd67d9
[shogi-server/shogi-server.git] / shogi_server / player.rb
1 ## $Id$
2
3 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
4 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
5 ##
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
10 ##
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ## GNU General Public License for more details.
15 ##
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, write to the Free Software
18 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 require 'shogi_server/command'
21
22 module ShogiServer # for a namespace
23
24 class BasicPlayer
25   def initialize
26     @player_id = nil
27     @name = nil
28     @password = nil
29     @rate = 0
30     @win  = 0
31     @loss = 0
32     @last_game_win = false
33     @rating_group = nil
34     @modified_at = nil
35     @sente = nil
36     @game_name = ""
37   end
38
39   # Idetifier of the player in the rating system
40   attr_accessor :player_id
41
42   # Name of the player
43   attr_accessor :name
44   
45   # Password of the player, which does not include a trip
46   attr_accessor :password
47
48   # Score in the rating sysem
49   attr_accessor :rate
50
51   # Number of games for win and loss in the rating system
52   attr_accessor :win, :loss
53   
54   # Group in the rating system
55   attr_accessor :rating_group
56
57   # Last timestamp when the rate was modified
58   attr_accessor :modified_at
59
60   # Whether win the previous game or not
61   attr_accessor :last_game_win
62
63   # true for Sente; false for Gote
64   attr_accessor :sente
65
66   # game name
67   attr_accessor :game_name
68
69   def is_human?
70     return [%r!_human$!, %r!_human@!].any? do |re|
71       re.match(@name)
72     end
73   end
74
75   def is_computer?
76     return !is_human?
77   end
78
79   def modified_at
80     @modified_at || Time.now
81   end
82
83   def rate=(new_rate)
84     if @rate != new_rate
85       @rate = new_rate
86       @modified_at = Time.now
87     end
88   end
89
90   def rated?
91     @player_id != nil
92   end
93
94   def last_game_win?
95     return @last_game_win
96   end
97
98   def simple_player_id
99     if @trip
100       simple_name = @name.gsub(/@.*?$/, '')
101       "%s+%s" % [simple_name, @trip[0..8]]
102     else
103       @name
104     end
105   end
106
107   ##
108   # Parses str in the LOGIN command, sets up @player_id and @trip
109   #
110   def set_password(str)
111     if str && !str.empty?
112       @password = str.strip
113       @player_id   = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
114     else
115       @player_id = @password = nil
116     end
117   end
118 end
119
120
121 class Player < BasicPlayer
122   WRITE_THREAD_WATCH_INTERVAL = 20 # sec
123   def initialize(str, socket, eol=nil)
124     super()
125     @socket = socket
126     @status = "connected"       # game_waiting -> agree_waiting -> start_waiting -> game -> finished
127
128     @protocol = nil             # CSA or x1
129     @eol = eol || "\m"          # favorite eol code
130     @game = nil
131     @mytime = 0                 # set in start method also
132     @socket_buffer = []
133     @main_thread = Thread::current
134     @write_queue = ShogiServer::TimeoutQueue.new(WRITE_THREAD_WATCH_INTERVAL)
135     @player_logger = nil
136     start_write_thread
137   end
138
139   attr_accessor :socket, :status
140   attr_accessor :protocol, :eol, :game, :mytime
141   attr_accessor :main_thread
142   attr_reader :socket_buffer
143   
144   def setup_logger(dir)
145     log_file = File.join(dir, "%s.log" % [simple_player_id])
146     @player_logger = Logger.new(log_file, 'daily')
147     @player_logger.formatter = ShogiServer::Formatter.new
148     @player_logger.level = $DEBUG ? Logger::DEBUG : Logger::INFO  
149     @player_logger.datetime_format = "%Y-%m-%d %H:%M:%S"
150   end
151
152   def log(level, direction, message)
153     return unless @player_logger
154     str = message.chomp
155     case direction
156       when :in
157         str = "IN: %s" % [str]
158       when :out
159         str = "OUT: %s" % [str]
160       else
161         str = "UNKNOWN DIRECTION: %s %s" % [direction, str]
162     end
163     case level
164       when :debug
165         @player_logger.debug(str)
166       when :info
167         @player_logger.info(str)
168       when :warn
169         @player_logger.warn(str)
170       when :error
171         @player_logger.error(str)
172       else
173         @player_logger.debug("UNKNOWN LEVEL: %s %s" % [level, str])
174     end
175   rescue Exception => ex
176     log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
177   end
178
179   def kill
180     log_message(sprintf("user %s killed", @name))
181     if (@game)
182       @game.kill(self)
183     end
184     finish
185     Thread::kill(@main_thread)  if @main_thread
186     Thread::kill(@write_thread) if @write_thread
187   end
188
189   def finish
190     if (@status != "finished")
191       @status = "finished"
192       log_message(sprintf("user %s finish", @name))    
193       begin
194         log_debug("Terminating %s's write thread..." % [@name])
195         if @write_thread && @write_thread.alive?
196           write_safe(nil)
197           Thread.pass # help the write_thread to terminate
198         end
199         @player_logger.close if @player_logger
200         log_debug("done.")
201       rescue
202         log_message(sprintf("user %s finish failed", @name))    
203       end
204     end
205   end
206
207   def start_write_thread
208     @write_thread = Thread.start do
209       Thread.pass
210       while !@socket.closed?
211         begin
212           str = @write_queue.deq
213           if (str == nil)
214             log_debug("%s's write thread terminated" % [@name])
215             break
216           end
217           if (str == :timeout)
218             log_debug("%s's write queue timed out. Try again..." % [@name])
219             next
220           end
221
222           if r = select(nil, [@socket], nil, 20)
223             r[1].first.write(str)
224             log(:info, :out, str)
225           else
226             log_error("Gave a try to send a message to #{@name}, but it timed out.")
227             break
228           end
229         rescue Exception => ex
230           log_error("Failed to send a message to #{@name}. #{ex.class}: #{ex.message}\t#{ex.backtrace[0]}")
231           break
232         end
233       end # while loop
234       log_error("%s's socket closed." % [@name]) if @socket.closed?
235       log_message("At least %d messages are not sent to the client." % 
236                   [@write_queue.get_messages.size])
237     end # thread
238   end
239
240   #
241   # Note that sending a message is included in the giant lock.
242   #
243   def write_safe(str)
244     @write_queue.enq(str)
245   end
246
247   def to_s
248     if ["game_waiting", "start_waiting", "agree_waiting", "game"].include?(status)
249       if (@sente)
250         return sprintf("%s %s %s %s +", rated? ? @player_id : @name, @protocol, @status, @game_name)
251       elsif (@sente == false)
252         return sprintf("%s %s %s %s -", rated? ? @player_id : @name, @protocol, @status, @game_name)
253       elsif (@sente == nil)
254         return sprintf("%s %s %s %s *", rated? ? @player_id : @name, @protocol, @status, @game_name)
255       end
256     else
257       return sprintf("%s %s %s", rated? ? @player_id : @name, @protocol, @status)
258     end
259   end
260
261   def run(csa_1st_str=nil)
262     while ( csa_1st_str || 
263             str = gets_safe(@socket, (@socket_buffer.empty? ? Default_Timeout : 1)) )
264       time = Time.now
265       log(:info, :in, str) if str && str.instance_of?(String) 
266       $mutex.lock
267       begin
268         if !@write_thread.alive?
269           log_error("%s's write thread is dead. Aborting..." % [@name])
270           return
271         end
272         if (@game && @game.turn?(self))
273           @socket_buffer << str
274           str = @socket_buffer.shift
275         end
276         log_debug("%s (%s)" % [str, @socket_buffer.map {|a| String === a ? a.strip : a }.join(",")])
277
278         if (csa_1st_str)
279           str = csa_1st_str
280           csa_1st_str = nil
281         end
282
283         if (@status == "finished")
284           return
285         end
286         str.chomp! if (str.class == String) # may be strip! ?
287
288         delay = Time.now - time
289         if delay > 5
290           log_warning("Detected a long delay: %.2f sec" % [delay])
291         end
292         cmd = ShogiServer::Command.factory(str, self, time)
293         case cmd.call
294         when :return
295           return
296         when :continue
297           # do nothing
298         else
299           # TODO never reach
300         end
301
302       ensure
303         $mutex.unlock
304       end
305     end # enf of while
306     log_warning("%s's socket was suddenly closed" % [@name])
307   end # def run
308 end # class
309
310 end # ShogiServer