3 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
4 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
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.
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.
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
20 require 'shogi_server/command'
22 module ShogiServer # for a namespace
32 @last_game_win = false
39 # Idetifier of the player in the rating system
40 attr_accessor :player_id
45 # Password of the player, which does not include a trip
46 attr_accessor :password
48 # Score in the rating sysem
51 # Number of games for win and loss in the rating system
52 attr_accessor :win, :loss
54 # Group in the rating system
55 attr_accessor :rating_group
57 # Last timestamp when the rate was modified
58 attr_accessor :modified_at
60 # Whether win the previous game or not
61 attr_accessor :last_game_win
63 # true for Sente; false for Gote
67 attr_accessor :game_name
70 return [%r!_human$!, %r!_human@!].any? do |re|
80 @modified_at || Time.now
86 @modified_at = Time.now
100 simple_name = @name.gsub(/@.*?$/, '')
101 "%s+%s" % [simple_name, @trip[0..8]]
108 # Parses str in the LOGIN command, sets up @player_id and @trip
110 def set_password(str)
111 if str && !str.empty?
112 @password = str.strip
113 @player_id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
115 @player_id = @password = nil
119 def set_sente_from_str(str)
121 when "+" then @sente = true
122 when "-" then @sente = false
131 class Player < BasicPlayer
132 WRITE_THREAD_WATCH_INTERVAL = 20 # sec
133 def initialize(str, socket, eol=nil)
136 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
138 @protocol = nil # CSA or x1
139 @eol = eol || "\m" # favorite eol code
141 @mytime = 0 # set in start method also
143 @main_thread = Thread::current
144 @write_queue = ShogiServer::TimeoutQueue.new(WRITE_THREAD_WATCH_INTERVAL)
149 attr_accessor :socket, :status
150 attr_accessor :protocol, :eol, :game, :mytime
151 attr_accessor :main_thread
152 attr_reader :socket_buffer
154 def setup_logger(dir)
155 log_file = File.join(dir, "%s.log" % [simple_player_id])
156 @player_logger = Logger.new(log_file, 'daily')
157 @player_logger.formatter = ShogiServer::Formatter.new
158 @player_logger.level = $DEBUG ? Logger::DEBUG : Logger::INFO
159 @player_logger.datetime_format = "%Y-%m-%d %H:%M:%S"
162 def log(level, direction, message)
163 return unless @player_logger
167 str = "IN: %s" % [str]
169 str = "OUT: %s" % [str]
171 str = "UNKNOWN DIRECTION: %s %s" % [direction, str]
175 @player_logger.debug(str)
177 @player_logger.info(str)
179 @player_logger.warn(str)
181 @player_logger.error(str)
183 @player_logger.debug("UNKNOWN LEVEL: %s %s" % [level, str])
185 rescue Exception => ex
186 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
190 log_message(sprintf("user %s killed", @name))
195 Thread::kill(@main_thread) if @main_thread
196 Thread::kill(@write_thread) if @write_thread
200 if (@status != "finished")
202 log_message(sprintf("user %s finish", @name))
204 log_debug("Terminating %s's write thread..." % [@name])
205 if @write_thread && @write_thread.alive?
207 Thread.pass # help the write_thread to terminate
211 log_message(sprintf("user %s finish failed", @name))
216 def start_write_thread
217 @write_thread = Thread.start do
219 while !@socket.closed?
221 str = @write_queue.deq
223 log_debug("%s's write thread terminated" % [@name])
227 log_debug("%s's write queue timed out. Try again..." % [@name])
231 if r = select(nil, [@socket], nil, 20)
232 r[1].first.write(str)
233 log(:info, :out, str)
235 log_error("Gave a try to send a message to #{@name}, but it timed out.")
238 rescue Exception => ex
239 log_error("Failed to send a message to #{@name}. #{ex.class}: #{ex.message}\t#{ex.backtrace[0]}")
243 log_error("%s's socket closed." % [@name]) if @socket.closed?
244 log_message("At least %d messages are not sent to the client." %
245 [@write_queue.get_messages.size])
250 # Wait for the write thread to finish.
251 # This method should be called just before this instance will be freed.
253 def wait_write_thread_finish(msec=1000)
254 while msec > 0 && @write_thread && @write_thread.alive?
255 sleep 0.1; msec -= 0.1
257 @player_logger.close if @player_logger
261 # Note that sending a message is included in the giant lock.
264 @write_queue.enq(str)
268 if ["game_waiting", "start_waiting", "agree_waiting", "game"].include?(status)
270 return sprintf("%s %s %s %s +", rated? ? @player_id : @name, @protocol, @status, @game_name)
271 elsif (@sente == false)
272 return sprintf("%s %s %s %s -", rated? ? @player_id : @name, @protocol, @status, @game_name)
273 elsif (@sente == nil)
274 return sprintf("%s %s %s %s *", rated? ? @player_id : @name, @protocol, @status, @game_name)
277 return sprintf("%s %s %s", rated? ? @player_id : @name, @protocol, @status)
281 def run(csa_1st_str=nil)
282 while ( csa_1st_str ||
283 str = gets_safe(@socket, (@socket_buffer.empty? ? Default_Timeout : 1)) )
285 log(:info, :in, str) if str && str.instance_of?(String)
288 if !@write_thread.alive?
289 log_error("%s's write thread is dead. Aborting..." % [@name])
292 if (@game && @game.turn?(self))
293 @socket_buffer << str
294 str = @socket_buffer.shift
296 log_debug("%s (%s)" % [str, @socket_buffer.map {|a| String === a ? a.strip : a }.join(",")])
303 if (@status == "finished")
306 str.chomp! if (str.class == String) # may be strip! ?
308 delay = Time.now - time
310 log_warning("Detected a long delay: %.2f sec" % [delay])
312 cmd = ShogiServer::Command.factory(str, self, time)
320 log_error("Detected a wrong return value for %s" % [cmd])
327 log_warning("%s's socket was suddenly closed" % [@name])