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
37 # Idetifier of the player in the rating system
38 attr_accessor :player_id
43 # Password of the player, which does not include a trip
44 attr_accessor :password
46 # Score in the rating sysem
49 # Number of games for win and loss in the rating system
50 attr_accessor :win, :loss
52 # Group in the rating system
53 attr_accessor :rating_group
55 # Last timestamp when the rate was modified
56 attr_accessor :modified_at
58 # Whether win the previous game or not
59 attr_accessor :last_game_win
61 # true for Sente; false for Gote
65 attr_accessor :game_name
68 return [%r!_human$!, %r!_human@!].any? do |re|
78 @modified_at || Time.now
84 @modified_at = Time.now
98 simple_name = @name.gsub(/@.*?$/, '')
99 "%s+%s" % [simple_name, @trip[0..8]]
106 # Parses str in the LOGIN command, sets up @player_id and @trip
108 def set_password(str)
109 if str && !str.empty?
110 @password = str.strip
111 @player_id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
113 @player_id = @password = nil
119 class Player < BasicPlayer
120 WRITE_THREAD_WATCH_INTERVAL = 20 # sec
121 def initialize(str, socket, eol=nil)
124 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
126 @protocol = nil # CSA or x1
127 @eol = eol || "\m" # favorite eol code
129 @mytime = 0 # set in start method also
131 @main_thread = Thread::current
132 @write_queue = ShogiServer::TimeoutQueue.new(WRITE_THREAD_WATCH_INTERVAL)
137 attr_accessor :socket, :status
138 attr_accessor :protocol, :eol, :game, :mytime
139 attr_accessor :main_thread
140 attr_reader :socket_buffer
142 def setup_logger(dir)
143 log_file = File.join(dir, "%s.log" % [simple_player_id])
144 @player_logger = Logger.new(log_file, 'daily')
145 @player_logger.formatter = ShogiServer::Formatter.new
146 @player_logger.level = $DEBUG ? Logger::DEBUG : Logger::INFO
147 @player_logger.datetime_format = "%Y-%m-%d %H:%M:%S"
150 def log(level, direction, message)
151 return unless @player_logger
155 str = "IN: %s" % [str]
157 str = "OUT: %s" % [str]
159 str = "UNKNOWN DIRECTION: %s %s" % [direction, str]
163 @player_logger.debug(str)
165 @player_logger.info(str)
167 @player_logger.warn(str)
169 @player_logger.error(str)
171 @player_logger.debug("UNKNOWN LEVEL: %s %s" % [level, str])
173 rescue Exception => ex
174 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
178 log_message(sprintf("user %s killed", @name))
183 Thread::kill(@main_thread) if @main_thread
184 Thread::kill(@write_thread) if @write_thread
188 if (@status != "finished")
190 log_message(sprintf("user %s finish", @name))
192 log_debug("Terminating %s's write thread..." % [@name])
193 if @write_thread && @write_thread.alive?
195 Thread.pass # help the write_thread to terminate
197 @player_logger.close if @player_logger
200 log_message(sprintf("user %s finish failed", @name))
205 def start_write_thread
206 @write_thread = Thread.start do
208 while !@socket.closed?
210 str = @write_queue.deq
212 log_debug("%s's write thread terminated" % [@name])
216 log_debug("%s's write queue timed out. Try again..." % [@name])
220 if r = select(nil, [@socket], nil, 20)
221 r[1].first.write(str)
222 log(:info, :out, str)
224 log_error("Gave a try to send a message to #{@name}, but it timed out.")
227 rescue Exception => ex
228 log_error("Failed to send a message to #{@name}. #{ex.class}: #{ex.message}\t#{ex.backtrace[0]}")
232 log_error("%s's socket closed." % [@name]) if @socket.closed?
233 log_message("At least %d messages are not sent to the client." %
234 [@write_queue.get_messages.size])
239 # Note that sending a message is included in the giant lock.
242 @write_queue.enq(str)
246 if ["game_waiting", "start_waiting", "agree_waiting", "game"].include?(status)
248 return sprintf("%s %s %s %s +", rated? ? @player_id : @name, @protocol, @status, @game_name)
249 elsif (@sente == false)
250 return sprintf("%s %s %s %s -", rated? ? @player_id : @name, @protocol, @status, @game_name)
251 elsif (@sente == nil)
252 return sprintf("%s %s %s %s *", rated? ? @player_id : @name, @protocol, @status, @game_name)
255 return sprintf("%s %s %s", rated? ? @player_id : @name, @protocol, @status)
259 def run(csa_1st_str=nil)
260 while ( csa_1st_str ||
261 str = gets_safe(@socket, (@socket_buffer.empty? ? Default_Timeout : 1)) )
263 log(:info, :in, str) if str && str.instance_of?(String)
266 if !@write_thread.alive?
267 log_error("%s's write thread is dead. Aborting..." % [@name])
270 if (@game && @game.turn?(self))
271 @socket_buffer << str
272 str = @socket_buffer.shift
274 log_debug("%s (%s)" % [str, @socket_buffer.map {|a| String === a ? a.strip : a }.join(",")])
281 if (@status == "finished")
284 str.chomp! if (str.class == String) # may be strip! ?
286 delay = Time.now - time
288 log_warning("Detected a long delay: %.2f sec" % [delay])
290 cmd = ShogiServer::Command.factory(str, self, time)
304 log_warning("%s's socket was suddenly closed" % [@name])