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
33 def gets_timeout(t = Default_Timeout)
44 def gets_safe(t = nil)
47 return :exception if closed?
53 rescue Exception => ex
54 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
68 return self.write(str)
76 module ShogiServer # for a namespace
78 Max_Write_Queue_Size = 1000
79 Max_Identifier_Length = 32
80 Default_Timeout = 60 # for single socket operation
82 Default_Game_Name = "default-1500-0"
85 Least_Time_Per_Move = 1
86 Login_Time = 300 # time for LOGIN
88 Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
89 Release.concat("-") if (Release == "")
90 Revision = "$Revision$".gsub(/[^\.\d]/, '')
97 return /^floodgate-\d+-\d+$/.match(str) ? true : false
101 def initialize(league)
108 @thread = Thread.new do
113 next if Time.now < @next_time
117 rescue Exception => ex
119 log_error("[in Floodgate's thread] #{ex}")
126 @thread.kill if @thread
134 @next_time = Time.mktime(now.year, now.month, now.day, now.hour, 30)
136 @next_time = Time.mktime(now.year, now.month, now.day, now.hour) + 3600
140 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min, 30)
142 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min) + 60
147 players = @league.find_all_players do |pl|
148 pl.status == "game_waiting" &&
149 Floodgate.game_name?(pl.game_name) &&
152 load File.join(File.dirname(__FILE__), "pairing.rb")
153 Pairing.default_pairing.match(players)
155 end # class Floodgate
158 @mutex = Mutex.new # guard @players
162 @dir = File.dirname(__FILE__)
163 @floodgate = Floodgate.new(self)
166 attr_accessor :players, :games, :event, :dir
169 @mutex.synchronize do
170 @players.each {|a| save(a)}
175 # this should be called just after instanciating a League object.
176 def setup_players_database
177 @db = YAML::Store.new(File.join(@dir, "players.yaml"))
181 self.load(player) if player.id
182 @mutex.synchronize do
183 @players[player.name] = player
188 @mutex.synchronize do
190 @players.delete(player.name)
195 @mutex.synchronize do
196 @players.each {|player| load(player)}
202 @mutex.synchronize do
203 found = @players.find_all do |name, player|
207 return found.map {|a| a.last}
210 def get_player(status, game_name, sente, searcher)
212 @mutex.synchronize do
213 found = @players.find do |name, player|
214 (player.status == status) &&
215 (player.game_name == game_name) &&
217 (player.sente == nil) ||
218 (player.sente == sente) ) &&
219 (player.name != searcher.name)
222 return found ? found.last : nil
226 hash = search(player.id)
230 player.name = hash['name']
231 player.rate = hash['rate'] || 0
232 player.modified_at = hash['last_modified']
233 player.rating_group = hash['rating_group']
234 player.win = hash['win'] || 0
235 player.loss = hash['loss'] || 0
236 player.last_game_win = hash['last_game_win'] || false
241 break unless @db["players"]
242 @db["players"].each do |group, players|
243 hash = players[player.id]
245 hash['last_game_win'] = player.last_game_win
254 @db.transaction(true) do
255 break unless @db["players"]
256 @db["players"].each do |group, players|
266 @db.transaction(true) do
267 break unless @db["players"]
268 @db["players"].each do |group, players_hash|
269 players << players_hash.keys
272 return players.flatten.collect do |id|
282 ######################################################
283 # Processes the LOGIN command.
286 def Login.good_login?(str)
288 if (((tokens.length == 3) || ((tokens.length == 4) && tokens[3] == "x1")) &&
289 (tokens[0] == "LOGIN") &&
290 (good_identifier?(tokens[1])))
297 def Login.good_game_name?(str)
298 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
305 def Login.good_identifier?(str)
306 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
313 def Login.factory(str, player)
314 (login, player.name, password, ext) = str.chomp.split
316 return Loginx1.new(player, password)
318 return LoginCSA.new(player, password)
324 # the first command that will be executed just after LOGIN.
325 # If it is nil, the default process will be started.
326 attr_reader :csa_1st_str
328 def initialize(player, password)
331 parse_password(password)
335 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
336 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
339 def incorrect_duplicated_player(str)
340 @player.write_safe("LOGIN:incorrect\n")
341 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
342 sleep 3 # wait for sending the above messages.
343 @player.name = "%s [duplicated]" % [@player.name]
348 ######################################################
349 # Processes LOGIN for the CSA standard mode.
351 class LoginCSA < Login
354 def initialize(player, password)
357 @player.protocol = PROTOCOL
360 def parse_password(password)
361 if Login.good_game_name?(password)
363 @player.set_password(nil)
364 elsif password.split(",").size > 1
365 @gamename, *trip = password.split(",")
366 @player.set_password(trip.join(","))
368 @player.set_password(password)
369 @gamename = Default_Game_Name
371 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
376 @csa_1st_str = "%%GAME #{@gamename} *"
380 ######################################################
381 # Processes LOGIN for the extented mode.
383 class Loginx1 < Login
386 def initialize(player, password)
388 @player.protocol = PROTOCOL
391 def parse_password(password)
392 @player.set_password(password)
397 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
407 @last_game_win = false
410 # Idetifier of the player in the rating system
416 # Password of the player, which does not include a trip
417 attr_accessor :password
419 # Score in the rating sysem
422 # Number of games for win and loss in the rating system
423 attr_accessor :win, :loss
425 # Group in the rating system
426 attr_accessor :rating_group
428 # Last timestamp when the rate was modified
429 attr_accessor :modified_at
431 # Whether win the previous game or not
432 attr_accessor :last_game_win
435 @modified_at || Time.now
441 @modified_at = Time.now
450 return @last_game_win
455 simple_name = @name.gsub(/@.*?$/, '')
456 "%s+%s" % [simple_name, @trip[0..8]]
463 # Parses str in the LOGIN command, sets up @id and @trip
465 def set_password(str)
466 if str && !str.empty?
467 @password = str.strip
468 @id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
470 @id = @password = nil
476 class Player < BasicPlayer
477 def initialize(str, socket)
480 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
482 @protocol = nil # CSA or x1
483 @eol = "\m" # favorite eol code
486 @mytime = 0 # set in start method also
488 @write_queue = Queue::new
489 @main_thread = Thread::current
490 @writer_thread = Thread::start do
496 attr_accessor :socket, :status
497 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
498 attr_accessor :main_thread, :writer_thread, :write_queue
501 log_message(sprintf("user %s killed", @name))
506 Thread::kill(@main_thread) if @main_thread
510 if (@status != "finished")
512 log_message(sprintf("user %s finish", @name))
513 # TODO you should confirm that there is no message in the queue.
514 Thread::kill(@writer_thread) if @writer_thread
516 # @socket.close if (! @socket.closed?)
518 log_message(sprintf("user %s finish failed", @name))
524 @write_queue.push(str.gsub(/[\r\n]+/, @eol))
528 while (str = @write_queue.pop)
531 rescue Exception => ex
532 log_error("Failed to send a message to #{@name}.")
533 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
540 if ((status == "game_waiting") ||
541 (status == "start_waiting") ||
542 (status == "agree_waiting") ||
545 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
546 elsif (@sente == false)
547 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
548 elsif (@sente == nil)
549 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
552 return sprintf("%s %s %s", @name, @protocol, @status)
556 def run(csa_1st_str=nil)
557 while (csa_1st_str || (str = @socket.gets_safe(Default_Timeout)))
561 if (@writer_thread == nil || !@writer_thread.status)
562 # The writer_thread has been killed because of socket errors.
570 if (@write_queue.size > Max_Write_Queue_Size)
571 log_warning(sprintf("write_queue of %s is %d", @name, @write_queue.size))
575 if (@status == "finished")
578 str.chomp! if (str.class == String) # may be strip! ?
579 log_message(str) if $DEBUG
582 # Application-level protocol for Keep-Alive
583 # If the server gets LF, it sends back LF.
584 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
587 if (@status == "game")
588 array_str = str.split(",")
589 move = array_str.shift
590 additional = array_str.shift
591 if /^'(.*)/ =~ additional
592 comment = array_str.unshift("'*#{$1}")
594 s = @game.handle_one_move(move, self)
595 @game.fh.print("#{comment}\n") if (comment && !s)
596 return if (s && @protocol == LoginCSA::PROTOCOL)
598 when /^%[^%]/, :timeout
599 if (@status == "game")
600 s = @game.handle_one_move(str, self)
601 return if (s && @protocol == LoginCSA::PROTOCOL)
604 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
605 # rescue Exception => ex
606 # log_error("Failed to send a keepalive to #{@name}.")
607 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
612 log_error("Failed to receive a message from #{@name}.")
615 if (@status == "agree_waiting")
617 return if (@protocol == LoginCSA::PROTOCOL)
619 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
622 if (@status == "agree_waiting")
623 @status = "start_waiting"
624 if ((@game.sente.status == "start_waiting") &&
625 (@game.gote.status == "start_waiting"))
627 @game.sente.status = "game"
628 @game.gote.status = "game"
631 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
633 when /^%%SHOW\s+(\S+)/
635 if (LEAGUE.games[game_id])
636 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
638 write_safe("##[SHOW] +OK\n")
639 when /^%%MONITORON\s+(\S+)/
641 if (LEAGUE.games[game_id])
642 LEAGUE.games[game_id].monitoron(self)
643 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
644 write_safe("##[MONITOR][#{game_id}] +OK\n")
646 when /^%%MONITOROFF\s+(\S+)/
648 if (LEAGUE.games[game_id])
649 LEAGUE.games[game_id].monitoroff(self)
653 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
655 players = LEAGUE.rated_players
656 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
657 write_safe("##[RATING] %s \t %4d @%s\n" %
658 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
660 write_safe("##[RATING] +OK\n")
662 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
663 write_safe("##[VERSION] +OK\n")
665 if ((@status == "connected") || (@status == "game_waiting"))
666 @status = "connected"
669 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
671 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
675 if (! Login::good_game_name?(game_name))
676 write_safe(sprintf("##[ERROR] bad game name\n"))
678 elsif ((@status == "connected") || (@status == "game_waiting"))
681 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
686 if (League::Floodgate.game_name?(game_name))
687 if (my_sente_str != "*")
688 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n"), my_sente_str, game_name)
693 if (my_sente_str == "*")
694 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
695 elsif (my_sente_str == "+")
696 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
697 elsif (my_sente_str == "-")
698 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
701 write_safe(sprintf("##[ERROR] bad game option\n"))
707 @game_name = game_name
708 if ((my_sente_str == "*") && (rival.sente == nil))
716 elsif (rival.sente == true) # rival has higher priority
718 elsif (rival.sente == false)
720 elsif (my_sente_str == "+")
723 elsif (my_sente_str == "-")
729 Game::new(@game_name, self, rival)
730 else # rival not found
731 if (command_name == "GAME")
732 @status = "game_waiting"
733 @game_name = game_name
734 if (my_sente_str == "+")
736 elsif (my_sente_str == "-")
742 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
743 @status = "connected"
748 when /^%%CHAT\s+(.+)/
750 LEAGUE.players.each do |name, player|
751 if (player.protocol != LoginCSA::PROTOCOL)
752 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
757 LEAGUE.games.each do |id, game|
758 buf.push(sprintf("##[LIST] %s\n", id))
760 buf.push("##[LIST] +OK\n")
764 LEAGUE.players.each do |name, player|
765 buf.push(sprintf("##[WHO] %s\n", player.to_s))
767 buf.push("##[WHO] +OK\n")
770 @status = "connected"
771 write_safe("LOGOUT:completed\n")
774 # This command is only available for CSA's official testing server.
775 # So, this means nothing for this program.
776 write_safe("CHALLENGE ACCEPTED\n")
778 ## ignore null string
780 msg = "##[ERROR] unknown command %s\n" % [str]
792 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
793 def initialize(board, x, y, sente, promoted=false)
800 if ((x == 0) || (y == 0))
802 hands = board.sente_hands
804 hands = board.gote_hands
811 @board.array[x][y] = self
814 attr_accessor :promoted, :sente, :x, :y, :board
816 def room_of_head?(x, y, name)
821 return adjacent_movable_grids + far_movable_grids
824 def far_movable_grids
829 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
830 if ((@board.array[x][y] == nil) || # dst is empty
831 (@board.array[x][y].sente != @sente)) # dst is enemy
839 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
840 if (@board.array[x][y] == nil) # dst is empty?
847 def adjacent_movable_grids
850 moves = @promoted_moves
852 moves = @normal_moves
854 moves.each do |(dx, dy)|
861 if (jump_to?(cand_x, cand_y))
862 grids.push([cand_x, cand_y])
868 def move_to?(x, y, name)
869 return false if (! room_of_head?(x, y, name))
870 return false if ((name != @name) && (name != @promoted_name))
871 return false if (@promoted && (name != @promoted_name)) # can't un-promote
874 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
876 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
878 return false if ((6 >= @y) && (6 >= y) && (name != @name))
882 if ((@x == 0) || (@y == 0))
883 return jump_to?(x, y)
885 return movable_grids.include?([x, y])
890 if ((@x == 0) || (@y == 0))
892 @board.sente_hands.delete(self)
894 @board.gote_hands.delete(self)
896 @board.array[x][y] = self
897 elsif ((x == 0) || (y == 0))
898 @promoted = false # clear promoted flag before moving to hands
900 @board.sente_hands.push(self)
902 @board.gote_hands.push(self)
904 @board.array[@x][@y] = nil
906 @board.array[@x][@y] = nil
907 @board.array[x][y] = self
940 class PieceFU < Piece
943 @normal_moves = [[0, +1]]
944 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
946 @promoted_name = "TO"
949 def room_of_head?(x, y, name)
952 return false if (y == 1)
954 return false if (y == 9)
960 if ((iy != @y) && # not source position
961 @board.array[x][iy] &&
962 (@board.array[x][iy].sente == @sente) && # mine
963 (@board.array[x][iy].name == "FU") &&
964 (@board.array[x][iy].promoted == false))
974 class PieceKY < Piece
978 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
980 @promoted_name = "NY"
983 def room_of_head?(x, y, name)
986 return false if (y == 1)
988 return false if (y == 9)
993 def far_movable_grids
1001 while (jump_to?(cand_x, cand_y))
1002 grids.push([cand_x, cand_y])
1003 break if (! put_to?(cand_x, cand_y))
1009 while (jump_to?(cand_x, cand_y))
1010 grids.push([cand_x, cand_y])
1011 break if (! put_to?(cand_x, cand_y))
1019 class PieceKE < Piece
1020 def initialize(*arg)
1022 @normal_moves = [[+1, +2], [-1, +2]]
1023 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1025 @promoted_name = "NK"
1028 def room_of_head?(x, y, name)
1031 return false if ((y == 1) || (y == 2))
1033 return false if ((y == 9) || (y == 8))
1039 class PieceGI < Piece
1040 def initialize(*arg)
1042 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1043 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1045 @promoted_name = "NG"
1049 class PieceKI < Piece
1050 def initialize(*arg)
1052 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1053 @promoted_moves = []
1055 @promoted_name = nil
1059 class PieceKA < Piece
1060 def initialize(*arg)
1063 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
1065 @promoted_name = "UM"
1068 def far_movable_grids
1073 while (jump_to?(cand_x, cand_y))
1074 grids.push([cand_x, cand_y])
1075 break if (! put_to?(cand_x, cand_y))
1082 while (jump_to?(cand_x, cand_y))
1083 grids.push([cand_x, cand_y])
1084 break if (! put_to?(cand_x, cand_y))
1091 while (jump_to?(cand_x, cand_y))
1092 grids.push([cand_x, cand_y])
1093 break if (! put_to?(cand_x, cand_y))
1100 while (jump_to?(cand_x, cand_y))
1101 grids.push([cand_x, cand_y])
1102 break if (! put_to?(cand_x, cand_y))
1109 class PieceHI < Piece
1110 def initialize(*arg)
1113 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1115 @promoted_name = "RY"
1118 def far_movable_grids
1123 while (jump_to?(cand_x, cand_y))
1124 grids.push([cand_x, cand_y])
1125 break if (! put_to?(cand_x, cand_y))
1131 while (jump_to?(cand_x, cand_y))
1132 grids.push([cand_x, cand_y])
1133 break if (! put_to?(cand_x, cand_y))
1139 while (jump_to?(cand_x, cand_y))
1140 grids.push([cand_x, cand_y])
1141 break if (! put_to?(cand_x, cand_y))
1147 while (jump_to?(cand_x, cand_y))
1148 grids.push([cand_x, cand_y])
1149 break if (! put_to?(cand_x, cand_y))
1155 class PieceOU < Piece
1156 def initialize(*arg)
1158 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1159 @promoted_moves = []
1161 @promoted_name = nil
1168 @sente_hands = Array::new
1169 @gote_hands = Array::new
1170 @history = Hash::new(0)
1171 @sente_history = Hash::new(0)
1172 @gote_history = Hash::new(0)
1173 @array = [[], [], [], [], [], [], [], [], [], []]
1176 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1177 attr_reader :move_count
1180 PieceKY::new(self, 1, 1, false)
1181 PieceKE::new(self, 2, 1, false)
1182 PieceGI::new(self, 3, 1, false)
1183 PieceKI::new(self, 4, 1, false)
1184 PieceOU::new(self, 5, 1, false)
1185 PieceKI::new(self, 6, 1, false)
1186 PieceGI::new(self, 7, 1, false)
1187 PieceKE::new(self, 8, 1, false)
1188 PieceKY::new(self, 9, 1, false)
1189 PieceKA::new(self, 2, 2, false)
1190 PieceHI::new(self, 8, 2, false)
1192 PieceFU::new(self, i, 3, false)
1195 PieceKY::new(self, 1, 9, true)
1196 PieceKE::new(self, 2, 9, true)
1197 PieceGI::new(self, 3, 9, true)
1198 PieceKI::new(self, 4, 9, true)
1199 PieceOU::new(self, 5, 9, true)
1200 PieceKI::new(self, 6, 9, true)
1201 PieceGI::new(self, 7, 9, true)
1202 PieceKE::new(self, 8, 9, true)
1203 PieceKY::new(self, 9, 9, true)
1204 PieceKA::new(self, 8, 8, true)
1205 PieceHI::new(self, 2, 8, true)
1207 PieceFU::new(self, i, 7, true)
1211 def have_piece?(hands, name)
1212 piece = hands.find { |i|
1218 def move_to(x0, y0, x1, y1, name, sente)
1220 hands = @sente_hands
1225 if ((x0 == 0) || (y0 == 0))
1226 piece = have_piece?(hands, name)
1227 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1228 piece.move_to(x1, y1)
1230 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1231 if (@array[x0][y0].name != name) # promoted ?
1232 @array[x0][y0].promoted = true
1234 if (@array[x1][y1]) # capture
1235 if (@array[x1][y1].name == "OU")
1236 return :outori # return board update
1238 @array[x1][y1].sente = @array[x0][y0].sente
1239 @array[x1][y1].move_to(0, 0)
1240 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1244 @array[x0][y0].move_to(x1, y1)
1250 def look_for_ou(sente)
1256 (@array[x][y].name == "OU") &&
1257 (@array[x][y].sente == sente))
1264 raise "can't find ou"
1267 # note checkmate, but check. sente is checked.
1268 def checkmated?(sente) # sente is loosing
1269 ou = look_for_ou(sente)
1275 (@array[x][y].sente != sente))
1276 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1287 def uchifuzume?(sente)
1288 rival_ou = look_for_ou(! sente) # rival's ou
1289 if (sente) # rival is gote
1290 if ((rival_ou.y != 9) &&
1291 (@array[rival_ou.x][rival_ou.y + 1]) &&
1292 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1293 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1295 fu_y = rival_ou.y + 1
1300 if ((rival_ou.y != 1) &&
1301 (@array[rival_ou.x][rival_ou.y - 1]) &&
1302 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1303 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1305 fu_y = rival_ou.y - 1
1311 ## case: rival_ou is moving
1312 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1313 tmp_board = Marshal.load(Marshal.dump(self))
1314 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1315 raise "internal error" if (s != true)
1316 if (! tmp_board.checkmated?(! sente)) # good move
1321 ## case: rival is capturing fu
1327 (@array[x][y].sente != sente) &&
1328 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1331 if (@array[x][y].promoted)
1332 names << @array[x][y].promoted_name
1334 names << @array[x][y].name
1335 if @array[x][y].promoted_name &&
1336 @array[x][y].move_to?(fu_x, fu_y, @array[x][y].promoted_name)
1337 names << @array[x][y].promoted_name
1340 names.map! do |name|
1341 tmp_board = Marshal.load(Marshal.dump(self))
1342 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1346 tmp_board.checkmated?(! sente) # result
1349 all_illegal = names.find {|a| a != :illegal}
1350 raise "internal error: legal move not found" if all_illegal == nil
1351 r = names.find {|a| a == false} # good move
1352 return false if r == false # found good move
1361 # @[sente|gote]_history has at least one item while the player is checking the other or
1362 # the other escapes.
1363 def update_sennichite(player)
1366 if checkmated?(!player)
1368 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
1370 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
1374 @sente_history.clear # no more continuous check
1376 @gote_history.clear # no more continuous check
1379 if @sente_history.size > 0 # possible for Sente's or Gote's turn
1380 @sente_history[str] += 1
1382 if @gote_history.size > 0 # possible for Sente's or Gote's turn
1383 @gote_history[str] += 1
1387 def oute_sennichite?(player)
1388 if (@sente_history[to_s] >= 4)
1389 return :oute_sennichite_sente_lose
1390 elsif (@gote_history[to_s] >= 4)
1391 return :oute_sennichite_gote_lose
1397 def sennichite?(sente)
1398 if (@history[to_s] >= 4) # already 3 times
1404 def good_kachi?(sente)
1405 if (checkmated?(sente))
1406 puts "'NG: Checkmating." if $DEBUG
1410 ou = look_for_ou(sente)
1411 if (sente && (ou.y >= 4))
1412 puts "'NG: Black's OU does not enter yet." if $DEBUG
1415 if (! sente && (ou.y <= 6))
1416 puts "'NG: White's OU does not enter yet." if $DEBUG
1424 hands = @sente_hands
1434 (@array[x][y].sente == sente) &&
1435 (@array[x][y].point > 0))
1436 point = point + @array[x][y].point
1442 hands.each do |piece|
1443 point = point + piece.point
1447 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1452 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1457 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1462 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1466 # sente is nil only if tests in test_board run
1467 def handle_one_move(str, sente=nil)
1468 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1475 elsif (str =~ /^%KACHI/)
1476 raise ArgumentError, "sente is null", caller if sente == nil
1477 if (good_kachi?(sente))
1482 elsif (str =~ /^%TORYO/)
1488 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1489 ((x0 != 0) || (y0 != 0)))
1491 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1497 sente = true if sente == nil # deprecated
1498 return :illegal unless sente == true # black player's move must be black
1499 hands = @sente_hands
1501 sente = false if sente == nil # deprecated
1502 return :illegal unless sente == false # white player's move must be white
1507 if ((x0 == 0) && (y0 == 0))
1508 return :illegal if (! have_piece?(hands, name))
1509 elsif (! @array[x0][y0])
1510 return :illegal # no piece
1511 elsif (@array[x0][y0].sente != sente)
1512 return :illegal # this is not mine
1513 elsif (@array[x0][y0].name != name)
1514 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1517 ## destination check
1518 if (@array[x1][y1] &&
1519 (@array[x1][y1].sente == sente)) # can't capture mine
1521 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1522 return :illegal # can't put on existing piece
1525 tmp_board = Marshal.load(Marshal.dump(self))
1526 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1527 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1528 tmp_board.update_sennichite(sente)
1529 os_result = tmp_board.oute_sennichite?(sente)
1530 return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
1531 return :sennichite if tmp_board.sennichite?(sente)
1533 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1537 move_to(x0, y0, x1, y1, name, sente)
1540 update_sennichite(sente)
1548 a.push(sprintf("P%d", y))
1551 piece = @array[x][y]
1560 a.push(sprintf("\n"))
1563 if (! sente_hands.empty?)
1565 sente_hands.each do |p|
1566 a.push("00" + p.name)
1570 if (! gote_hands.empty?)
1572 gote_hands.each do |p|
1573 a.push("00" + p.name)
1583 attr_reader :players, :black, :white
1585 def initialize(p1, p2)
1587 if p1.sente && !p2.sente
1588 @black, @white = p1, p2
1589 elsif !p1.sente && p2.sente
1590 @black, @white = p2, p1
1592 raise "Never reached!"
1597 class GameResultWin < GameResult
1598 attr_reader :winner, :loser
1600 def initialize(winner, loser)
1602 @winner, @loser = winner, loser
1603 @winner.last_game_win = true
1604 @loser.last_game_win = false
1608 black_name = @black.id || @black.name
1609 white_name = @white.id || @white.name
1610 "%s:%s" % [black_name, white_name]
1614 class GameResultDraw < GameResult
1615 def initialize(p1, p2)
1617 p1.last_game_win = false
1618 p2.last_game_win = false
1626 def initialize(game_name, player0, player1)
1627 @monitors = Array::new
1628 @game_name = game_name
1629 if (@game_name =~ /-(\d+)-(\d+)$/)
1630 @total_time = $1.to_i
1641 @current_player = @sente
1642 @next_player = @gote
1650 @sente.status = "agree_waiting"
1651 @gote.status = "agree_waiting"
1653 @id = sprintf("%s+%s+%s+%s+%s",
1654 LEAGUE.event, @game_name, @sente.name, @gote.name, issue_current_time)
1655 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1657 LEAGUE.games[@id] = self
1659 log_message(sprintf("game created %s", @id))
1669 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1670 attr_accessor :last_move, :current_turn
1674 @sente.rated? && @gote.rated?
1677 def monitoron(monitor)
1678 @monitors.delete(monitor)
1679 @monitors.push(monitor)
1682 def monitoroff(monitor)
1683 @monitors.delete(monitor)
1686 def reject(rejector)
1687 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1688 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1693 if ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
1695 elsif (@current_player == killer)
1702 log_message(sprintf("game finished %s", @id))
1703 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1708 @sente.status = "connected"
1709 @gote.status = "connected"
1711 if (@current_player.protocol == LoginCSA::PROTOCOL)
1712 @current_player.finish
1714 if (@next_player.protocol == LoginCSA::PROTOCOL)
1717 @monitors = Array::new
1720 @current_player = nil
1722 LEAGUE.games.delete(@id)
1725 def handle_one_move(str, player)
1727 if (@current_player == player)
1728 @end_time = Time::new
1729 t = (@end_time - @start_time).floor
1730 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
1733 if ((@current_player.mytime - t <= -@byoyomi) && ((@total_time > 0) || (@byoyomi > 0)))
1735 elsif (str == :timeout)
1736 return false # time isn't expired. players aren't swapped. continue game
1738 @current_player.mytime = @current_player.mytime - t
1739 if (@current_player.mytime < 0)
1740 @current_player.mytime = 0
1744 move_status = @board.handle_one_move(str, @sente == @current_player)
1746 # log_error("handle_one_move raise exception for #{str}")
1747 # move_status = :illegal
1750 if ((move_status == :illegal) || (move_status == :uchifuzme) || (move_status == :oute_kaihimore))
1751 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1753 if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite_sente_lose) || (move_status == :oute_sennichite_gote_lose))
1754 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1755 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1756 @fh.printf("%s\nT%d\n", str, t)
1757 @last_move = sprintf("%s,T%d", str, t)
1758 @current_turn = @current_turn + 1
1761 @monitors.each do |monitor|
1762 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1763 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1768 if (@next_player.status != "game") # rival is logout or disconnected
1770 elsif (status == :timeout)
1772 elsif (move_status == :illegal)
1774 elsif (move_status == :kachi_win)
1776 elsif (move_status == :kachi_lose)
1778 elsif (move_status == :toryo)
1780 elsif (move_status == :outori)
1782 elsif (move_status == :oute_sennichite_sente_lose)
1783 oute_sennichite_win_lose(@gote, @sente) # Sente is checking
1784 elsif (move_status == :oute_sennichite_gote_lose)
1785 oute_sennichite_win_lose(@sente, @gote) # Gote is checking
1786 elsif (move_status == :sennichite)
1788 elsif (move_status == :uchifuzume)
1790 elsif (move_status == :oute_kaihimore)
1791 oute_kaihimore_lose()
1795 finish() if finish_flag
1796 (@current_player, @next_player) = [@next_player, @current_player]
1797 @start_time = Time::new
1803 @current_player.status = "connected"
1804 @next_player.status = "connected"
1805 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1806 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1807 @fh.printf("%%TORYO\n")
1808 @fh.print(@board.to_s.gsub(/^/, "\'"))
1809 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1810 @result = GameResultWin.new(@current_player, @next_player)
1811 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1812 @monitors.each do |monitor|
1813 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1818 @current_player.status = "connected"
1819 @next_player.status = "connected"
1820 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1821 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1822 @fh.printf("%%TORYO\n")
1823 @fh.print(@board.to_s.gsub(/^/, "\'"))
1824 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1825 @result = GameResultWin.new(@next_player, @current_player)
1826 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1827 @monitors.each do |monitor|
1828 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1833 @current_player.status = "connected"
1834 @next_player.status = "connected"
1835 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1836 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1837 @fh.print(@board.to_s.gsub(/^/, "\'"))
1838 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1839 @result = GameResultDraw.new(@current_player, @next_player)
1840 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1841 @monitors.each do |monitor|
1842 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @id))
1846 def oute_sennichite_win_lose(winner, loser)
1847 @current_player.status = "connected"
1848 @next_player.status = "connected"
1849 loser.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1850 winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1851 @fh.print(@board.to_s.gsub(/^/, "\'"))
1852 if loser == @current_player
1853 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1855 @fh.printf("'summary:oute_sennichite:%s win:%s lose\n", @current_player.name, @next_player.name)
1857 @result = GameResultWin.new(winner, loser)
1858 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1859 @monitors.each do |monitor|
1860 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1865 @current_player.status = "connected"
1866 @next_player.status = "connected"
1867 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1868 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1869 @fh.print(@board.to_s.gsub(/^/, "\'"))
1870 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1871 @result = GameResultWin.new(@next_player, @current_player)
1872 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1873 @monitors.each do |monitor|
1874 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1879 @current_player.status = "connected"
1880 @next_player.status = "connected"
1881 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1882 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1883 @fh.print(@board.to_s.gsub(/^/, "\'"))
1884 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1885 @result = GameResultWin.new(@next_player, @current_player)
1886 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1887 @monitors.each do |monitor|
1888 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1892 def oute_kaihimore_lose
1893 @current_player.status = "connected"
1894 @next_player.status = "connected"
1895 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1896 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1897 @fh.print(@board.to_s.gsub(/^/, "\'"))
1898 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1899 @result = GameResultWin.new(@next_player, @current_player)
1900 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1901 @monitors.each do |monitor|
1902 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1907 @current_player.status = "connected"
1908 @next_player.status = "connected"
1909 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1910 @next_player.write_safe("#TIME_UP\n#WIN\n")
1911 @fh.print(@board.to_s.gsub(/^/, "\'"))
1912 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1913 @result = GameResultWin.new(@next_player, @current_player)
1914 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1915 @monitors.each do |monitor|
1916 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
1921 @current_player.status = "connected"
1922 @next_player.status = "connected"
1923 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1924 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1925 @fh.printf("%%KACHI\n")
1926 @fh.print(@board.to_s.gsub(/^/, "\'"))
1927 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1928 @result = GameResultWin.new(@current_player, @next_player)
1929 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1930 @monitors.each do |monitor|
1931 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1936 @current_player.status = "connected"
1937 @next_player.status = "connected"
1938 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1939 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1940 @fh.printf("%%KACHI\n")
1941 @fh.print(@board.to_s.gsub(/^/, "\'"))
1942 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1943 @result = GameResultWin.new(@next_player, @current_player)
1944 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1945 @monitors.each do |monitor|
1946 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1951 @current_player.status = "connected"
1952 @next_player.status = "connected"
1953 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1954 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1955 @fh.printf("%%TORYO\n")
1956 @fh.print(@board.to_s.gsub(/^/, "\'"))
1957 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1958 @result = GameResultWin.new(@next_player, @current_player)
1959 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1960 @monitors.each do |monitor|
1961 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1966 @current_player.status = "connected"
1967 @next_player.status = "connected"
1968 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1969 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1970 @fh.print(@board.to_s.gsub(/^/, "\'"))
1971 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1972 @result = GameResultWin.new(@current_player, @next_player)
1973 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1974 @monitors.each do |monitor|
1975 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1980 log_message(sprintf("game started %s", @id))
1981 @sente.write_safe(sprintf("START:%s\n", @id))
1982 @gote.write_safe(sprintf("START:%s\n", @id))
1983 @sente.mytime = @total_time
1984 @gote.mytime = @total_time
1985 @start_time = Time::new
1989 @fh = open(@logfile, "w")
1993 @fh.puts("N+#{@sente.name}")
1994 @fh.puts("N-#{@gote.name}")
1995 @fh.puts("$EVENT:#{@id}")
1997 @sente.write_safe(propose_message("+"))
1998 @gote.write_safe(propose_message("-"))
2000 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
2001 @fh.puts("$START_TIME:#{now}")
2003 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2004 P2 * -HI * * * * * -KA *
2005 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2006 P4 * * * * * * * * *
2007 P5 * * * * * * * * *
2008 P6 * * * * * * * * *
2009 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2010 P8 * +KA * * * * * +HI *
2011 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2019 Protocol_Version:1.1
2020 Protocol_Mode:Server
2022 Declaration:Jishogi 1.1
2024 Name+:#{@sente.name}
2030 Total_Time:#{@total_time}
2032 Least_Time_Per_Move:#{Least_Time_Per_Move}
2033 Remaining_Time+:#{@sente.mytime}
2034 Remaining_Time-:#{@gote.mytime}
2035 Last_Move:#{@last_move}
2036 Current_Turn:#{@current_turn}
2046 return str0 + @board.to_s + str1
2049 def propose_message(sg_flag)
2052 Protocol_Version:1.1
2053 Protocol_Mode:Server
2055 Declaration:Jishogi 1.1
2057 Name+:#{@sente.name}
2059 Your_Turn:#{sg_flag}
2064 Total_Time:#{@total_time}
2066 Least_Time_Per_Move:#{Least_Time_Per_Move}
2069 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2070 P2 * -HI * * * * * -KA *
2071 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2072 P4 * * * * * * * * *
2073 P5 * * * * * * * * *
2074 P6 * * * * * * * * *
2075 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2076 P8 * +KA * * * * * +HI *
2077 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2089 def issue_current_time
2090 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
2091 @@mutex.synchronize do
2092 while time <= @@time do
2099 end # module ShogiServer
2101 #################################################
2108 shogi-server - server for CSA server protocol
2111 shogi-server [OPTIONS] event_name port_number
2114 server for CSA server protocol
2118 specify filename for logging process ID
2120 run as a daemon. Log files will be put in dir.
2123 this file is distributed under GPL version2 and might be compiled by Exerb
2128 #{ShogiServer::Release}
2131 #{ShogiServer::Revision}
2139 def log_message(str)
2143 def log_warning(str)
2152 def parse_command_line
2154 parser = GetoptLong.new( ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2155 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT]
2159 parser.each_option do |name, arg|
2160 name.sub!(/^--/, '')
2161 options[name] = arg.dup
2165 raise parser.error_message
2170 def write_pid_file(file)
2171 open(file, "w") do |fh|
2176 def mutex_watchdog(mutex, sec)
2188 log_error("mutex watchdog timeout")
2199 mutex_watchdog($mutex, 10)
2202 $options = parse_command_line
2203 if (ARGV.length != 2)
2208 LEAGUE.event = ARGV.shift
2211 dir = $options["daemon"]
2212 dir = File.expand_path(dir) if dir
2213 if dir && ! File.exist?(dir)
2214 FileUtils.mkdir(dir)
2216 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2217 $logger = WEBrick::Log.new(log_file)
2219 LEAGUE.dir = dir || File.dirname(__FILE__)
2220 LEAGUE.setup_players_database
2223 config[:Port] = port
2224 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2225 config[:Logger] = $logger
2226 if $options["pid-file"]
2227 pid_file = File.expand_path($options["pid-file"])
2228 config[:StartCallback] = Proc.new do
2229 write_pid_file(pid_file)
2231 config[:StopCallback] = Proc.new do
2232 FileUtils.rm(pid_file, :force => true)
2236 server = WEBrick::GenericServer.new(config)
2237 ["INT", "TERM"].each do |signal|
2243 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2244 log_message("server started [Revision: #{ShogiServer::Revision}]")
2246 server.start do |client|
2247 # client.sync = true # this is already set in WEBrick
2248 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2249 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2252 while (str = client.gets_timeout(ShogiServer::Login_Time))
2257 if (ShogiServer::Login::good_login?(str))
2258 player = ShogiServer::Player::new(str, client)
2260 login = ShogiServer::Login::factory(str, player)
2261 if (LEAGUE.players[player.name])
2262 if ((LEAGUE.players[player.name].password == player.password) &&
2263 (LEAGUE.players[player.name].status != "game"))
2264 log_message(sprintf("user %s login forcely", player.name))
2265 LEAGUE.players[player.name].kill
2267 login.incorrect_duplicated_player(str)
2278 client.write_safe("LOGIN:incorrect" + eol)
2279 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2291 log_message(sprintf("user %s login", player.name))
2293 player.run(login.csa_1st_str)
2297 player.game.kill(player)
2299 player.finish # socket has been closed
2300 LEAGUE.delete(player)
2301 log_message(sprintf("user %s logout", player.name))
2312 TCPSocket.do_not_reverse_lookup = true
2313 Thread.abort_on_exception = false
2315 LEAGUE = ShogiServer::League::new