4 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
5 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ## GNU General Public License for more details.
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, write to the Free Software
19 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32 def gets_safe(socket, timeout=nil)
33 if r = select([socket], nil, nil, timeout)
34 return r[0].first.gets
38 rescue Exception => ex
39 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
43 module ShogiServer # for a namespace
45 Max_Identifier_Length = 32
46 Default_Timeout = 60 # for single socket operation
48 Default_Game_Name = "default-1500-0"
51 Least_Time_Per_Move = 1
52 Login_Time = 300 # time for LOGIN
54 Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
55 Release.concat("-") if (Release == "")
56 Revision = "$Revision$".gsub(/[^\.\d]/, '')
63 return /^floodgate-\d+-\d+$/.match(str) ? true : false
67 def initialize(league)
74 @thread = Thread.new do
79 next if Time.now < @next_time
83 rescue Exception => ex
85 log_error("[in Floodgate's thread] #{ex}")
92 @thread.kill if @thread
100 @next_time = Time.mktime(now.year, now.month, now.day, now.hour, 30)
102 @next_time = Time.mktime(now.year, now.month, now.day, now.hour) + 3600
106 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min, 30)
108 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min) + 60
113 players = @league.find_all_players do |pl|
114 pl.status == "game_waiting" &&
115 Floodgate.game_name?(pl.game_name) &&
118 log_warning("DEBUG: %s" % [File.join(File.dirname(__FILE__), "pairing.rb")])
119 load File.join(File.dirname(__FILE__), "pairing.rb")
120 Pairing.default_pairing.match(players)
122 end # class Floodgate
125 @mutex = Mutex.new # guard @players
129 @dir = File.dirname(__FILE__)
130 @floodgate = Floodgate.new(self)
133 attr_accessor :players, :games, :event, :dir
136 @mutex.synchronize do
137 @players.each {|a| save(a)}
142 # this should be called just after instanciating a League object.
143 def setup_players_database
144 @db = YAML::Store.new(File.join(@dir, "players.yaml"))
148 self.load(player) if player.id
149 @mutex.synchronize do
150 @players[player.name] = player
155 @mutex.synchronize do
157 @players.delete(player.name)
162 @mutex.synchronize do
163 @players.each {|player| load(player)}
169 @mutex.synchronize do
170 found = @players.find_all do |name, player|
174 return found.map {|a| a.last}
177 def find(player_name)
179 @mutex.synchronize do
180 found = @players[player_name]
185 def get_player(status, game_name, sente, searcher)
187 @mutex.synchronize do
188 found = @players.find do |name, player|
189 (player.status == status) &&
190 (player.game_name == game_name) &&
192 (player.sente == nil) ||
193 (player.sente == sente) ) &&
194 (player.name != searcher.name)
197 return found ? found.last : nil
201 hash = search(player.id)
205 player.name = hash['name']
206 player.rate = hash['rate'] || 0
207 player.modified_at = hash['last_modified']
208 player.rating_group = hash['rating_group']
209 player.win = hash['win'] || 0
210 player.loss = hash['loss'] || 0
211 player.last_game_win = hash['last_game_win'] || false
216 break unless @db["players"]
217 @db["players"].each do |group, players|
218 hash = players[player.id]
220 hash['last_game_win'] = player.last_game_win
229 @db.transaction(true) do
230 break unless @db["players"]
231 @db["players"].each do |group, players|
241 @db.transaction(true) do
242 break unless @db["players"]
243 @db["players"].each do |group, players_hash|
244 players << players_hash.keys
247 return players.flatten.collect do |id|
257 ######################################################
258 # Processes the LOGIN command.
261 def Login.good_login?(str)
263 if (((tokens.length == 3) ||
264 ((tokens.length == 4) && tokens[3] == "x1")) &&
265 (tokens[0] == "LOGIN") &&
266 (good_identifier?(tokens[1])))
273 def Login.good_game_name?(str)
274 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
281 def Login.good_identifier?(str)
282 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
289 def Login.factory(str, player)
290 (login, player.name, password, ext) = str.chomp.split
292 return Loginx1.new(player, password)
294 return LoginCSA.new(player, password)
300 # the first command that will be executed just after LOGIN.
301 # If it is nil, the default process will be started.
302 attr_reader :csa_1st_str
304 def initialize(player, password)
307 parse_password(password)
311 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
312 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
315 def incorrect_duplicated_player(str)
316 @player.write_safe("LOGIN:incorrect\n")
317 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
318 sleep 3 # wait for sending the above messages.
319 @player.name = "%s [duplicated]" % [@player.name]
324 ######################################################
325 # Processes LOGIN for the CSA standard mode.
327 class LoginCSA < Login
330 def initialize(player, password)
333 @player.protocol = PROTOCOL
336 def parse_password(password)
337 if Login.good_game_name?(password)
339 @player.set_password(nil)
340 elsif password.split(",").size > 1
341 @gamename, *trip = password.split(",")
342 @player.set_password(trip.join(","))
344 @player.set_password(password)
345 @gamename = Default_Game_Name
347 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
352 @csa_1st_str = "%%GAME #{@gamename} *"
356 ######################################################
357 # Processes LOGIN for the extented mode.
359 class Loginx1 < Login
362 def initialize(player, password)
364 @player.protocol = PROTOCOL
367 def parse_password(password)
368 @player.set_password(password)
373 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
383 @last_game_win = false
386 # Idetifier of the player in the rating system
392 # Password of the player, which does not include a trip
393 attr_accessor :password
395 # Score in the rating sysem
398 # Number of games for win and loss in the rating system
399 attr_accessor :win, :loss
401 # Group in the rating system
402 attr_accessor :rating_group
404 # Last timestamp when the rate was modified
405 attr_accessor :modified_at
407 # Whether win the previous game or not
408 attr_accessor :last_game_win
411 @modified_at || Time.now
417 @modified_at = Time.now
426 return @last_game_win
431 simple_name = @name.gsub(/@.*?$/, '')
432 "%s+%s" % [simple_name, @trip[0..8]]
439 # Parses str in the LOGIN command, sets up @id and @trip
441 def set_password(str)
442 if str && !str.empty?
443 @password = str.strip
444 @id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
446 @id = @password = nil
452 class Player < BasicPlayer
453 def initialize(str, socket, eol=nil)
456 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
458 @protocol = nil # CSA or x1
459 @eol = eol || "\m" # favorite eol code
462 @mytime = 0 # set in start method also
464 @main_thread = Thread::current
467 attr_accessor :socket, :status
468 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
469 attr_accessor :main_thread
472 log_message(sprintf("user %s killed", @name))
477 Thread::kill(@main_thread) if @main_thread
481 if (@status != "finished")
483 log_message(sprintf("user %s finish", @name))
485 # @socket.close if (! @socket.closed?)
487 log_message(sprintf("user %s finish failed", @name))
495 rescue Exception => ex
496 log_error("Failed to send a message to #{@name}.")
497 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
503 if ["game_waiting", "start_waiting", "agree_waiting", "game"].include?(status)
505 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
506 elsif (@sente == false)
507 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
508 elsif (@sente == nil)
509 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
512 return sprintf("%s %s %s", @name, @protocol, @status)
516 def run(csa_1st_str=nil)
517 while (csa_1st_str || (str = gets_safe(@socket, Default_Timeout)))
526 if (@status == "finished")
529 str.chomp! if (str.class == String) # may be strip! ?
530 log_message(str) if $DEBUG
533 # Application-level protocol for Keep-Alive
534 # If the server gets LF, it sends back LF.
535 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
538 if (@status == "game")
539 array_str = str.split(",")
540 move = array_str.shift
541 additional = array_str.shift
542 if /^'(.*)/ =~ additional
543 comment = array_str.unshift("'*#{$1.toeuc}")
545 s = @game.handle_one_move(move, self)
546 @game.fh.print("#{comment}\n") if (comment && !s)
547 return if (s && @protocol == LoginCSA::PROTOCOL)
549 when /^%[^%]/, :timeout
550 if (@status == "game")
551 s = @game.handle_one_move(str, self)
552 return if (s && @protocol == LoginCSA::PROTOCOL)
555 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
556 # rescue Exception => ex
557 # log_error("Failed to send a keepalive to #{@name}.")
558 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
563 log_error("Failed to receive a message from #{@name}.")
566 if (@status == "agree_waiting")
568 return if (@protocol == LoginCSA::PROTOCOL)
570 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
573 if (@status == "agree_waiting")
574 @status = "start_waiting"
575 if ((@game.sente.status == "start_waiting") &&
576 (@game.gote.status == "start_waiting"))
578 @game.sente.status = "game"
579 @game.gote.status = "game"
582 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
584 when /^%%SHOW\s+(\S+)/
586 if (LEAGUE.games[game_id])
587 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
589 write_safe("##[SHOW] +OK\n")
590 when /^%%MONITORON\s+(\S+)/
592 if (LEAGUE.games[game_id])
593 LEAGUE.games[game_id].monitoron(self)
594 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
595 write_safe("##[MONITOR][#{game_id}] +OK\n")
597 when /^%%MONITOROFF\s+(\S+)/
599 if (LEAGUE.games[game_id])
600 LEAGUE.games[game_id].monitoroff(self)
604 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
606 players = LEAGUE.rated_players
607 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
608 write_safe("##[RATING] %s \t %4d @%s\n" %
609 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
611 write_safe("##[RATING] +OK\n")
613 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
614 write_safe("##[VERSION] +OK\n")
616 if ((@status == "connected") || (@status == "game_waiting"))
617 @status = "connected"
620 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
622 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
626 if (! Login::good_game_name?(game_name))
627 write_safe(sprintf("##[ERROR] bad game name\n"))
629 elsif ((@status == "connected") || (@status == "game_waiting"))
632 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
637 if (League::Floodgate.game_name?(game_name))
638 if (my_sente_str != "*")
639 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", my_sente_str, game_name))
644 if (my_sente_str == "*")
645 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
646 elsif (my_sente_str == "+")
647 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
648 elsif (my_sente_str == "-")
649 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
652 write_safe(sprintf("##[ERROR] bad game option\n"))
658 @game_name = game_name
659 if ((my_sente_str == "*") && (rival.sente == nil))
667 elsif (rival.sente == true) # rival has higher priority
669 elsif (rival.sente == false)
671 elsif (my_sente_str == "+")
674 elsif (my_sente_str == "-")
680 Game::new(@game_name, self, rival)
681 else # rival not found
682 if (command_name == "GAME")
683 @status = "game_waiting"
684 @game_name = game_name
685 if (my_sente_str == "+")
687 elsif (my_sente_str == "-")
693 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
694 @status = "connected"
699 when /^%%CHAT\s+(.+)/
701 LEAGUE.players.each do |name, player|
702 if (player.protocol != LoginCSA::PROTOCOL)
703 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
708 LEAGUE.games.each do |id, game|
709 buf.push(sprintf("##[LIST] %s\n", id))
711 buf.push("##[LIST] +OK\n")
715 LEAGUE.players.each do |name, player|
716 buf.push(sprintf("##[WHO] %s\n", player.to_s))
718 buf.push("##[WHO] +OK\n")
721 @status = "connected"
722 write_safe("LOGOUT:completed\n")
725 # This command is only available for CSA's official testing server.
726 # So, this means nothing for this program.
727 write_safe("CHALLENGE ACCEPTED\n")
729 ## ignore null string
731 msg = "##[ERROR] unknown command %s\n" % [str]
743 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK",
744 "GI" => "NG", "KA" => "UM", "HI" => "RY"}
745 def initialize(board, x, y, sente, promoted=false)
752 if ((x == 0) || (y == 0))
754 hands = board.sente_hands
756 hands = board.gote_hands
763 @board.array[x][y] = self
766 attr_accessor :promoted, :sente, :x, :y, :board
768 def room_of_head?(x, y, name)
773 return adjacent_movable_grids + far_movable_grids
776 def far_movable_grids
781 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
782 if ((@board.array[x][y] == nil) || # dst is empty
783 (@board.array[x][y].sente != @sente)) # dst is enemy
791 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
792 if (@board.array[x][y] == nil) # dst is empty?
799 def adjacent_movable_grids
802 moves = @promoted_moves
804 moves = @normal_moves
806 moves.each do |(dx, dy)|
813 if (jump_to?(cand_x, cand_y))
814 grids.push([cand_x, cand_y])
820 def move_to?(x, y, name)
821 return false if (! room_of_head?(x, y, name))
822 return false if ((name != @name) && (name != @promoted_name))
823 return false if (@promoted && (name != @promoted_name)) # can't un-promote
826 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
828 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
830 return false if ((6 >= @y) && (6 >= y) && (name != @name))
834 if ((@x == 0) || (@y == 0))
835 return jump_to?(x, y)
837 return movable_grids.include?([x, y])
842 if ((@x == 0) || (@y == 0))
844 @board.sente_hands.delete(self)
846 @board.gote_hands.delete(self)
848 @board.array[x][y] = self
849 elsif ((x == 0) || (y == 0))
850 @promoted = false # clear promoted flag before moving to hands
852 @board.sente_hands.push(self)
854 @board.gote_hands.push(self)
856 @board.array[@x][@y] = nil
858 @board.array[@x][@y] = nil
859 @board.array[x][y] = self
892 class PieceFU < Piece
895 @normal_moves = [[0, +1]]
896 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
898 @promoted_name = "TO"
901 def room_of_head?(x, y, name)
904 return false if (y == 1)
906 return false if (y == 9)
912 if ((iy != @y) && # not source position
913 @board.array[x][iy] &&
914 (@board.array[x][iy].sente == @sente) && # mine
915 (@board.array[x][iy].name == "FU") &&
916 (@board.array[x][iy].promoted == false))
926 class PieceKY < Piece
930 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
932 @promoted_name = "NY"
935 def room_of_head?(x, y, name)
938 return false if (y == 1)
940 return false if (y == 9)
945 def far_movable_grids
953 while (jump_to?(cand_x, cand_y))
954 grids.push([cand_x, cand_y])
955 break if (! put_to?(cand_x, cand_y))
961 while (jump_to?(cand_x, cand_y))
962 grids.push([cand_x, cand_y])
963 break if (! put_to?(cand_x, cand_y))
971 class PieceKE < Piece
974 @normal_moves = [[+1, +2], [-1, +2]]
975 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
977 @promoted_name = "NK"
980 def room_of_head?(x, y, name)
983 return false if ((y == 1) || (y == 2))
985 return false if ((y == 9) || (y == 8))
991 class PieceGI < Piece
994 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
995 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
997 @promoted_name = "NG"
1001 class PieceKI < Piece
1002 def initialize(*arg)
1004 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1005 @promoted_moves = []
1007 @promoted_name = nil
1011 class PieceKA < Piece
1012 def initialize(*arg)
1015 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
1017 @promoted_name = "UM"
1020 def far_movable_grids
1025 while (jump_to?(cand_x, cand_y))
1026 grids.push([cand_x, cand_y])
1027 break if (! put_to?(cand_x, cand_y))
1034 while (jump_to?(cand_x, cand_y))
1035 grids.push([cand_x, cand_y])
1036 break if (! put_to?(cand_x, cand_y))
1043 while (jump_to?(cand_x, cand_y))
1044 grids.push([cand_x, cand_y])
1045 break if (! put_to?(cand_x, cand_y))
1052 while (jump_to?(cand_x, cand_y))
1053 grids.push([cand_x, cand_y])
1054 break if (! put_to?(cand_x, cand_y))
1061 class PieceHI < Piece
1062 def initialize(*arg)
1065 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1067 @promoted_name = "RY"
1070 def far_movable_grids
1075 while (jump_to?(cand_x, cand_y))
1076 grids.push([cand_x, cand_y])
1077 break if (! put_to?(cand_x, cand_y))
1083 while (jump_to?(cand_x, cand_y))
1084 grids.push([cand_x, cand_y])
1085 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))
1099 while (jump_to?(cand_x, cand_y))
1100 grids.push([cand_x, cand_y])
1101 break if (! put_to?(cand_x, cand_y))
1107 class PieceOU < Piece
1108 def initialize(*arg)
1110 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1111 @promoted_moves = []
1113 @promoted_name = nil
1120 @sente_hands = Array::new
1121 @gote_hands = Array::new
1122 @history = Hash::new(0)
1123 @sente_history = Hash::new(0)
1124 @gote_history = Hash::new(0)
1125 @array = [[], [], [], [], [], [], [], [], [], []]
1128 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1129 attr_reader :move_count
1132 PieceKY::new(self, 1, 1, false)
1133 PieceKE::new(self, 2, 1, false)
1134 PieceGI::new(self, 3, 1, false)
1135 PieceKI::new(self, 4, 1, false)
1136 PieceOU::new(self, 5, 1, false)
1137 PieceKI::new(self, 6, 1, false)
1138 PieceGI::new(self, 7, 1, false)
1139 PieceKE::new(self, 8, 1, false)
1140 PieceKY::new(self, 9, 1, false)
1141 PieceKA::new(self, 2, 2, false)
1142 PieceHI::new(self, 8, 2, false)
1144 PieceFU::new(self, i, 3, false)
1147 PieceKY::new(self, 1, 9, true)
1148 PieceKE::new(self, 2, 9, true)
1149 PieceGI::new(self, 3, 9, true)
1150 PieceKI::new(self, 4, 9, true)
1151 PieceOU::new(self, 5, 9, true)
1152 PieceKI::new(self, 6, 9, true)
1153 PieceGI::new(self, 7, 9, true)
1154 PieceKE::new(self, 8, 9, true)
1155 PieceKY::new(self, 9, 9, true)
1156 PieceKA::new(self, 8, 8, true)
1157 PieceHI::new(self, 2, 8, true)
1159 PieceFU::new(self, i, 7, true)
1163 def have_piece?(hands, name)
1164 piece = hands.find { |i|
1170 def move_to(x0, y0, x1, y1, name, sente)
1172 hands = @sente_hands
1177 if ((x0 == 0) || (y0 == 0))
1178 piece = have_piece?(hands, name)
1179 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1180 piece.move_to(x1, y1)
1182 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1183 if (@array[x0][y0].name != name) # promoted ?
1184 @array[x0][y0].promoted = true
1186 if (@array[x1][y1]) # capture
1187 if (@array[x1][y1].name == "OU")
1188 return :outori # return board update
1190 @array[x1][y1].sente = @array[x0][y0].sente
1191 @array[x1][y1].move_to(0, 0)
1192 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1196 @array[x0][y0].move_to(x1, y1)
1202 def look_for_ou(sente)
1208 (@array[x][y].name == "OU") &&
1209 (@array[x][y].sente == sente))
1216 raise "can't find ou"
1219 # note checkmate, but check. sente is checked.
1220 def checkmated?(sente) # sente is loosing
1221 ou = look_for_ou(sente)
1227 (@array[x][y].sente != sente))
1228 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1239 def uchifuzume?(sente)
1240 rival_ou = look_for_ou(! sente) # rival's ou
1241 if (sente) # rival is gote
1242 if ((rival_ou.y != 9) &&
1243 (@array[rival_ou.x][rival_ou.y + 1]) &&
1244 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1245 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1247 fu_y = rival_ou.y + 1
1252 if ((rival_ou.y != 1) &&
1253 (@array[rival_ou.x][rival_ou.y - 1]) &&
1254 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1255 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1257 fu_y = rival_ou.y - 1
1263 ## case: rival_ou is moving
1264 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1265 tmp_board = Marshal.load(Marshal.dump(self))
1266 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1267 raise "internal error" if (s != true)
1268 if (! tmp_board.checkmated?(! sente)) # good move
1273 ## case: rival is capturing fu
1279 (@array[x][y].sente != sente) &&
1280 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1283 if (@array[x][y].promoted)
1284 names << @array[x][y].promoted_name
1286 names << @array[x][y].name
1287 if @array[x][y].promoted_name &&
1288 @array[x][y].move_to?(fu_x, fu_y, @array[x][y].promoted_name)
1289 names << @array[x][y].promoted_name
1292 names.map! do |name|
1293 tmp_board = Marshal.load(Marshal.dump(self))
1294 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1298 tmp_board.checkmated?(! sente) # result
1301 all_illegal = names.find {|a| a != :illegal}
1302 raise "internal error: legal move not found" if all_illegal == nil
1303 r = names.find {|a| a == false} # good move
1304 return false if r == false # found good move
1313 # @[sente|gote]_history has at least one item while the player is checking the other or
1314 # the other escapes.
1315 def update_sennichite(player)
1318 if checkmated?(!player)
1320 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
1322 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
1326 @sente_history.clear # no more continuous check
1328 @gote_history.clear # no more continuous check
1331 if @sente_history.size > 0 # possible for Sente's or Gote's turn
1332 @sente_history[str] += 1
1334 if @gote_history.size > 0 # possible for Sente's or Gote's turn
1335 @gote_history[str] += 1
1339 def oute_sennichite?(player)
1340 if (@sente_history[to_s] >= 4)
1341 return :oute_sennichite_sente_lose
1342 elsif (@gote_history[to_s] >= 4)
1343 return :oute_sennichite_gote_lose
1349 def sennichite?(sente)
1350 if (@history[to_s] >= 4) # already 3 times
1356 def good_kachi?(sente)
1357 if (checkmated?(sente))
1358 puts "'NG: Checkmating." if $DEBUG
1362 ou = look_for_ou(sente)
1363 if (sente && (ou.y >= 4))
1364 puts "'NG: Black's OU does not enter yet." if $DEBUG
1367 if (! sente && (ou.y <= 6))
1368 puts "'NG: White's OU does not enter yet." if $DEBUG
1376 hands = @sente_hands
1386 (@array[x][y].sente == sente) &&
1387 (@array[x][y].point > 0))
1388 point = point + @array[x][y].point
1394 hands.each do |piece|
1395 point = point + piece.point
1399 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1404 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1409 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1414 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1418 # sente is nil only if tests in test_board run
1419 def handle_one_move(str, sente=nil)
1420 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1427 elsif (str =~ /^%KACHI/)
1428 raise ArgumentError, "sente is null", caller if sente == nil
1429 if (good_kachi?(sente))
1434 elsif (str =~ /^%TORYO/)
1440 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1441 ((x0 != 0) || (y0 != 0)))
1443 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1448 sente = true if sente == nil # deprecated
1449 return :illegal unless sente == true # black player's move must be black
1450 hands = @sente_hands
1452 sente = false if sente == nil # deprecated
1453 return :illegal unless sente == false # white player's move must be white
1458 if ((x0 == 0) && (y0 == 0))
1459 return :illegal if (! have_piece?(hands, name))
1460 elsif (! @array[x0][y0])
1461 return :illegal # no piece
1462 elsif (@array[x0][y0].sente != sente)
1463 return :illegal # this is not mine
1464 elsif (@array[x0][y0].name != name)
1465 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1468 ## destination check
1469 if (@array[x1][y1] &&
1470 (@array[x1][y1].sente == sente)) # can't capture mine
1472 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1473 return :illegal # can't put on existing piece
1476 tmp_board = Marshal.load(Marshal.dump(self))
1477 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1478 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1479 tmp_board.update_sennichite(sente)
1480 os_result = tmp_board.oute_sennichite?(sente)
1481 return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
1482 return :sennichite if tmp_board.sennichite?(sente)
1484 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1488 move_to(x0, y0, x1, y1, name, sente)
1491 update_sennichite(sente)
1499 a.push(sprintf("P%d", y))
1502 piece = @array[x][y]
1511 a.push(sprintf("\n"))
1514 if (! sente_hands.empty?)
1516 sente_hands.each do |p|
1517 a.push("00" + p.name)
1521 if (! gote_hands.empty?)
1523 gote_hands.each do |p|
1524 a.push("00" + p.name)
1534 attr_reader :players, :black, :white
1536 def initialize(p1, p2)
1538 if p1.sente && !p2.sente
1539 @black, @white = p1, p2
1540 elsif !p1.sente && p2.sente
1541 @black, @white = p2, p1
1543 raise "Never reached!"
1548 class GameResultWin < GameResult
1549 attr_reader :winner, :loser
1551 def initialize(winner, loser)
1553 @winner, @loser = winner, loser
1554 @winner.last_game_win = true
1555 @loser.last_game_win = false
1559 black_name = @black.id || @black.name
1560 white_name = @white.id || @white.name
1561 "%s:%s" % [black_name, white_name]
1565 class GameResultDraw < GameResult
1566 def initialize(p1, p2)
1568 p1.last_game_win = false
1569 p2.last_game_win = false
1577 def initialize(game_name, player0, player1)
1578 @monitors = Array::new
1579 @game_name = game_name
1580 if (@game_name =~ /-(\d+)-(\d+)$/)
1581 @total_time = $1.to_i
1586 @sente, @gote = player0, player1
1588 @sente, @gote = player1, player0
1590 @current_player, @next_player = @sente, @gote
1597 @sente.status = "agree_waiting"
1598 @gote.status = "agree_waiting"
1600 @id = sprintf("%s+%s+%s+%s+%s",
1601 LEAGUE.event, @game_name,
1602 @sente.name, @gote.name, issue_current_time)
1603 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1605 LEAGUE.games[@id] = self
1607 log_message(sprintf("game created %s", @id))
1617 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1618 attr_accessor :last_move, :current_turn
1622 @sente.rated? && @gote.rated?
1625 def monitoron(monitor)
1626 @monitors.delete(monitor)
1627 @monitors.push(monitor)
1630 def monitoroff(monitor)
1631 @monitors.delete(monitor)
1634 def reject(rejector)
1635 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1636 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1641 if ["agree_waiting", "start_waiting"].include?(@sente.status)
1643 elsif (@current_player == killer)
1650 log_message(sprintf("game finished %s", @id))
1651 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1656 @sente.status = "connected"
1657 @gote.status = "connected"
1659 if (@current_player.protocol == LoginCSA::PROTOCOL)
1660 @current_player.finish
1662 if (@next_player.protocol == LoginCSA::PROTOCOL)
1665 @monitors = Array::new
1668 @current_player = nil
1670 LEAGUE.games.delete(@id)
1673 def handle_one_move(str, player)
1674 return nil unless @current_player == player
1677 @end_time = Time::new
1678 t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
1681 if ((@current_player.mytime - t <= -@byoyomi) &&
1682 ((@total_time > 0) || (@byoyomi > 0)))
1684 elsif (str == :timeout)
1685 return false # time isn't expired. players aren't swapped. continue game
1687 @current_player.mytime -= t
1688 if (@current_player.mytime < 0)
1689 @current_player.mytime = 0
1692 move_status = @board.handle_one_move(str, @sente == @current_player)
1694 if [:illegal, :uchifuzme, :oute_kaihimore].include?(move_status)
1695 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1697 if [:normal, :outori, :sennichite, :oute_sennichite_sente_lose, :oute_sennichite_gote_lose].include?(move_status)
1698 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1699 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1700 @fh.printf("%s\nT%d\n", str, t)
1701 @last_move = sprintf("%s,T%d", str, t)
1705 @monitors.each do |monitor|
1706 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1707 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1712 if (@next_player.status != "game") # rival is logout or disconnected
1714 elsif (status == :timeout)
1716 elsif (move_status == :illegal)
1718 elsif (move_status == :kachi_win)
1720 elsif (move_status == :kachi_lose)
1722 elsif (move_status == :toryo)
1724 elsif (move_status == :outori)
1726 elsif (move_status == :oute_sennichite_sente_lose)
1727 oute_sennichite_win_lose(@gote, @sente) # Sente is checking
1728 elsif (move_status == :oute_sennichite_gote_lose)
1729 oute_sennichite_win_lose(@sente, @gote) # Gote is checking
1730 elsif (move_status == :sennichite)
1732 elsif (move_status == :uchifuzume)
1734 elsif (move_status == :oute_kaihimore)
1735 oute_kaihimore_lose()
1739 finish() if finish_flag
1740 @current_player, @next_player = @next_player, @current_player
1741 @start_time = Time::new
1746 @current_player.status = "connected"
1747 @next_player.status = "connected"
1748 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1749 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1750 @fh.printf("%%TORYO\n")
1751 @fh.print(@board.to_s.gsub(/^/, "\'"))
1752 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1753 @result = GameResultWin.new(@current_player, @next_player)
1754 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1755 @monitors.each do |monitor|
1756 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1761 @current_player.status = "connected"
1762 @next_player.status = "connected"
1763 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1764 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1765 @fh.printf("%%TORYO\n")
1766 @fh.print(@board.to_s.gsub(/^/, "\'"))
1767 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1768 @result = GameResultWin.new(@next_player, @current_player)
1769 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1770 @monitors.each do |monitor|
1771 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1776 @current_player.status = "connected"
1777 @next_player.status = "connected"
1778 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1779 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1780 @fh.print(@board.to_s.gsub(/^/, "\'"))
1781 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1782 @result = GameResultDraw.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] #SENNICHITE\n", @id))
1789 def oute_sennichite_win_lose(winner, loser)
1790 @current_player.status = "connected"
1791 @next_player.status = "connected"
1792 loser.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1793 winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1794 @fh.print(@board.to_s.gsub(/^/, "\'"))
1795 if loser == @current_player
1796 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1798 @fh.printf("'summary:oute_sennichite:%s win:%s lose\n", @current_player.name, @next_player.name)
1800 @result = GameResultWin.new(winner, loser)
1801 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1802 @monitors.each do |monitor|
1803 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1808 @current_player.status = "connected"
1809 @next_player.status = "connected"
1810 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1811 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1812 @fh.print(@board.to_s.gsub(/^/, "\'"))
1813 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1814 @result = GameResultWin.new(@next_player, @current_player)
1815 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1816 @monitors.each do |monitor|
1817 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1822 @current_player.status = "connected"
1823 @next_player.status = "connected"
1824 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1825 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1826 @fh.print(@board.to_s.gsub(/^/, "\'"))
1827 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1828 @result = GameResultWin.new(@next_player, @current_player)
1829 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1830 @monitors.each do |monitor|
1831 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1835 def oute_kaihimore_lose
1836 @current_player.status = "connected"
1837 @next_player.status = "connected"
1838 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1839 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1840 @fh.print(@board.to_s.gsub(/^/, "\'"))
1841 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1842 @result = GameResultWin.new(@next_player, @current_player)
1843 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1844 @monitors.each do |monitor|
1845 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1850 @current_player.status = "connected"
1851 @next_player.status = "connected"
1852 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1853 @next_player.write_safe("#TIME_UP\n#WIN\n")
1854 @fh.print(@board.to_s.gsub(/^/, "\'"))
1855 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1856 @result = GameResultWin.new(@next_player, @current_player)
1857 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1858 @monitors.each do |monitor|
1859 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
1864 @current_player.status = "connected"
1865 @next_player.status = "connected"
1866 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1867 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1868 @fh.printf("%%KACHI\n")
1869 @fh.print(@board.to_s.gsub(/^/, "\'"))
1870 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1871 @result = GameResultWin.new(@current_player, @next_player)
1872 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1873 @monitors.each do |monitor|
1874 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1879 @current_player.status = "connected"
1880 @next_player.status = "connected"
1881 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1882 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1883 @fh.printf("%%KACHI\n")
1884 @fh.print(@board.to_s.gsub(/^/, "\'"))
1885 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1886 @result = GameResultWin.new(@next_player, @current_player)
1887 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1888 @monitors.each do |monitor|
1889 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1894 @current_player.status = "connected"
1895 @next_player.status = "connected"
1896 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1897 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1898 @fh.printf("%%TORYO\n")
1899 @fh.print(@board.to_s.gsub(/^/, "\'"))
1900 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1901 @result = GameResultWin.new(@next_player, @current_player)
1902 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1903 @monitors.each do |monitor|
1904 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1909 @current_player.status = "connected"
1910 @next_player.status = "connected"
1911 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1912 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1913 @fh.print(@board.to_s.gsub(/^/, "\'"))
1914 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1915 @result = GameResultWin.new(@current_player, @next_player)
1916 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1917 @monitors.each do |monitor|
1918 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1923 log_message(sprintf("game started %s", @id))
1924 @sente.write_safe(sprintf("START:%s\n", @id))
1925 @gote.write_safe(sprintf("START:%s\n", @id))
1926 @sente.mytime = @total_time
1927 @gote.mytime = @total_time
1928 @start_time = Time::new
1932 @fh = open(@logfile, "w")
1936 @fh.puts("N+#{@sente.name}")
1937 @fh.puts("N-#{@gote.name}")
1938 @fh.puts("$EVENT:#{@id}")
1940 @sente.write_safe(propose_message("+"))
1941 @gote.write_safe(propose_message("-"))
1943 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
1944 @fh.puts("$START_TIME:#{now}")
1946 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1947 P2 * -HI * * * * * -KA *
1948 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1949 P4 * * * * * * * * *
1950 P5 * * * * * * * * *
1951 P6 * * * * * * * * *
1952 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1953 P8 * +KA * * * * * +HI *
1954 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1962 Protocol_Version:1.1
1963 Protocol_Mode:Server
1965 Declaration:Jishogi 1.1
1967 Name+:#{@sente.name}
1973 Total_Time:#{@total_time}
1975 Least_Time_Per_Move:#{Least_Time_Per_Move}
1976 Remaining_Time+:#{@sente.mytime}
1977 Remaining_Time-:#{@gote.mytime}
1978 Last_Move:#{@last_move}
1979 Current_Turn:#{@current_turn}
1989 return str0 + @board.to_s + str1
1992 def propose_message(sg_flag)
1995 Protocol_Version:1.1
1996 Protocol_Mode:Server
1998 Declaration:Jishogi 1.1
2000 Name+:#{@sente.name}
2002 Your_Turn:#{sg_flag}
2007 Total_Time:#{@total_time}
2009 Least_Time_Per_Move:#{Least_Time_Per_Move}
2012 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2013 P2 * -HI * * * * * -KA *
2014 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2015 P4 * * * * * * * * *
2016 P5 * * * * * * * * *
2017 P6 * * * * * * * * *
2018 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2019 P8 * +KA * * * * * +HI *
2020 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2032 def issue_current_time
2033 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
2034 @@mutex.synchronize do
2035 while time <= @@time do
2042 end # module ShogiServer
2044 #################################################
2051 shogi-server - server for CSA server protocol
2054 shogi-server [OPTIONS] event_name port_number
2057 server for CSA server protocol
2061 specify filename for logging process ID
2063 run as a daemon. Log files will be put in dir.
2066 this file is distributed under GPL version2 and might be compiled by Exerb
2071 #{ShogiServer::Release}
2074 #{ShogiServer::Revision}
2082 def log_message(str)
2086 def log_warning(str)
2095 def parse_command_line
2097 parser = GetoptLong.new(
2098 ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2099 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT])
2102 parser.each_option do |name, arg|
2103 name.sub!(/^--/, '')
2104 options[name] = arg.dup
2108 raise parser.error_message
2113 def write_pid_file(file)
2114 open(file, "w") do |fh|
2119 def mutex_watchdog(mutex, sec)
2131 log_error("mutex watchdog timeout")
2137 def login_loop(client)
2138 player = login = nil
2140 while r = select([client], nil, nil, ShogiServer::Login_Time) do
2141 break unless str = r[0].first.gets
2142 $mutex.lock # guards LEAGUE
2146 if (ShogiServer::Login::good_login?(str))
2147 player = ShogiServer::Player::new(str, client, eol)
2148 login = ShogiServer::Login::factory(str, player)
2149 if (current_player = LEAGUE.find(player.name))
2150 if (current_player.password == player.password &&
2151 current_player.status != "game")
2152 log_message(sprintf("user %s login forcely", player.name))
2155 login.incorrect_duplicated_player(str)
2163 client.write_safe("LOGIN:incorrect" + eol)
2164 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2170 return [player, login]
2178 mutex_watchdog($mutex, 10)
2181 $options = parse_command_line
2182 if (ARGV.length != 2)
2187 LEAGUE.event = ARGV.shift
2190 dir = $options["daemon"]
2191 dir = File.expand_path(dir) if dir
2192 if dir && ! File.exist?(dir)
2193 FileUtils.mkdir(dir)
2195 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2196 $logger = WEBrick::Log.new(log_file) # thread safe
2198 LEAGUE.dir = dir || File.dirname(__FILE__)
2199 LEAGUE.setup_players_database
2202 config[:Port] = port
2203 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2204 config[:Logger] = $logger
2205 if $options["pid-file"]
2206 pid_file = File.expand_path($options["pid-file"])
2207 config[:StartCallback] = Proc.new do
2208 write_pid_file(pid_file)
2210 config[:StopCallback] = Proc.new do
2211 FileUtils.rm(pid_file, :force => true)
2215 server = WEBrick::GenericServer.new(config)
2216 ["INT", "TERM"].each do |signal|
2222 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2223 log_message("server started [Revision: #{ShogiServer::Revision}]")
2225 server.start do |client|
2226 # client.sync = true # this is already set in WEBrick
2227 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2228 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2229 player, login = login_loop(client) # loop
2232 log_message(sprintf("user %s login", player.name))
2234 player.run(login.csa_1st_str) # loop
2238 player.game.kill(player)
2240 player.finish # socket has been closed
2241 LEAGUE.delete(player)
2242 log_message(sprintf("user %s logout", player.name))
2253 TCPSocket.do_not_reverse_lookup = true
2254 Thread.abort_on_exception = $DEBUG ? true : false
2256 LEAGUE = ShogiServer::League::new