4 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
5 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ## GNU General Public License for more details.
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, write to the Free Software
19 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32 def gets_safe(socket, timeout=nil)
33 if r = select([socket], nil, nil, timeout)
34 return r[0].first.gets
38 rescue Exception => ex
39 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
43 module ShogiServer # for a namespace
45 Max_Identifier_Length = 32
46 Default_Timeout = 60 # for single socket operation
48 Default_Game_Name = "default-1500-0"
51 Least_Time_Per_Move = 1
52 Login_Time = 300 # time for LOGIN
54 Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
55 Release.concat("-") if (Release == "")
56 Revision = "$Revision$".gsub(/[^\.\d]/, '')
63 return /^floodgate-\d+-\d+$/.match(str) ? true : false
67 def initialize(league)
74 @thread = Thread.new do
79 next if Time.now < @next_time
83 rescue Exception => ex
85 log_error("[in Floodgate's thread] #{ex}")
92 @thread.kill if @thread
100 @next_time = Time.mktime(now.year, now.month, now.day, now.hour, 30)
102 @next_time = Time.mktime(now.year, now.month, now.day, now.hour) + 3600
106 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min, 30)
108 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min) + 60
113 players = @league.find_all_players do |pl|
114 pl.status == "game_waiting" &&
115 Floodgate.game_name?(pl.game_name) &&
118 log_warning("DEBUG: %s" % [File.join(File.dirname(__FILE__), "pairing.rb")])
119 load File.join(File.dirname(__FILE__), "pairing.rb")
120 Pairing.default_pairing.match(players)
122 end # class Floodgate
125 @mutex = Mutex.new # guard @players
129 @dir = File.dirname(__FILE__)
130 @floodgate = Floodgate.new(self)
133 attr_accessor :players, :games, :event, :dir
136 @mutex.synchronize do
137 @players.each {|a| save(a)}
142 # this should be called just after instanciating a League object.
143 def setup_players_database
144 @db = YAML::Store.new(File.join(@dir, "players.yaml"))
148 self.load(player) if player.id
149 @mutex.synchronize do
150 @players[player.name] = player
155 @mutex.synchronize do
157 @players.delete(player.name)
162 @mutex.synchronize do
163 @players.each {|player| load(player)}
169 @mutex.synchronize do
170 found = @players.find_all do |name, player|
174 return found.map {|a| a.last}
177 def find(player_name)
179 @mutex.synchronize do
180 found = @players[player_name]
185 def get_player(status, game_name, sente, searcher)
187 @mutex.synchronize do
188 found = @players.find do |name, player|
189 (player.status == status) &&
190 (player.game_name == game_name) &&
192 (player.sente == nil) ||
193 (player.sente == sente) ) &&
194 (player.name != searcher.name)
197 return found ? found.last : nil
201 hash = search(player.id)
205 player.name = hash['name']
206 player.rate = hash['rate'] || 0
207 player.modified_at = hash['last_modified']
208 player.rating_group = hash['rating_group']
209 player.win = hash['win'] || 0
210 player.loss = hash['loss'] || 0
211 player.last_game_win = hash['last_game_win'] || false
216 break unless @db["players"]
217 @db["players"].each do |group, players|
218 hash = players[player.id]
220 hash['last_game_win'] = player.last_game_win
229 @db.transaction(true) do
230 break unless @db["players"]
231 @db["players"].each do |group, players|
241 @db.transaction(true) do
242 break unless @db["players"]
243 @db["players"].each do |group, players_hash|
244 players << players_hash.keys
247 return players.flatten.collect do |id|
257 ######################################################
258 # Processes the LOGIN command.
261 def Login.good_login?(str)
263 if (((tokens.length == 3) ||
264 ((tokens.length == 4) && tokens[3] == "x1")) &&
265 (tokens[0] == "LOGIN") &&
266 (good_identifier?(tokens[1])))
273 def Login.good_game_name?(str)
274 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
281 def Login.good_identifier?(str)
282 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
289 def Login.factory(str, player)
290 (login, player.name, password, ext) = str.chomp.split
292 return Loginx1.new(player, password)
294 return LoginCSA.new(player, password)
300 # the first command that will be executed just after LOGIN.
301 # If it is nil, the default process will be started.
302 attr_reader :csa_1st_str
304 def initialize(player, password)
307 parse_password(password)
311 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
312 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
315 def incorrect_duplicated_player(str)
316 @player.write_safe("LOGIN:incorrect\n")
317 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
318 sleep 3 # wait for sending the above messages.
319 @player.name = "%s [duplicated]" % [@player.name]
324 ######################################################
325 # Processes LOGIN for the CSA standard mode.
327 class LoginCSA < Login
330 def initialize(player, password)
333 @player.protocol = PROTOCOL
336 def parse_password(password)
337 if Login.good_game_name?(password)
339 @player.set_password(nil)
340 elsif password.split(",").size > 1
341 @gamename, *trip = password.split(",")
342 @player.set_password(trip.join(","))
344 @player.set_password(password)
345 @gamename = Default_Game_Name
347 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
352 @csa_1st_str = "%%GAME #{@gamename} *"
356 ######################################################
357 # Processes LOGIN for the extented mode.
359 class Loginx1 < Login
362 def initialize(player, password)
364 @player.protocol = PROTOCOL
367 def parse_password(password)
368 @player.set_password(password)
373 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
383 @last_game_win = false
386 # Idetifier of the player in the rating system
392 # Password of the player, which does not include a trip
393 attr_accessor :password
395 # Score in the rating sysem
398 # Number of games for win and loss in the rating system
399 attr_accessor :win, :loss
401 # Group in the rating system
402 attr_accessor :rating_group
404 # Last timestamp when the rate was modified
405 attr_accessor :modified_at
407 # Whether win the previous game or not
408 attr_accessor :last_game_win
411 @modified_at || Time.now
417 @modified_at = Time.now
426 return @last_game_win
431 simple_name = @name.gsub(/@.*?$/, '')
432 "%s+%s" % [simple_name, @trip[0..8]]
439 # Parses str in the LOGIN command, sets up @id and @trip
441 def set_password(str)
442 if str && !str.empty?
443 @password = str.strip
444 @id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
446 @id = @password = nil
452 class Player < BasicPlayer
453 def initialize(str, socket, eol=nil)
456 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
458 @protocol = nil # CSA or x1
459 @eol = eol || "\m" # favorite eol code
462 @mytime = 0 # set in start method also
465 @main_thread = Thread::current
466 @mutex_write_guard = Mutex.new
469 attr_accessor :socket, :status
470 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
471 attr_accessor :main_thread
472 attr_reader :socket_buffer
475 log_message(sprintf("user %s killed", @name))
480 Thread::kill(@main_thread) if @main_thread
484 if (@status != "finished")
486 log_message(sprintf("user %s finish", @name))
488 # @socket.close if (! @socket.closed?)
490 log_message(sprintf("user %s finish failed", @name))
496 @mutex_write_guard.synchronize do
499 log_warning("%s's socket has been closed." % [@name])
502 if r = select(nil, [@socket], nil, 20)
503 r[1].first.write(str)
505 log_error("Sending a message to #{@name} timed up.")
507 rescue Exception => ex
508 log_error("Failed to send a message to #{@name}. #{ex.class}: #{ex.message}\t#{ex.backtrace[0]}")
514 if ["game_waiting", "start_waiting", "agree_waiting", "game"].include?(status)
516 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
517 elsif (@sente == false)
518 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
519 elsif (@sente == nil)
520 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
523 return sprintf("%s %s %s", @name, @protocol, @status)
527 def run(csa_1st_str=nil)
528 while ( csa_1st_str ||
529 str = gets_safe(@socket, (@socket_buffer.empty? ? Default_Timeout : 1)) )
532 if (@game && @game.turn?(self))
533 @socket_buffer << str
534 str = @socket_buffer.shift
536 log_message("%s (%s)" % [str, @socket_buffer.map {|a| String === a ? a.strip : a }.join(",")]) if $DEBUG
543 if (@status == "finished")
546 str.chomp! if (str.class == String) # may be strip! ?
549 # Application-level protocol for Keep-Alive
550 # If the server gets LF, it sends back LF.
551 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
554 if (@status == "game")
555 array_str = str.split(",")
556 move = array_str.shift
557 additional = array_str.shift
558 if /^'(.*)/ =~ additional
559 comment = array_str.unshift("'*#{$1.toeuc}")
561 s = @game.handle_one_move(move, self)
562 @game.fh.print("#{Kconv.toeuc(comment.first)}\n") if (comment && comment.first && !s)
563 return if (s && @protocol == LoginCSA::PROTOCOL)
565 when /^%[^%]/, :timeout
566 if (@status == "game")
567 s = @game.handle_one_move(str, self)
568 return if (s && @protocol == LoginCSA::PROTOCOL)
571 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
572 # rescue Exception => ex
573 # log_error("Failed to send a keepalive to #{@name}.")
574 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
579 log_error("Failed to receive a message from #{@name}.")
582 if (@status == "agree_waiting")
584 return if (@protocol == LoginCSA::PROTOCOL)
586 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
589 if (@status == "agree_waiting")
590 @status = "start_waiting"
591 if ((@game.sente.status == "start_waiting") &&
592 (@game.gote.status == "start_waiting"))
594 @game.sente.status = "game"
595 @game.gote.status = "game"
598 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
600 when /^%%SHOW\s+(\S+)/
602 if (LEAGUE.games[game_id])
603 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
605 write_safe("##[SHOW] +OK\n")
606 when /^%%MONITORON\s+(\S+)/
608 if (LEAGUE.games[game_id])
609 LEAGUE.games[game_id].monitoron(self)
610 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
611 write_safe("##[MONITOR][#{game_id}] +OK\n")
613 when /^%%MONITOROFF\s+(\S+)/
615 if (LEAGUE.games[game_id])
616 LEAGUE.games[game_id].monitoroff(self)
620 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
622 players = LEAGUE.rated_players
623 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
624 write_safe("##[RATING] %s \t %4d @%s\n" %
625 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
627 write_safe("##[RATING] +OK\n")
629 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
630 write_safe("##[VERSION] +OK\n")
632 if ((@status == "connected") || (@status == "game_waiting"))
633 @status = "connected"
636 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
638 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
642 if (! Login::good_game_name?(game_name))
643 write_safe(sprintf("##[ERROR] bad game name\n"))
645 elsif ((@status == "connected") || (@status == "game_waiting"))
648 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
653 if (League::Floodgate.game_name?(game_name))
654 if (my_sente_str != "*")
655 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", my_sente_str, game_name))
660 if (my_sente_str == "*")
661 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
662 elsif (my_sente_str == "+")
663 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
664 elsif (my_sente_str == "-")
665 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
668 write_safe(sprintf("##[ERROR] bad game option\n"))
674 @game_name = game_name
675 if ((my_sente_str == "*") && (rival.sente == nil))
683 elsif (rival.sente == true) # rival has higher priority
685 elsif (rival.sente == false)
687 elsif (my_sente_str == "+")
690 elsif (my_sente_str == "-")
696 Game::new(@game_name, self, rival)
697 else # rival not found
698 if (command_name == "GAME")
699 @status = "game_waiting"
700 @game_name = game_name
701 if (my_sente_str == "+")
703 elsif (my_sente_str == "-")
709 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
710 @status = "connected"
715 when /^%%CHAT\s+(.+)/
717 LEAGUE.players.each do |name, player|
718 if (player.protocol != LoginCSA::PROTOCOL)
719 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
724 LEAGUE.games.each do |id, game|
725 buf.push(sprintf("##[LIST] %s\n", id))
727 buf.push("##[LIST] +OK\n")
731 LEAGUE.players.each do |name, player|
732 buf.push(sprintf("##[WHO] %s\n", player.to_s))
734 buf.push("##[WHO] +OK\n")
737 @status = "connected"
738 write_safe("LOGOUT:completed\n")
741 # This command is only available for CSA's official testing server.
742 # So, this means nothing for this program.
743 write_safe("CHALLENGE ACCEPTED\n")
745 ## ignore null string
747 msg = "##[ERROR] unknown command %s\n" % [str]
759 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK",
760 "GI" => "NG", "KA" => "UM", "HI" => "RY"}
761 def initialize(board, x, y, sente, promoted=false)
768 if ((x == 0) || (y == 0))
770 hands = board.sente_hands
772 hands = board.gote_hands
779 @board.array[x][y] = self
782 attr_accessor :promoted, :sente, :x, :y, :board
784 def room_of_head?(x, y, name)
789 return adjacent_movable_grids + far_movable_grids
792 def far_movable_grids
797 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
798 if ((@board.array[x][y] == nil) || # dst is empty
799 (@board.array[x][y].sente != @sente)) # dst is enemy
807 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
808 if (@board.array[x][y] == nil) # dst is empty?
815 def adjacent_movable_grids
818 moves = @promoted_moves
820 moves = @normal_moves
822 moves.each do |(dx, dy)|
829 if (jump_to?(cand_x, cand_y))
830 grids.push([cand_x, cand_y])
836 def move_to?(x, y, name)
837 return false if (! room_of_head?(x, y, name))
838 return false if ((name != @name) && (name != @promoted_name))
839 return false if (@promoted && (name != @promoted_name)) # can't un-promote
842 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
844 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
846 return false if ((6 >= @y) && (6 >= y) && (name != @name))
850 if ((@x == 0) || (@y == 0))
851 return jump_to?(x, y)
853 return movable_grids.include?([x, y])
858 if ((@x == 0) || (@y == 0))
860 @board.sente_hands.delete(self)
862 @board.gote_hands.delete(self)
864 @board.array[x][y] = self
865 elsif ((x == 0) || (y == 0))
866 @promoted = false # clear promoted flag before moving to hands
868 @board.sente_hands.push(self)
870 @board.gote_hands.push(self)
872 @board.array[@x][@y] = nil
874 @board.array[@x][@y] = nil
875 @board.array[x][y] = self
908 class PieceFU < Piece
911 @normal_moves = [[0, +1]]
912 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
914 @promoted_name = "TO"
917 def room_of_head?(x, y, name)
920 return false if (y == 1)
922 return false if (y == 9)
928 if ((iy != @y) && # not source position
929 @board.array[x][iy] &&
930 (@board.array[x][iy].sente == @sente) && # mine
931 (@board.array[x][iy].name == "FU") &&
932 (@board.array[x][iy].promoted == false))
942 class PieceKY < Piece
946 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
948 @promoted_name = "NY"
951 def room_of_head?(x, y, name)
954 return false if (y == 1)
956 return false if (y == 9)
961 def far_movable_grids
969 while (jump_to?(cand_x, cand_y))
970 grids.push([cand_x, cand_y])
971 break if (! put_to?(cand_x, cand_y))
977 while (jump_to?(cand_x, cand_y))
978 grids.push([cand_x, cand_y])
979 break if (! put_to?(cand_x, cand_y))
987 class PieceKE < Piece
990 @normal_moves = [[+1, +2], [-1, +2]]
991 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
993 @promoted_name = "NK"
996 def room_of_head?(x, y, name)
999 return false if ((y == 1) || (y == 2))
1001 return false if ((y == 9) || (y == 8))
1007 class PieceGI < Piece
1008 def initialize(*arg)
1010 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1011 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1013 @promoted_name = "NG"
1017 class PieceKI < Piece
1018 def initialize(*arg)
1020 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1021 @promoted_moves = []
1023 @promoted_name = nil
1027 class PieceKA < Piece
1028 def initialize(*arg)
1031 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
1033 @promoted_name = "UM"
1036 def far_movable_grids
1041 while (jump_to?(cand_x, cand_y))
1042 grids.push([cand_x, cand_y])
1043 break if (! put_to?(cand_x, cand_y))
1050 while (jump_to?(cand_x, cand_y))
1051 grids.push([cand_x, cand_y])
1052 break if (! put_to?(cand_x, cand_y))
1059 while (jump_to?(cand_x, cand_y))
1060 grids.push([cand_x, cand_y])
1061 break if (! put_to?(cand_x, cand_y))
1068 while (jump_to?(cand_x, cand_y))
1069 grids.push([cand_x, cand_y])
1070 break if (! put_to?(cand_x, cand_y))
1077 class PieceHI < Piece
1078 def initialize(*arg)
1081 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1083 @promoted_name = "RY"
1086 def far_movable_grids
1091 while (jump_to?(cand_x, cand_y))
1092 grids.push([cand_x, cand_y])
1093 break if (! put_to?(cand_x, cand_y))
1099 while (jump_to?(cand_x, cand_y))
1100 grids.push([cand_x, cand_y])
1101 break if (! put_to?(cand_x, cand_y))
1107 while (jump_to?(cand_x, cand_y))
1108 grids.push([cand_x, cand_y])
1109 break if (! put_to?(cand_x, cand_y))
1115 while (jump_to?(cand_x, cand_y))
1116 grids.push([cand_x, cand_y])
1117 break if (! put_to?(cand_x, cand_y))
1123 class PieceOU < Piece
1124 def initialize(*arg)
1126 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1127 @promoted_moves = []
1129 @promoted_name = nil
1136 @sente_hands = Array::new
1137 @gote_hands = Array::new
1138 @history = Hash::new(0)
1139 @sente_history = Hash::new(0)
1140 @gote_history = Hash::new(0)
1141 @array = [[], [], [], [], [], [], [], [], [], []]
1143 @teban = nil # black => true, white => false
1145 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1146 attr_reader :move_count
1149 PieceKY::new(self, 1, 1, false)
1150 PieceKE::new(self, 2, 1, false)
1151 PieceGI::new(self, 3, 1, false)
1152 PieceKI::new(self, 4, 1, false)
1153 PieceOU::new(self, 5, 1, false)
1154 PieceKI::new(self, 6, 1, false)
1155 PieceGI::new(self, 7, 1, false)
1156 PieceKE::new(self, 8, 1, false)
1157 PieceKY::new(self, 9, 1, false)
1158 PieceKA::new(self, 2, 2, false)
1159 PieceHI::new(self, 8, 2, false)
1161 PieceFU::new(self, i, 3, false)
1164 PieceKY::new(self, 1, 9, true)
1165 PieceKE::new(self, 2, 9, true)
1166 PieceGI::new(self, 3, 9, true)
1167 PieceKI::new(self, 4, 9, true)
1168 PieceOU::new(self, 5, 9, true)
1169 PieceKI::new(self, 6, 9, true)
1170 PieceGI::new(self, 7, 9, true)
1171 PieceKE::new(self, 8, 9, true)
1172 PieceKY::new(self, 9, 9, true)
1173 PieceKA::new(self, 8, 8, true)
1174 PieceHI::new(self, 2, 8, true)
1176 PieceFU::new(self, i, 7, true)
1181 def have_piece?(hands, name)
1182 piece = hands.find { |i|
1188 def move_to(x0, y0, x1, y1, name, sente)
1190 hands = @sente_hands
1195 if ((x0 == 0) || (y0 == 0))
1196 piece = have_piece?(hands, name)
1197 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1198 piece.move_to(x1, y1)
1200 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1201 if (@array[x0][y0].name != name) # promoted ?
1202 @array[x0][y0].promoted = true
1204 if (@array[x1][y1]) # capture
1205 if (@array[x1][y1].name == "OU")
1206 return :outori # return board update
1208 @array[x1][y1].sente = @array[x0][y0].sente
1209 @array[x1][y1].move_to(0, 0)
1210 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1214 @array[x0][y0].move_to(x1, y1)
1217 @teban = @teban ? false : true
1221 def look_for_ou(sente)
1227 (@array[x][y].name == "OU") &&
1228 (@array[x][y].sente == sente))
1235 raise "can't find ou"
1238 # note checkmate, but check. sente is checked.
1239 def checkmated?(sente) # sente is loosing
1240 ou = look_for_ou(sente)
1246 (@array[x][y].sente != sente))
1247 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1258 def uchifuzume?(sente)
1259 rival_ou = look_for_ou(! sente) # rival's ou
1260 if (sente) # rival is gote
1261 if ((rival_ou.y != 9) &&
1262 (@array[rival_ou.x][rival_ou.y + 1]) &&
1263 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1264 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1266 fu_y = rival_ou.y + 1
1271 if ((rival_ou.y != 1) &&
1272 (@array[rival_ou.x][rival_ou.y - 1]) &&
1273 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1274 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1276 fu_y = rival_ou.y - 1
1282 ## case: rival_ou is moving
1283 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1284 tmp_board = Marshal.load(Marshal.dump(self))
1285 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1286 raise "internal error" if (s != true)
1287 if (! tmp_board.checkmated?(! sente)) # good move
1292 ## case: rival is capturing fu
1298 (@array[x][y].sente != sente) &&
1299 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1302 if (@array[x][y].promoted)
1303 names << @array[x][y].promoted_name
1305 names << @array[x][y].name
1306 if @array[x][y].promoted_name &&
1307 @array[x][y].move_to?(fu_x, fu_y, @array[x][y].promoted_name)
1308 names << @array[x][y].promoted_name
1311 names.map! do |name|
1312 tmp_board = Marshal.load(Marshal.dump(self))
1313 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1317 tmp_board.checkmated?(! sente) # result
1320 all_illegal = names.find {|a| a != :illegal}
1321 raise "internal error: legal move not found" if all_illegal == nil
1322 r = names.find {|a| a == false} # good move
1323 return false if r == false # found good move
1332 # @[sente|gote]_history has at least one item while the player is checking the other or
1333 # the other escapes.
1334 def update_sennichite(player)
1337 if checkmated?(!player)
1339 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
1341 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
1345 @sente_history.clear # no more continuous check
1347 @gote_history.clear # no more continuous check
1350 if @sente_history.size > 0 # possible for Sente's or Gote's turn
1351 @sente_history[str] += 1
1353 if @gote_history.size > 0 # possible for Sente's or Gote's turn
1354 @gote_history[str] += 1
1358 def oute_sennichite?(player)
1359 if (@sente_history[to_s] >= 4)
1360 return :oute_sennichite_sente_lose
1361 elsif (@gote_history[to_s] >= 4)
1362 return :oute_sennichite_gote_lose
1368 def sennichite?(sente)
1369 if (@history[to_s] >= 4) # already 3 times
1375 def good_kachi?(sente)
1376 if (checkmated?(sente))
1377 puts "'NG: Checkmating." if $DEBUG
1381 ou = look_for_ou(sente)
1382 if (sente && (ou.y >= 4))
1383 puts "'NG: Black's OU does not enter yet." if $DEBUG
1386 if (! sente && (ou.y <= 6))
1387 puts "'NG: White's OU does not enter yet." if $DEBUG
1395 hands = @sente_hands
1405 (@array[x][y].sente == sente) &&
1406 (@array[x][y].point > 0))
1407 point = point + @array[x][y].point
1413 hands.each do |piece|
1414 point = point + piece.point
1418 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1423 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1428 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1433 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1437 # sente is nil only if tests in test_board run
1438 def handle_one_move(str, sente=nil)
1439 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1446 elsif (str =~ /^%KACHI/)
1447 raise ArgumentError, "sente is null", caller if sente == nil
1448 if (good_kachi?(sente))
1453 elsif (str =~ /^%TORYO/)
1459 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1460 ((x0 != 0) || (y0 != 0)))
1462 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1467 sente = true if sente == nil # deprecated
1468 return :illegal unless sente == true # black player's move must be black
1469 hands = @sente_hands
1471 sente = false if sente == nil # deprecated
1472 return :illegal unless sente == false # white player's move must be white
1477 if ((x0 == 0) && (y0 == 0))
1478 return :illegal if (! have_piece?(hands, name))
1479 elsif (! @array[x0][y0])
1480 return :illegal # no piece
1481 elsif (@array[x0][y0].sente != sente)
1482 return :illegal # this is not mine
1483 elsif (@array[x0][y0].name != name)
1484 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1487 ## destination check
1488 if (@array[x1][y1] &&
1489 (@array[x1][y1].sente == sente)) # can't capture mine
1491 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1492 return :illegal # can't put on existing piece
1495 tmp_board = Marshal.load(Marshal.dump(self))
1496 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1497 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1498 tmp_board.update_sennichite(sente)
1499 os_result = tmp_board.oute_sennichite?(sente)
1500 return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
1501 return :sennichite if tmp_board.sennichite?(sente)
1503 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1507 move_to(x0, y0, x1, y1, name, sente)
1509 update_sennichite(sente)
1517 a.push(sprintf("P%d", y))
1520 piece = @array[x][y]
1529 a.push(sprintf("\n"))
1532 if (! sente_hands.empty?)
1534 sente_hands.each do |p|
1535 a.push("00" + p.name)
1539 if (! gote_hands.empty?)
1541 gote_hands.each do |p|
1542 a.push("00" + p.name)
1546 a.push("%s\n" % [@teban ? "+" : "-"])
1552 attr_reader :players, :black, :white
1554 def initialize(p1, p2)
1556 if p1.sente && !p2.sente
1557 @black, @white = p1, p2
1558 elsif !p1.sente && p2.sente
1559 @black, @white = p2, p1
1561 raise "Never reached!"
1566 class GameResultWin < GameResult
1567 attr_reader :winner, :loser
1569 def initialize(winner, loser)
1571 @winner, @loser = winner, loser
1572 @winner.last_game_win = true
1573 @loser.last_game_win = false
1577 black_name = @black.id || @black.name
1578 white_name = @white.id || @white.name
1579 "%s:%s" % [black_name, white_name]
1583 class GameResultDraw < GameResult
1584 def initialize(p1, p2)
1586 p1.last_game_win = false
1587 p2.last_game_win = false
1595 def initialize(game_name, player0, player1)
1596 @monitors = Array::new
1597 @game_name = game_name
1598 if (@game_name =~ /-(\d+)-(\d+)$/)
1599 @total_time = $1.to_i
1604 @sente, @gote = player0, player1
1606 @sente, @gote = player1, player0
1608 @sente.socket_buffer.clear
1609 @gote.socket_buffer.clear
1610 @current_player, @next_player = @sente, @gote
1617 @sente.status = "agree_waiting"
1618 @gote.status = "agree_waiting"
1620 @id = sprintf("%s+%s+%s+%s+%s",
1621 LEAGUE.event, @game_name,
1622 @sente.name, @gote.name, issue_current_time)
1623 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1625 LEAGUE.games[@id] = self
1627 log_message(sprintf("game created %s", @id))
1637 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1638 attr_accessor :last_move, :current_turn
1642 @sente.rated? && @gote.rated?
1646 return player.status == "game" && @current_player == player
1649 def monitoron(monitor)
1650 @monitors.delete(monitor)
1651 @monitors.push(monitor)
1654 def monitoroff(monitor)
1655 @monitors.delete(monitor)
1658 def reject(rejector)
1659 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1660 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1665 if ["agree_waiting", "start_waiting"].include?(@sente.status)
1667 elsif (@current_player == killer)
1674 log_message(sprintf("game finished %s", @id))
1675 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1680 @sente.status = "connected"
1681 @gote.status = "connected"
1683 if (@current_player.protocol == LoginCSA::PROTOCOL)
1684 @current_player.finish
1686 if (@next_player.protocol == LoginCSA::PROTOCOL)
1689 @monitors = Array::new
1692 @current_player = nil
1694 LEAGUE.games.delete(@id)
1698 def handle_one_move(str, player)
1699 unless turn?(player)
1700 return false if str == :timeout
1702 @fh.puts("'Deferred %s" % [str])
1703 log_warning("Deferred a move [%s] scince it is not %s 's turn." %
1705 player.socket_buffer << str # always in the player's thread
1710 @end_time = Time::new
1711 t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
1714 if ((@current_player.mytime - t <= -@byoyomi) &&
1715 ((@total_time > 0) || (@byoyomi > 0)))
1717 elsif (str == :timeout)
1718 return false # time isn't expired. players aren't swapped. continue game
1720 @current_player.mytime -= t
1721 if (@current_player.mytime < 0)
1722 @current_player.mytime = 0
1725 move_status = @board.handle_one_move(str, @sente == @current_player)
1727 if [:illegal, :uchifuzme, :oute_kaihimore].include?(move_status)
1728 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1730 if [:normal, :outori, :sennichite, :oute_sennichite_sente_lose, :oute_sennichite_gote_lose].include?(move_status)
1731 # Thinking time includes network traffic
1732 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1733 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1734 @fh.printf("%s\nT%d\n", str, t)
1735 @last_move = sprintf("%s,T%d", str, t)
1739 @monitors.each do |monitor|
1740 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1741 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1746 if (@next_player.status != "game") # rival is logout or disconnected
1748 elsif (status == :timeout)
1750 elsif (move_status == :illegal)
1752 elsif (move_status == :kachi_win)
1754 elsif (move_status == :kachi_lose)
1756 elsif (move_status == :toryo)
1758 elsif (move_status == :outori)
1760 elsif (move_status == :oute_sennichite_sente_lose)
1761 oute_sennichite_win_lose(@gote, @sente) # Sente is checking
1762 elsif (move_status == :oute_sennichite_gote_lose)
1763 oute_sennichite_win_lose(@sente, @gote) # Gote is checking
1764 elsif (move_status == :sennichite)
1766 elsif (move_status == :uchifuzume)
1768 elsif (move_status == :oute_kaihimore)
1769 oute_kaihimore_lose()
1773 finish() if finish_flag
1774 @current_player, @next_player = @next_player, @current_player
1775 @start_time = Time::new
1780 @current_player.status = "connected"
1781 @next_player.status = "connected"
1782 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1783 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1784 @fh.printf("%%TORYO\n")
1785 @fh.print(@board.to_s.gsub(/^/, "\'"))
1786 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1787 @result = GameResultWin.new(@current_player, @next_player)
1788 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1789 @monitors.each do |monitor|
1790 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1795 @current_player.status = "connected"
1796 @next_player.status = "connected"
1797 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1798 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1799 @fh.printf("%%TORYO\n")
1800 @fh.print(@board.to_s.gsub(/^/, "\'"))
1801 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1802 @result = GameResultWin.new(@next_player, @current_player)
1803 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1804 @monitors.each do |monitor|
1805 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1810 @current_player.status = "connected"
1811 @next_player.status = "connected"
1812 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1813 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1814 @fh.print(@board.to_s.gsub(/^/, "\'"))
1815 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1816 @result = GameResultDraw.new(@current_player, @next_player)
1817 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1818 @monitors.each do |monitor|
1819 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @id))
1823 def oute_sennichite_win_lose(winner, loser)
1824 @current_player.status = "connected"
1825 @next_player.status = "connected"
1826 loser.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1827 winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1828 @fh.print(@board.to_s.gsub(/^/, "\'"))
1829 if loser == @current_player
1830 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1832 @fh.printf("'summary:oute_sennichite:%s win:%s lose\n", @current_player.name, @next_player.name)
1834 @result = GameResultWin.new(winner, loser)
1835 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1836 @monitors.each do |monitor|
1837 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1842 @current_player.status = "connected"
1843 @next_player.status = "connected"
1844 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1845 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1846 @fh.print(@board.to_s.gsub(/^/, "\'"))
1847 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1848 @result = GameResultWin.new(@next_player, @current_player)
1849 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1850 @monitors.each do |monitor|
1851 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1856 @current_player.status = "connected"
1857 @next_player.status = "connected"
1858 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1859 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1860 @fh.print(@board.to_s.gsub(/^/, "\'"))
1861 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1862 @result = GameResultWin.new(@next_player, @current_player)
1863 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1864 @monitors.each do |monitor|
1865 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1869 def oute_kaihimore_lose
1870 @current_player.status = "connected"
1871 @next_player.status = "connected"
1872 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1873 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1874 @fh.print(@board.to_s.gsub(/^/, "\'"))
1875 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1876 @result = GameResultWin.new(@next_player, @current_player)
1877 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1878 @monitors.each do |monitor|
1879 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1884 @current_player.status = "connected"
1885 @next_player.status = "connected"
1886 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1887 @next_player.write_safe("#TIME_UP\n#WIN\n")
1888 @fh.print(@board.to_s.gsub(/^/, "\'"))
1889 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1890 @result = GameResultWin.new(@next_player, @current_player)
1891 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1892 @monitors.each do |monitor|
1893 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
1898 @current_player.status = "connected"
1899 @next_player.status = "connected"
1900 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1901 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1902 @fh.printf("%%KACHI\n")
1903 @fh.print(@board.to_s.gsub(/^/, "\'"))
1904 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1905 @result = GameResultWin.new(@current_player, @next_player)
1906 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1907 @monitors.each do |monitor|
1908 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1913 @current_player.status = "connected"
1914 @next_player.status = "connected"
1915 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1916 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1917 @fh.printf("%%KACHI\n")
1918 @fh.print(@board.to_s.gsub(/^/, "\'"))
1919 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1920 @result = GameResultWin.new(@next_player, @current_player)
1921 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1922 @monitors.each do |monitor|
1923 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1928 @current_player.status = "connected"
1929 @next_player.status = "connected"
1930 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1931 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1932 @fh.printf("%%TORYO\n")
1933 @fh.print(@board.to_s.gsub(/^/, "\'"))
1934 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1935 @result = GameResultWin.new(@next_player, @current_player)
1936 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1937 @monitors.each do |monitor|
1938 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1943 @current_player.status = "connected"
1944 @next_player.status = "connected"
1945 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1946 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1947 @fh.print(@board.to_s.gsub(/^/, "\'"))
1948 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1949 @result = GameResultWin.new(@current_player, @next_player)
1950 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1951 @monitors.each do |monitor|
1952 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1957 log_message(sprintf("game started %s", @id))
1958 @sente.write_safe(sprintf("START:%s\n", @id))
1959 @gote.write_safe(sprintf("START:%s\n", @id))
1960 @sente.mytime = @total_time
1961 @gote.mytime = @total_time
1962 @start_time = Time::new
1966 @fh = open(@logfile, "w")
1970 @fh.puts("N+#{@sente.name}")
1971 @fh.puts("N-#{@gote.name}")
1972 @fh.puts("$EVENT:#{@id}")
1974 @sente.write_safe(propose_message("+"))
1975 @gote.write_safe(propose_message("-"))
1977 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
1978 @fh.puts("$START_TIME:#{now}")
1980 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1981 P2 * -HI * * * * * -KA *
1982 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1983 P4 * * * * * * * * *
1984 P5 * * * * * * * * *
1985 P6 * * * * * * * * *
1986 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1987 P8 * +KA * * * * * +HI *
1988 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1996 Protocol_Version:1.1
1997 Protocol_Mode:Server
1999 Declaration:Jishogi 1.1
2001 Name+:#{@sente.name}
2007 Total_Time:#{@total_time}
2009 Least_Time_Per_Move:#{Least_Time_Per_Move}
2010 Remaining_Time+:#{@sente.mytime}
2011 Remaining_Time-:#{@gote.mytime}
2012 Last_Move:#{@last_move}
2013 Current_Turn:#{@current_turn}
2023 return str0 + @board.to_s + str1
2026 def propose_message(sg_flag)
2029 Protocol_Version:1.1
2030 Protocol_Mode:Server
2032 Declaration:Jishogi 1.1
2034 Name+:#{@sente.name}
2036 Your_Turn:#{sg_flag}
2041 Total_Time:#{@total_time}
2043 Least_Time_Per_Move:#{Least_Time_Per_Move}
2046 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2047 P2 * -HI * * * * * -KA *
2048 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2049 P4 * * * * * * * * *
2050 P5 * * * * * * * * *
2051 P6 * * * * * * * * *
2052 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2053 P8 * +KA * * * * * +HI *
2054 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2066 def issue_current_time
2067 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
2068 @@mutex.synchronize do
2069 while time <= @@time do
2076 end # module ShogiServer
2078 #################################################
2085 shogi-server - server for CSA server protocol
2088 shogi-server [OPTIONS] event_name port_number
2091 server for CSA server protocol
2095 specify filename for logging process ID
2097 run as a daemon. Log files will be put in dir.
2100 this file is distributed under GPL version2 and might be compiled by Exerb
2105 #{ShogiServer::Release}
2108 #{ShogiServer::Revision}
2116 def log_message(str)
2120 def log_warning(str)
2129 def parse_command_line
2131 parser = GetoptLong.new(
2132 ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2133 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT])
2136 parser.each_option do |name, arg|
2137 name.sub!(/^--/, '')
2138 options[name] = arg.dup
2142 raise parser.error_message
2147 def write_pid_file(file)
2148 open(file, "w") do |fh|
2153 def mutex_watchdog(mutex, sec)
2165 log_error("mutex watchdog timeout")
2171 def login_loop(client)
2172 player = login = nil
2174 while r = select([client], nil, nil, ShogiServer::Login_Time) do
2175 break unless str = r[0].first.gets
2176 $mutex.lock # guards LEAGUE
2180 if (ShogiServer::Login::good_login?(str))
2181 player = ShogiServer::Player::new(str, client, eol)
2182 login = ShogiServer::Login::factory(str, player)
2183 if (current_player = LEAGUE.find(player.name))
2184 if (current_player.password == player.password &&
2185 current_player.status != "game")
2186 log_message(sprintf("user %s login forcely", player.name))
2189 login.incorrect_duplicated_player(str)
2197 client.write("LOGIN:incorrect" + eol)
2198 client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2204 return [player, login]
2212 mutex_watchdog($mutex, 10)
2215 $options = parse_command_line
2216 if (ARGV.length != 2)
2221 LEAGUE.event = ARGV.shift
2224 dir = $options["daemon"]
2225 dir = File.expand_path(dir) if dir
2226 if dir && ! File.exist?(dir)
2227 FileUtils.mkdir(dir)
2229 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2230 $logger = WEBrick::Log.new(log_file) # thread safe
2232 LEAGUE.dir = dir || File.dirname(__FILE__)
2233 LEAGUE.setup_players_database
2236 config[:Port] = port
2237 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2238 config[:Logger] = $logger
2239 if $options["pid-file"]
2240 pid_file = File.expand_path($options["pid-file"])
2241 config[:StartCallback] = Proc.new do
2242 write_pid_file(pid_file)
2244 config[:StopCallback] = Proc.new do
2245 FileUtils.rm(pid_file, :force => true)
2249 server = WEBrick::GenericServer.new(config)
2250 ["INT", "TERM"].each do |signal|
2256 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2257 log_message("server started [Revision: #{ShogiServer::Revision}]")
2259 server.start do |client|
2260 # client.sync = true # this is already set in WEBrick
2261 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2262 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2263 player, login = login_loop(client) # loop
2266 log_message(sprintf("user %s login", player.name))
2268 player.run(login.csa_1st_str) # loop
2272 player.game.kill(player)
2274 player.finish # socket has been closed
2275 LEAGUE.delete(player)
2276 log_message(sprintf("user %s logout", player.name))
2287 TCPSocket.do_not_reverse_lookup = true
2288 Thread.abort_on_exception = $DEBUG ? true : false
2290 LEAGUE = ShogiServer::League::new