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
55 Revision = (r = /Revision: (\d+)/.match("$Revision$") ? r[1] : 0)
62 return /^floodgate-\d+-\d+$/.match(str) ? true : false
66 def initialize(league)
73 @thread = Thread.new do
78 next if Time.now < @next_time
82 rescue Exception => ex
84 log_error("[in Floodgate's thread] #{ex} #{ex.backtrace}")
91 @thread.kill if @thread
99 @next_time = Time.mktime(now.year, now.month, now.day, now.hour, 30)
101 @next_time = Time.mktime(now.year, now.month, now.day, now.hour) + 3600
105 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min, 30)
107 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min) + 60
112 players = @league.find_all_players do |pl|
113 pl.status == "game_waiting" &&
114 Floodgate.game_name?(pl.game_name) &&
117 log_warning("DEBUG: %s" % [File.join(File.dirname(__FILE__), "pairing.rb")])
118 load File.join(File.dirname(__FILE__), "pairing.rb")
119 Pairing.default_pairing.match(players)
121 end # class Floodgate
124 # This manages those players who have their player_id.
125 # Since mk_rate mainly updates the yaml file, basically,
126 # this only reads data. But this writes some properties.
127 # TODO Such data should be facoted out to another file
130 def initialize(filename)
131 @db = YAML::Store.new(filename)
132 @db.transaction do |pstore|
133 @db['players'] ||= Hash.new
138 # trancaction=true means read only
140 def each_group(transaction=false)
141 @db.transaction(transaction) do
142 groups = @db["players"] || Hash.new
143 groups.each do |group, players|
149 def load_player(player)
150 return unless player.player_id
153 each_group(true) do |group, players|
154 hash = players[player.player_id]
160 player.name = hash['name']
161 player.rate = hash['rate'] || 0
162 player.modified_at = hash['last_modified']
163 player.rating_group = hash['rating_group']
164 player.win = hash['win'] || 0
165 player.loss = hash['loss'] || 0
166 player.last_game_win = hash['last_game_win'] || false
170 return unless player.player_id
172 each_group do |group, players|
173 hash = players[player.player_id]
175 # write only this property.
176 # the others are updated by ./mk_rate
177 hash['last_game_win'] = player.last_game_win
185 each_group(true) do |group, players_hash|
186 players << players_hash.keys
188 return players.flatten.collect do |player_id|
190 p.player_id = player_id
195 end # class Persistent
198 @mutex = Mutex.new # guard @players
202 @dir = File.dirname(__FILE__)
203 @floodgate = Floodgate.new(self)
206 attr_accessor :players, :games, :event, :dir
209 @mutex.synchronize do
210 @players.each do |name, player|
211 @persistent.save(player)
217 # this should be called just after instanciating a League object.
218 def setup_players_database
219 filename = File.join(@dir, "players.yaml")
220 @persistent = Persistent.new(filename)
224 @persistent.load_player(player)
225 @mutex.synchronize do
226 @players[player.name] = player
231 @persistent.save(player)
232 @mutex.synchronize do
233 @players.delete(player.name)
238 @persistent.save(player)
242 @mutex.synchronize do
243 @players.each do |name, player|
244 @persistent.load_player(player)
251 @mutex.synchronize do
252 found = @players.find_all do |name, player|
256 return found.map {|a| a.last}
259 def find(player_name)
261 @mutex.synchronize do
262 found = @players[player_name]
267 def get_player(status, game_name, sente, searcher)
269 @mutex.synchronize do
270 found = @players.find do |name, player|
271 (player.status == status) &&
272 (player.game_name == game_name) &&
274 (player.sente == nil) ||
275 (player.sente == sente) ) &&
276 (player.name != searcher.name)
279 return found ? found.last : nil
283 return @persistent.get_players
288 ######################################################
289 # Processes the LOGIN command.
292 def Login.good_login?(str)
294 if (((tokens.length == 3) ||
295 ((tokens.length == 4) && tokens[3] == "x1")) &&
296 (tokens[0] == "LOGIN") &&
297 (good_identifier?(tokens[1])))
304 def Login.good_game_name?(str)
305 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
312 def Login.good_identifier?(str)
313 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
320 def Login.factory(str, player)
321 (login, player.name, password, ext) = str.chomp.split
323 return Loginx1.new(player, password)
325 return LoginCSA.new(player, password)
331 # the first command that will be executed just after LOGIN.
332 # If it is nil, the default process will be started.
333 attr_reader :csa_1st_str
335 def initialize(player, password)
338 parse_password(password)
342 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
343 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
346 def incorrect_duplicated_player(str)
347 @player.write_safe("LOGIN:incorrect\n")
348 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
349 sleep 3 # wait for sending the above messages.
350 @player.name = "%s [duplicated]" % [@player.name]
355 ######################################################
356 # Processes LOGIN for the CSA standard mode.
358 class LoginCSA < Login
361 def initialize(player, password)
364 @player.protocol = PROTOCOL
367 def parse_password(password)
368 if Login.good_game_name?(password)
370 @player.set_password(nil)
371 elsif password.split(",").size > 1
372 @gamename, *trip = password.split(",")
373 @player.set_password(trip.join(","))
375 @player.set_password(password)
376 @gamename = Default_Game_Name
378 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
383 @csa_1st_str = "%%GAME #{@gamename} *"
387 ######################################################
388 # Processes LOGIN for the extented mode.
390 class Loginx1 < Login
393 def initialize(player, password)
395 @player.protocol = PROTOCOL
398 def parse_password(password)
399 @player.set_password(password)
404 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
417 @last_game_win = false
420 # Idetifier of the player in the rating system
421 attr_accessor :player_id
426 # Password of the player, which does not include a trip
427 attr_accessor :password
429 # Score in the rating sysem
432 # Number of games for win and loss in the rating system
433 attr_accessor :win, :loss
435 # Group in the rating system
436 attr_accessor :rating_group
438 # Last timestamp when the rate was modified
439 attr_accessor :modified_at
441 # Whether win the previous game or not
442 attr_accessor :last_game_win
445 @modified_at || Time.now
451 @modified_at = Time.now
460 return @last_game_win
465 simple_name = @name.gsub(/@.*?$/, '')
466 "%s+%s" % [simple_name, @trip[0..8]]
473 # Parses str in the LOGIN command, sets up @player_id and @trip
475 def set_password(str)
476 if str && !str.empty?
477 @password = str.strip
478 @player_id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
480 @player_id = @password = nil
486 class Player < BasicPlayer
487 def initialize(str, socket, eol=nil)
490 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
492 @protocol = nil # CSA or x1
493 @eol = eol || "\m" # favorite eol code
496 @mytime = 0 # set in start method also
499 @main_thread = Thread::current
500 @mutex_write_guard = Mutex.new
503 attr_accessor :socket, :status
504 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
505 attr_accessor :main_thread
506 attr_reader :socket_buffer
509 log_message(sprintf("user %s killed", @name))
514 Thread::kill(@main_thread) if @main_thread
518 if (@status != "finished")
520 log_message(sprintf("user %s finish", @name))
522 # @socket.close if (! @socket.closed?)
524 log_message(sprintf("user %s finish failed", @name))
530 @mutex_write_guard.synchronize do
533 log_warning("%s's socket has been closed." % [@name])
536 if r = select(nil, [@socket], nil, 20)
537 r[1].first.write(str)
539 log_error("Sending a message to #{@name} timed up.")
541 rescue Exception => ex
542 log_error("Failed to send a message to #{@name}. #{ex.class}: #{ex.message}\t#{ex.backtrace[0]}")
548 if ["game_waiting", "start_waiting", "agree_waiting", "game"].include?(status)
550 return sprintf("%s %s %s %s +", rated? ? @player_id : @name, @protocol, @status, @game_name)
551 elsif (@sente == false)
552 return sprintf("%s %s %s %s -", rated? ? @player_id : @name, @protocol, @status, @game_name)
553 elsif (@sente == nil)
554 return sprintf("%s %s %s %s *", rated? ? @player_id : @name, @protocol, @status, @game_name)
557 return sprintf("%s %s %s", rated? ? @player_id : @name, @protocol, @status)
561 def run(csa_1st_str=nil)
562 while ( csa_1st_str ||
563 str = gets_safe(@socket, (@socket_buffer.empty? ? Default_Timeout : 1)) )
566 if (@game && @game.turn?(self))
567 @socket_buffer << str
568 str = @socket_buffer.shift
570 log_message("%s (%s)" % [str, @socket_buffer.map {|a| String === a ? a.strip : a }.join(",")]) if $DEBUG
577 if (@status == "finished")
580 str.chomp! if (str.class == String) # may be strip! ?
583 # Application-level protocol for Keep-Alive
584 # If the server gets LF, it sends back LF.
585 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
588 if (@status == "game")
589 array_str = str.split(",")
590 move = array_str.shift
591 additional = array_str.shift
592 if /^'(.*)/ =~ additional
593 comment = array_str.unshift("'*#{$1.toeuc}")
595 s = @game.handle_one_move(move, self)
596 @game.fh.print("#{Kconv.toeuc(comment.first)}\n") if (comment && comment.first && !s)
597 return if (s && @protocol == LoginCSA::PROTOCOL)
599 when /^%[^%]/, :timeout
600 if (@status == "game")
601 s = @game.handle_one_move(str, self)
602 return if (s && @protocol == LoginCSA::PROTOCOL)
605 log_error("Failed to receive a message from #{@name}.")
608 if (@status == "agree_waiting")
610 return if (@protocol == LoginCSA::PROTOCOL)
612 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
615 if (@status == "agree_waiting")
616 @status = "start_waiting"
617 if ((@game.sente.status == "start_waiting") &&
618 (@game.gote.status == "start_waiting"))
620 @game.sente.status = "game"
621 @game.gote.status = "game"
624 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
626 when /^%%SHOW\s+(\S+)/
628 if (LEAGUE.games[game_id])
629 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
631 write_safe("##[SHOW] +OK\n")
632 when /^%%MONITORON\s+(\S+)/
634 if (LEAGUE.games[game_id])
635 LEAGUE.games[game_id].monitoron(self)
636 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
637 write_safe("##[MONITOR][#{game_id}] +OK\n")
639 when /^%%MONITOROFF\s+(\S+)/
641 if (LEAGUE.games[game_id])
642 LEAGUE.games[game_id].monitoroff(self)
646 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
648 players = LEAGUE.rated_players
649 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
650 write_safe("##[RATING] %s \t %4d @%s\n" %
651 [p.simple_player_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
653 write_safe("##[RATING] +OK\n")
655 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
656 write_safe("##[VERSION] +OK\n")
658 if ((@status == "connected") || (@status == "game_waiting"))
659 @status = "connected"
662 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
664 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
668 if (! Login::good_game_name?(game_name))
669 write_safe(sprintf("##[ERROR] bad game name\n"))
671 elsif ((@status == "connected") || (@status == "game_waiting"))
674 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
679 if (League::Floodgate.game_name?(game_name))
680 if (my_sente_str != "*")
681 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", my_sente_str, game_name))
686 if (my_sente_str == "*")
687 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
688 elsif (my_sente_str == "+")
689 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
690 elsif (my_sente_str == "-")
691 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
694 write_safe(sprintf("##[ERROR] bad game option\n"))
700 @game_name = game_name
701 if ((my_sente_str == "*") && (rival.sente == nil))
709 elsif (rival.sente == true) # rival has higher priority
711 elsif (rival.sente == false)
713 elsif (my_sente_str == "+")
716 elsif (my_sente_str == "-")
722 Game::new(@game_name, self, rival)
723 else # rival not found
724 if (command_name == "GAME")
725 @status = "game_waiting"
726 @game_name = game_name
727 if (my_sente_str == "+")
729 elsif (my_sente_str == "-")
735 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
736 @status = "connected"
741 when /^%%CHAT\s+(.+)/
743 LEAGUE.players.each do |name, player|
744 if (player.protocol != LoginCSA::PROTOCOL)
745 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
750 LEAGUE.games.each do |id, game|
751 buf.push(sprintf("##[LIST] %s\n", id))
753 buf.push("##[LIST] +OK\n")
757 LEAGUE.players.each do |name, player|
758 buf.push(sprintf("##[WHO] %s\n", player.to_s))
760 buf.push("##[WHO] +OK\n")
763 @status = "connected"
764 write_safe("LOGOUT:completed\n")
767 # This command is only available for CSA's official testing server.
768 # So, this means nothing for this program.
769 write_safe("CHALLENGE ACCEPTED\n")
771 ## ignore null string
773 msg = "##[ERROR] unknown command %s\n" % [str]
785 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK",
786 "GI" => "NG", "KA" => "UM", "HI" => "RY"}
787 def initialize(board, x, y, sente, promoted=false)
794 if ((x == 0) || (y == 0))
796 hands = board.sente_hands
798 hands = board.gote_hands
805 @board.array[x][y] = self
808 attr_accessor :promoted, :sente, :x, :y, :board
810 def room_of_head?(x, y, name)
815 return adjacent_movable_grids + far_movable_grids
818 def far_movable_grids
823 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
824 if ((@board.array[x][y] == nil) || # dst is empty
825 (@board.array[x][y].sente != @sente)) # dst is enemy
833 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
834 if (@board.array[x][y] == nil) # dst is empty?
841 def adjacent_movable_grids
844 moves = @promoted_moves
846 moves = @normal_moves
848 moves.each do |(dx, dy)|
855 if (jump_to?(cand_x, cand_y))
856 grids.push([cand_x, cand_y])
862 def move_to?(x, y, name)
863 return false if (! room_of_head?(x, y, name))
864 return false if ((name != @name) && (name != @promoted_name))
865 return false if (@promoted && (name != @promoted_name)) # can't un-promote
868 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
870 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
872 return false if ((6 >= @y) && (6 >= y) && (name != @name))
876 if ((@x == 0) || (@y == 0))
877 return jump_to?(x, y)
879 return movable_grids.include?([x, y])
884 if ((@x == 0) || (@y == 0))
886 @board.sente_hands.delete(self)
888 @board.gote_hands.delete(self)
890 @board.array[x][y] = self
891 elsif ((x == 0) || (y == 0))
892 @promoted = false # clear promoted flag before moving to hands
894 @board.sente_hands.push(self)
896 @board.gote_hands.push(self)
898 @board.array[@x][@y] = nil
900 @board.array[@x][@y] = nil
901 @board.array[x][y] = self
934 class PieceFU < Piece
937 @normal_moves = [[0, +1]]
938 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
940 @promoted_name = "TO"
943 def room_of_head?(x, y, name)
946 return false if (y == 1)
948 return false if (y == 9)
954 if ((iy != @y) && # not source position
955 @board.array[x][iy] &&
956 (@board.array[x][iy].sente == @sente) && # mine
957 (@board.array[x][iy].name == "FU") &&
958 (@board.array[x][iy].promoted == false))
968 class PieceKY < Piece
972 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
974 @promoted_name = "NY"
977 def room_of_head?(x, y, name)
980 return false if (y == 1)
982 return false if (y == 9)
987 def far_movable_grids
995 while (jump_to?(cand_x, cand_y))
996 grids.push([cand_x, cand_y])
997 break if (! put_to?(cand_x, cand_y))
1003 while (jump_to?(cand_x, cand_y))
1004 grids.push([cand_x, cand_y])
1005 break if (! put_to?(cand_x, cand_y))
1013 class PieceKE < Piece
1014 def initialize(*arg)
1016 @normal_moves = [[+1, +2], [-1, +2]]
1017 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1019 @promoted_name = "NK"
1022 def room_of_head?(x, y, name)
1025 return false if ((y == 1) || (y == 2))
1027 return false if ((y == 9) || (y == 8))
1033 class PieceGI < Piece
1034 def initialize(*arg)
1036 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1037 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1039 @promoted_name = "NG"
1043 class PieceKI < Piece
1044 def initialize(*arg)
1046 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1047 @promoted_moves = []
1049 @promoted_name = nil
1053 class PieceKA < Piece
1054 def initialize(*arg)
1057 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
1059 @promoted_name = "UM"
1062 def far_movable_grids
1067 while (jump_to?(cand_x, cand_y))
1068 grids.push([cand_x, cand_y])
1069 break if (! put_to?(cand_x, cand_y))
1076 while (jump_to?(cand_x, cand_y))
1077 grids.push([cand_x, cand_y])
1078 break if (! put_to?(cand_x, cand_y))
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 class PieceHI < Piece
1104 def initialize(*arg)
1107 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1109 @promoted_name = "RY"
1112 def far_movable_grids
1117 while (jump_to?(cand_x, cand_y))
1118 grids.push([cand_x, cand_y])
1119 break if (! put_to?(cand_x, cand_y))
1125 while (jump_to?(cand_x, cand_y))
1126 grids.push([cand_x, cand_y])
1127 break if (! put_to?(cand_x, cand_y))
1133 while (jump_to?(cand_x, cand_y))
1134 grids.push([cand_x, cand_y])
1135 break if (! put_to?(cand_x, cand_y))
1141 while (jump_to?(cand_x, cand_y))
1142 grids.push([cand_x, cand_y])
1143 break if (! put_to?(cand_x, cand_y))
1149 class PieceOU < Piece
1150 def initialize(*arg)
1152 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1153 @promoted_moves = []
1155 @promoted_name = nil
1162 @sente_hands = Array::new
1163 @gote_hands = Array::new
1164 @history = Hash::new(0)
1165 @sente_history = Hash::new(0)
1166 @gote_history = Hash::new(0)
1167 @array = [[], [], [], [], [], [], [], [], [], []]
1169 @teban = nil # black => true, white => false
1171 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1172 attr_reader :move_count
1175 PieceKY::new(self, 1, 1, false)
1176 PieceKE::new(self, 2, 1, false)
1177 PieceGI::new(self, 3, 1, false)
1178 PieceKI::new(self, 4, 1, false)
1179 PieceOU::new(self, 5, 1, false)
1180 PieceKI::new(self, 6, 1, false)
1181 PieceGI::new(self, 7, 1, false)
1182 PieceKE::new(self, 8, 1, false)
1183 PieceKY::new(self, 9, 1, false)
1184 PieceKA::new(self, 2, 2, false)
1185 PieceHI::new(self, 8, 2, false)
1187 PieceFU::new(self, i, 3, false)
1190 PieceKY::new(self, 1, 9, true)
1191 PieceKE::new(self, 2, 9, true)
1192 PieceGI::new(self, 3, 9, true)
1193 PieceKI::new(self, 4, 9, true)
1194 PieceOU::new(self, 5, 9, true)
1195 PieceKI::new(self, 6, 9, true)
1196 PieceGI::new(self, 7, 9, true)
1197 PieceKE::new(self, 8, 9, true)
1198 PieceKY::new(self, 9, 9, true)
1199 PieceKA::new(self, 8, 8, true)
1200 PieceHI::new(self, 2, 8, true)
1202 PieceFU::new(self, i, 7, true)
1207 def have_piece?(hands, name)
1208 piece = hands.find { |i|
1214 def move_to(x0, y0, x1, y1, name, sente)
1216 hands = @sente_hands
1221 if ((x0 == 0) || (y0 == 0))
1222 piece = have_piece?(hands, name)
1223 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1224 piece.move_to(x1, y1)
1226 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1227 if (@array[x0][y0].name != name) # promoted ?
1228 @array[x0][y0].promoted = true
1230 if (@array[x1][y1]) # capture
1231 if (@array[x1][y1].name == "OU")
1232 return :outori # return board update
1234 @array[x1][y1].sente = @array[x0][y0].sente
1235 @array[x1][y1].move_to(0, 0)
1236 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1240 @array[x0][y0].move_to(x1, y1)
1243 @teban = @teban ? false : true
1247 def look_for_ou(sente)
1253 (@array[x][y].name == "OU") &&
1254 (@array[x][y].sente == sente))
1261 raise "can't find ou"
1264 # note checkmate, but check. sente is checked.
1265 def checkmated?(sente) # sente is loosing
1266 ou = look_for_ou(sente)
1272 (@array[x][y].sente != sente))
1273 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1284 def uchifuzume?(sente)
1285 rival_ou = look_for_ou(! sente) # rival's ou
1286 if (sente) # rival is gote
1287 if ((rival_ou.y != 9) &&
1288 (@array[rival_ou.x][rival_ou.y + 1]) &&
1289 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1290 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1292 fu_y = rival_ou.y + 1
1297 if ((rival_ou.y != 1) &&
1298 (@array[rival_ou.x][rival_ou.y - 1]) &&
1299 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1300 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1302 fu_y = rival_ou.y - 1
1308 ## case: rival_ou is moving
1309 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1310 tmp_board = Marshal.load(Marshal.dump(self))
1311 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1312 raise "internal error" if (s != true)
1313 if (! tmp_board.checkmated?(! sente)) # good move
1318 ## case: rival is capturing fu
1324 (@array[x][y].sente != sente) &&
1325 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1328 if (@array[x][y].promoted)
1329 names << @array[x][y].promoted_name
1331 names << @array[x][y].name
1332 if @array[x][y].promoted_name &&
1333 @array[x][y].move_to?(fu_x, fu_y, @array[x][y].promoted_name)
1334 names << @array[x][y].promoted_name
1337 names.map! do |name|
1338 tmp_board = Marshal.load(Marshal.dump(self))
1339 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1343 tmp_board.checkmated?(! sente) # result
1346 all_illegal = names.find {|a| a != :illegal}
1347 raise "internal error: legal move not found" if all_illegal == nil
1348 r = names.find {|a| a == false} # good move
1349 return false if r == false # found good move
1358 # @[sente|gote]_history has at least one item while the player is checking the other or
1359 # the other escapes.
1360 def update_sennichite(player)
1363 if checkmated?(!player)
1365 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
1367 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
1371 @sente_history.clear # no more continuous check
1373 @gote_history.clear # no more continuous check
1376 if @sente_history.size > 0 # possible for Sente's or Gote's turn
1377 @sente_history[str] += 1
1379 if @gote_history.size > 0 # possible for Sente's or Gote's turn
1380 @gote_history[str] += 1
1384 def oute_sennichite?(player)
1385 if (@sente_history[to_s] >= 4)
1386 return :oute_sennichite_sente_lose
1387 elsif (@gote_history[to_s] >= 4)
1388 return :oute_sennichite_gote_lose
1394 def sennichite?(sente)
1395 if (@history[to_s] >= 4) # already 3 times
1401 def good_kachi?(sente)
1402 if (checkmated?(sente))
1403 puts "'NG: Checkmating." if $DEBUG
1407 ou = look_for_ou(sente)
1408 if (sente && (ou.y >= 4))
1409 puts "'NG: Black's OU does not enter yet." if $DEBUG
1412 if (! sente && (ou.y <= 6))
1413 puts "'NG: White's OU does not enter yet." if $DEBUG
1421 hands = @sente_hands
1431 (@array[x][y].sente == sente) &&
1432 (@array[x][y].point > 0))
1433 point = point + @array[x][y].point
1439 hands.each do |piece|
1440 point = point + piece.point
1444 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1449 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1454 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1459 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1463 # sente is nil only if tests in test_board run
1464 def handle_one_move(str, sente=nil)
1465 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1472 elsif (str =~ /^%KACHI/)
1473 raise ArgumentError, "sente is null", caller if sente == nil
1474 if (good_kachi?(sente))
1479 elsif (str =~ /^%TORYO/)
1485 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1486 ((x0 != 0) || (y0 != 0)))
1488 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1493 sente = true if sente == nil # deprecated
1494 return :illegal unless sente == true # black player's move must be black
1495 hands = @sente_hands
1497 sente = false if sente == nil # deprecated
1498 return :illegal unless sente == false # white player's move must be white
1503 if ((x0 == 0) && (y0 == 0))
1504 return :illegal if (! have_piece?(hands, name))
1505 elsif (! @array[x0][y0])
1506 return :illegal # no piece
1507 elsif (@array[x0][y0].sente != sente)
1508 return :illegal # this is not mine
1509 elsif (@array[x0][y0].name != name)
1510 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1513 ## destination check
1514 if (@array[x1][y1] &&
1515 (@array[x1][y1].sente == sente)) # can't capture mine
1517 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1518 return :illegal # can't put on existing piece
1521 tmp_board = Marshal.load(Marshal.dump(self))
1522 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1523 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1524 tmp_board.update_sennichite(sente)
1525 os_result = tmp_board.oute_sennichite?(sente)
1526 return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
1527 return :sennichite if tmp_board.sennichite?(sente)
1529 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1533 move_to(x0, y0, x1, y1, name, sente)
1535 update_sennichite(sente)
1543 a.push(sprintf("P%d", y))
1546 piece = @array[x][y]
1555 a.push(sprintf("\n"))
1558 if (! sente_hands.empty?)
1560 sente_hands.each do |p|
1561 a.push("00" + p.name)
1565 if (! gote_hands.empty?)
1567 gote_hands.each do |p|
1568 a.push("00" + p.name)
1572 a.push("%s\n" % [@teban ? "+" : "-"])
1578 attr_reader :players, :black, :white
1580 def initialize(game, p1, p2)
1583 if p1.sente && !p2.sente
1584 @black, @white = p1, p2
1585 elsif !p1.sente && p2.sente
1586 @black, @white = p2, p1
1588 raise "Never reached!"
1590 @players.each do |player|
1591 player.status = "connected"
1597 raise "Implement me!"
1605 log(@game.board.to_s.gsub(/^/, "\'"))
1609 log("'rating:%s\n" % [self.to_s]) if @game.rated?
1613 black_name = @black.rated? ? @black.player_id : @black.name
1614 white_name = @white.rated? ? @white.player_id : @white.name
1615 return "%s:%s" % [black_name, white_name]
1618 def notify_monitor(type)
1619 @game.each_monitor do |monitor|
1620 monitor.write_safe(sprintf("##[MONITOR][%s] %s\n", @game.game_id, type))
1625 class GameResultWin < GameResult
1626 attr_reader :winner, :loser
1628 def initialize(game, winner, loser)
1630 @winner, @loser = winner, loser
1631 @winner.last_game_win = true
1632 @loser.last_game_win = false
1635 def log_summary(type)
1638 black_result = white_result = ""
1639 if @black == @winner
1640 black_result = "win"
1641 white_result = "lose"
1643 black_result = "lose"
1644 white_result = "win"
1646 log("'summary:%s:%s %s:%s %s\n" % [type,
1647 @black.name, black_result,
1648 @white.name, white_result])
1654 class GameResultAbnormalWin < GameResultWin
1656 @winner.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1657 @loser.write_safe( "%TORYO\n#RESIGN\n#LOSE\n")
1659 log_summary("abnormal")
1660 notify_monitor("%%TORYO")
1664 class GameResultTimeoutWin < GameResultWin
1666 @winner.write_safe("#TIME_UP\n#WIN\n")
1667 @loser.write_safe( "#TIME_UP\n#LOSE\n")
1668 log_summary("time up")
1669 notify_monitor("#TIME_UP")
1673 # A player declares (successful) Kachi
1674 class GameResultKachiWin < GameResultWin
1676 @winner.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1677 @loser.write_safe( "%KACHI\n#JISHOGI\n#LOSE\n")
1679 log_summary("kachi")
1680 notify_monitor("%%KACHI")
1684 # A player declares wrong Kachi
1685 class GameResultIllegalKachiWin < GameResultWin
1687 @winner.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1688 @loser.write_safe( "%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1690 log_summary("illegal kachi")
1691 notify_monitor("%%KACHI")
1695 class GameResultIllegalWin < GameResultWin
1696 def initialize(game, winner, loser, cause)
1697 super(game, winner, loser)
1702 @winner.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1703 @loser.write_safe( "#ILLEGAL_MOVE\n#LOSE\n")
1705 notify_monitor("#ILLEGAL_MOVE")
1709 class GameResultIllegalMoveWin < GameResultIllegalWin
1710 def initialize(game, winner, loser)
1711 super(game, winner, loser, "illegal move")
1715 class GameResultUchifuzumeWin < GameResultIllegalWin
1716 def initialize(game, winner, loser)
1717 super(game, winner, loser, "uchifuzume")
1721 class GameResultOuteKaihiMoreWin < GameResultWin
1722 def initialize(game, winner, loser)
1723 super(game, winner, loser, "oute_kaihimore")
1727 class GameResultOutoriWin < GameResultWin
1728 def initialize(game, winner, loser)
1729 super(game, winner, loser, "outori")
1733 class GameReulstToryoWin < GameResultWin
1735 @winner.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1736 @loser.write_safe( "%TORYO\n#RESIGN\n#LOSE\n")
1738 log_summary("toryo")
1739 notify_monitor("%%TORYO")
1743 class GameResultOuteSennichiteWin < GameResultWin
1745 @winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1746 @loser.write_safe( "#OUTE_SENNICHITE\n#LOSE\n")
1747 log_summary("oute_sennichite")
1748 notify_monitor("#OUTE_SENNICHITE")
1752 class GameResultDraw < GameResult
1753 def initialize(game, p1, p2)
1755 p1.last_game_win = false
1756 p2.last_game_win = false
1759 def log_summary(type)
1761 log("'summary:%s:%s draw:%s draw\n", type, @black.name, @white.name)
1766 class GameResultSennichiteDraw < GameResultDraw
1768 @players.each do |player|
1769 player.write_safe("#SENNICHITE\n#DRAW\n")
1771 log_summary("sennichite")
1772 notify_monitor("#SENNICHITE")
1780 def initialize(game_name, player0, player1)
1781 @monitors = Array::new
1782 @game_name = game_name
1783 if (@game_name =~ /-(\d+)-(\d+)$/)
1784 @total_time = $1.to_i
1789 @sente, @gote = player0, player1
1791 @sente, @gote = player1, player0
1793 @sente.socket_buffer.clear
1794 @gote.socket_buffer.clear
1795 @current_player, @next_player = @sente, @gote
1802 @sente.status = "agree_waiting"
1803 @gote.status = "agree_waiting"
1805 @game_id = sprintf("%s+%s+%s+%s+%s",
1806 LEAGUE.event, @game_name,
1807 @sente.name, @gote.name, issue_current_time)
1810 log_dir_name = File.join(LEAGUE.dir,
1814 FileUtils.mkdir_p(log_dir_name) unless File.exist?(log_dir_name)
1815 @logfile = File.join(log_dir_name, @game_id + ".csa")
1817 LEAGUE.games[@game_id] = self
1819 log_message(sprintf("game created %s", @game_id))
1824 @fh = open(@logfile, "w")
1830 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors
1831 attr_accessor :last_move, :current_turn
1835 @sente.rated? && @gote.rated?
1839 return player.status == "game" && @current_player == player
1842 def monitoron(monitor)
1843 @monitors.delete(monitor)
1844 @monitors.push(monitor)
1847 def monitoroff(monitor)
1848 @monitors.delete(monitor)
1852 @monitors.each do |monitor|
1859 log_error("Failed to write to Game[%s]'s log file: %s" %
1862 @fh.printf("%s\n", str)
1865 def reject(rejector)
1866 @sente.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
1867 @gote.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
1872 if ["agree_waiting", "start_waiting"].include?(@sente.status)
1874 elsif (@current_player == killer)
1875 result = GameResultAbnormalWin.new(self, @next_player, @current_player)
1882 log_message(sprintf("game finished %s", @game_id))
1883 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1888 @sente.status = "connected"
1889 @gote.status = "connected"
1891 if (@current_player.protocol == LoginCSA::PROTOCOL)
1892 @current_player.finish
1894 if (@next_player.protocol == LoginCSA::PROTOCOL)
1897 @monitors = Array::new
1900 @current_player = nil
1902 LEAGUE.games.delete(@game_id)
1906 def handle_one_move(str, player)
1907 unless turn?(player)
1908 return false if str == :timeout
1910 @fh.puts("'Deferred %s" % [str])
1911 log_warning("Deferred a move [%s] scince it is not %s 's turn." %
1913 player.socket_buffer << str # always in the player's thread
1918 @end_time = Time::new
1919 t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
1922 if ((@current_player.mytime - t <= -@byoyomi) &&
1923 ((@total_time > 0) || (@byoyomi > 0)))
1925 elsif (str == :timeout)
1926 return false # time isn't expired. players aren't swapped. continue game
1928 @current_player.mytime -= t
1929 if (@current_player.mytime < 0)
1930 @current_player.mytime = 0
1933 move_status = @board.handle_one_move(str, @sente == @current_player)
1935 if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
1936 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1938 if [:normal, :outori, :sennichite, :oute_sennichite_sente_lose, :oute_sennichite_gote_lose].include?(move_status)
1939 # Thinking time includes network traffic
1940 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1941 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1942 @fh.printf("%s\nT%d\n", str, t)
1943 @last_move = sprintf("%s,T%d", str, t)
1947 @monitors.each do |monitor|
1948 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@game_id}] "))
1949 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @game_id))
1955 if (@next_player.status != "game") # rival is logout or disconnected
1956 result = GameResultAbnormalWin.new(self, @current_player, @next_player)
1957 elsif (status == :timeout)
1958 # current_player losed
1959 result = GameResultTimeoutWin.new(self, @next_player, @current_player)
1960 elsif (move_status == :illegal)
1961 result = GameResultIllegalMoveWin.new(self, @next_player, @current_player)
1962 elsif (move_status == :kachi_win)
1963 result = GameResultKachiWin.new(self, @current_player, @next_player)
1964 elsif (move_status == :kachi_lose)
1965 result = GameResultIllegalKachiWin.new(self, @next_player, @current_player)
1966 elsif (move_status == :toryo)
1967 result = GameReulstToryoWin.new(self, @next_player, @current_player)
1968 elsif (move_status == :outori)
1969 # The current player captures the next player's king
1970 result = GameResultOutoriWin.new(self, @current_player, @next_player)
1971 elsif (move_status == :oute_sennichite_sente_lose)
1972 result = GameResultOuteSennichiteWin.new(self, @gote, @sente) # Sente is checking
1973 elsif (move_status == :oute_sennichite_gote_lose)
1974 result = GameResultOuteSennichiteWin.new(self, @sente, @gote) # Gote is checking
1975 elsif (move_status == :sennichite)
1976 result = GameResultSennichiteDraw.new(self, @current_player, @next_player)
1977 elsif (move_status == :uchifuzume)
1978 # the current player losed
1979 result = GameResultUchifuzumeWin.new(self, @next_player, @current_player)
1980 elsif (move_status == :oute_kaihimore)
1981 # the current player losed
1982 result = GameResultOuteKaihiMoreWin.new(self, @next_player, @current_player)
1986 result.process if result
1987 finish() if finish_flag
1988 @current_player, @next_player = @next_player, @current_player
1989 @start_time = Time::new
1994 log_message(sprintf("game started %s", @game_id))
1995 @sente.write_safe(sprintf("START:%s\n", @game_id))
1996 @gote.write_safe(sprintf("START:%s\n", @game_id))
1997 @sente.mytime = @total_time
1998 @gote.mytime = @total_time
1999 @start_time = Time::new
2004 @fh.puts("N+#{@sente.name}")
2005 @fh.puts("N-#{@gote.name}")
2006 @fh.puts("$EVENT:#{@game_id}")
2008 @sente.write_safe(propose_message("+"))
2009 @gote.write_safe(propose_message("-"))
2011 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
2012 @fh.puts("$START_TIME:#{now}")
2014 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2015 P2 * -HI * * * * * -KA *
2016 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2017 P4 * * * * * * * * *
2018 P5 * * * * * * * * *
2019 P6 * * * * * * * * *
2020 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2021 P8 * +KA * * * * * +HI *
2022 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2030 Protocol_Version:1.1
2031 Protocol_Mode:Server
2033 Declaration:Jishogi 1.1
2035 Name+:#{@sente.name}
2041 Total_Time:#{@total_time}
2043 Least_Time_Per_Move:#{Least_Time_Per_Move}
2044 Remaining_Time+:#{@sente.mytime}
2045 Remaining_Time-:#{@gote.mytime}
2046 Last_Move:#{@last_move}
2047 Current_Turn:#{@current_turn}
2057 return str0 + @board.to_s + str1
2060 def propose_message(sg_flag)
2063 Protocol_Version:1.1
2064 Protocol_Mode:Server
2066 Declaration:Jishogi 1.1
2068 Name+:#{@sente.name}
2070 Your_Turn:#{sg_flag}
2075 Total_Time:#{@total_time}
2077 Least_Time_Per_Move:#{Least_Time_Per_Move}
2080 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2081 P2 * -HI * * * * * -KA *
2082 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2083 P4 * * * * * * * * *
2084 P5 * * * * * * * * *
2085 P6 * * * * * * * * *
2086 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2087 P8 * +KA * * * * * +HI *
2088 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2100 def issue_current_time
2101 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
2102 @@mutex.synchronize do
2103 while time <= @@time do
2110 end # module ShogiServer
2112 #################################################
2119 shogi-server - server for CSA server protocol
2122 shogi-server [OPTIONS] event_name port_number
2125 server for CSA server protocol
2129 specify filename for logging process ID
2131 run as a daemon. Log files will be put in dir.
2134 this file is distributed under GPL version2 and might be compiled by Exerb
2139 #{ShogiServer::Release}
2142 #{ShogiServer::Revision}
2150 def log_message(str)
2154 def log_warning(str)
2163 def parse_command_line
2165 parser = GetoptLong.new(
2166 ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2167 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT])
2170 parser.each_option do |name, arg|
2171 name.sub!(/^--/, '')
2172 options[name] = arg.dup
2176 raise parser.error_message
2181 def write_pid_file(file)
2182 open(file, "w") do |fh|
2187 def mutex_watchdog(mutex, sec)
2199 log_error("mutex watchdog timeout")
2205 def login_loop(client)
2206 player = login = nil
2208 while r = select([client], nil, nil, ShogiServer::Login_Time) do
2209 break unless str = r[0].first.gets
2210 $mutex.lock # guards LEAGUE
2214 if (ShogiServer::Login::good_login?(str))
2215 player = ShogiServer::Player::new(str, client, eol)
2216 login = ShogiServer::Login::factory(str, player)
2217 if (current_player = LEAGUE.find(player.name))
2218 if (current_player.password == player.password &&
2219 current_player.status != "game")
2220 log_message(sprintf("user %s login forcely", player.name))
2223 login.incorrect_duplicated_player(str)
2231 client.write("LOGIN:incorrect" + eol)
2232 client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2238 return [player, login]
2246 mutex_watchdog($mutex, 10)
2249 $options = parse_command_line
2250 if (ARGV.length != 2)
2255 LEAGUE.event = ARGV.shift
2258 dir = $options["daemon"]
2259 dir = File.expand_path(dir) if dir
2260 if dir && ! File.exist?(dir)
2261 FileUtils.mkdir(dir)
2263 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2264 $logger = WEBrick::Log.new(log_file) # thread safe
2266 LEAGUE.dir = dir || File.dirname(__FILE__)
2267 LEAGUE.setup_players_database
2270 config[:Port] = port
2271 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2272 config[:Logger] = $logger
2273 if $options["pid-file"]
2274 pid_file = File.expand_path($options["pid-file"])
2275 config[:StartCallback] = Proc.new do
2276 write_pid_file(pid_file)
2278 config[:StopCallback] = Proc.new do
2279 FileUtils.rm(pid_file, :force => true)
2283 server = WEBrick::GenericServer.new(config)
2284 ["INT", "TERM"].each do |signal|
2290 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2291 log_message("server started [Revision: #{ShogiServer::Revision}]")
2293 server.start do |client|
2294 # client.sync = true # this is already set in WEBrick
2295 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2296 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2297 player, login = login_loop(client) # loop
2300 log_message(sprintf("user %s login", player.name))
2302 player.run(login.csa_1st_str) # loop
2306 player.game.kill(player)
2308 player.finish # socket has been closed
2309 LEAGUE.delete(player)
2310 log_message(sprintf("user %s logout", player.name))
2321 TCPSocket.do_not_reverse_lookup = true
2322 Thread.abort_on_exception = $DEBUG ? true : false
2324 LEAGUE = ShogiServer::League::new