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)
52 rescue Exception => ex
53 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
66 return self.write(str)
74 module ShogiServer # for a namespace
76 Max_Write_Queue_Size = 1000
77 Max_Identifier_Length = 32
78 Default_Timeout = 60 # for single socket operation
80 Default_Game_Name = "default-1500-0"
83 Least_Time_Per_Move = 1
84 Login_Time = 300 # time for LOGIN
86 Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
87 Release.concat("-") if (Release == "")
88 Revision = "$Revision$".gsub(/[^\.\d]/, '')
95 return /^floodgate-\d+-\d+$/.match(str) ? true : false
99 def initialize(league)
106 @thread = Thread.new do
111 next if Time.now < @next_time
115 rescue Exception => ex
117 log_error("[in Floodgate's thread] #{ex}")
124 @thread.kill if @thread
132 @next_time = Time.mktime(now.year, now.month, now.day, now.hour, 30)
134 @next_time = Time.mktime(now.year, now.month, now.day, now.hour) + 3600
138 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min, 30)
140 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min) + 60
145 players = @league.find_all_players do |pl|
146 pl.status == "game_waiting" &&
147 Floodgate.game_name?(pl.game_name) &&
150 load File.join(File.dirname(__FILE__), "pairing.rb")
151 Pairing.default_pairing.match(players)
153 end # class Floodgate
156 @mutex = Mutex.new # guard @players
160 @dir = File.dirname(__FILE__)
161 @floodgate = Floodgate.new(self)
164 attr_accessor :players, :games, :event, :dir
167 @mutex.synchronize do
168 @players.each {|a| save(a)}
173 # this should be called just after instanciating a League object.
174 def setup_players_database
175 @db = YAML::Store.new(File.join(@dir, "players.yaml"))
179 self.load(player) if player.id
180 @mutex.synchronize do
181 @players[player.name] = player
186 @mutex.synchronize do
188 @players.delete(player.name)
193 @mutex.synchronize do
194 @players.each {|player| load(player)}
200 @mutex.synchronize do
201 found = @players.find_all do |name, player|
205 return found.map {|a| a.last}
208 def get_player(status, game_name, sente, searcher)
210 @mutex.synchronize do
211 found = @players.find do |name, player|
212 (player.status == status) &&
213 (player.game_name == game_name) &&
215 (player.sente == nil) ||
216 (player.sente == sente) ) &&
217 (player.name != searcher.name)
220 return found ? found.last : nil
224 hash = search(player.id)
228 player.name = hash['name']
229 player.rate = hash['rate'] || 0
230 player.modified_at = hash['last_modified']
231 player.rating_group = hash['rating_group']
232 player.win = hash['win'] || 0
233 player.loss = hash['loss'] || 0
234 player.last_game_win = hash['last_game_win'] || false
239 break unless @db["players"]
240 @db["players"].each do |group, players|
241 hash = players[player.id]
243 hash['last_game_win'] = player.last_game_win
252 @db.transaction(true) do
253 break unless @db["players"]
254 @db["players"].each do |group, players|
264 @db.transaction(true) do
265 break unless @db["players"]
266 @db["players"].each do |group, players_hash|
267 players << players_hash.keys
270 return players.flatten.collect do |id|
280 ######################################################
281 # Processes the LOGIN command.
284 def Login.good_login?(str)
286 if (((tokens.length == 3) || ((tokens.length == 4) && tokens[3] == "x1")) &&
287 (tokens[0] == "LOGIN") &&
288 (good_identifier?(tokens[1])))
295 def Login.good_game_name?(str)
296 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
303 def Login.good_identifier?(str)
304 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
311 def Login.factory(str, player)
312 (login, player.name, password, ext) = str.chomp.split
314 return Loginx1.new(player, password)
316 return LoginCSA.new(player, password)
322 # the first command that will be executed just after LOGIN.
323 # If it is nil, the default process will be started.
324 attr_reader :csa_1st_str
326 def initialize(player, password)
329 parse_password(password)
333 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
334 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
337 def incorrect_duplicated_player(str)
338 @player.write_safe("LOGIN:incorrect\n")
339 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
340 sleep 3 # wait for sending the above messages.
341 @player.name = "%s [duplicated]" % [@player.name]
346 ######################################################
347 # Processes LOGIN for the CSA standard mode.
349 class LoginCSA < Login
352 def initialize(player, password)
355 @player.protocol = PROTOCOL
358 def parse_password(password)
359 if Login.good_game_name?(password)
361 @player.set_password(nil)
362 elsif password.split(",").size > 1
363 @gamename, *trip = password.split(",")
364 @player.set_password(trip.join(","))
366 @player.set_password(password)
367 @gamename = Default_Game_Name
369 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
374 @csa_1st_str = "%%GAME #{@gamename} *"
378 ######################################################
379 # Processes LOGIN for the extented mode.
381 class Loginx1 < Login
384 def initialize(player, password)
386 @player.protocol = PROTOCOL
389 def parse_password(password)
390 @player.set_password(password)
395 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
405 @last_game_win = false
408 # Idetifier of the player in the rating system
414 # Password of the player, which does not include a trip
415 attr_accessor :password
417 # Score in the rating sysem
420 # Number of games for win and loss in the rating system
421 attr_accessor :win, :loss
423 # Group in the rating system
424 attr_accessor :rating_group
426 # Last timestamp when the rate was modified
427 attr_accessor :modified_at
429 # Whether win the previous game or not
430 attr_accessor :last_game_win
433 @modified_at || Time.now
439 @modified_at = Time.now
448 return @last_game_win
453 simple_name = @name.gsub(/@.*?$/, '')
454 "%s+%s" % [simple_name, @trip[0..8]]
461 # Parses str in the LOGIN command, sets up @id and @trip
463 def set_password(str)
464 if str && !str.empty?
465 @password = str.strip
466 @id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
468 @id = @password = nil
474 class Player < BasicPlayer
475 def initialize(str, socket)
478 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
480 @protocol = nil # CSA or x1
481 @eol = "\m" # favorite eol code
484 @mytime = 0 # set in start method also
486 @write_queue = Queue::new
487 @main_thread = Thread::current
488 @writer_thread = Thread::start do
494 attr_accessor :socket, :status
495 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
496 attr_accessor :main_thread, :writer_thread, :write_queue
499 log_message(sprintf("user %s killed", @name))
504 Thread::kill(@main_thread) if @main_thread
508 if (@status != "finished")
510 log_message(sprintf("user %s finish", @name))
511 # TODO you should confirm that there is no message in the queue.
512 Thread::kill(@writer_thread) if @writer_thread
514 # @socket.close if (! @socket.closed?)
516 log_message(sprintf("user %s finish failed", @name))
522 @write_queue.push(str.gsub(/[\r\n]+/, @eol))
526 while (str = @write_queue.pop)
529 rescue Exception => ex
530 log_error("Failed to send a message to #{@name}.")
531 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
538 if ((status == "game_waiting") ||
539 (status == "start_waiting") ||
540 (status == "agree_waiting") ||
543 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
544 elsif (@sente == false)
545 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
546 elsif (@sente == nil)
547 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
550 return sprintf("%s %s %s", @name, @protocol, @status)
554 def run(csa_1st_str=nil)
555 while (csa_1st_str || (str = @socket.gets_safe(Default_Timeout)))
559 if (@writer_thread == nil || @writer_thread.status == false)
560 # The writer_thread has been killed because of socket errors.
568 if (@write_queue.size > Max_Write_Queue_Size)
569 log_warning(sprintf("write_queue of %s is %d", @name, @write_queue.size))
573 if (@status == "finished")
576 str.chomp! if (str.class == String) # may be strip! ?
577 log_message(str) if $DEBUG
580 # Application-level protocol for Keep-Alive
581 # If the server gets LF, it sends back LF.
582 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
585 if (@status == "game")
586 array_str = str.split(",")
587 move = array_str.shift
588 additional = array_str.shift
589 if /^'(.*)/ =~ additional
590 comment = array_str.unshift("'*#{$1}")
592 s = @game.handle_one_move(move, self)
593 @game.fh.print("#{comment}\n") if (comment && !s)
594 return if (s && @protocol == LoginCSA::PROTOCOL)
596 when /^%[^%]/, :timeout
597 if (@status == "game")
598 s = @game.handle_one_move(str, self)
599 return if (s && @protocol == LoginCSA::PROTOCOL)
602 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
603 # rescue Exception => ex
604 # log_error("Failed to send a keepalive to #{@name}.")
605 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
610 log_error("Failed to receive a message from #{@name}.")
613 if (@status == "agree_waiting")
615 return if (@protocol == LoginCSA::PROTOCOL)
617 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
620 if (@status == "agree_waiting")
621 @status = "start_waiting"
622 if ((@game.sente.status == "start_waiting") &&
623 (@game.gote.status == "start_waiting"))
625 @game.sente.status = "game"
626 @game.gote.status = "game"
629 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
631 when /^%%SHOW\s+(\S+)/
633 if (LEAGUE.games[game_id])
634 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
636 write_safe("##[SHOW] +OK\n")
637 when /^%%MONITORON\s+(\S+)/
639 if (LEAGUE.games[game_id])
640 LEAGUE.games[game_id].monitoron(self)
641 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
642 write_safe("##[MONITOR][#{game_id}] +OK\n")
644 when /^%%MONITOROFF\s+(\S+)/
646 if (LEAGUE.games[game_id])
647 LEAGUE.games[game_id].monitoroff(self)
651 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
653 players = LEAGUE.rated_players
654 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
655 write_safe("##[RATING] %s \t %4d @%s\n" %
656 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
658 write_safe("##[RATING] +OK\n")
660 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
661 write_safe("##[VERSION] +OK\n")
663 if ((@status == "connected") || (@status == "game_waiting"))
664 @status = "connected"
667 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
669 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
673 if (! Login::good_game_name?(game_name))
674 write_safe(sprintf("##[ERROR] bad game name\n"))
676 elsif ((@status == "connected") || (@status == "game_waiting"))
679 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
684 if (League::Floodgate.game_name?(game_name))
685 if (my_sente_str != "*")
686 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n"), my_sente_str, game_name)
691 if (my_sente_str == "*")
692 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
693 elsif (my_sente_str == "+")
694 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
695 elsif (my_sente_str == "-")
696 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
699 write_safe(sprintf("##[ERROR] bad game option\n"))
705 @game_name = game_name
706 if ((my_sente_str == "*") && (rival.sente == nil))
714 elsif (rival.sente == true) # rival has higher priority
716 elsif (rival.sente == false)
718 elsif (my_sente_str == "+")
721 elsif (my_sente_str == "-")
727 Game::new(@game_name, self, rival)
728 else # rival not found
729 if (command_name == "GAME")
730 @status = "game_waiting"
731 @game_name = game_name
732 if (my_sente_str == "+")
734 elsif (my_sente_str == "-")
740 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
741 @status = "connected"
746 when /^%%CHAT\s+(.+)/
748 LEAGUE.players.each do |name, player|
749 if (player.protocol != LoginCSA::PROTOCOL)
750 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
755 LEAGUE.games.each do |id, game|
756 buf.push(sprintf("##[LIST] %s\n", id))
758 buf.push("##[LIST] +OK\n")
762 LEAGUE.players.each do |name, player|
763 buf.push(sprintf("##[WHO] %s\n", player.to_s))
765 buf.push("##[WHO] +OK\n")
768 @status = "connected"
769 write_safe("LOGOUT:completed\n")
772 # This command is only available for CSA's official testing server.
773 # So, this means nothing for this program.
774 write_safe("CHALLENGE ACCEPTED\n")
776 ## ignore null string
778 msg = "##[ERROR] unknown command %s\n" % [str]
790 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
791 def initialize(board, x, y, sente, promoted=false)
798 if ((x == 0) || (y == 0))
800 hands = board.sente_hands
802 hands = board.gote_hands
809 @board.array[x][y] = self
812 attr_accessor :promoted, :sente, :x, :y, :board
814 def room_of_head?(x, y, name)
819 return adjacent_movable_grids + far_movable_grids
822 def far_movable_grids
827 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
828 if ((@board.array[x][y] == nil) || # dst is empty
829 (@board.array[x][y].sente != @sente)) # dst is enemy
837 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
838 if (@board.array[x][y] == nil) # dst is empty?
845 def adjacent_movable_grids
848 moves = @promoted_moves
850 moves = @normal_moves
852 moves.each do |(dx, dy)|
859 if (jump_to?(cand_x, cand_y))
860 grids.push([cand_x, cand_y])
866 def move_to?(x, y, name)
867 return false if (! room_of_head?(x, y, name))
868 return false if ((name != @name) && (name != @promoted_name))
869 return false if (@promoted && (name != @promoted_name)) # can't un-promote
872 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
874 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
876 return false if ((6 >= @y) && (6 >= y) && (name != @name))
880 if ((@x == 0) || (@y == 0))
881 return jump_to?(x, y)
883 return movable_grids.include?([x, y])
888 if ((@x == 0) || (@y == 0))
890 @board.sente_hands.delete(self)
892 @board.gote_hands.delete(self)
894 @board.array[x][y] = self
895 elsif ((x == 0) || (y == 0))
896 @promoted = false # clear promoted flag before moving to hands
898 @board.sente_hands.push(self)
900 @board.gote_hands.push(self)
902 @board.array[@x][@y] = nil
904 @board.array[@x][@y] = nil
905 @board.array[x][y] = self
938 class PieceFU < Piece
941 @normal_moves = [[0, +1]]
942 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
944 @promoted_name = "TO"
947 def room_of_head?(x, y, name)
950 return false if (y == 1)
952 return false if (y == 9)
958 if ((iy != @y) && # not source position
959 @board.array[x][iy] &&
960 (@board.array[x][iy].sente == @sente) && # mine
961 (@board.array[x][iy].name == "FU") &&
962 (@board.array[x][iy].promoted == false))
972 class PieceKY < Piece
976 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
978 @promoted_name = "NY"
981 def room_of_head?(x, y, name)
984 return false if (y == 1)
986 return false if (y == 9)
991 def far_movable_grids
999 while (jump_to?(cand_x, cand_y))
1000 grids.push([cand_x, cand_y])
1001 break if (! put_to?(cand_x, cand_y))
1007 while (jump_to?(cand_x, cand_y))
1008 grids.push([cand_x, cand_y])
1009 break if (! put_to?(cand_x, cand_y))
1017 class PieceKE < Piece
1018 def initialize(*arg)
1020 @normal_moves = [[+1, +2], [-1, +2]]
1021 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1023 @promoted_name = "NK"
1026 def room_of_head?(x, y, name)
1029 return false if ((y == 1) || (y == 2))
1031 return false if ((y == 9) || (y == 8))
1037 class PieceGI < Piece
1038 def initialize(*arg)
1040 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1041 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1043 @promoted_name = "NG"
1047 class PieceKI < Piece
1048 def initialize(*arg)
1050 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1051 @promoted_moves = []
1053 @promoted_name = nil
1057 class PieceKA < Piece
1058 def initialize(*arg)
1061 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
1063 @promoted_name = "UM"
1066 def far_movable_grids
1071 while (jump_to?(cand_x, cand_y))
1072 grids.push([cand_x, cand_y])
1073 break if (! put_to?(cand_x, cand_y))
1080 while (jump_to?(cand_x, cand_y))
1081 grids.push([cand_x, cand_y])
1082 break if (! put_to?(cand_x, cand_y))
1089 while (jump_to?(cand_x, cand_y))
1090 grids.push([cand_x, cand_y])
1091 break if (! put_to?(cand_x, cand_y))
1098 while (jump_to?(cand_x, cand_y))
1099 grids.push([cand_x, cand_y])
1100 break if (! put_to?(cand_x, cand_y))
1107 class PieceHI < Piece
1108 def initialize(*arg)
1111 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1113 @promoted_name = "RY"
1116 def far_movable_grids
1121 while (jump_to?(cand_x, cand_y))
1122 grids.push([cand_x, cand_y])
1123 break if (! put_to?(cand_x, cand_y))
1129 while (jump_to?(cand_x, cand_y))
1130 grids.push([cand_x, cand_y])
1131 break if (! put_to?(cand_x, cand_y))
1137 while (jump_to?(cand_x, cand_y))
1138 grids.push([cand_x, cand_y])
1139 break if (! put_to?(cand_x, cand_y))
1145 while (jump_to?(cand_x, cand_y))
1146 grids.push([cand_x, cand_y])
1147 break if (! put_to?(cand_x, cand_y))
1153 class PieceOU < Piece
1154 def initialize(*arg)
1156 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1157 @promoted_moves = []
1159 @promoted_name = nil
1166 @sente_hands = Array::new
1167 @gote_hands = Array::new
1168 @history = Hash::new(0)
1169 @sente_history = Hash::new(0)
1170 @gote_history = Hash::new(0)
1171 @array = [[], [], [], [], [], [], [], [], [], []]
1174 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1175 attr_reader :move_count
1178 PieceKY::new(self, 1, 1, false)
1179 PieceKE::new(self, 2, 1, false)
1180 PieceGI::new(self, 3, 1, false)
1181 PieceKI::new(self, 4, 1, false)
1182 PieceOU::new(self, 5, 1, false)
1183 PieceKI::new(self, 6, 1, false)
1184 PieceGI::new(self, 7, 1, false)
1185 PieceKE::new(self, 8, 1, false)
1186 PieceKY::new(self, 9, 1, false)
1187 PieceKA::new(self, 2, 2, false)
1188 PieceHI::new(self, 8, 2, false)
1190 PieceFU::new(self, i, 3, false)
1193 PieceKY::new(self, 1, 9, true)
1194 PieceKE::new(self, 2, 9, true)
1195 PieceGI::new(self, 3, 9, true)
1196 PieceKI::new(self, 4, 9, true)
1197 PieceOU::new(self, 5, 9, true)
1198 PieceKI::new(self, 6, 9, true)
1199 PieceGI::new(self, 7, 9, true)
1200 PieceKE::new(self, 8, 9, true)
1201 PieceKY::new(self, 9, 9, true)
1202 PieceKA::new(self, 8, 8, true)
1203 PieceHI::new(self, 2, 8, true)
1205 PieceFU::new(self, i, 7, true)
1209 def have_piece?(hands, name)
1210 piece = hands.find { |i|
1216 def move_to(x0, y0, x1, y1, name, sente)
1218 hands = @sente_hands
1223 if ((x0 == 0) || (y0 == 0))
1224 piece = have_piece?(hands, name)
1225 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1226 piece.move_to(x1, y1)
1228 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1229 if (@array[x0][y0].name != name) # promoted ?
1230 @array[x0][y0].promoted = true
1232 if (@array[x1][y1]) # capture
1233 if (@array[x1][y1].name == "OU")
1234 return :outori # return board update
1236 @array[x1][y1].sente = @array[x0][y0].sente
1237 @array[x1][y1].move_to(0, 0)
1238 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1242 @array[x0][y0].move_to(x1, y1)
1248 def look_for_ou(sente)
1254 (@array[x][y].name == "OU") &&
1255 (@array[x][y].sente == sente))
1262 raise "can't find ou"
1265 # note checkmate, but check. sente is checked.
1266 def checkmated?(sente) # sente is loosing
1267 ou = look_for_ou(sente)
1273 (@array[x][y].sente != sente))
1274 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1285 def uchifuzume?(sente)
1286 rival_ou = look_for_ou(! sente) # rival's ou
1287 if (sente) # rival is gote
1288 if ((rival_ou.y != 9) &&
1289 (@array[rival_ou.x][rival_ou.y + 1]) &&
1290 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1291 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1293 fu_y = rival_ou.y + 1
1298 if ((rival_ou.y != 0) &&
1299 (@array[rival_ou.x][rival_ou.y - 1]) &&
1300 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1301 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1303 fu_y = rival_ou.y - 1
1309 ## case: rival_ou is moving
1311 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1312 tmp_board = Marshal.load(Marshal.dump(self))
1313 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1314 raise "internal error" if (s != true)
1315 if (! tmp_board.checkmated?(! sente)) # good move
1320 ## case: rival is capturing fu
1326 (@array[x][y].sente != sente) &&
1327 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1328 if (@array[x][y].promoted)
1329 name = @array[x][y].promoted_name
1331 name = @array[x][y].name
1333 tmp_board = Marshal.load(Marshal.dump(self))
1334 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1335 raise "internal error" if (s != true)
1336 if (! tmp_board.checkmated?(! sente)) # good move
1347 # @[sente|gote]_history has at least one item while the player is checking the other or
1348 # the other escapes.
1349 def update_sennichite(player)
1352 if checkmated?(!player)
1354 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
1356 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
1360 @sente_history.clear # no more continuous check
1362 @gote_history.clear # no more continuous check
1365 if @sente_history.size > 0 # possible for Sente's or Gote's turn
1366 @sente_history[str] += 1
1368 if @gote_history.size > 0 # possible for Sente's or Gote's turn
1369 @gote_history[str] += 1
1373 def oute_sennichite?(player)
1374 if (@sente_history[to_s] >= 4)
1375 return :oute_sennichite_sente_lose
1376 elsif (@gote_history[to_s] >= 4)
1377 return :oute_sennichite_gote_lose
1383 def sennichite?(sente)
1384 if (@history[to_s] >= 4) # already 3 times
1390 def good_kachi?(sente)
1391 if (checkmated?(sente))
1392 puts "'NG: Checkmating." if $DEBUG
1396 ou = look_for_ou(sente)
1397 if (sente && (ou.y >= 4))
1398 puts "'NG: Black's OU does not enter yet." if $DEBUG
1401 if (! sente && (ou.y <= 6))
1402 puts "'NG: White's OU does not enter yet." if $DEBUG
1410 hands = @sente_hands
1420 (@array[x][y].sente == sente) &&
1421 (@array[x][y].point > 0))
1422 point = point + @array[x][y].point
1428 hands.each do |piece|
1429 point = point + piece.point
1433 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1438 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1443 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1448 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1452 # sente is nil only if tests in test_board run
1453 def handle_one_move(str, sente=nil)
1454 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1461 elsif (str =~ /^%KACHI/)
1462 raise ArgumentError, "sente is null", caller if sente == nil
1463 if (good_kachi?(sente))
1468 elsif (str =~ /^%TORYO/)
1474 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1475 ((x0 != 0) || (y0 != 0)))
1477 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1483 sente = true if sente == nil # deprecated
1484 return :illegal unless sente == true # black player's move must be black
1485 hands = @sente_hands
1487 sente = false if sente == nil # deprecated
1488 return :illegal unless sente == false # white player's move must be white
1493 if ((x0 == 0) && (y0 == 0))
1494 return :illegal if (! have_piece?(hands, name))
1495 elsif (! @array[x0][y0])
1496 return :illegal # no piece
1497 elsif (@array[x0][y0].sente != sente)
1498 return :illegal # this is not mine
1499 elsif (@array[x0][y0].name != name)
1500 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1503 ## destination check
1504 if (@array[x1][y1] &&
1505 (@array[x1][y1].sente == sente)) # can't capture mine
1507 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1508 return :illegal # can't put on existing piece
1511 tmp_board = Marshal.load(Marshal.dump(self))
1512 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1513 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1514 tmp_board.update_sennichite(sente)
1515 os_result = tmp_board.oute_sennichite?(sente)
1516 return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
1517 return :sennichite if tmp_board.sennichite?(sente)
1519 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1523 move_to(x0, y0, x1, y1, name, sente)
1526 update_sennichite(sente)
1534 a.push(sprintf("P%d", y))
1537 piece = @array[x][y]
1546 a.push(sprintf("\n"))
1549 if (! sente_hands.empty?)
1551 sente_hands.each do |p|
1552 a.push("00" + p.name)
1556 if (! gote_hands.empty?)
1558 gote_hands.each do |p|
1559 a.push("00" + p.name)
1569 attr_reader :players, :black, :white
1571 def initialize(p1, p2)
1573 if p1.sente && !p2.sente
1574 @black, @white = p1, p2
1575 elsif !p1.sente && p2.sente
1576 @black, @white = p2, p1
1578 raise "Never reached!"
1583 class GameResultWin < GameResult
1584 attr_reader :winner, :loser
1586 def initialize(winner, loser)
1588 @winner, @loser = winner, loser
1589 @winner.last_game_win = true
1590 @loser.last_game_win = false
1594 black_name = @black.id || @black.name
1595 white_name = @white.id || @white.name
1596 "%s:%s" % [black_name, white_name]
1600 class GameResultDraw < GameResult
1601 def initialize(p1, p2)
1603 p1.last_game_win = false
1604 p2.last_game_win = false
1612 def initialize(game_name, player0, player1)
1613 @monitors = Array::new
1614 @game_name = game_name
1615 if (@game_name =~ /-(\d+)-(\d+)$/)
1616 @total_time = $1.to_i
1627 @current_player = @sente
1628 @next_player = @gote
1636 @sente.status = "agree_waiting"
1637 @gote.status = "agree_waiting"
1639 @id = sprintf("%s+%s+%s+%s+%s",
1640 LEAGUE.event, @game_name, @sente.name, @gote.name, issue_current_time)
1641 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1643 LEAGUE.games[@id] = self
1645 log_message(sprintf("game created %s", @id))
1655 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1656 attr_accessor :last_move, :current_turn
1660 @sente.rated? && @gote.rated?
1663 def monitoron(monitor)
1664 @monitors.delete(monitor)
1665 @monitors.push(monitor)
1668 def monitoroff(monitor)
1669 @monitors.delete(monitor)
1672 def reject(rejector)
1673 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1674 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1679 if ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
1681 elsif (@current_player == killer)
1688 log_message(sprintf("game finished %s", @id))
1689 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1694 @sente.status = "connected"
1695 @gote.status = "connected"
1697 if (@current_player.protocol == LoginCSA::PROTOCOL)
1698 @current_player.finish
1700 if (@next_player.protocol == LoginCSA::PROTOCOL)
1703 @monitors = Array::new
1706 @current_player = nil
1708 LEAGUE.games.delete(@id)
1711 def handle_one_move(str, player)
1713 if (@current_player == player)
1714 @end_time = Time::new
1715 t = (@end_time - @start_time).floor
1716 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
1719 if ((@current_player.mytime - t <= -@byoyomi) && ((@total_time > 0) || (@byoyomi > 0)))
1721 elsif (str == :timeout)
1722 return false # time isn't expired. players aren't swapped. continue game
1724 @current_player.mytime = @current_player.mytime - t
1725 if (@current_player.mytime < 0)
1726 @current_player.mytime = 0
1730 move_status = @board.handle_one_move(str, @sente == @current_player)
1732 # log_error("handle_one_move raise exception for #{str}")
1733 # move_status = :illegal
1736 if ((move_status == :illegal) || (move_status == :uchifuzme) || (move_status == :oute_kaihimore))
1737 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1739 if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite_sente_lose) || (move_status == :oute_sennichite_gote_lose))
1740 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1741 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1742 @fh.printf("%s\nT%d\n", str, t)
1743 @last_move = sprintf("%s,T%d", str, t)
1744 @current_turn = @current_turn + 1
1747 @monitors.each do |monitor|
1748 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1749 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1754 if (@next_player.status != "game") # rival is logout or disconnected
1756 elsif (status == :timeout)
1758 elsif (move_status == :illegal)
1760 elsif (move_status == :kachi_win)
1762 elsif (move_status == :kachi_lose)
1764 elsif (move_status == :toryo)
1766 elsif (move_status == :outori)
1768 elsif (move_status == :oute_sennichite_sente_lose)
1769 oute_sennichite_win_lose(@gote, @sente) # Sente is checking
1770 elsif (move_status == :oute_sennichite_gote_lose)
1771 oute_sennichite_win_lose(@sente, @gote) # Gote is checking
1772 elsif (move_status == :sennichite)
1774 elsif (move_status == :uchifuzume)
1776 elsif (move_status == :oute_kaihimore)
1777 oute_kaihimore_lose()
1781 finish() if finish_flag
1782 (@current_player, @next_player) = [@next_player, @current_player]
1783 @start_time = Time::new
1789 @current_player.status = "connected"
1790 @next_player.status = "connected"
1791 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1792 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1793 @fh.printf("%%TORYO\n")
1794 @fh.print(@board.to_s.gsub(/^/, "\'"))
1795 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1796 @result = GameResultWin.new(@current_player, @next_player)
1797 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1798 @monitors.each do |monitor|
1799 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1804 @current_player.status = "connected"
1805 @next_player.status = "connected"
1806 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1807 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1808 @fh.printf("%%TORYO\n")
1809 @fh.print(@board.to_s.gsub(/^/, "\'"))
1810 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1811 @result = GameResultWin.new(@next_player, @current_player)
1812 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1813 @monitors.each do |monitor|
1814 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1819 @current_player.status = "connected"
1820 @next_player.status = "connected"
1821 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1822 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1823 @fh.print(@board.to_s.gsub(/^/, "\'"))
1824 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1825 @result = GameResultDraw.new(@current_player, @next_player)
1826 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1827 @monitors.each do |monitor|
1828 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @id))
1832 def oute_sennichite_win_lose(winner, loser)
1833 @current_player.status = "connected"
1834 @next_player.status = "connected"
1835 loser.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1836 winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1837 @fh.print(@board.to_s.gsub(/^/, "\'"))
1838 if loser == @current_player
1839 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1841 @fh.printf("'summary:oute_sennichite:%s win:%s lose\n", @current_player.name, @next_player.name)
1843 @result = GameResultWin.new(winner, loser)
1844 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1845 @monitors.each do |monitor|
1846 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1851 @current_player.status = "connected"
1852 @next_player.status = "connected"
1853 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1854 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1855 @fh.print(@board.to_s.gsub(/^/, "\'"))
1856 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1857 @result = GameResultWin.new(@next_player, @current_player)
1858 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1859 @monitors.each do |monitor|
1860 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\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:uchifuzume:%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))
1878 def oute_kaihimore_lose
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:oute_kaihimore:%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))
1893 @current_player.status = "connected"
1894 @next_player.status = "connected"
1895 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1896 @next_player.write_safe("#TIME_UP\n#WIN\n")
1897 @fh.print(@board.to_s.gsub(/^/, "\'"))
1898 @fh.printf("'summary:time up:%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] #TIME_UP\n", @id))
1907 @current_player.status = "connected"
1908 @next_player.status = "connected"
1909 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1910 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1911 @fh.printf("%%KACHI\n")
1912 @fh.print(@board.to_s.gsub(/^/, "\'"))
1913 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1914 @result = GameResultWin.new(@current_player, @next_player)
1915 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1916 @monitors.each do |monitor|
1917 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1922 @current_player.status = "connected"
1923 @next_player.status = "connected"
1924 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1925 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1926 @fh.printf("%%KACHI\n")
1927 @fh.print(@board.to_s.gsub(/^/, "\'"))
1928 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1929 @result = GameResultWin.new(@next_player, @current_player)
1930 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1931 @monitors.each do |monitor|
1932 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1937 @current_player.status = "connected"
1938 @next_player.status = "connected"
1939 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1940 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1941 @fh.printf("%%TORYO\n")
1942 @fh.print(@board.to_s.gsub(/^/, "\'"))
1943 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1944 @result = GameResultWin.new(@next_player, @current_player)
1945 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1946 @monitors.each do |monitor|
1947 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1952 @current_player.status = "connected"
1953 @next_player.status = "connected"
1954 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1955 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1956 @fh.print(@board.to_s.gsub(/^/, "\'"))
1957 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1958 @result = GameResultWin.new(@current_player, @next_player)
1959 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1960 @monitors.each do |monitor|
1961 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1966 log_message(sprintf("game started %s", @id))
1967 @sente.write_safe(sprintf("START:%s\n", @id))
1968 @gote.write_safe(sprintf("START:%s\n", @id))
1969 @sente.mytime = @total_time
1970 @gote.mytime = @total_time
1971 @start_time = Time::new
1975 @fh = open(@logfile, "w")
1979 @fh.puts("N+#{@sente.name}")
1980 @fh.puts("N-#{@gote.name}")
1981 @fh.puts("$EVENT:#{@id}")
1983 @sente.write_safe(propose_message("+"))
1984 @gote.write_safe(propose_message("-"))
1986 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
1987 @fh.puts("$START_TIME:#{now}")
1989 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1990 P2 * -HI * * * * * -KA *
1991 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1992 P4 * * * * * * * * *
1993 P5 * * * * * * * * *
1994 P6 * * * * * * * * *
1995 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1996 P8 * +KA * * * * * +HI *
1997 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2005 Protocol_Version:1.1
2006 Protocol_Mode:Server
2008 Declaration:Jishogi 1.1
2010 Name+:#{@sente.name}
2016 Total_Time:#{@total_time}
2018 Least_Time_Per_Move:#{Least_Time_Per_Move}
2019 Remaining_Time+:#{@sente.mytime}
2020 Remaining_Time-:#{@gote.mytime}
2021 Last_Move:#{@last_move}
2022 Current_Turn:#{@current_turn}
2032 return str0 + @board.to_s + str1
2035 def propose_message(sg_flag)
2038 Protocol_Version:1.1
2039 Protocol_Mode:Server
2041 Declaration:Jishogi 1.1
2043 Name+:#{@sente.name}
2045 Your_Turn:#{sg_flag}
2050 Total_Time:#{@total_time}
2052 Least_Time_Per_Move:#{Least_Time_Per_Move}
2055 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2056 P2 * -HI * * * * * -KA *
2057 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2058 P4 * * * * * * * * *
2059 P5 * * * * * * * * *
2060 P6 * * * * * * * * *
2061 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2062 P8 * +KA * * * * * +HI *
2063 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2075 def issue_current_time
2076 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
2077 @@mutex.synchronize do
2078 while time <= @@time do
2085 end # module ShogiServer
2087 #################################################
2094 shogi-server - server for CSA server protocol
2097 shogi-server [OPTIONS] event_name port_number
2100 server for CSA server protocol
2104 specify filename for logging process ID
2106 run as a daemon. Log files will be put in dir.
2109 this file is distributed under GPL version2 and might be compiled by Exerb
2114 #{ShogiServer::Release}
2117 #{ShogiServer::Revision}
2125 def log_message(str)
2129 def log_warning(str)
2138 def parse_command_line
2140 parser = GetoptLong.new( ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2141 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT]
2145 parser.each_option do |name, arg|
2146 name.sub!(/^--/, '')
2147 options[name] = arg.dup
2151 raise parser.error_message
2156 def write_pid_file(file)
2157 open(file, "w") do |fh|
2162 def mutex_watchdog(mutex, sec)
2174 log_error("mutex watchdog timeout")
2185 mutex_watchdog($mutex, 10)
2188 $options = parse_command_line
2189 if (ARGV.length != 2)
2194 LEAGUE.event = ARGV.shift
2197 dir = $options["daemon"]
2198 dir = File.expand_path(dir) if dir
2199 if dir && ! File.exist?(dir)
2200 FileUtils.mkdir(dir)
2202 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2203 $logger = WEBrick::Log.new(log_file)
2205 LEAGUE.dir = dir || File.dirname(__FILE__)
2206 LEAGUE.setup_players_database
2209 config[:Port] = port
2210 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2211 config[:Logger] = $logger
2212 if $options["pid-file"]
2213 pid_file = File.expand_path($options["pid-file"])
2214 config[:StartCallback] = Proc.new do
2215 write_pid_file(pid_file)
2217 config[:StopCallback] = Proc.new do
2218 FileUtils.rm(pid_file, :force => true)
2222 server = WEBrick::GenericServer.new(config)
2223 ["INT", "TERM"].each do |signal|
2229 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2230 log_message("server started [Revision: #{ShogiServer::Revision}]")
2232 server.start do |client|
2233 # client.sync = true # this is already set in WEBrick
2234 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2235 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2238 while (str = client.gets_timeout(ShogiServer::Login_Time))
2243 if (ShogiServer::Login::good_login?(str))
2244 player = ShogiServer::Player::new(str, client)
2246 login = ShogiServer::Login::factory(str, player)
2247 if (LEAGUE.players[player.name])
2248 if ((LEAGUE.players[player.name].password == player.password) &&
2249 (LEAGUE.players[player.name].status != "game"))
2250 log_message(sprintf("user %s login forcely", player.name))
2251 LEAGUE.players[player.name].kill
2253 login.incorrect_duplicated_player(str)
2264 client.write_safe("LOGIN:incorrect" + eol)
2265 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2277 log_message(sprintf("user %s login", player.name))
2279 player.run(login.csa_1st_str)
2283 player.game.kill(player)
2285 player.finish # socket has been closed
2286 LEAGUE.delete(player)
2287 log_message(sprintf("user %s logout", player.name))
2298 TCPSocket.do_not_reverse_lookup = true
2299 Thread.abort_on_exception = true
2301 LEAGUE = ShogiServer::League::new