OSDN Git Service

5acb702c70b9ed4f6a9fea9fa59c48384250ca79
[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 module ShogiServer # for a namespace
21
22 class BasicPlayer
23   def initialize
24     @player_id = nil
25     @name = nil
26     @password = nil
27     @rate = 0
28     @win  = 0
29     @loss = 0
30     @last_game_win = false
31   end
32
33   # Idetifier of the player in the rating system
34   attr_accessor :player_id
35
36   # Name of the player
37   attr_accessor :name
38   
39   # Password of the player, which does not include a trip
40   attr_accessor :password
41
42   # Score in the rating sysem
43   attr_accessor :rate
44
45   # Number of games for win and loss in the rating system
46   attr_accessor :win, :loss
47   
48   # Group in the rating system
49   attr_accessor :rating_group
50
51   # Last timestamp when the rate was modified
52   attr_accessor :modified_at
53
54   # Whether win the previous game or not
55   attr_accessor :last_game_win
56
57   def modified_at
58     @modified_at || Time.now
59   end
60
61   def rate=(new_rate)
62     if @rate != new_rate
63       @rate = new_rate
64       @modified_at = Time.now
65     end
66   end
67
68   def rated?
69     @player_id != nil
70   end
71
72   def last_game_win?
73     return @last_game_win
74   end
75
76   def simple_player_id
77     if @trip
78       simple_name = @name.gsub(/@.*?$/, '')
79       "%s+%s" % [simple_name, @trip[0..8]]
80     else
81       @name
82     end
83   end
84
85   ##
86   # Parses str in the LOGIN command, sets up @player_id and @trip
87   #
88   def set_password(str)
89     if str && !str.empty?
90       @password = str.strip
91       @player_id   = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
92     else
93       @player_id = @password = nil
94     end
95   end
96 end
97
98
99 class Player < BasicPlayer
100   def initialize(str, socket, eol=nil)
101     super()
102     @socket = socket
103     @status = "connected"       # game_waiting -> agree_waiting -> start_waiting -> game -> finished
104
105     @protocol = nil             # CSA or x1
106     @eol = eol || "\m"          # favorite eol code
107     @game = nil
108     @game_name = ""
109     @mytime = 0                 # set in start method also
110     @sente = nil
111     @socket_buffer = []
112     @main_thread = Thread::current
113     @write_queue = Queue.new
114     @player_logger = nil
115     start_write_thread
116   end
117
118   attr_accessor :socket, :status
119   attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
120   attr_accessor :main_thread
121   attr_reader :socket_buffer
122   
123   def setup_logger(dir)
124     log_file = File.join(dir, "%s.log" % [simple_player_id])
125     @player_logger = Logger.new(log_file, 'daily')
126     @player_logger.formatter = ShogiServer::Formatter.new
127     @player_logger.level = $DEBUG ? Logger::DEBUG : Logger::INFO  
128     @player_logger.datetime_format = "%Y-%m-%d %H:%M:%S"
129   end
130
131   def log(level, direction, message)
132     return unless @player_logger
133     str = message.chomp
134     case direction
135       when :in
136         str = "IN: %s" % [str]
137       when :out
138         str = "OUT: %s" % [str]
139       else
140         str = "UNKNOWN DIRECTION: %s %s" % [direction, str]
141     end
142     case level
143       when :debug
144         @player_logger.debug(str)
145       when :info
146         @player_logger.info(str)
147       when :warn
148         @player_logger.warn(str)
149       when :error
150         @player_logger.error(str)
151       else
152         @player_logger.debug("UNKNOWN LEVEL: %s %s" % [level, str])
153     end
154   rescue Exception => ex
155     log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
156   end
157
158   def kill
159     log_message(sprintf("user %s killed", @name))
160     if (@game)
161       @game.kill(self)
162     end
163     finish
164     Thread::kill(@main_thread)  if @main_thread
165     Thread::kill(@write_thread) if @write_thread
166   end
167
168   def finish
169     if (@status != "finished")
170       @status = "finished"
171       log_message(sprintf("user %s finish", @name))    
172       begin
173 #        @socket.close if (! @socket.closed?)
174         write_safe(nil)
175         @write_thread.join
176         @player_logger.close if @player_logger
177       rescue
178         log_message(sprintf("user %s finish failed", @name))    
179       end
180     end
181   end
182
183   def start_write_thread
184     @write_thread = Thread.start do
185       Thread.pass
186       while !@socket.closed?
187         str = ""
188         begin
189           begin
190             timeout(5) do
191               str = @write_queue.deq
192             end
193             if str == nil
194               break
195             end
196           rescue TimeoutError
197             next
198           end
199           if r = select(nil, [@socket], nil, 20)
200             r[1].first.write(str)
201             log(:info, :out, str)
202           else
203             log_error("Sending a message to #{@name} timed up.")
204           end
205         rescue Exception => ex
206           log_error("Failed to send a message to #{@name}. #{ex.class}: #{ex.message}\t#{ex.backtrace[0]}")
207         end
208       end # while loop
209       log_message("terminated %s's write thread" % [@name])
210     end # thread
211   rescue
212
213   end
214
215   #
216   # Note that sending a message is included in the giant lock.
217   #
218   def write_safe(str)
219     @write_queue.enq str
220   end
221
222   def to_s
223     if ["game_waiting", "start_waiting", "agree_waiting", "game"].include?(status)
224       if (@sente)
225         return sprintf("%s %s %s %s +", rated? ? @player_id : @name, @protocol, @status, @game_name)
226       elsif (@sente == false)
227         return sprintf("%s %s %s %s -", rated? ? @player_id : @name, @protocol, @status, @game_name)
228       elsif (@sente == nil)
229         return sprintf("%s %s %s %s *", rated? ? @player_id : @name, @protocol, @status, @game_name)
230       end
231     else
232       return sprintf("%s %s %s", rated? ? @player_id : @name, @protocol, @status)
233     end
234   end
235
236   def run(csa_1st_str=nil)
237     while ( csa_1st_str || 
238             str = gets_safe(@socket, (@socket_buffer.empty? ? Default_Timeout : 1)) )
239       log(:info, :in, str) if str && str.instance_of?(String) 
240       $mutex.lock
241       begin
242         if !@write_thread.alive?
243           log_error("%s's write thread is dead. Aborting..." % [@name])
244           return
245         end
246         if (@game && @game.turn?(self))
247           @socket_buffer << str
248           str = @socket_buffer.shift
249         end
250         log_message("%s (%s)" % [str, @socket_buffer.map {|a| String === a ? a.strip : a }.join(",")]) if $DEBUG
251
252         if (csa_1st_str)
253           str = csa_1st_str
254           csa_1st_str = nil
255         end
256
257         if (@status == "finished")
258           return
259         end
260         str.chomp! if (str.class == String) # may be strip! ?
261         case str 
262         when "" 
263           # Application-level protocol for Keep-Alive
264           # If the server gets LF, it sends back LF.
265           # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
266           write_safe("\n")
267         when /^[\+\-][^%]/
268           if (@status == "game")
269             array_str = str.split(",")
270             move = array_str.shift
271             additional = array_str.shift
272             if /^'(.*)/ =~ additional
273               comment = array_str.unshift("'*#{$1.toeuc}")
274             end
275             s = @game.handle_one_move(move, self)
276             @game.fh.print("#{Kconv.toeuc(comment.first)}\n") if (comment && comment.first && !s)
277             return if (s && @protocol == LoginCSA::PROTOCOL)
278           end
279         when /^%[^%]/, :timeout
280           if (@status == "game")
281             s = @game.handle_one_move(str, self)
282             return if (s && @protocol == LoginCSA::PROTOCOL)
283           end
284         when :exception
285           log_error("Failed to receive a message from #{@name}.")
286           return
287         when /^REJECT/
288           if (@status == "agree_waiting")
289             @game.reject(@name)
290             return if (@protocol == LoginCSA::PROTOCOL)
291           else
292             write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
293           end
294         when /^AGREE/
295           if (@status == "agree_waiting")
296             @status = "start_waiting"
297             if ((@game.sente.status == "start_waiting") &&
298                 (@game.gote.status == "start_waiting"))
299               @game.start
300               @game.sente.status = "game"
301               @game.gote.status = "game"
302             end
303           else
304             write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
305           end
306         when /^%%SHOW\s+(\S+)/
307           game_id = $1
308           if (LEAGUE.games[game_id])
309             write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
310           end
311           write_safe("##[SHOW] +OK\n")
312         when /^%%MONITORON\s+(\S+)/
313           game_id = $1
314           if (LEAGUE.games[game_id])
315             LEAGUE.games[game_id].monitoron(self)
316             write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
317             write_safe("##[MONITOR][#{game_id}] +OK\n")
318           end
319         when /^%%MONITOROFF\s+(\S+)/
320           game_id = $1
321           if (LEAGUE.games[game_id])
322             LEAGUE.games[game_id].monitoroff(self)
323           end
324         when /^%%HELP/
325           write_safe(
326             %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
327         when /^%%RATING/
328           players = LEAGUE.rated_players
329           players.sort {|a,b| b.rate <=> a.rate}.each do |p|
330             write_safe("##[RATING] %s \t %4d @%s\n" % 
331                        [p.simple_player_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
332           end
333           write_safe("##[RATING] +OK\n")
334         when /^%%VERSION/
335           write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
336           write_safe("##[VERSION] +OK\n")
337         when /^%%GAME\s*$/
338           if ((@status == "connected") || (@status == "game_waiting"))
339             @status = "connected"
340             @game_name = ""
341           else
342             write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
343           end
344         when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
345           command_name = $1
346           game_name = $2
347           my_sente_str = $3
348           if (! Login::good_game_name?(game_name))
349             write_safe(sprintf("##[ERROR] bad game name\n"))
350             next
351           elsif ((@status == "connected") || (@status == "game_waiting"))
352             ## continue
353           else
354             write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
355             next
356           end
357
358           rival = nil
359           if (League::Floodgate.game_name?(game_name))
360             if (my_sente_str != "*")
361               write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", my_sente_str, game_name))
362               next
363             end
364             @sente = nil
365           else
366             if (my_sente_str == "*")
367               rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
368             elsif (my_sente_str == "+")
369               rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
370             elsif (my_sente_str == "-")
371               rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
372             else
373               ## never reached
374               write_safe(sprintf("##[ERROR] bad game option\n"))
375               next
376             end
377           end
378
379           if (rival)
380             @game_name = game_name
381             if ((my_sente_str == "*") && (rival.sente == nil))
382               if (rand(2) == 0)
383                 @sente = true
384                 rival.sente = false
385               else
386                 @sente = false
387                 rival.sente = true
388               end
389             elsif (rival.sente == true) # rival has higher priority
390               @sente = false
391             elsif (rival.sente == false)
392               @sente = true
393             elsif (my_sente_str == "+")
394               @sente = true
395               rival.sente = false
396             elsif (my_sente_str == "-")
397               @sente = false
398               rival.sente = true
399             else
400               ## never reached
401             end
402             Game::new(@game_name, self, rival)
403           else # rival not found
404             if (command_name == "GAME")
405               @status = "game_waiting"
406               @game_name = game_name
407               if (my_sente_str == "+")
408                 @sente = true
409               elsif (my_sente_str == "-")
410                 @sente = false
411               else
412                 @sente = nil
413               end
414             else                # challenge
415               write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
416               @status = "connected"
417               @game_name = ""
418               @sente = nil
419             end
420           end
421         when /^%%CHAT\s+(.+)/
422           message = $1
423           LEAGUE.players.each do |name, player|
424             if (player.protocol != LoginCSA::PROTOCOL)
425               player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message)) 
426             end
427           end
428         when /^%%LIST/
429           buf = Array::new
430           LEAGUE.games.each do |id, game|
431             buf.push(sprintf("##[LIST] %s\n", id))
432           end
433           buf.push("##[LIST] +OK\n")
434           write_safe(buf.join)
435         when /^%%WHO/
436           buf = Array::new
437           LEAGUE.players.each do |name, player|
438             buf.push(sprintf("##[WHO] %s\n", player.to_s))
439           end
440           buf.push("##[WHO] +OK\n")
441           write_safe(buf.join)
442         when /^LOGOUT/
443           @status = "connected"
444           write_safe("LOGOUT:completed\n")
445           return
446         when /^CHALLENGE/
447           # This command is only available for CSA's official testing server.
448           # So, this means nothing for this program.
449           write_safe("CHALLENGE ACCEPTED\n")
450         when /^\s*$/
451           ## ignore null string
452         else
453           msg = "##[ERROR] unknown command %s\n" % [str]
454           write_safe(msg)
455           log_error(msg)
456         end
457       ensure
458         $mutex.unlock
459       end
460     end # enf of while
461   end # def run
462 end # class
463
464 end # ShogiServer