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
116 rescue Exception => ex
118 log_error("[in Floodgate's thread] #{ex}")
125 @thread.kill if @thread
133 @next_time = Time.mktime(now.year, now.month, now.day, now.hour, 30)
135 @next_time = Time.mktime(now.year, now.month, now.day, now.hour) + 3600
139 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min, 30)
141 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min) + 60
146 players = @league.find_all_players do |pl|
147 pl.status == "game_waiting" &&
148 Floodgate.game_name?(pl.game_name) &&
151 random_match(players)
154 def random_match(players)
156 log_message("Floodgate: too few players [%d]" % [players.size])
159 log_message("Floodgate: found %d players. Making games..." % [players.size])
160 random_players = players.sort{ rand < 0.5 ? 1 : -1 }
161 pairs = [[random_players.shift]]
162 while !random_players.empty? do
163 if pairs.last.size < 2
164 pairs.last << random_players.shift
166 pairs << [random_players.shift]
169 if pairs.last.size < 2
173 start_game(pair.first, pair.last)
177 def start_game(p1, p2)
180 Game.new(p1.game_name, p1, p2)
182 end # class Floodgate
185 @mutex = Mutex.new # guard @players
189 @dir = File.dirname(__FILE__)
190 @floodgate = Floodgate.new(self)
193 attr_accessor :players, :games, :event, :dir
199 # this should be called just after instanciating a League object.
200 def setup_players_database
201 @db = YAML::Store.new(File.join(@dir, "players.yaml"))
205 self.load(player) if player.id
206 @mutex.synchronize do
207 @players[player.name] = player
212 @mutex.synchronize do
213 @players.delete(player.name)
219 @mutex.synchronize do
220 found = @players.find_all do |name, player|
224 return found.map {|a| a.last}
227 def get_player(status, game_name, sente, searcher)
229 @mutex.synchronize do
230 found = @players.find do |name, player|
231 (player.status == status) &&
232 (player.game_name == game_name) &&
234 (player.sente == nil) ||
235 (player.sente == sente) ) &&
236 (player.name != searcher.name)
239 return found ? found.last : nil
243 hash = search(player.id)
246 player.name = hash['name']
247 player.rate = hash['rate']
248 player.modified_at = hash['last_modified']
249 player.rating_group = hash['rating_group']
256 break unless @db["players"]
257 @db["players"].each do |group, players|
267 @db.transaction(true) do
268 break unless @db["players"]
269 @db["players"].each do |group, players_hash|
270 players << players_hash.keys
273 return players.flatten.collect do |id|
283 ######################################################
284 # Processes the LOGIN command.
287 def Login.good_login?(str)
289 if (((tokens.length == 3) || ((tokens.length == 4) && tokens[3] == "x1")) &&
290 (tokens[0] == "LOGIN") &&
291 (good_identifier?(tokens[1])))
298 def Login.good_game_name?(str)
299 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
306 def Login.good_identifier?(str)
307 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
314 def Login.factory(str, player)
315 (login, player.name, password, ext) = str.chomp.split
317 return Loginx1.new(player, password)
319 return LoginCSA.new(player, password)
325 # the first command that will be executed just after LOGIN.
326 # If it is nil, the default process will be started.
327 attr_reader :csa_1st_str
329 def initialize(player, password)
332 parse_password(password)
336 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
337 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
340 def incorrect_duplicated_player(str)
341 @player.write_safe("LOGIN:incorrect\n")
342 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
343 sleep 3 # wait for sending the above messages.
344 @player.name = "%s [duplicated]" % [@player.name]
349 ######################################################
350 # Processes LOGIN for the CSA standard mode.
352 class LoginCSA < Login
355 def initialize(player, password)
358 @player.protocol = PROTOCOL
361 def parse_password(password)
362 if Login.good_game_name?(password)
364 @player.set_password(nil)
365 elsif password.split(",").size > 1
366 @gamename, *trip = password.split(",")
367 @player.set_password(trip.join(","))
369 @player.set_password(password)
370 @gamename = Default_Game_Name
372 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
377 @csa_1st_str = "%%GAME #{@gamename} *"
381 ######################################################
382 # Processes LOGIN for the extented mode.
384 class Loginx1 < Login
387 def initialize(player, password)
389 @player.protocol = PROTOCOL
392 def parse_password(password)
393 @player.set_password(password)
398 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
404 # Idetifier of the player in the rating system
410 # Password of the player, which does not include a trip
411 attr_accessor :password
413 # Score in the rating sysem
416 # Group in the rating system
417 attr_accessor :rating_group
419 # Last timestamp when the rate was modified
420 attr_accessor :modified_at
428 @modified_at || Time.now
434 @modified_at = Time.now
444 simple_name = @name.gsub(/@.*?$/, '')
445 "%s+%s" % [simple_name, @trip[0..8]]
452 # Parses str in the LOGIN command, sets up @id and @trip
454 def set_password(str)
455 if str && !str.empty?
456 @password = str.strip
457 @id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
459 @id = @password = nil
465 class Player < BasicPlayer
466 def initialize(str, socket)
469 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
471 @protocol = nil # CSA or x1
472 @eol = "\m" # favorite eol code
475 @mytime = 0 # set in start method also
477 @write_queue = Queue::new
478 @main_thread = Thread::current
479 @writer_thread = Thread::start do
485 attr_accessor :socket, :status
486 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
487 attr_accessor :main_thread, :writer_thread, :write_queue
490 log_message(sprintf("user %s killed", @name))
495 Thread::kill(@main_thread) if @main_thread
499 if (@status != "finished")
501 log_message(sprintf("user %s finish", @name))
502 # TODO you should confirm that there is no message in the queue.
503 Thread::kill(@writer_thread) if @writer_thread
505 # @socket.close if (! @socket.closed?)
507 log_message(sprintf("user %s finish failed", @name))
513 @write_queue.push(str.gsub(/[\r\n]+/, @eol))
517 while (str = @write_queue.pop)
520 rescue Exception => ex
521 log_error("Failed to send a message to #{@name}.")
522 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
529 if ((status == "game_waiting") ||
530 (status == "start_waiting") ||
531 (status == "agree_waiting") ||
534 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
535 elsif (@sente == false)
536 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
537 elsif (@sente == nil)
538 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
541 return sprintf("%s %s %s", @name, @protocol, @status)
545 def run(csa_1st_str=nil)
546 while (csa_1st_str || (str = @socket.gets_safe(Default_Timeout)))
550 if (@writer_thread == nil || @writer_thread.status == false)
551 # The writer_thread has been killed because of socket errors.
559 if (@write_queue.size > Max_Write_Queue_Size)
560 log_warning(sprintf("write_queue of %s is %d", @name, @write_queue.size))
564 if (@status == "finished")
567 str.chomp! if (str.class == String) # may be strip! ?
568 log_message(str) if $DEBUG
571 # Application-level protocol for Keep-Alive
572 # If the server gets LF, it sends back LF.
573 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
576 if (@status == "game")
577 array_str = str.split(",")
578 move = array_str.shift
579 additional = array_str.shift
580 if /^'(.*)/ =~ additional
581 comment = array_str.unshift("'*#{$1}")
583 s = @game.handle_one_move(move, self)
584 @game.fh.print("#{comment}\n") if (comment && !s)
585 return if (s && @protocol == LoginCSA::PROTOCOL)
587 when /^%[^%]/, :timeout
588 if (@status == "game")
589 s = @game.handle_one_move(str, self)
590 return if (s && @protocol == LoginCSA::PROTOCOL)
593 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
594 # rescue Exception => ex
595 # log_error("Failed to send a keepalive to #{@name}.")
596 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
601 log_error("Failed to receive a message from #{@name}.")
604 if (@status == "agree_waiting")
606 return if (@protocol == LoginCSA::PROTOCOL)
608 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
611 if (@status == "agree_waiting")
612 @status = "start_waiting"
613 if ((@game.sente.status == "start_waiting") &&
614 (@game.gote.status == "start_waiting"))
616 @game.sente.status = "game"
617 @game.gote.status = "game"
620 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
622 when /^%%SHOW\s+(\S+)/
624 if (LEAGUE.games[game_id])
625 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
627 write_safe("##[SHOW] +OK\n")
628 when /^%%MONITORON\s+(\S+)/
630 if (LEAGUE.games[game_id])
631 LEAGUE.games[game_id].monitoron(self)
632 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
633 write_safe("##[MONITOR][#{game_id}] +OK\n")
635 when /^%%MONITOROFF\s+(\S+)/
637 if (LEAGUE.games[game_id])
638 LEAGUE.games[game_id].monitoroff(self)
642 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
644 players = LEAGUE.rated_players
645 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
646 write_safe("##[RATING] %s \t %4d @%s\n" %
647 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
649 write_safe("##[RATING] +OK\n")
651 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
652 write_safe("##[VERSION] +OK\n")
654 if ((@status == "connected") || (@status == "game_waiting"))
655 @status = "connected"
658 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
660 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
664 if (! Login::good_game_name?(game_name))
665 write_safe(sprintf("##[ERROR] bad game name\n"))
667 elsif ((@status == "connected") || (@status == "game_waiting"))
670 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
675 if (League::Floodgate.game_name?(game_name))
676 if (my_sente_str != "*")
677 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n"), my_sente_str, game_name)
682 if (my_sente_str == "*")
683 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
684 elsif (my_sente_str == "+")
685 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
686 elsif (my_sente_str == "-")
687 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
690 write_safe(sprintf("##[ERROR] bad game option\n"))
696 @game_name = game_name
697 if ((my_sente_str == "*") && (rival.sente == nil))
705 elsif (rival.sente == true) # rival has higher priority
707 elsif (rival.sente == false)
709 elsif (my_sente_str == "+")
712 elsif (my_sente_str == "-")
718 Game::new(@game_name, self, rival)
719 else # rival not found
720 if (command_name == "GAME")
721 @status = "game_waiting"
722 @game_name = game_name
723 if (my_sente_str == "+")
725 elsif (my_sente_str == "-")
731 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
732 @status = "connected"
737 when /^%%CHAT\s+(.+)/
739 LEAGUE.players.each do |name, player|
740 if (player.protocol != LoginCSA::PROTOCOL)
741 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
746 LEAGUE.games.each do |id, game|
747 buf.push(sprintf("##[LIST] %s\n", id))
749 buf.push("##[LIST] +OK\n")
753 LEAGUE.players.each do |name, player|
754 buf.push(sprintf("##[WHO] %s\n", player.to_s))
756 buf.push("##[WHO] +OK\n")
759 @status = "connected"
760 write_safe("LOGOUT:completed\n")
763 # This command is only available for CSA's official testing server.
764 # So, this means nothing for this program.
765 write_safe("CHALLENGE ACCEPTED\n")
767 ## ignore null string
769 msg = "##[ERROR] unknown command %s\n" % [str]
781 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
782 def initialize(board, x, y, sente, promoted=false)
789 if ((x == 0) || (y == 0))
791 hands = board.sente_hands
793 hands = board.gote_hands
800 @board.array[x][y] = self
803 attr_accessor :promoted, :sente, :x, :y, :board
805 def room_of_head?(x, y, name)
810 return adjacent_movable_grids + far_movable_grids
813 def far_movable_grids
818 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
819 if ((@board.array[x][y] == nil) || # dst is empty
820 (@board.array[x][y].sente != @sente)) # dst is enemy
828 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
829 if (@board.array[x][y] == nil) # dst is empty?
836 def adjacent_movable_grids
839 moves = @promoted_moves
841 moves = @normal_moves
843 moves.each do |(dx, dy)|
850 if (jump_to?(cand_x, cand_y))
851 grids.push([cand_x, cand_y])
857 def move_to?(x, y, name)
858 return false if (! room_of_head?(x, y, name))
859 return false if ((name != @name) && (name != @promoted_name))
860 return false if (@promoted && (name != @promoted_name)) # can't un-promote
863 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
865 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
867 return false if ((6 >= @y) && (6 >= y) && (name != @name))
871 if ((@x == 0) || (@y == 0))
872 return jump_to?(x, y)
874 return movable_grids.include?([x, y])
879 if ((@x == 0) || (@y == 0))
881 @board.sente_hands.delete(self)
883 @board.gote_hands.delete(self)
885 @board.array[x][y] = self
886 elsif ((x == 0) || (y == 0))
887 @promoted = false # clear promoted flag before moving to hands
889 @board.sente_hands.push(self)
891 @board.gote_hands.push(self)
893 @board.array[@x][@y] = nil
895 @board.array[@x][@y] = nil
896 @board.array[x][y] = self
929 class PieceFU < Piece
932 @normal_moves = [[0, +1]]
933 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
935 @promoted_name = "TO"
938 def room_of_head?(x, y, name)
941 return false if (y == 1)
943 return false if (y == 9)
949 if ((iy != @y) && # not source position
950 @board.array[x][iy] &&
951 (@board.array[x][iy].sente == @sente) && # mine
952 (@board.array[x][iy].name == "FU") &&
953 (@board.array[x][iy].promoted == false))
963 class PieceKY < Piece
967 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
969 @promoted_name = "NY"
972 def room_of_head?(x, y, name)
975 return false if (y == 1)
977 return false if (y == 9)
982 def far_movable_grids
990 while (jump_to?(cand_x, cand_y))
991 grids.push([cand_x, cand_y])
992 break if (! put_to?(cand_x, cand_y))
998 while (jump_to?(cand_x, cand_y))
999 grids.push([cand_x, cand_y])
1000 break if (! put_to?(cand_x, cand_y))
1008 class PieceKE < Piece
1009 def initialize(*arg)
1011 @normal_moves = [[+1, +2], [-1, +2]]
1012 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1014 @promoted_name = "NK"
1017 def room_of_head?(x, y, name)
1020 return false if ((y == 1) || (y == 2))
1022 return false if ((y == 9) || (y == 8))
1028 class PieceGI < Piece
1029 def initialize(*arg)
1031 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1032 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1034 @promoted_name = "NG"
1038 class PieceKI < Piece
1039 def initialize(*arg)
1041 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1042 @promoted_moves = []
1044 @promoted_name = nil
1048 class PieceKA < Piece
1049 def initialize(*arg)
1052 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
1054 @promoted_name = "UM"
1057 def far_movable_grids
1062 while (jump_to?(cand_x, cand_y))
1063 grids.push([cand_x, cand_y])
1064 break if (! put_to?(cand_x, cand_y))
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 class PieceHI < Piece
1099 def initialize(*arg)
1102 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1104 @promoted_name = "RY"
1107 def far_movable_grids
1112 while (jump_to?(cand_x, cand_y))
1113 grids.push([cand_x, cand_y])
1114 break if (! put_to?(cand_x, cand_y))
1120 while (jump_to?(cand_x, cand_y))
1121 grids.push([cand_x, cand_y])
1122 break if (! put_to?(cand_x, cand_y))
1128 while (jump_to?(cand_x, cand_y))
1129 grids.push([cand_x, cand_y])
1130 break if (! put_to?(cand_x, cand_y))
1136 while (jump_to?(cand_x, cand_y))
1137 grids.push([cand_x, cand_y])
1138 break if (! put_to?(cand_x, cand_y))
1144 class PieceOU < Piece
1145 def initialize(*arg)
1147 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1148 @promoted_moves = []
1150 @promoted_name = nil
1157 @sente_hands = Array::new
1158 @gote_hands = Array::new
1159 @history = Hash::new(0)
1160 @sente_history = Hash::new(0)
1161 @gote_history = Hash::new(0)
1162 @array = [[], [], [], [], [], [], [], [], [], []]
1165 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1166 attr_reader :move_count
1169 PieceKY::new(self, 1, 1, false)
1170 PieceKE::new(self, 2, 1, false)
1171 PieceGI::new(self, 3, 1, false)
1172 PieceKI::new(self, 4, 1, false)
1173 PieceOU::new(self, 5, 1, false)
1174 PieceKI::new(self, 6, 1, false)
1175 PieceGI::new(self, 7, 1, false)
1176 PieceKE::new(self, 8, 1, false)
1177 PieceKY::new(self, 9, 1, false)
1178 PieceKA::new(self, 2, 2, false)
1179 PieceHI::new(self, 8, 2, false)
1181 PieceFU::new(self, i, 3, false)
1184 PieceKY::new(self, 1, 9, true)
1185 PieceKE::new(self, 2, 9, true)
1186 PieceGI::new(self, 3, 9, true)
1187 PieceKI::new(self, 4, 9, true)
1188 PieceOU::new(self, 5, 9, true)
1189 PieceKI::new(self, 6, 9, true)
1190 PieceGI::new(self, 7, 9, true)
1191 PieceKE::new(self, 8, 9, true)
1192 PieceKY::new(self, 9, 9, true)
1193 PieceKA::new(self, 8, 8, true)
1194 PieceHI::new(self, 2, 8, true)
1196 PieceFU::new(self, i, 7, true)
1200 def have_piece?(hands, name)
1201 piece = hands.find { |i|
1207 def move_to(x0, y0, x1, y1, name, sente)
1209 hands = @sente_hands
1214 if ((x0 == 0) || (y0 == 0))
1215 piece = have_piece?(hands, name)
1216 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1217 piece.move_to(x1, y1)
1219 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1220 if (@array[x0][y0].name != name) # promoted ?
1221 @array[x0][y0].promoted = true
1223 if (@array[x1][y1]) # capture
1224 if (@array[x1][y1].name == "OU")
1225 return :outori # return board update
1227 @array[x1][y1].sente = @array[x0][y0].sente
1228 @array[x1][y1].move_to(0, 0)
1229 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1233 @array[x0][y0].move_to(x1, y1)
1239 def look_for_ou(sente)
1245 (@array[x][y].name == "OU") &&
1246 (@array[x][y].sente == sente))
1253 raise "can't find ou"
1256 # note checkmate, but check. sente is checked.
1257 def checkmated?(sente) # sente is loosing
1258 ou = look_for_ou(sente)
1264 (@array[x][y].sente != sente))
1265 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1276 def uchifuzume?(sente)
1277 rival_ou = look_for_ou(! sente) # rival's ou
1278 if (sente) # rival is gote
1279 if ((rival_ou.y != 9) &&
1280 (@array[rival_ou.x][rival_ou.y + 1]) &&
1281 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1282 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1284 fu_y = rival_ou.y + 1
1289 if ((rival_ou.y != 0) &&
1290 (@array[rival_ou.x][rival_ou.y - 1]) &&
1291 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1292 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1294 fu_y = rival_ou.y - 1
1300 ## case: rival_ou is moving
1302 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1303 tmp_board = Marshal.load(Marshal.dump(self))
1304 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1305 raise "internal error" if (s != true)
1306 if (! tmp_board.checkmated?(! sente)) # good move
1311 ## case: rival is capturing fu
1317 (@array[x][y].sente != sente) &&
1318 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1319 if (@array[x][y].promoted)
1320 name = @array[x][y].promoted_name
1322 name = @array[x][y].name
1324 tmp_board = Marshal.load(Marshal.dump(self))
1325 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1326 raise "internal error" if (s != true)
1327 if (! tmp_board.checkmated?(! sente)) # good move
1338 # @[sente|gote]_history has at least one item while the player is checking the other or
1339 # the other escapes.
1340 def update_sennichite(player)
1343 if checkmated?(!player)
1345 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
1347 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
1351 @sente_history.clear # no more continuous check
1353 @gote_history.clear # no more continuous check
1356 if @sente_history.size > 0 # possible for Sente's or Gote's turn
1357 @sente_history[str] += 1
1359 if @gote_history.size > 0 # possible for Sente's or Gote's turn
1360 @gote_history[str] += 1
1364 def oute_sennichite?(player)
1365 if (@sente_history[to_s] >= 4)
1366 return :oute_sennichite_sente_lose
1367 elsif (@gote_history[to_s] >= 4)
1368 return :oute_sennichite_gote_lose
1374 def sennichite?(sente)
1375 if (@history[to_s] >= 4) # already 3 times
1381 def good_kachi?(sente)
1382 if (checkmated?(sente))
1383 puts "'NG: Checkmating." if $DEBUG
1387 ou = look_for_ou(sente)
1388 if (sente && (ou.y >= 4))
1389 puts "'NG: Black's OU does not enter yet." if $DEBUG
1392 if (! sente && (ou.y <= 6))
1393 puts "'NG: White's OU does not enter yet." if $DEBUG
1401 hands = @sente_hands
1411 (@array[x][y].sente == sente) &&
1412 (@array[x][y].point > 0))
1413 point = point + @array[x][y].point
1419 hands.each do |piece|
1420 point = point + piece.point
1424 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1429 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1434 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1439 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1443 # sente is nil only if tests in test_board run
1444 def handle_one_move(str, sente=nil)
1445 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1452 elsif (str =~ /^%KACHI/)
1453 raise ArgumentError, "sente is null", caller if sente == nil
1454 if (good_kachi?(sente))
1459 elsif (str =~ /^%TORYO/)
1465 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1466 ((x0 != 0) || (y0 != 0)))
1468 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1474 sente = true if sente == nil # deprecated
1475 return :illegal unless sente == true # black player's move must be black
1476 hands = @sente_hands
1478 sente = false if sente == nil # deprecated
1479 return :illegal unless sente == false # white player's move must be white
1484 if ((x0 == 0) && (y0 == 0))
1485 return :illegal if (! have_piece?(hands, name))
1486 elsif (! @array[x0][y0])
1487 return :illegal # no piece
1488 elsif (@array[x0][y0].sente != sente)
1489 return :illegal # this is not mine
1490 elsif (@array[x0][y0].name != name)
1491 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1494 ## destination check
1495 if (@array[x1][y1] &&
1496 (@array[x1][y1].sente == sente)) # can't capture mine
1498 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1499 return :illegal # can't put on existing piece
1502 tmp_board = Marshal.load(Marshal.dump(self))
1503 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1504 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1505 tmp_board.update_sennichite(sente)
1506 os_result = tmp_board.oute_sennichite?(sente)
1507 return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
1508 return :sennichite if tmp_board.sennichite?(sente)
1510 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1514 move_to(x0, y0, x1, y1, name, sente)
1517 update_sennichite(sente)
1525 a.push(sprintf("P%d", y))
1528 piece = @array[x][y]
1537 a.push(sprintf("\n"))
1540 if (! sente_hands.empty?)
1542 sente_hands.each do |p|
1543 a.push("00" + p.name)
1547 if (! gote_hands.empty?)
1549 gote_hands.each do |p|
1550 a.push("00" + p.name)
1560 attr_reader :players, :black, :white
1562 def initialize(p1, p2)
1564 if p1.sente && !p2.sente
1565 @black, @white = p1, p2
1566 elsif !p1.sente && p2.sente
1567 @black, @white = p2, p1
1569 raise "Never reached!"
1574 class GameResultWin < GameResult
1575 attr_reader :winner, :loser
1577 def initialize(winner, loser)
1579 @winner, @loser = winner, loser
1583 black_name = @black.id || @black.name
1584 white_name = @white.id || @white.name
1585 "%s:%s" % [black_name, white_name]
1589 class GameResultDraw < GameResult
1597 def initialize(game_name, player0, player1)
1598 @monitors = Array::new
1599 @game_name = game_name
1600 if (@game_name =~ /-(\d+)-(\d+)$/)
1601 @total_time = $1.to_i
1612 @current_player = @sente
1613 @next_player = @gote
1621 @sente.status = "agree_waiting"
1622 @gote.status = "agree_waiting"
1624 @id = sprintf("%s+%s+%s+%s+%s",
1625 LEAGUE.event, @game_name, @sente.name, @gote.name, issue_current_time)
1626 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1628 LEAGUE.games[@id] = self
1630 log_message(sprintf("game created %s", @id))
1640 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1641 attr_accessor :last_move, :current_turn
1645 @sente.rated? && @gote.rated?
1648 def monitoron(monitor)
1649 @monitors.delete(monitor)
1650 @monitors.push(monitor)
1653 def monitoroff(monitor)
1654 @monitors.delete(monitor)
1657 def reject(rejector)
1658 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1659 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1664 if ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
1666 elsif (@current_player == killer)
1673 log_message(sprintf("game finished %s", @id))
1674 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1679 @sente.status = "connected"
1680 @gote.status = "connected"
1682 if (@current_player.protocol == LoginCSA::PROTOCOL)
1683 @current_player.finish
1685 if (@next_player.protocol == LoginCSA::PROTOCOL)
1688 @monitors = Array::new
1691 @current_player = nil
1693 LEAGUE.games.delete(@id)
1696 def handle_one_move(str, player)
1698 if (@current_player == player)
1699 @end_time = Time::new
1700 t = (@end_time - @start_time).floor
1701 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
1704 if ((@current_player.mytime - t <= -@byoyomi) && ((@total_time > 0) || (@byoyomi > 0)))
1706 elsif (str == :timeout)
1707 return false # time isn't expired. players aren't swapped. continue game
1709 @current_player.mytime = @current_player.mytime - t
1710 if (@current_player.mytime < 0)
1711 @current_player.mytime = 0
1715 move_status = @board.handle_one_move(str, @sente == @current_player)
1717 # log_error("handle_one_move raise exception for #{str}")
1718 # move_status = :illegal
1721 if ((move_status == :illegal) || (move_status == :uchifuzme) || (move_status == :oute_kaihimore))
1722 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1724 if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite_sente_lose) || (move_status == :oute_sennichite_gote_lose))
1725 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1726 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1727 @fh.printf("%s\nT%d\n", str, t)
1728 @last_move = sprintf("%s,T%d", str, t)
1729 @current_turn = @current_turn + 1
1732 @monitors.each do |monitor|
1733 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1734 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1739 if (@next_player.status != "game") # rival is logout or disconnected
1741 elsif (status == :timeout)
1743 elsif (move_status == :illegal)
1745 elsif (move_status == :kachi_win)
1747 elsif (move_status == :kachi_lose)
1749 elsif (move_status == :toryo)
1751 elsif (move_status == :outori)
1753 elsif (move_status == :oute_sennichite_sente_lose)
1754 oute_sennichite_win_lose(@gote, @sente) # Sente is checking
1755 elsif (move_status == :oute_sennichite_gote_lose)
1756 oute_sennichite_win_lose(@sente, @gote) # Gote is checking
1757 elsif (move_status == :sennichite)
1759 elsif (move_status == :uchifuzume)
1761 elsif (move_status == :oute_kaihimore)
1762 oute_kaihimore_lose()
1766 finish() if finish_flag
1767 (@current_player, @next_player) = [@next_player, @current_player]
1768 @start_time = Time::new
1774 @current_player.status = "connected"
1775 @next_player.status = "connected"
1776 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1777 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1778 @fh.printf("%%TORYO\n")
1779 @fh.print(@board.to_s.gsub(/^/, "\'"))
1780 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1781 @result = GameResultWin.new(@current_player, @next_player)
1782 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1783 @monitors.each do |monitor|
1784 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1789 @current_player.status = "connected"
1790 @next_player.status = "connected"
1791 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1792 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1793 @fh.printf("%%TORYO\n")
1794 @fh.print(@board.to_s.gsub(/^/, "\'"))
1795 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1796 @result = GameResultWin.new(@next_player, @current_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("#SENNICHITE\n#DRAW\n")
1807 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1808 @fh.print(@board.to_s.gsub(/^/, "\'"))
1809 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1810 @result = GameResultDraw.new(@current_player, @next_player)
1811 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1812 @monitors.each do |monitor|
1813 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @id))
1817 def oute_sennichite_win_lose(winner, loser)
1818 @current_player.status = "connected"
1819 @next_player.status = "connected"
1820 loser.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1821 winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1822 @fh.print(@board.to_s.gsub(/^/, "\'"))
1823 if loser == @current_player
1824 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1826 @fh.printf("'summary:oute_sennichite:%s win:%s lose\n", @current_player.name, @next_player.name)
1828 @result = GameResultWin.new(winner, loser)
1829 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1830 @monitors.each do |monitor|
1831 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
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:illegal move:%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("#ILLEGAL_MOVE\n#LOSE\n")
1853 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1854 @fh.print(@board.to_s.gsub(/^/, "\'"))
1855 @fh.printf("'summary:uchifuzume:%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] #ILLEGAL_MOVE\n", @id))
1863 def oute_kaihimore_lose
1864 @current_player.status = "connected"
1865 @next_player.status = "connected"
1866 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1867 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1868 @fh.print(@board.to_s.gsub(/^/, "\'"))
1869 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1870 @result = GameResultWin.new(@next_player, @current_player)
1871 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1872 @monitors.each do |monitor|
1873 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1878 @current_player.status = "connected"
1879 @next_player.status = "connected"
1880 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1881 @next_player.write_safe("#TIME_UP\n#WIN\n")
1882 @fh.print(@board.to_s.gsub(/^/, "\'"))
1883 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1884 @result = GameResultWin.new(@next_player, @current_player)
1885 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1886 @monitors.each do |monitor|
1887 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
1892 @current_player.status = "connected"
1893 @next_player.status = "connected"
1894 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1895 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1896 @fh.printf("%%KACHI\n")
1897 @fh.print(@board.to_s.gsub(/^/, "\'"))
1898 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1899 @result = GameResultWin.new(@current_player, @next_player)
1900 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1901 @monitors.each do |monitor|
1902 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1907 @current_player.status = "connected"
1908 @next_player.status = "connected"
1909 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1910 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1911 @fh.printf("%%KACHI\n")
1912 @fh.print(@board.to_s.gsub(/^/, "\'"))
1913 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1914 @result = GameResultWin.new(@next_player, @current_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("%TORYO\n#RESIGN\n#LOSE\n")
1925 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1926 @fh.printf("%%TORYO\n")
1927 @fh.print(@board.to_s.gsub(/^/, "\'"))
1928 @fh.printf("'summary:toryo:%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] %%TORYO\n", @id))
1937 @current_player.status = "connected"
1938 @next_player.status = "connected"
1939 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1940 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1941 @fh.print(@board.to_s.gsub(/^/, "\'"))
1942 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1943 @result = GameResultWin.new(@current_player, @next_player)
1944 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1945 @monitors.each do |monitor|
1946 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1951 log_message(sprintf("game started %s", @id))
1952 @sente.write_safe(sprintf("START:%s\n", @id))
1953 @gote.write_safe(sprintf("START:%s\n", @id))
1954 @sente.mytime = @total_time
1955 @gote.mytime = @total_time
1956 @start_time = Time::new
1960 @fh = open(@logfile, "w")
1964 @fh.puts("N+#{@sente.name}")
1965 @fh.puts("N-#{@gote.name}")
1966 @fh.puts("$EVENT:#{@id}")
1968 @sente.write_safe(propose_message("+"))
1969 @gote.write_safe(propose_message("-"))
1971 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
1972 @fh.puts("$START_TIME:#{now}")
1974 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1975 P2 * -HI * * * * * -KA *
1976 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1977 P4 * * * * * * * * *
1978 P5 * * * * * * * * *
1979 P6 * * * * * * * * *
1980 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1981 P8 * +KA * * * * * +HI *
1982 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1990 Protocol_Version:1.1
1991 Protocol_Mode:Server
1993 Declaration:Jishogi 1.1
1995 Name+:#{@sente.name}
2001 Total_Time:#{@total_time}
2003 Least_Time_Per_Move:#{Least_Time_Per_Move}
2004 Remaining_Time+:#{@sente.mytime}
2005 Remaining_Time-:#{@gote.mytime}
2006 Last_Move:#{@last_move}
2007 Current_Turn:#{@current_turn}
2017 return str0 + @board.to_s + str1
2020 def propose_message(sg_flag)
2023 Protocol_Version:1.1
2024 Protocol_Mode:Server
2026 Declaration:Jishogi 1.1
2028 Name+:#{@sente.name}
2030 Your_Turn:#{sg_flag}
2035 Total_Time:#{@total_time}
2037 Least_Time_Per_Move:#{Least_Time_Per_Move}
2040 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2041 P2 * -HI * * * * * -KA *
2042 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2043 P4 * * * * * * * * *
2044 P5 * * * * * * * * *
2045 P6 * * * * * * * * *
2046 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2047 P8 * +KA * * * * * +HI *
2048 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2060 def issue_current_time
2061 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
2062 @@mutex.synchronize do
2063 while time <= @@time do
2070 end # module ShogiServer
2072 #################################################
2079 shogi-server - server for CSA server protocol
2082 shogi-server [OPTIONS] event_name port_number
2085 server for CSA server protocol
2089 specify filename for logging process ID
2091 run as a daemon. Log files will be put in dir.
2094 this file is distributed under GPL version2 and might be compiled by Exerb
2099 #{ShogiServer::Release}
2102 #{ShogiServer::Revision}
2110 def log_message(str)
2114 def log_warning(str)
2123 def parse_command_line
2125 parser = GetoptLong.new( ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2126 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT]
2130 parser.each_option do |name, arg|
2131 name.sub!(/^--/, '')
2132 options[name] = arg.dup
2136 raise parser.error_message
2141 def write_pid_file(file)
2142 open(file, "w") do |fh|
2147 def mutex_watchdog(mutex, sec)
2159 log_error("mutex watchdog timeout")
2170 mutex_watchdog($mutex, 10)
2173 $options = parse_command_line
2174 if (ARGV.length != 2)
2179 LEAGUE.event = ARGV.shift
2182 dir = $options["daemon"]
2183 dir = File.expand_path(dir) if dir
2184 if dir && ! File.exist?(dir)
2185 FileUtils.mkdir(dir)
2187 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2188 $logger = WEBrick::Log.new(log_file)
2190 LEAGUE.dir = dir || File.dirname(__FILE__)
2191 LEAGUE.setup_players_database
2194 config[:Port] = port
2195 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2196 config[:Logger] = $logger
2197 if $options["pid-file"]
2198 pid_file = File.expand_path($options["pid-file"])
2199 config[:StartCallback] = Proc.new do
2200 write_pid_file(pid_file)
2202 config[:StopCallback] = Proc.new do
2203 FileUtils.rm(pid_file, :force => true)
2207 server = WEBrick::GenericServer.new(config)
2208 ["INT", "TERM"].each do |signal|
2214 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2215 log_message("server started [Revision: #{ShogiServer::Revision}]")
2217 server.start do |client|
2218 # client.sync = true # this is already set in WEBrick
2219 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2220 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2223 while (str = client.gets_timeout(ShogiServer::Login_Time))
2228 if (ShogiServer::Login::good_login?(str))
2229 player = ShogiServer::Player::new(str, client)
2231 login = ShogiServer::Login::factory(str, player)
2232 if (LEAGUE.players[player.name])
2233 if ((LEAGUE.players[player.name].password == player.password) &&
2234 (LEAGUE.players[player.name].status != "game"))
2235 log_message(sprintf("user %s login forcely", player.name))
2236 LEAGUE.players[player.name].kill
2238 login.incorrect_duplicated_player(str)
2249 client.write_safe("LOGIN:incorrect" + eol)
2250 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2262 log_message(sprintf("user %s login", player.name))
2264 player.run(login.csa_1st_str)
2268 player.game.kill(player)
2270 player.finish # socket has been closed
2271 LEAGUE.delete(player)
2272 log_message(sprintf("user %s logout", player.name))
2283 TCPSocket.do_not_reverse_lookup = true
2284 Thread.abort_on_exception = true
2286 LEAGUE = ShogiServer::League::new