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 def start_game(p1, p2)
100 Game.new(p1.game_name, p1, p2)
103 def delete_most_playing_player(players)
104 if players.size % 2 == 1
105 max_player = players.max {|a,b| a.win + a.loss <=> b.win + b.loss}
106 players.delete(max_player)
111 class RandomPairing < Pairing
114 log_message("Floodgate: too few players [%d]" % [players.size])
117 log_message("Floodgate: found %d players. Making games..." % [players.size])
118 delete_most_playing_player(players)
120 random_players = players.sort{ rand < 0.5 ? 1 : -1 }
121 pairs = [[random_players.shift]]
122 while !random_players.empty? do
123 if pairs.last.size < 2
124 pairs.last << random_players.shift
126 pairs << [random_players.shift]
130 start_game(pair.first, pair.last)
138 return /^floodgate-\d+-\d+$/.match(str) ? true : false
142 def initialize(league)
145 @pairing = RandomPairing.new
150 @thread = Thread.new do
155 next if Time.now < @next_time
159 rescue Exception => ex
161 log_error("[in Floodgate's thread] #{ex}")
168 @thread.kill if @thread
176 @next_time = Time.mktime(now.year, now.month, now.day, now.hour, 30)
178 @next_time = Time.mktime(now.year, now.month, now.day, now.hour) + 3600
182 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min, 30)
184 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min) + 60
189 players = @league.find_all_players do |pl|
190 pl.status == "game_waiting" &&
191 Floodgate.game_name?(pl.game_name) &&
194 @pairing.match(players)
196 end # class Floodgate
199 @mutex = Mutex.new # guard @players
203 @dir = File.dirname(__FILE__)
204 @floodgate = Floodgate.new(self)
207 attr_accessor :players, :games, :event, :dir
213 # this should be called just after instanciating a League object.
214 def setup_players_database
215 @db = YAML::Store.new(File.join(@dir, "players.yaml"))
219 self.load(player) if player.id
220 @mutex.synchronize do
221 @players[player.name] = player
226 @mutex.synchronize do
227 @players.delete(player.name)
232 @players.each {|player| load(player)}
237 @mutex.synchronize do
238 found = @players.find_all do |name, player|
242 return found.map {|a| a.last}
245 def get_player(status, game_name, sente, searcher)
247 @mutex.synchronize do
248 found = @players.find do |name, player|
249 (player.status == status) &&
250 (player.game_name == game_name) &&
252 (player.sente == nil) ||
253 (player.sente == sente) ) &&
254 (player.name != searcher.name)
257 return found ? found.last : nil
261 hash = search(player.id)
264 player.name = hash['name']
265 player.rate = hash['rate']
266 player.modified_at = hash['last_modified']
267 player.rating_group = hash['rating_group']
268 player.win = hash['win']
269 player.loss = hash['loss']
276 break unless @db["players"]
277 @db["players"].each do |group, players|
287 @db.transaction(true) do
288 break unless @db["players"]
289 @db["players"].each do |group, players_hash|
290 players << players_hash.keys
293 return players.flatten.collect do |id|
303 ######################################################
304 # Processes the LOGIN command.
307 def Login.good_login?(str)
309 if (((tokens.length == 3) || ((tokens.length == 4) && tokens[3] == "x1")) &&
310 (tokens[0] == "LOGIN") &&
311 (good_identifier?(tokens[1])))
318 def Login.good_game_name?(str)
319 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
326 def Login.good_identifier?(str)
327 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
334 def Login.factory(str, player)
335 (login, player.name, password, ext) = str.chomp.split
337 return Loginx1.new(player, password)
339 return LoginCSA.new(player, password)
345 # the first command that will be executed just after LOGIN.
346 # If it is nil, the default process will be started.
347 attr_reader :csa_1st_str
349 def initialize(player, password)
352 parse_password(password)
356 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
357 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
360 def incorrect_duplicated_player(str)
361 @player.write_safe("LOGIN:incorrect\n")
362 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
363 sleep 3 # wait for sending the above messages.
364 @player.name = "%s [duplicated]" % [@player.name]
369 ######################################################
370 # Processes LOGIN for the CSA standard mode.
372 class LoginCSA < Login
375 def initialize(player, password)
378 @player.protocol = PROTOCOL
381 def parse_password(password)
382 if Login.good_game_name?(password)
384 @player.set_password(nil)
385 elsif password.split(",").size > 1
386 @gamename, *trip = password.split(",")
387 @player.set_password(trip.join(","))
389 @player.set_password(password)
390 @gamename = Default_Game_Name
392 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
397 @csa_1st_str = "%%GAME #{@gamename} *"
401 ######################################################
402 # Processes LOGIN for the extented mode.
404 class Loginx1 < Login
407 def initialize(player, password)
409 @player.protocol = PROTOCOL
412 def parse_password(password)
413 @player.set_password(password)
418 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
424 # Idetifier of the player in the rating system
430 # Password of the player, which does not include a trip
431 attr_accessor :password
433 # Score in the rating sysem
436 # Number of games for win and loss in the rating system
437 attr_accessor :win, :loss
439 # Group in the rating system
440 attr_accessor :rating_group
442 # Last timestamp when the rate was modified
443 attr_accessor :modified_at
451 @modified_at || Time.now
457 @modified_at = Time.now
467 simple_name = @name.gsub(/@.*?$/, '')
468 "%s+%s" % [simple_name, @trip[0..8]]
475 # Parses str in the LOGIN command, sets up @id and @trip
477 def set_password(str)
478 if str && !str.empty?
479 @password = str.strip
480 @id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
482 @id = @password = nil
488 class Player < BasicPlayer
489 def initialize(str, socket)
492 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
494 @protocol = nil # CSA or x1
495 @eol = "\m" # favorite eol code
498 @mytime = 0 # set in start method also
500 @write_queue = Queue::new
501 @main_thread = Thread::current
502 @writer_thread = Thread::start do
508 attr_accessor :socket, :status
509 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
510 attr_accessor :main_thread, :writer_thread, :write_queue
513 log_message(sprintf("user %s killed", @name))
518 Thread::kill(@main_thread) if @main_thread
522 if (@status != "finished")
524 log_message(sprintf("user %s finish", @name))
525 # TODO you should confirm that there is no message in the queue.
526 Thread::kill(@writer_thread) if @writer_thread
528 # @socket.close if (! @socket.closed?)
530 log_message(sprintf("user %s finish failed", @name))
536 @write_queue.push(str.gsub(/[\r\n]+/, @eol))
540 while (str = @write_queue.pop)
543 rescue Exception => ex
544 log_error("Failed to send a message to #{@name}.")
545 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
552 if ((status == "game_waiting") ||
553 (status == "start_waiting") ||
554 (status == "agree_waiting") ||
557 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
558 elsif (@sente == false)
559 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
560 elsif (@sente == nil)
561 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
564 return sprintf("%s %s %s", @name, @protocol, @status)
568 def run(csa_1st_str=nil)
569 while (csa_1st_str || (str = @socket.gets_safe(Default_Timeout)))
573 if (@writer_thread == nil || @writer_thread.status == false)
574 # The writer_thread has been killed because of socket errors.
582 if (@write_queue.size > Max_Write_Queue_Size)
583 log_warning(sprintf("write_queue of %s is %d", @name, @write_queue.size))
587 if (@status == "finished")
590 str.chomp! if (str.class == String) # may be strip! ?
591 log_message(str) if $DEBUG
594 # Application-level protocol for Keep-Alive
595 # If the server gets LF, it sends back LF.
596 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
599 if (@status == "game")
600 array_str = str.split(",")
601 move = array_str.shift
602 additional = array_str.shift
603 if /^'(.*)/ =~ additional
604 comment = array_str.unshift("'*#{$1}")
606 s = @game.handle_one_move(move, self)
607 @game.fh.print("#{comment}\n") if (comment && !s)
608 return if (s && @protocol == LoginCSA::PROTOCOL)
610 when /^%[^%]/, :timeout
611 if (@status == "game")
612 s = @game.handle_one_move(str, self)
613 return if (s && @protocol == LoginCSA::PROTOCOL)
616 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
617 # rescue Exception => ex
618 # log_error("Failed to send a keepalive to #{@name}.")
619 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
624 log_error("Failed to receive a message from #{@name}.")
627 if (@status == "agree_waiting")
629 return if (@protocol == LoginCSA::PROTOCOL)
631 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
634 if (@status == "agree_waiting")
635 @status = "start_waiting"
636 if ((@game.sente.status == "start_waiting") &&
637 (@game.gote.status == "start_waiting"))
639 @game.sente.status = "game"
640 @game.gote.status = "game"
643 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
645 when /^%%SHOW\s+(\S+)/
647 if (LEAGUE.games[game_id])
648 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
650 write_safe("##[SHOW] +OK\n")
651 when /^%%MONITORON\s+(\S+)/
653 if (LEAGUE.games[game_id])
654 LEAGUE.games[game_id].monitoron(self)
655 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
656 write_safe("##[MONITOR][#{game_id}] +OK\n")
658 when /^%%MONITOROFF\s+(\S+)/
660 if (LEAGUE.games[game_id])
661 LEAGUE.games[game_id].monitoroff(self)
665 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
667 players = LEAGUE.rated_players
668 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
669 write_safe("##[RATING] %s \t %4d @%s\n" %
670 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
672 write_safe("##[RATING] +OK\n")
674 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
675 write_safe("##[VERSION] +OK\n")
677 if ((@status == "connected") || (@status == "game_waiting"))
678 @status = "connected"
681 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
683 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
687 if (! Login::good_game_name?(game_name))
688 write_safe(sprintf("##[ERROR] bad game name\n"))
690 elsif ((@status == "connected") || (@status == "game_waiting"))
693 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
698 if (League::Floodgate.game_name?(game_name))
699 if (my_sente_str != "*")
700 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n"), my_sente_str, game_name)
705 if (my_sente_str == "*")
706 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
707 elsif (my_sente_str == "+")
708 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
709 elsif (my_sente_str == "-")
710 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
713 write_safe(sprintf("##[ERROR] bad game option\n"))
719 @game_name = game_name
720 if ((my_sente_str == "*") && (rival.sente == nil))
728 elsif (rival.sente == true) # rival has higher priority
730 elsif (rival.sente == false)
732 elsif (my_sente_str == "+")
735 elsif (my_sente_str == "-")
741 Game::new(@game_name, self, rival)
742 else # rival not found
743 if (command_name == "GAME")
744 @status = "game_waiting"
745 @game_name = game_name
746 if (my_sente_str == "+")
748 elsif (my_sente_str == "-")
754 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
755 @status = "connected"
760 when /^%%CHAT\s+(.+)/
762 LEAGUE.players.each do |name, player|
763 if (player.protocol != LoginCSA::PROTOCOL)
764 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
769 LEAGUE.games.each do |id, game|
770 buf.push(sprintf("##[LIST] %s\n", id))
772 buf.push("##[LIST] +OK\n")
776 LEAGUE.players.each do |name, player|
777 buf.push(sprintf("##[WHO] %s\n", player.to_s))
779 buf.push("##[WHO] +OK\n")
782 @status = "connected"
783 write_safe("LOGOUT:completed\n")
786 # This command is only available for CSA's official testing server.
787 # So, this means nothing for this program.
788 write_safe("CHALLENGE ACCEPTED\n")
790 ## ignore null string
792 msg = "##[ERROR] unknown command %s\n" % [str]
804 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
805 def initialize(board, x, y, sente, promoted=false)
812 if ((x == 0) || (y == 0))
814 hands = board.sente_hands
816 hands = board.gote_hands
823 @board.array[x][y] = self
826 attr_accessor :promoted, :sente, :x, :y, :board
828 def room_of_head?(x, y, name)
833 return adjacent_movable_grids + far_movable_grids
836 def far_movable_grids
841 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
842 if ((@board.array[x][y] == nil) || # dst is empty
843 (@board.array[x][y].sente != @sente)) # dst is enemy
851 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
852 if (@board.array[x][y] == nil) # dst is empty?
859 def adjacent_movable_grids
862 moves = @promoted_moves
864 moves = @normal_moves
866 moves.each do |(dx, dy)|
873 if (jump_to?(cand_x, cand_y))
874 grids.push([cand_x, cand_y])
880 def move_to?(x, y, name)
881 return false if (! room_of_head?(x, y, name))
882 return false if ((name != @name) && (name != @promoted_name))
883 return false if (@promoted && (name != @promoted_name)) # can't un-promote
886 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
888 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
890 return false if ((6 >= @y) && (6 >= y) && (name != @name))
894 if ((@x == 0) || (@y == 0))
895 return jump_to?(x, y)
897 return movable_grids.include?([x, y])
902 if ((@x == 0) || (@y == 0))
904 @board.sente_hands.delete(self)
906 @board.gote_hands.delete(self)
908 @board.array[x][y] = self
909 elsif ((x == 0) || (y == 0))
910 @promoted = false # clear promoted flag before moving to hands
912 @board.sente_hands.push(self)
914 @board.gote_hands.push(self)
916 @board.array[@x][@y] = nil
918 @board.array[@x][@y] = nil
919 @board.array[x][y] = self
952 class PieceFU < Piece
955 @normal_moves = [[0, +1]]
956 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
958 @promoted_name = "TO"
961 def room_of_head?(x, y, name)
964 return false if (y == 1)
966 return false if (y == 9)
972 if ((iy != @y) && # not source position
973 @board.array[x][iy] &&
974 (@board.array[x][iy].sente == @sente) && # mine
975 (@board.array[x][iy].name == "FU") &&
976 (@board.array[x][iy].promoted == false))
986 class PieceKY < Piece
990 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
992 @promoted_name = "NY"
995 def room_of_head?(x, y, name)
998 return false if (y == 1)
1000 return false if (y == 9)
1005 def far_movable_grids
1013 while (jump_to?(cand_x, cand_y))
1014 grids.push([cand_x, cand_y])
1015 break if (! put_to?(cand_x, cand_y))
1021 while (jump_to?(cand_x, cand_y))
1022 grids.push([cand_x, cand_y])
1023 break if (! put_to?(cand_x, cand_y))
1031 class PieceKE < Piece
1032 def initialize(*arg)
1034 @normal_moves = [[+1, +2], [-1, +2]]
1035 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1037 @promoted_name = "NK"
1040 def room_of_head?(x, y, name)
1043 return false if ((y == 1) || (y == 2))
1045 return false if ((y == 9) || (y == 8))
1051 class PieceGI < Piece
1052 def initialize(*arg)
1054 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1055 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1057 @promoted_name = "NG"
1061 class PieceKI < Piece
1062 def initialize(*arg)
1064 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1065 @promoted_moves = []
1067 @promoted_name = nil
1071 class PieceKA < Piece
1072 def initialize(*arg)
1075 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
1077 @promoted_name = "UM"
1080 def far_movable_grids
1085 while (jump_to?(cand_x, cand_y))
1086 grids.push([cand_x, cand_y])
1087 break if (! put_to?(cand_x, cand_y))
1094 while (jump_to?(cand_x, cand_y))
1095 grids.push([cand_x, cand_y])
1096 break if (! put_to?(cand_x, cand_y))
1103 while (jump_to?(cand_x, cand_y))
1104 grids.push([cand_x, cand_y])
1105 break if (! put_to?(cand_x, cand_y))
1112 while (jump_to?(cand_x, cand_y))
1113 grids.push([cand_x, cand_y])
1114 break if (! put_to?(cand_x, cand_y))
1121 class PieceHI < Piece
1122 def initialize(*arg)
1125 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1127 @promoted_name = "RY"
1130 def far_movable_grids
1135 while (jump_to?(cand_x, cand_y))
1136 grids.push([cand_x, cand_y])
1137 break if (! put_to?(cand_x, cand_y))
1143 while (jump_to?(cand_x, cand_y))
1144 grids.push([cand_x, cand_y])
1145 break if (! put_to?(cand_x, cand_y))
1151 while (jump_to?(cand_x, cand_y))
1152 grids.push([cand_x, cand_y])
1153 break if (! put_to?(cand_x, cand_y))
1159 while (jump_to?(cand_x, cand_y))
1160 grids.push([cand_x, cand_y])
1161 break if (! put_to?(cand_x, cand_y))
1167 class PieceOU < Piece
1168 def initialize(*arg)
1170 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1171 @promoted_moves = []
1173 @promoted_name = nil
1180 @sente_hands = Array::new
1181 @gote_hands = Array::new
1182 @history = Hash::new(0)
1183 @sente_history = Hash::new(0)
1184 @gote_history = Hash::new(0)
1185 @array = [[], [], [], [], [], [], [], [], [], []]
1188 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1189 attr_reader :move_count
1192 PieceKY::new(self, 1, 1, false)
1193 PieceKE::new(self, 2, 1, false)
1194 PieceGI::new(self, 3, 1, false)
1195 PieceKI::new(self, 4, 1, false)
1196 PieceOU::new(self, 5, 1, false)
1197 PieceKI::new(self, 6, 1, false)
1198 PieceGI::new(self, 7, 1, false)
1199 PieceKE::new(self, 8, 1, false)
1200 PieceKY::new(self, 9, 1, false)
1201 PieceKA::new(self, 2, 2, false)
1202 PieceHI::new(self, 8, 2, false)
1204 PieceFU::new(self, i, 3, false)
1207 PieceKY::new(self, 1, 9, true)
1208 PieceKE::new(self, 2, 9, true)
1209 PieceGI::new(self, 3, 9, true)
1210 PieceKI::new(self, 4, 9, true)
1211 PieceOU::new(self, 5, 9, true)
1212 PieceKI::new(self, 6, 9, true)
1213 PieceGI::new(self, 7, 9, true)
1214 PieceKE::new(self, 8, 9, true)
1215 PieceKY::new(self, 9, 9, true)
1216 PieceKA::new(self, 8, 8, true)
1217 PieceHI::new(self, 2, 8, true)
1219 PieceFU::new(self, i, 7, true)
1223 def have_piece?(hands, name)
1224 piece = hands.find { |i|
1230 def move_to(x0, y0, x1, y1, name, sente)
1232 hands = @sente_hands
1237 if ((x0 == 0) || (y0 == 0))
1238 piece = have_piece?(hands, name)
1239 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1240 piece.move_to(x1, y1)
1242 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1243 if (@array[x0][y0].name != name) # promoted ?
1244 @array[x0][y0].promoted = true
1246 if (@array[x1][y1]) # capture
1247 if (@array[x1][y1].name == "OU")
1248 return :outori # return board update
1250 @array[x1][y1].sente = @array[x0][y0].sente
1251 @array[x1][y1].move_to(0, 0)
1252 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1256 @array[x0][y0].move_to(x1, y1)
1262 def look_for_ou(sente)
1268 (@array[x][y].name == "OU") &&
1269 (@array[x][y].sente == sente))
1276 raise "can't find ou"
1279 # note checkmate, but check. sente is checked.
1280 def checkmated?(sente) # sente is loosing
1281 ou = look_for_ou(sente)
1287 (@array[x][y].sente != sente))
1288 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1299 def uchifuzume?(sente)
1300 rival_ou = look_for_ou(! sente) # rival's ou
1301 if (sente) # rival is gote
1302 if ((rival_ou.y != 9) &&
1303 (@array[rival_ou.x][rival_ou.y + 1]) &&
1304 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1305 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1307 fu_y = rival_ou.y + 1
1312 if ((rival_ou.y != 0) &&
1313 (@array[rival_ou.x][rival_ou.y - 1]) &&
1314 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1315 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1317 fu_y = rival_ou.y - 1
1323 ## case: rival_ou is moving
1325 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1326 tmp_board = Marshal.load(Marshal.dump(self))
1327 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1328 raise "internal error" if (s != true)
1329 if (! tmp_board.checkmated?(! sente)) # good move
1334 ## case: rival is capturing fu
1340 (@array[x][y].sente != sente) &&
1341 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1342 if (@array[x][y].promoted)
1343 name = @array[x][y].promoted_name
1345 name = @array[x][y].name
1347 tmp_board = Marshal.load(Marshal.dump(self))
1348 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1349 raise "internal error" if (s != true)
1350 if (! tmp_board.checkmated?(! sente)) # good move
1361 # @[sente|gote]_history has at least one item while the player is checking the other or
1362 # the other escapes.
1363 def update_sennichite(player)
1366 if checkmated?(!player)
1368 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
1370 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
1374 @sente_history.clear # no more continuous check
1376 @gote_history.clear # no more continuous check
1379 if @sente_history.size > 0 # possible for Sente's or Gote's turn
1380 @sente_history[str] += 1
1382 if @gote_history.size > 0 # possible for Sente's or Gote's turn
1383 @gote_history[str] += 1
1387 def oute_sennichite?(player)
1388 if (@sente_history[to_s] >= 4)
1389 return :oute_sennichite_sente_lose
1390 elsif (@gote_history[to_s] >= 4)
1391 return :oute_sennichite_gote_lose
1397 def sennichite?(sente)
1398 if (@history[to_s] >= 4) # already 3 times
1404 def good_kachi?(sente)
1405 if (checkmated?(sente))
1406 puts "'NG: Checkmating." if $DEBUG
1410 ou = look_for_ou(sente)
1411 if (sente && (ou.y >= 4))
1412 puts "'NG: Black's OU does not enter yet." if $DEBUG
1415 if (! sente && (ou.y <= 6))
1416 puts "'NG: White's OU does not enter yet." if $DEBUG
1424 hands = @sente_hands
1434 (@array[x][y].sente == sente) &&
1435 (@array[x][y].point > 0))
1436 point = point + @array[x][y].point
1442 hands.each do |piece|
1443 point = point + piece.point
1447 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1452 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1457 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1462 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1466 # sente is nil only if tests in test_board run
1467 def handle_one_move(str, sente=nil)
1468 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1475 elsif (str =~ /^%KACHI/)
1476 raise ArgumentError, "sente is null", caller if sente == nil
1477 if (good_kachi?(sente))
1482 elsif (str =~ /^%TORYO/)
1488 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1489 ((x0 != 0) || (y0 != 0)))
1491 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1497 sente = true if sente == nil # deprecated
1498 return :illegal unless sente == true # black player's move must be black
1499 hands = @sente_hands
1501 sente = false if sente == nil # deprecated
1502 return :illegal unless sente == false # white player's move must be white
1507 if ((x0 == 0) && (y0 == 0))
1508 return :illegal if (! have_piece?(hands, name))
1509 elsif (! @array[x0][y0])
1510 return :illegal # no piece
1511 elsif (@array[x0][y0].sente != sente)
1512 return :illegal # this is not mine
1513 elsif (@array[x0][y0].name != name)
1514 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1517 ## destination check
1518 if (@array[x1][y1] &&
1519 (@array[x1][y1].sente == sente)) # can't capture mine
1521 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1522 return :illegal # can't put on existing piece
1525 tmp_board = Marshal.load(Marshal.dump(self))
1526 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1527 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1528 tmp_board.update_sennichite(sente)
1529 os_result = tmp_board.oute_sennichite?(sente)
1530 return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
1531 return :sennichite if tmp_board.sennichite?(sente)
1533 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1537 move_to(x0, y0, x1, y1, name, sente)
1540 update_sennichite(sente)
1548 a.push(sprintf("P%d", y))
1551 piece = @array[x][y]
1560 a.push(sprintf("\n"))
1563 if (! sente_hands.empty?)
1565 sente_hands.each do |p|
1566 a.push("00" + p.name)
1570 if (! gote_hands.empty?)
1572 gote_hands.each do |p|
1573 a.push("00" + p.name)
1583 attr_reader :players, :black, :white
1585 def initialize(p1, p2)
1587 if p1.sente && !p2.sente
1588 @black, @white = p1, p2
1589 elsif !p1.sente && p2.sente
1590 @black, @white = p2, p1
1592 raise "Never reached!"
1597 class GameResultWin < GameResult
1598 attr_reader :winner, :loser
1600 def initialize(winner, loser)
1602 @winner, @loser = winner, loser
1606 black_name = @black.id || @black.name
1607 white_name = @white.id || @white.name
1608 "%s:%s" % [black_name, white_name]
1612 class GameResultDraw < GameResult
1620 def initialize(game_name, player0, player1)
1621 @monitors = Array::new
1622 @game_name = game_name
1623 if (@game_name =~ /-(\d+)-(\d+)$/)
1624 @total_time = $1.to_i
1635 @current_player = @sente
1636 @next_player = @gote
1644 @sente.status = "agree_waiting"
1645 @gote.status = "agree_waiting"
1647 @id = sprintf("%s+%s+%s+%s+%s",
1648 LEAGUE.event, @game_name, @sente.name, @gote.name, issue_current_time)
1649 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1651 LEAGUE.games[@id] = self
1653 log_message(sprintf("game created %s", @id))
1663 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1664 attr_accessor :last_move, :current_turn
1668 @sente.rated? && @gote.rated?
1671 def monitoron(monitor)
1672 @monitors.delete(monitor)
1673 @monitors.push(monitor)
1676 def monitoroff(monitor)
1677 @monitors.delete(monitor)
1680 def reject(rejector)
1681 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1682 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1687 if ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
1689 elsif (@current_player == killer)
1696 log_message(sprintf("game finished %s", @id))
1697 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1702 @sente.status = "connected"
1703 @gote.status = "connected"
1705 if (@current_player.protocol == LoginCSA::PROTOCOL)
1706 @current_player.finish
1708 if (@next_player.protocol == LoginCSA::PROTOCOL)
1711 @monitors = Array::new
1714 @current_player = nil
1716 LEAGUE.games.delete(@id)
1719 def handle_one_move(str, player)
1721 if (@current_player == player)
1722 @end_time = Time::new
1723 t = (@end_time - @start_time).floor
1724 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
1727 if ((@current_player.mytime - t <= -@byoyomi) && ((@total_time > 0) || (@byoyomi > 0)))
1729 elsif (str == :timeout)
1730 return false # time isn't expired. players aren't swapped. continue game
1732 @current_player.mytime = @current_player.mytime - t
1733 if (@current_player.mytime < 0)
1734 @current_player.mytime = 0
1738 move_status = @board.handle_one_move(str, @sente == @current_player)
1740 # log_error("handle_one_move raise exception for #{str}")
1741 # move_status = :illegal
1744 if ((move_status == :illegal) || (move_status == :uchifuzme) || (move_status == :oute_kaihimore))
1745 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1747 if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite_sente_lose) || (move_status == :oute_sennichite_gote_lose))
1748 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1749 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1750 @fh.printf("%s\nT%d\n", str, t)
1751 @last_move = sprintf("%s,T%d", str, t)
1752 @current_turn = @current_turn + 1
1755 @monitors.each do |monitor|
1756 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1757 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1762 if (@next_player.status != "game") # rival is logout or disconnected
1764 elsif (status == :timeout)
1766 elsif (move_status == :illegal)
1768 elsif (move_status == :kachi_win)
1770 elsif (move_status == :kachi_lose)
1772 elsif (move_status == :toryo)
1774 elsif (move_status == :outori)
1776 elsif (move_status == :oute_sennichite_sente_lose)
1777 oute_sennichite_win_lose(@gote, @sente) # Sente is checking
1778 elsif (move_status == :oute_sennichite_gote_lose)
1779 oute_sennichite_win_lose(@sente, @gote) # Gote is checking
1780 elsif (move_status == :sennichite)
1782 elsif (move_status == :uchifuzume)
1784 elsif (move_status == :oute_kaihimore)
1785 oute_kaihimore_lose()
1789 finish() if finish_flag
1790 (@current_player, @next_player) = [@next_player, @current_player]
1791 @start_time = Time::new
1797 @current_player.status = "connected"
1798 @next_player.status = "connected"
1799 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1800 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1801 @fh.printf("%%TORYO\n")
1802 @fh.print(@board.to_s.gsub(/^/, "\'"))
1803 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1804 @result = GameResultWin.new(@current_player, @next_player)
1805 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1806 @monitors.each do |monitor|
1807 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1812 @current_player.status = "connected"
1813 @next_player.status = "connected"
1814 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1815 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1816 @fh.printf("%%TORYO\n")
1817 @fh.print(@board.to_s.gsub(/^/, "\'"))
1818 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1819 @result = GameResultWin.new(@next_player, @current_player)
1820 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1821 @monitors.each do |monitor|
1822 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1827 @current_player.status = "connected"
1828 @next_player.status = "connected"
1829 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1830 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1831 @fh.print(@board.to_s.gsub(/^/, "\'"))
1832 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1833 @result = GameResultDraw.new(@current_player, @next_player)
1834 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1835 @monitors.each do |monitor|
1836 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @id))
1840 def oute_sennichite_win_lose(winner, loser)
1841 @current_player.status = "connected"
1842 @next_player.status = "connected"
1843 loser.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1844 winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1845 @fh.print(@board.to_s.gsub(/^/, "\'"))
1846 if loser == @current_player
1847 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1849 @fh.printf("'summary:oute_sennichite:%s win:%s lose\n", @current_player.name, @next_player.name)
1851 @result = GameResultWin.new(winner, loser)
1852 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1853 @monitors.each do |monitor|
1854 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1859 @current_player.status = "connected"
1860 @next_player.status = "connected"
1861 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1862 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1863 @fh.print(@board.to_s.gsub(/^/, "\'"))
1864 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1865 @result = GameResultWin.new(@next_player, @current_player)
1866 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1867 @monitors.each do |monitor|
1868 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1873 @current_player.status = "connected"
1874 @next_player.status = "connected"
1875 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1876 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1877 @fh.print(@board.to_s.gsub(/^/, "\'"))
1878 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1879 @result = GameResultWin.new(@next_player, @current_player)
1880 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1881 @monitors.each do |monitor|
1882 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1886 def oute_kaihimore_lose
1887 @current_player.status = "connected"
1888 @next_player.status = "connected"
1889 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1890 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1891 @fh.print(@board.to_s.gsub(/^/, "\'"))
1892 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1893 @result = GameResultWin.new(@next_player, @current_player)
1894 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1895 @monitors.each do |monitor|
1896 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1901 @current_player.status = "connected"
1902 @next_player.status = "connected"
1903 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1904 @next_player.write_safe("#TIME_UP\n#WIN\n")
1905 @fh.print(@board.to_s.gsub(/^/, "\'"))
1906 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1907 @result = GameResultWin.new(@next_player, @current_player)
1908 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1909 @monitors.each do |monitor|
1910 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
1915 @current_player.status = "connected"
1916 @next_player.status = "connected"
1917 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1918 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1919 @fh.printf("%%KACHI\n")
1920 @fh.print(@board.to_s.gsub(/^/, "\'"))
1921 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1922 @result = GameResultWin.new(@current_player, @next_player)
1923 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1924 @monitors.each do |monitor|
1925 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1930 @current_player.status = "connected"
1931 @next_player.status = "connected"
1932 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1933 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1934 @fh.printf("%%KACHI\n")
1935 @fh.print(@board.to_s.gsub(/^/, "\'"))
1936 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1937 @result = GameResultWin.new(@next_player, @current_player)
1938 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1939 @monitors.each do |monitor|
1940 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1945 @current_player.status = "connected"
1946 @next_player.status = "connected"
1947 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1948 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1949 @fh.printf("%%TORYO\n")
1950 @fh.print(@board.to_s.gsub(/^/, "\'"))
1951 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1952 @result = GameResultWin.new(@next_player, @current_player)
1953 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1954 @monitors.each do |monitor|
1955 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1960 @current_player.status = "connected"
1961 @next_player.status = "connected"
1962 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1963 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1964 @fh.print(@board.to_s.gsub(/^/, "\'"))
1965 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1966 @result = GameResultWin.new(@current_player, @next_player)
1967 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1968 @monitors.each do |monitor|
1969 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1974 log_message(sprintf("game started %s", @id))
1975 @sente.write_safe(sprintf("START:%s\n", @id))
1976 @gote.write_safe(sprintf("START:%s\n", @id))
1977 @sente.mytime = @total_time
1978 @gote.mytime = @total_time
1979 @start_time = Time::new
1983 @fh = open(@logfile, "w")
1987 @fh.puts("N+#{@sente.name}")
1988 @fh.puts("N-#{@gote.name}")
1989 @fh.puts("$EVENT:#{@id}")
1991 @sente.write_safe(propose_message("+"))
1992 @gote.write_safe(propose_message("-"))
1994 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
1995 @fh.puts("$START_TIME:#{now}")
1997 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1998 P2 * -HI * * * * * -KA *
1999 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2000 P4 * * * * * * * * *
2001 P5 * * * * * * * * *
2002 P6 * * * * * * * * *
2003 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2004 P8 * +KA * * * * * +HI *
2005 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2013 Protocol_Version:1.1
2014 Protocol_Mode:Server
2016 Declaration:Jishogi 1.1
2018 Name+:#{@sente.name}
2024 Total_Time:#{@total_time}
2026 Least_Time_Per_Move:#{Least_Time_Per_Move}
2027 Remaining_Time+:#{@sente.mytime}
2028 Remaining_Time-:#{@gote.mytime}
2029 Last_Move:#{@last_move}
2030 Current_Turn:#{@current_turn}
2040 return str0 + @board.to_s + str1
2043 def propose_message(sg_flag)
2046 Protocol_Version:1.1
2047 Protocol_Mode:Server
2049 Declaration:Jishogi 1.1
2051 Name+:#{@sente.name}
2053 Your_Turn:#{sg_flag}
2058 Total_Time:#{@total_time}
2060 Least_Time_Per_Move:#{Least_Time_Per_Move}
2063 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2064 P2 * -HI * * * * * -KA *
2065 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2066 P4 * * * * * * * * *
2067 P5 * * * * * * * * *
2068 P6 * * * * * * * * *
2069 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2070 P8 * +KA * * * * * +HI *
2071 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2083 def issue_current_time
2084 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
2085 @@mutex.synchronize do
2086 while time <= @@time do
2093 end # module ShogiServer
2095 #################################################
2102 shogi-server - server for CSA server protocol
2105 shogi-server [OPTIONS] event_name port_number
2108 server for CSA server protocol
2112 specify filename for logging process ID
2114 run as a daemon. Log files will be put in dir.
2117 this file is distributed under GPL version2 and might be compiled by Exerb
2122 #{ShogiServer::Release}
2125 #{ShogiServer::Revision}
2133 def log_message(str)
2137 def log_warning(str)
2146 def parse_command_line
2148 parser = GetoptLong.new( ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2149 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT]
2153 parser.each_option do |name, arg|
2154 name.sub!(/^--/, '')
2155 options[name] = arg.dup
2159 raise parser.error_message
2164 def write_pid_file(file)
2165 open(file, "w") do |fh|
2170 def mutex_watchdog(mutex, sec)
2182 log_error("mutex watchdog timeout")
2193 mutex_watchdog($mutex, 10)
2196 $options = parse_command_line
2197 if (ARGV.length != 2)
2202 LEAGUE.event = ARGV.shift
2205 dir = $options["daemon"]
2206 dir = File.expand_path(dir) if dir
2207 if dir && ! File.exist?(dir)
2208 FileUtils.mkdir(dir)
2210 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2211 $logger = WEBrick::Log.new(log_file)
2213 LEAGUE.dir = dir || File.dirname(__FILE__)
2214 LEAGUE.setup_players_database
2217 config[:Port] = port
2218 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2219 config[:Logger] = $logger
2220 if $options["pid-file"]
2221 pid_file = File.expand_path($options["pid-file"])
2222 config[:StartCallback] = Proc.new do
2223 write_pid_file(pid_file)
2225 config[:StopCallback] = Proc.new do
2226 FileUtils.rm(pid_file, :force => true)
2230 server = WEBrick::GenericServer.new(config)
2231 ["INT", "TERM"].each do |signal|
2237 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2238 log_message("server started [Revision: #{ShogiServer::Revision}]")
2240 server.start do |client|
2241 # client.sync = true # this is already set in WEBrick
2242 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2243 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2246 while (str = client.gets_timeout(ShogiServer::Login_Time))
2251 if (ShogiServer::Login::good_login?(str))
2252 player = ShogiServer::Player::new(str, client)
2254 login = ShogiServer::Login::factory(str, player)
2255 if (LEAGUE.players[player.name])
2256 if ((LEAGUE.players[player.name].password == player.password) &&
2257 (LEAGUE.players[player.name].status != "game"))
2258 log_message(sprintf("user %s login forcely", player.name))
2259 LEAGUE.players[player.name].kill
2261 login.incorrect_duplicated_player(str)
2272 client.write_safe("LOGIN:incorrect" + eol)
2273 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2285 log_message(sprintf("user %s login", player.name))
2287 player.run(login.csa_1st_str)
2291 player.game.kill(player)
2293 player.finish # socket has been closed
2294 LEAGUE.delete(player)
2295 log_message(sprintf("user %s logout", player.name))
2306 TCPSocket.do_not_reverse_lookup = true
2307 Thread.abort_on_exception = true
2309 LEAGUE = ShogiServer::League::new