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]/, '')
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
115 rescue Exception => ex
117 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 random_match(players)
155 def random_match(players)
157 log_message("Floodgate: too few players [%d]" % [players.size])
160 log_message("Floodgate: found %d players. Making games..." % [players.size])
161 random_players = players.sort{ rand < 0.5 ? 1 : -1 }
162 pairs = [[random_players.shift]]
163 while !random_players.empty? do
164 if pairs.last.size < 2
165 pairs.last << random_players.shift
167 pairs << [random_players.shift]
170 if pairs.last.size < 2
174 start_game(pair.first, pair.last)
178 def start_game(p1, p2)
181 Game.new(p1.game_name, p1, p2)
183 end # class Floodgate
186 @mutex = Mutex.new # guard @players
190 @dir = File.dirname(__FILE__)
191 @floodgate = Floodgate.new(self)
194 attr_accessor :players, :games, :event, :dir
200 # this should be called just after instanciating a League object.
201 def setup_players_database
202 @db = YAML::Store.new(File.join(@dir, "players.yaml"))
206 self.load(player) if player.id
207 @mutex.synchronize do
208 @players[player.name] = player
213 @mutex.synchronize do
214 @players.delete(player.name)
220 @mutex.synchronize do
221 found = @players.find_all do |name, player|
225 return found.map {|a| a.last}
228 def get_player(status, game_name, sente, searcher)
230 @mutex.synchronize do
231 found = @players.find do |name, player|
232 (player.status == status) &&
233 (player.game_name == game_name) &&
235 (player.sente == nil) ||
236 (player.sente == sente) ) &&
237 (player.name != searcher.name)
240 return found ? found.last : nil
244 hash = search(player.id)
247 player.name = hash['name']
248 player.rate = hash['rate']
249 player.modified_at = hash['last_modified']
250 player.rating_group = hash['rating_group']
257 break unless @db["players"]
258 @db["players"].each do |group, players|
268 @db.transaction(true) do
269 break unless @db["players"]
270 @db["players"].each do |group, players_hash|
271 players << players_hash.keys
274 return players.flatten.collect do |id|
284 ######################################################
285 # Processes the LOGIN command.
288 def Login.good_login?(str)
290 if (((tokens.length == 3) || ((tokens.length == 4) && tokens[3] == "x1")) &&
291 (tokens[0] == "LOGIN") &&
292 (good_identifier?(tokens[1])))
299 def Login.good_game_name?(str)
300 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
307 def Login.good_identifier?(str)
308 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
315 def Login.factory(str, player)
316 (login, player.name, password, ext) = str.chomp.split
318 return Loginx1.new(player, password)
320 return LoginCSA.new(player, password)
326 # the first command that will be executed just after LOGIN.
327 # If it is nil, the default process will be started.
328 attr_reader :csa_1st_str
330 def initialize(player, password)
333 parse_password(password)
337 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
338 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
341 def incorrect_duplicated_player(str)
342 @player.write_safe("LOGIN:incorrect\n")
343 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
344 sleep 3 # wait for sending the above messages.
345 @player.name = "%s [duplicated]" % [@player.name]
350 ######################################################
351 # Processes LOGIN for the CSA standard mode.
353 class LoginCSA < Login
356 def initialize(player, password)
359 @player.protocol = PROTOCOL
362 def parse_password(password)
363 if Login.good_game_name?(password)
365 @player.set_password(nil)
366 elsif password.split(",").size > 1
367 @gamename, *trip = password.split(",")
368 @player.set_password(trip.join(","))
370 @player.set_password(password)
371 @gamename = Default_Game_Name
373 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
378 @csa_1st_str = "%%GAME #{@gamename} *"
382 ######################################################
383 # Processes LOGIN for the extented mode.
385 class Loginx1 < Login
388 def initialize(player, password)
390 @player.protocol = PROTOCOL
393 def parse_password(password)
394 @player.set_password(password)
399 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
405 # Idetifier of the player in the rating system
411 # Password of the player, which does not include a trip
412 attr_accessor :password
414 # Score in the rating sysem
417 # Group in the rating system
418 attr_accessor :rating_group
420 # Last timestamp when the rate was modified
421 attr_accessor :modified_at
429 @modified_at || Time.now
435 @modified_at = Time.now
445 simple_name = @name.gsub(/@.*?$/, '')
446 "%s+%s" % [simple_name, @trip[0..8]]
453 # Parses str in the LOGIN command, sets up @id and @trip
455 def set_password(str)
456 if str && !str.empty?
457 @password = str.strip
458 @id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
460 @id = @password = nil
466 class Player < BasicPlayer
467 def initialize(str, socket)
470 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
472 @protocol = nil # CSA or x1
473 @eol = "\m" # favorite eol code
476 @mytime = 0 # set in start method also
478 @write_queue = Queue::new
479 @main_thread = Thread::current
480 @writer_thread = Thread::start do
486 attr_accessor :socket, :status
487 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
488 attr_accessor :main_thread, :writer_thread, :write_queue
491 log_message(sprintf("user %s killed", @name))
496 Thread::kill(@main_thread) if @main_thread
500 if (@status != "finished")
502 log_message(sprintf("user %s finish", @name))
503 # TODO you should confirm that there is no message in the queue.
504 Thread::kill(@writer_thread) if @writer_thread
506 # @socket.close if (! @socket.closed?)
508 log_message(sprintf("user %s finish failed", @name))
514 @write_queue.push(str.gsub(/[\r\n]+/, @eol))
518 while (str = @write_queue.pop)
521 rescue Exception => ex
522 log_error("Failed to send a message to #{@name}.")
523 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
530 if ((status == "game_waiting") ||
531 (status == "start_waiting") ||
532 (status == "agree_waiting") ||
535 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
536 elsif (@sente == false)
537 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
538 elsif (@sente == nil)
539 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
542 return sprintf("%s %s %s", @name, @protocol, @status)
546 def run(csa_1st_str=nil)
547 while (csa_1st_str || (str = @socket.gets_safe(Default_Timeout)))
551 if (@writer_thread == nil || @writer_thread.status == false)
552 # The writer_thread has been killed because of socket errors.
560 if (@write_queue.size > Max_Write_Queue_Size)
561 log_warning(sprintf("write_queue of %s is %d", @name, @write_queue.size))
565 if (@status == "finished")
568 str.chomp! if (str.class == String) # may be strip! ?
569 log_message(str) if $DEBUG
572 # Application-level protocol for Keep-Alive
573 # If the server gets LF, it sends back LF.
574 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
577 if (@status == "game")
578 array_str = str.split(",")
579 move = array_str.shift
580 additional = array_str.shift
581 if /^'(.*)/ =~ additional
582 comment = array_str.unshift("'*#{$1}")
584 s = @game.handle_one_move(move, self)
585 @game.fh.print("#{comment}\n") if (comment && !s)
586 return if (s && @protocol == LoginCSA::PROTOCOL)
588 when /^%[^%]/, :timeout
589 if (@status == "game")
590 s = @game.handle_one_move(str, self)
591 return if (s && @protocol == LoginCSA::PROTOCOL)
594 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
595 # rescue Exception => ex
596 # log_error("Failed to send a keepalive to #{@name}.")
597 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
602 log_error("Failed to receive a message from #{@name}.")
605 if (@status == "agree_waiting")
607 return if (@protocol == LoginCSA::PROTOCOL)
609 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
612 if (@status == "agree_waiting")
613 @status = "start_waiting"
614 if ((@game.sente.status == "start_waiting") &&
615 (@game.gote.status == "start_waiting"))
617 @game.sente.status = "game"
618 @game.gote.status = "game"
621 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
623 when /^%%SHOW\s+(\S+)/
625 if (LEAGUE.games[game_id])
626 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
628 write_safe("##[SHOW] +OK\n")
629 when /^%%MONITORON\s+(\S+)/
631 if (LEAGUE.games[game_id])
632 LEAGUE.games[game_id].monitoron(self)
633 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
634 write_safe("##[MONITOR][#{game_id}] +OK\n")
636 when /^%%MONITOROFF\s+(\S+)/
638 if (LEAGUE.games[game_id])
639 LEAGUE.games[game_id].monitoroff(self)
643 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
645 players = LEAGUE.rated_players
646 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
647 write_safe("##[RATING] %s \t %4d @%s\n" %
648 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
650 write_safe("##[RATING] +OK\n")
652 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
653 write_safe("##[VERSION] +OK\n")
655 if ((@status == "connected") || (@status == "game_waiting"))
656 @status = "connected"
659 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
661 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
665 if (! Login::good_game_name?(game_name))
666 write_safe(sprintf("##[ERROR] bad game name\n"))
668 elsif ((@status == "connected") || (@status == "game_waiting"))
671 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
676 if (League::Floodgate.game_name?(game_name))
677 if (my_sente_str != "*")
678 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n"), my_sente_str, game_name)
683 if (my_sente_str == "*")
684 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
685 elsif (my_sente_str == "+")
686 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
687 elsif (my_sente_str == "-")
688 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
691 write_safe(sprintf("##[ERROR] bad game option\n"))
697 @game_name = game_name
698 if ((my_sente_str == "*") && (rival.sente == nil))
706 elsif (rival.sente == true) # rival has higher priority
708 elsif (rival.sente == false)
710 elsif (my_sente_str == "+")
713 elsif (my_sente_str == "-")
719 Game::new(@game_name, self, rival)
720 else # rival not found
721 if (command_name == "GAME")
722 @status = "game_waiting"
723 @game_name = game_name
724 if (my_sente_str == "+")
726 elsif (my_sente_str == "-")
732 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
733 @status = "connected"
738 when /^%%CHAT\s+(.+)/
740 LEAGUE.players.each do |name, player|
741 if (player.protocol != LoginCSA::PROTOCOL)
742 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
747 LEAGUE.games.each do |id, game|
748 buf.push(sprintf("##[LIST] %s\n", id))
750 buf.push("##[LIST] +OK\n")
754 LEAGUE.players.each do |name, player|
755 buf.push(sprintf("##[WHO] %s\n", player.to_s))
757 buf.push("##[WHO] +OK\n")
760 @status = "connected"
761 write_safe("LOGOUT:completed\n")
764 # This command is only available for CSA's official testing server.
765 # So, this means nothing for this program.
766 write_safe("CHALLENGE ACCEPTED\n")
768 ## ignore null string
770 msg = "##[ERROR] unknown command %s\n" % [str]
782 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
783 def initialize(board, x, y, sente, promoted=false)
790 if ((x == 0) || (y == 0))
792 hands = board.sente_hands
794 hands = board.gote_hands
801 @board.array[x][y] = self
804 attr_accessor :promoted, :sente, :x, :y, :board
806 def room_of_head?(x, y, name)
811 return adjacent_movable_grids + far_movable_grids
814 def far_movable_grids
819 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
820 if ((@board.array[x][y] == nil) || # dst is empty
821 (@board.array[x][y].sente != @sente)) # dst is enemy
829 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
830 if (@board.array[x][y] == nil) # dst is empty?
837 def adjacent_movable_grids
840 moves = @promoted_moves
842 moves = @normal_moves
844 moves.each do |(dx, dy)|
851 if (jump_to?(cand_x, cand_y))
852 grids.push([cand_x, cand_y])
858 def move_to?(x, y, name)
859 return false if (! room_of_head?(x, y, name))
860 return false if ((name != @name) && (name != @promoted_name))
861 return false if (@promoted && (name != @promoted_name)) # can't un-promote
864 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
866 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
868 return false if ((6 >= @y) && (6 >= y) && (name != @name))
872 if ((@x == 0) || (@y == 0))
873 return jump_to?(x, y)
875 return movable_grids.include?([x, y])
880 if ((@x == 0) || (@y == 0))
882 @board.sente_hands.delete(self)
884 @board.gote_hands.delete(self)
886 @board.array[x][y] = self
887 elsif ((x == 0) || (y == 0))
888 @promoted = false # clear promoted flag before moving to hands
890 @board.sente_hands.push(self)
892 @board.gote_hands.push(self)
894 @board.array[@x][@y] = nil
896 @board.array[@x][@y] = nil
897 @board.array[x][y] = self
930 class PieceFU < Piece
933 @normal_moves = [[0, +1]]
934 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
936 @promoted_name = "TO"
939 def room_of_head?(x, y, name)
942 return false if (y == 1)
944 return false if (y == 9)
950 if ((iy != @y) && # not source position
951 @board.array[x][iy] &&
952 (@board.array[x][iy].sente == @sente) && # mine
953 (@board.array[x][iy].name == "FU") &&
954 (@board.array[x][iy].promoted == false))
964 class PieceKY < Piece
968 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
970 @promoted_name = "NY"
973 def room_of_head?(x, y, name)
976 return false if (y == 1)
978 return false if (y == 9)
983 def far_movable_grids
991 while (jump_to?(cand_x, cand_y))
992 grids.push([cand_x, cand_y])
993 break if (! put_to?(cand_x, cand_y))
999 while (jump_to?(cand_x, cand_y))
1000 grids.push([cand_x, cand_y])
1001 break if (! put_to?(cand_x, cand_y))
1009 class PieceKE < Piece
1010 def initialize(*arg)
1012 @normal_moves = [[+1, +2], [-1, +2]]
1013 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1015 @promoted_name = "NK"
1018 def room_of_head?(x, y, name)
1021 return false if ((y == 1) || (y == 2))
1023 return false if ((y == 9) || (y == 8))
1029 class PieceGI < Piece
1030 def initialize(*arg)
1032 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1033 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1035 @promoted_name = "NG"
1039 class PieceKI < Piece
1040 def initialize(*arg)
1042 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1043 @promoted_moves = []
1045 @promoted_name = nil
1049 class PieceKA < Piece
1050 def initialize(*arg)
1053 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
1055 @promoted_name = "UM"
1058 def far_movable_grids
1063 while (jump_to?(cand_x, cand_y))
1064 grids.push([cand_x, cand_y])
1065 break if (! put_to?(cand_x, cand_y))
1072 while (jump_to?(cand_x, cand_y))
1073 grids.push([cand_x, cand_y])
1074 break if (! put_to?(cand_x, cand_y))
1081 while (jump_to?(cand_x, cand_y))
1082 grids.push([cand_x, cand_y])
1083 break if (! put_to?(cand_x, cand_y))
1090 while (jump_to?(cand_x, cand_y))
1091 grids.push([cand_x, cand_y])
1092 break if (! put_to?(cand_x, cand_y))
1099 class PieceHI < Piece
1100 def initialize(*arg)
1103 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1105 @promoted_name = "RY"
1108 def far_movable_grids
1113 while (jump_to?(cand_x, cand_y))
1114 grids.push([cand_x, cand_y])
1115 break if (! put_to?(cand_x, cand_y))
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 class PieceOU < Piece
1146 def initialize(*arg)
1148 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1149 @promoted_moves = []
1151 @promoted_name = nil
1158 @sente_hands = Array::new
1159 @gote_hands = Array::new
1160 @history = Hash::new(0)
1161 @sente_history = Hash::new(0)
1162 @gote_history = Hash::new(0)
1163 @array = [[], [], [], [], [], [], [], [], [], []]
1166 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1167 attr_reader :move_count
1170 PieceKY::new(self, 1, 1, false)
1171 PieceKE::new(self, 2, 1, false)
1172 PieceGI::new(self, 3, 1, false)
1173 PieceKI::new(self, 4, 1, false)
1174 PieceOU::new(self, 5, 1, false)
1175 PieceKI::new(self, 6, 1, false)
1176 PieceGI::new(self, 7, 1, false)
1177 PieceKE::new(self, 8, 1, false)
1178 PieceKY::new(self, 9, 1, false)
1179 PieceKA::new(self, 2, 2, false)
1180 PieceHI::new(self, 8, 2, false)
1182 PieceFU::new(self, i, 3, false)
1185 PieceKY::new(self, 1, 9, true)
1186 PieceKE::new(self, 2, 9, true)
1187 PieceGI::new(self, 3, 9, true)
1188 PieceKI::new(self, 4, 9, true)
1189 PieceOU::new(self, 5, 9, true)
1190 PieceKI::new(self, 6, 9, true)
1191 PieceGI::new(self, 7, 9, true)
1192 PieceKE::new(self, 8, 9, true)
1193 PieceKY::new(self, 9, 9, true)
1194 PieceKA::new(self, 8, 8, true)
1195 PieceHI::new(self, 2, 8, true)
1197 PieceFU::new(self, i, 7, true)
1201 def have_piece?(hands, name)
1202 piece = hands.find { |i|
1208 def move_to(x0, y0, x1, y1, name, sente)
1210 hands = @sente_hands
1215 if ((x0 == 0) || (y0 == 0))
1216 piece = have_piece?(hands, name)
1217 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1218 piece.move_to(x1, y1)
1220 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1221 if (@array[x0][y0].name != name) # promoted ?
1222 @array[x0][y0].promoted = true
1224 if (@array[x1][y1]) # capture
1225 if (@array[x1][y1].name == "OU")
1226 return :outori # return board update
1228 @array[x1][y1].sente = @array[x0][y0].sente
1229 @array[x1][y1].move_to(0, 0)
1230 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1234 @array[x0][y0].move_to(x1, y1)
1240 def look_for_ou(sente)
1246 (@array[x][y].name == "OU") &&
1247 (@array[x][y].sente == sente))
1254 raise "can't find ou"
1257 # note checkmate, but check. sente is checked.
1258 def checkmated?(sente) # sente is loosing
1259 ou = look_for_ou(sente)
1265 (@array[x][y].sente != sente))
1266 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1277 def uchifuzume?(sente)
1278 rival_ou = look_for_ou(! sente) # rival's ou
1279 if (sente) # rival is gote
1280 if ((rival_ou.y != 9) &&
1281 (@array[rival_ou.x][rival_ou.y + 1]) &&
1282 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1283 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1285 fu_y = rival_ou.y + 1
1290 if ((rival_ou.y != 0) &&
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
1301 ## case: rival_ou is moving
1303 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1304 tmp_board = Marshal.load(Marshal.dump(self))
1305 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1306 raise "internal error" if (s != true)
1307 if (! tmp_board.checkmated?(! sente)) # good move
1312 ## case: rival is capturing fu
1318 (@array[x][y].sente != sente) &&
1319 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1320 if (@array[x][y].promoted)
1321 name = @array[x][y].promoted_name
1323 name = @array[x][y].name
1325 tmp_board = Marshal.load(Marshal.dump(self))
1326 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1327 raise "internal error" if (s != true)
1328 if (! tmp_board.checkmated?(! sente)) # good move
1339 # @[sente|gote]_history has at least one item while the player is checking the other or
1340 # the other escapes.
1341 def update_sennichite(player)
1344 if checkmated?(!player)
1346 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
1348 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
1352 @sente_history.clear # no more continuous check
1354 @gote_history.clear # no more continuous check
1357 if @sente_history.size > 0 # possible for Sente's or Gote's turn
1358 @sente_history[str] += 1
1360 if @gote_history.size > 0 # possible for Sente's or Gote's turn
1361 @gote_history[str] += 1
1365 def oute_sennichite?(player)
1366 if (@sente_history[to_s] >= 4)
1367 return :oute_sennichite_sente_lose
1368 elsif (@gote_history[to_s] >= 4)
1369 return :oute_sennichite_gote_lose
1375 def sennichite?(sente)
1376 if (@history[to_s] >= 4) # already 3 times
1382 def good_kachi?(sente)
1383 if (checkmated?(sente))
1384 puts "'NG: Checkmating." if $DEBUG
1388 ou = look_for_ou(sente)
1389 if (sente && (ou.y >= 4))
1390 puts "'NG: Black's OU does not enter yet." if $DEBUG
1393 if (! sente && (ou.y <= 6))
1394 puts "'NG: White's OU does not enter yet." if $DEBUG
1402 hands = @sente_hands
1412 (@array[x][y].sente == sente) &&
1413 (@array[x][y].point > 0))
1414 point = point + @array[x][y].point
1420 hands.each do |piece|
1421 point = point + piece.point
1425 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1430 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1435 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1440 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1444 # sente is nil only if tests in test_board run
1445 def handle_one_move(str, sente=nil)
1446 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1453 elsif (str =~ /^%KACHI/)
1454 raise ArgumentError, "sente is null", caller if sente == nil
1455 if (good_kachi?(sente))
1460 elsif (str =~ /^%TORYO/)
1466 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1467 ((x0 != 0) || (y0 != 0)))
1469 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1475 sente = true if sente == nil # deprecated
1476 return :illegal unless sente == true # black player's move must be black
1477 hands = @sente_hands
1479 sente = false if sente == nil # deprecated
1480 return :illegal unless sente == false # white player's move must be white
1485 if ((x0 == 0) && (y0 == 0))
1486 return :illegal if (! have_piece?(hands, name))
1487 elsif (! @array[x0][y0])
1488 return :illegal # no piece
1489 elsif (@array[x0][y0].sente != sente)
1490 return :illegal # this is not mine
1491 elsif (@array[x0][y0].name != name)
1492 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1495 ## destination check
1496 if (@array[x1][y1] &&
1497 (@array[x1][y1].sente == sente)) # can't capture mine
1499 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1500 return :illegal # can't put on existing piece
1503 tmp_board = Marshal.load(Marshal.dump(self))
1504 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1505 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1506 tmp_board.update_sennichite(sente)
1507 os_result = tmp_board.oute_sennichite?(sente)
1508 return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
1509 return :sennichite if tmp_board.sennichite?(sente)
1511 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1515 move_to(x0, y0, x1, y1, name, sente)
1518 update_sennichite(sente)
1526 a.push(sprintf("P%d", y))
1529 piece = @array[x][y]
1538 a.push(sprintf("\n"))
1541 if (! sente_hands.empty?)
1543 sente_hands.each do |p|
1544 a.push("00" + p.name)
1548 if (! gote_hands.empty?)
1550 gote_hands.each do |p|
1551 a.push("00" + p.name)
1561 attr_reader :players, :black, :white
1563 def initialize(p1, p2)
1565 if p1.sente && !p2.sente
1566 @black, @white = p1, p2
1567 elsif !p1.sente && p2.sente
1568 @black, @white = p2, p1
1570 raise "Never reached!"
1575 class GameResultWin < GameResult
1576 attr_reader :winner, :loser
1578 def initialize(winner, loser)
1580 @winner, @loser = winner, loser
1584 black_name = @black.id || @black.name
1585 white_name = @white.id || @white.name
1586 "%s:%s" % [black_name, white_name]
1590 class GameResultDraw < GameResult
1598 def initialize(game_name, player0, player1)
1599 @monitors = Array::new
1600 @game_name = game_name
1601 if (@game_name =~ /-(\d+)-(\d+)$/)
1602 @total_time = $1.to_i
1613 @current_player = @sente
1614 @next_player = @gote
1622 @sente.status = "agree_waiting"
1623 @gote.status = "agree_waiting"
1625 @id = sprintf("%s+%s+%s+%s+%s",
1626 LEAGUE.event, @game_name, @sente.name, @gote.name, issue_current_time)
1627 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1629 LEAGUE.games[@id] = self
1631 log_message(sprintf("game created %s", @id))
1641 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1642 attr_accessor :last_move, :current_turn
1646 @sente.rated? && @gote.rated?
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 ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
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)
1697 def handle_one_move(str, player)
1699 if (@current_player == player)
1700 @end_time = Time::new
1701 t = (@end_time - @start_time).floor
1702 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
1705 if ((@current_player.mytime - t <= -@byoyomi) && ((@total_time > 0) || (@byoyomi > 0)))
1707 elsif (str == :timeout)
1708 return false # time isn't expired. players aren't swapped. continue game
1710 @current_player.mytime = @current_player.mytime - t
1711 if (@current_player.mytime < 0)
1712 @current_player.mytime = 0
1716 move_status = @board.handle_one_move(str, @sente == @current_player)
1718 # log_error("handle_one_move raise exception for #{str}")
1719 # move_status = :illegal
1722 if ((move_status == :illegal) || (move_status == :uchifuzme) || (move_status == :oute_kaihimore))
1723 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1725 if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite_sente_lose) || (move_status == :oute_sennichite_gote_lose))
1726 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1727 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1728 @fh.printf("%s\nT%d\n", str, t)
1729 @last_move = sprintf("%s,T%d", str, t)
1730 @current_turn = @current_turn + 1
1733 @monitors.each do |monitor|
1734 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1735 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1740 if (@next_player.status != "game") # rival is logout or disconnected
1742 elsif (status == :timeout)
1744 elsif (move_status == :illegal)
1746 elsif (move_status == :kachi_win)
1748 elsif (move_status == :kachi_lose)
1750 elsif (move_status == :toryo)
1752 elsif (move_status == :outori)
1754 elsif (move_status == :oute_sennichite_sente_lose)
1755 oute_sennichite_win_lose(@gote, @sente) # Sente is checking
1756 elsif (move_status == :oute_sennichite_gote_lose)
1757 oute_sennichite_win_lose(@sente, @gote) # Gote is checking
1758 elsif (move_status == :sennichite)
1760 elsif (move_status == :uchifuzume)
1762 elsif (move_status == :oute_kaihimore)
1763 oute_kaihimore_lose()
1767 finish() if finish_flag
1768 (@current_player, @next_player) = [@next_player, @current_player]
1769 @start_time = Time::new
1775 @current_player.status = "connected"
1776 @next_player.status = "connected"
1777 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1778 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1779 @fh.printf("%%TORYO\n")
1780 @fh.print(@board.to_s.gsub(/^/, "\'"))
1781 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1782 @result = GameResultWin.new(@current_player, @next_player)
1783 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1784 @monitors.each do |monitor|
1785 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1790 @current_player.status = "connected"
1791 @next_player.status = "connected"
1792 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1793 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1794 @fh.printf("%%TORYO\n")
1795 @fh.print(@board.to_s.gsub(/^/, "\'"))
1796 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1797 @result = GameResultWin.new(@next_player, @current_player)
1798 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1799 @monitors.each do |monitor|
1800 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1805 @current_player.status = "connected"
1806 @next_player.status = "connected"
1807 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1808 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1809 @fh.print(@board.to_s.gsub(/^/, "\'"))
1810 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1811 @result = GameResultDraw.new(@current_player, @next_player)
1812 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1813 @monitors.each do |monitor|
1814 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @id))
1818 def oute_sennichite_win_lose(winner, loser)
1819 @current_player.status = "connected"
1820 @next_player.status = "connected"
1821 loser.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1822 winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1823 @fh.print(@board.to_s.gsub(/^/, "\'"))
1824 if loser == @current_player
1825 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1827 @fh.printf("'summary:oute_sennichite:%s win:%s lose\n", @current_player.name, @next_player.name)
1829 @result = GameResultWin.new(winner, loser)
1830 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1831 @monitors.each do |monitor|
1832 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1837 @current_player.status = "connected"
1838 @next_player.status = "connected"
1839 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1840 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1841 @fh.print(@board.to_s.gsub(/^/, "\'"))
1842 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1843 @result = GameResultWin.new(@next_player, @current_player)
1844 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1845 @monitors.each do |monitor|
1846 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\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:uchifuzume:%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))
1864 def oute_kaihimore_lose
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:oute_kaihimore:%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("#TIME_UP\n#LOSE\n")
1882 @next_player.write_safe("#TIME_UP\n#WIN\n")
1883 @fh.print(@board.to_s.gsub(/^/, "\'"))
1884 @fh.printf("'summary:time up:%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] #TIME_UP\n", @id))
1893 @current_player.status = "connected"
1894 @next_player.status = "connected"
1895 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1896 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1897 @fh.printf("%%KACHI\n")
1898 @fh.print(@board.to_s.gsub(/^/, "\'"))
1899 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1900 @result = GameResultWin.new(@current_player, @next_player)
1901 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1902 @monitors.each do |monitor|
1903 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1908 @current_player.status = "connected"
1909 @next_player.status = "connected"
1910 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1911 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1912 @fh.printf("%%KACHI\n")
1913 @fh.print(@board.to_s.gsub(/^/, "\'"))
1914 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1915 @result = GameResultWin.new(@next_player, @current_player)
1916 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1917 @monitors.each do |monitor|
1918 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1923 @current_player.status = "connected"
1924 @next_player.status = "connected"
1925 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1926 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1927 @fh.printf("%%TORYO\n")
1928 @fh.print(@board.to_s.gsub(/^/, "\'"))
1929 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1930 @result = GameResultWin.new(@next_player, @current_player)
1931 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1932 @monitors.each do |monitor|
1933 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1938 @current_player.status = "connected"
1939 @next_player.status = "connected"
1940 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1941 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1942 @fh.print(@board.to_s.gsub(/^/, "\'"))
1943 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1944 @result = GameResultWin.new(@current_player, @next_player)
1945 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1946 @monitors.each do |monitor|
1947 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1952 log_message(sprintf("game started %s", @id))
1953 @sente.write_safe(sprintf("START:%s\n", @id))
1954 @gote.write_safe(sprintf("START:%s\n", @id))
1955 @sente.mytime = @total_time
1956 @gote.mytime = @total_time
1957 @start_time = Time::new
1961 @fh = open(@logfile, "w")
1965 @fh.puts("N+#{@sente.name}")
1966 @fh.puts("N-#{@gote.name}")
1967 @fh.puts("$EVENT:#{@id}")
1969 @sente.write_safe(propose_message("+"))
1970 @gote.write_safe(propose_message("-"))
1972 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
1973 @fh.puts("$START_TIME:#{now}")
1975 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1976 P2 * -HI * * * * * -KA *
1977 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1978 P4 * * * * * * * * *
1979 P5 * * * * * * * * *
1980 P6 * * * * * * * * *
1981 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1982 P8 * +KA * * * * * +HI *
1983 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1991 Protocol_Version:1.1
1992 Protocol_Mode:Server
1994 Declaration:Jishogi 1.1
1996 Name+:#{@sente.name}
2002 Total_Time:#{@total_time}
2004 Least_Time_Per_Move:#{Least_Time_Per_Move}
2005 Remaining_Time+:#{@sente.mytime}
2006 Remaining_Time-:#{@gote.mytime}
2007 Last_Move:#{@last_move}
2008 Current_Turn:#{@current_turn}
2018 return str0 + @board.to_s + str1
2021 def propose_message(sg_flag)
2024 Protocol_Version:1.1
2025 Protocol_Mode:Server
2027 Declaration:Jishogi 1.1
2029 Name+:#{@sente.name}
2031 Your_Turn:#{sg_flag}
2036 Total_Time:#{@total_time}
2038 Least_Time_Per_Move:#{Least_Time_Per_Move}
2041 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2042 P2 * -HI * * * * * -KA *
2043 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2044 P4 * * * * * * * * *
2045 P5 * * * * * * * * *
2046 P6 * * * * * * * * *
2047 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2048 P8 * +KA * * * * * +HI *
2049 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2061 def issue_current_time
2062 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
2063 @@mutex.synchronize do
2064 while time <= @@time do
2071 end # module ShogiServer
2073 #################################################
2080 shogi-server - server for CSA server protocol
2083 shogi-server [OPTIONS] event_name port_number
2086 server for CSA server protocol
2090 specify filename for logging process ID
2092 run as a daemon. Log files will be put in dir.
2095 this file is distributed under GPL version2 and might be compiled by Exerb
2100 #{ShogiServer::Release}
2103 #{ShogiServer::Revision}
2111 def log_message(str)
2115 def log_warning(str)
2124 def parse_command_line
2126 parser = GetoptLong.new( ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2127 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT]
2131 parser.each_option do |name, arg|
2132 name.sub!(/^--/, '')
2133 options[name] = arg.dup
2137 raise parser.error_message
2142 def write_pid_file(file)
2143 open(file, "w") do |fh|
2144 fh.print Process::pid, "\n"
2148 def mutex_watchdog(mutex, sec)
2160 log_error("mutex watchdog timeout")
2171 mutex_watchdog($mutex, 10)
2174 $options = parse_command_line
2175 if (ARGV.length != 2)
2180 LEAGUE.event = ARGV.shift
2183 write_pid_file($options["pid-file"]) if ($options["pid-file"])
2185 dir = $options["daemon"] || nil
2186 if dir && ! File.exist?(dir)
2187 FileUtils.mkdir(dir)
2189 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2190 $logger = WEBrick::Log.new(log_file)
2192 LEAGUE.dir = dir || File.dirname(__FILE__)
2193 LEAGUE.setup_players_database
2196 config[:Port] = port
2197 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2198 config[:Logger] = $logger
2200 server = WEBrick::GenericServer.new(config)
2201 ["INT", "TERM"].each do |signal|
2207 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2208 log_message("server started [Revision: #{ShogiServer::Revision}]")
2210 server.start do |client|
2211 # client.sync = true # this is already set in WEBrick
2212 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2213 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2216 while (str = client.gets_timeout(ShogiServer::Login_Time))
2221 if (ShogiServer::Login::good_login?(str))
2222 player = ShogiServer::Player::new(str, client)
2224 login = ShogiServer::Login::factory(str, player)
2225 if (LEAGUE.players[player.name])
2226 if ((LEAGUE.players[player.name].password == player.password) &&
2227 (LEAGUE.players[player.name].status != "game"))
2228 log_message(sprintf("user %s login forcely", player.name))
2229 LEAGUE.players[player.name].kill
2231 login.incorrect_duplicated_player(str)
2242 client.write_safe("LOGIN:incorrect" + eol)
2243 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2255 log_message(sprintf("user %s login", player.name))
2257 player.run(login.csa_1st_str)
2261 player.game.kill(player)
2263 player.finish # socket has been closed
2264 LEAGUE.delete(player)
2265 log_message(sprintf("user %s logout", player.name))
2276 TCPSocket.do_not_reverse_lookup = true
2277 Thread.abort_on_exception = true
2279 LEAGUE = ShogiServer::League::new