4 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
5 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ## GNU General Public License for more details.
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, write to the Free Software
19 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32 def gets_safe(socket, timeout=nil)
33 if r = select([socket], nil, nil, timeout)
34 return r[0].first.gets
38 rescue Exception => ex
39 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
43 module ShogiServer # for a namespace
45 Max_Identifier_Length = 32
46 Default_Timeout = 60 # for single socket operation
48 Default_Game_Name = "default-1500-0"
51 Least_Time_Per_Move = 1
52 Login_Time = 300 # time for LOGIN
54 Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
55 Release.concat("-") if (Release == "")
56 Revision = "$Revision$".gsub(/[^\.\d]/, '')
63 return /^floodgate-\d+-\d+$/.match(str) ? true : false
67 def initialize(league)
74 @thread = Thread.new do
79 next if Time.now < @next_time
83 rescue Exception => ex
85 log_error("[in Floodgate's thread] #{ex}")
92 @thread.kill if @thread
100 @next_time = Time.mktime(now.year, now.month, now.day, now.hour, 30)
102 @next_time = Time.mktime(now.year, now.month, now.day, now.hour) + 3600
106 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min, 30)
108 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min) + 60
113 players = @league.find_all_players do |pl|
114 pl.status == "game_waiting" &&
115 Floodgate.game_name?(pl.game_name) &&
118 log_warning("DEBUG: %s" % [File.join(File.dirname(__FILE__), "pairing.rb")])
119 load File.join(File.dirname(__FILE__), "pairing.rb")
120 Pairing.default_pairing.match(players)
122 end # class Floodgate
125 @mutex = Mutex.new # guard @players
129 @dir = File.dirname(__FILE__)
130 @floodgate = Floodgate.new(self)
133 attr_accessor :players, :games, :event, :dir
136 @mutex.synchronize do
137 @players.each {|a| save(a)}
142 # this should be called just after instanciating a League object.
143 def setup_players_database
144 @db = YAML::Store.new(File.join(@dir, "players.yaml"))
148 self.load(player) if player.id
149 @mutex.synchronize do
150 @players[player.name] = player
155 @mutex.synchronize do
157 @players.delete(player.name)
162 @mutex.synchronize do
163 @players.each {|player| load(player)}
169 @mutex.synchronize do
170 found = @players.find_all do |name, player|
174 return found.map {|a| a.last}
177 def find(player_name)
179 @mutex.synchronize do
180 found = @players[player_name]
185 def get_player(status, game_name, sente, searcher)
187 @mutex.synchronize do
188 found = @players.find do |name, player|
189 (player.status == status) &&
190 (player.game_name == game_name) &&
192 (player.sente == nil) ||
193 (player.sente == sente) ) &&
194 (player.name != searcher.name)
197 return found ? found.last : nil
201 hash = search(player.id)
205 player.name = hash['name']
206 player.rate = hash['rate'] || 0
207 player.modified_at = hash['last_modified']
208 player.rating_group = hash['rating_group']
209 player.win = hash['win'] || 0
210 player.loss = hash['loss'] || 0
211 player.last_game_win = hash['last_game_win'] || false
216 break unless @db["players"]
217 @db["players"].each do |group, players|
218 hash = players[player.id]
220 hash['last_game_win'] = player.last_game_win
229 @db.transaction(true) do
230 break unless @db["players"]
231 @db["players"].each do |group, players|
241 @db.transaction(true) do
242 break unless @db["players"]
243 @db["players"].each do |group, players_hash|
244 players << players_hash.keys
247 return players.flatten.collect do |id|
257 ######################################################
258 # Processes the LOGIN command.
261 def Login.good_login?(str)
263 if (((tokens.length == 3) ||
264 ((tokens.length == 4) && tokens[3] == "x1")) &&
265 (tokens[0] == "LOGIN") &&
266 (good_identifier?(tokens[1])))
273 def Login.good_game_name?(str)
274 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
281 def Login.good_identifier?(str)
282 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
289 def Login.factory(str, player)
290 (login, player.name, password, ext) = str.chomp.split
292 return Loginx1.new(player, password)
294 return LoginCSA.new(player, password)
300 # the first command that will be executed just after LOGIN.
301 # If it is nil, the default process will be started.
302 attr_reader :csa_1st_str
304 def initialize(player, password)
307 parse_password(password)
311 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
312 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
315 def incorrect_duplicated_player(str)
316 @player.write_safe("LOGIN:incorrect\n")
317 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
318 sleep 3 # wait for sending the above messages.
319 @player.name = "%s [duplicated]" % [@player.name]
324 ######################################################
325 # Processes LOGIN for the CSA standard mode.
327 class LoginCSA < Login
330 def initialize(player, password)
333 @player.protocol = PROTOCOL
336 def parse_password(password)
337 if Login.good_game_name?(password)
339 @player.set_password(nil)
340 elsif password.split(",").size > 1
341 @gamename, *trip = password.split(",")
342 @player.set_password(trip.join(","))
344 @player.set_password(password)
345 @gamename = Default_Game_Name
347 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
352 @csa_1st_str = "%%GAME #{@gamename} *"
356 ######################################################
357 # Processes LOGIN for the extented mode.
359 class Loginx1 < Login
362 def initialize(player, password)
364 @player.protocol = PROTOCOL
367 def parse_password(password)
368 @player.set_password(password)
373 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
383 @last_game_win = false
386 # Idetifier of the player in the rating system
392 # Password of the player, which does not include a trip
393 attr_accessor :password
395 # Score in the rating sysem
398 # Number of games for win and loss in the rating system
399 attr_accessor :win, :loss
401 # Group in the rating system
402 attr_accessor :rating_group
404 # Last timestamp when the rate was modified
405 attr_accessor :modified_at
407 # Whether win the previous game or not
408 attr_accessor :last_game_win
411 @modified_at || Time.now
417 @modified_at = Time.now
426 return @last_game_win
431 simple_name = @name.gsub(/@.*?$/, '')
432 "%s+%s" % [simple_name, @trip[0..8]]
439 # Parses str in the LOGIN command, sets up @id and @trip
441 def set_password(str)
442 if str && !str.empty?
443 @password = str.strip
444 @id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
446 @id = @password = nil
452 class Player < BasicPlayer
453 def initialize(str, socket, eol=nil)
456 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
458 @protocol = nil # CSA or x1
459 @eol = eol || "\m" # favorite eol code
462 @mytime = 0 # set in start method also
465 @main_thread = Thread::current
466 @mutex_write_guard = Mutex.new
469 attr_accessor :socket, :status
470 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
471 attr_accessor :main_thread
472 attr_reader :socket_buffer
475 log_message(sprintf("user %s killed", @name))
480 Thread::kill(@main_thread) if @main_thread
484 if (@status != "finished")
486 log_message(sprintf("user %s finish", @name))
488 # @socket.close if (! @socket.closed?)
490 log_message(sprintf("user %s finish failed", @name))
496 @mutex_write_guard.synchronize do
498 if r = select(nil, [@socket], nil, 20)
499 r[1].first.write(str)
501 log_error("Sending a message to #{@name} timed up.")
503 rescue Exception => ex
504 log_error("Failed to send a message to #{@name}.")
505 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
512 if ["game_waiting", "start_waiting", "agree_waiting", "game"].include?(status)
514 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
515 elsif (@sente == false)
516 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
517 elsif (@sente == nil)
518 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
521 return sprintf("%s %s %s", @name, @protocol, @status)
525 def run(csa_1st_str=nil)
526 while (csa_1st_str ||
527 str = @socket_buffer.shift || gets_safe(@socket, Default_Timeout))
530 log_message(str) if $DEBUG
537 if (@status == "finished")
540 str.chomp! if (str.class == String) # may be strip! ?
543 # Application-level protocol for Keep-Alive
544 # If the server gets LF, it sends back LF.
545 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
548 if (@status == "game")
549 array_str = str.split(",")
550 move = array_str.shift
551 additional = array_str.shift
552 if /^'(.*)/ =~ additional
553 comment = array_str.unshift("'*#{$1.toeuc}")
555 s = @game.handle_one_move(move, self)
556 @game.fh.print("#{Kconv.toeuc(comment.first)}\n") if (comment && comment.first && !s)
557 return if (s && @protocol == LoginCSA::PROTOCOL)
559 when /^%[^%]/, :timeout
560 if (@status == "game")
561 s = @game.handle_one_move(str, self)
562 return if (s && @protocol == LoginCSA::PROTOCOL)
565 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
566 # rescue Exception => ex
567 # log_error("Failed to send a keepalive to #{@name}.")
568 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
573 log_error("Failed to receive a message from #{@name}.")
576 if (@status == "agree_waiting")
578 return if (@protocol == LoginCSA::PROTOCOL)
580 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
583 if (@status == "agree_waiting")
584 @status = "start_waiting"
585 if ((@game.sente.status == "start_waiting") &&
586 (@game.gote.status == "start_waiting"))
588 @game.sente.status = "game"
589 @game.gote.status = "game"
592 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
594 when /^%%SHOW\s+(\S+)/
596 if (LEAGUE.games[game_id])
597 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
599 write_safe("##[SHOW] +OK\n")
600 when /^%%MONITORON\s+(\S+)/
602 if (LEAGUE.games[game_id])
603 LEAGUE.games[game_id].monitoron(self)
604 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
605 write_safe("##[MONITOR][#{game_id}] +OK\n")
607 when /^%%MONITOROFF\s+(\S+)/
609 if (LEAGUE.games[game_id])
610 LEAGUE.games[game_id].monitoroff(self)
614 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
616 players = LEAGUE.rated_players
617 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
618 write_safe("##[RATING] %s \t %4d @%s\n" %
619 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
621 write_safe("##[RATING] +OK\n")
623 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
624 write_safe("##[VERSION] +OK\n")
626 if ((@status == "connected") || (@status == "game_waiting"))
627 @status = "connected"
630 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
632 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
636 if (! Login::good_game_name?(game_name))
637 write_safe(sprintf("##[ERROR] bad game name\n"))
639 elsif ((@status == "connected") || (@status == "game_waiting"))
642 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
647 if (League::Floodgate.game_name?(game_name))
648 if (my_sente_str != "*")
649 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", my_sente_str, game_name))
654 if (my_sente_str == "*")
655 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
656 elsif (my_sente_str == "+")
657 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
658 elsif (my_sente_str == "-")
659 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
662 write_safe(sprintf("##[ERROR] bad game option\n"))
668 @game_name = game_name
669 if ((my_sente_str == "*") && (rival.sente == nil))
677 elsif (rival.sente == true) # rival has higher priority
679 elsif (rival.sente == false)
681 elsif (my_sente_str == "+")
684 elsif (my_sente_str == "-")
690 Game::new(@game_name, self, rival)
691 else # rival not found
692 if (command_name == "GAME")
693 @status = "game_waiting"
694 @game_name = game_name
695 if (my_sente_str == "+")
697 elsif (my_sente_str == "-")
703 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
704 @status = "connected"
709 when /^%%CHAT\s+(.+)/
711 LEAGUE.players.each do |name, player|
712 if (player.protocol != LoginCSA::PROTOCOL)
713 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
718 LEAGUE.games.each do |id, game|
719 buf.push(sprintf("##[LIST] %s\n", id))
721 buf.push("##[LIST] +OK\n")
725 LEAGUE.players.each do |name, player|
726 buf.push(sprintf("##[WHO] %s\n", player.to_s))
728 buf.push("##[WHO] +OK\n")
731 @status = "connected"
732 write_safe("LOGOUT:completed\n")
735 # This command is only available for CSA's official testing server.
736 # So, this means nothing for this program.
737 write_safe("CHALLENGE ACCEPTED\n")
739 ## ignore null string
741 msg = "##[ERROR] unknown command %s\n" % [str]
748 unless @socket_buffer.empty?
756 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK",
757 "GI" => "NG", "KA" => "UM", "HI" => "RY"}
758 def initialize(board, x, y, sente, promoted=false)
765 if ((x == 0) || (y == 0))
767 hands = board.sente_hands
769 hands = board.gote_hands
776 @board.array[x][y] = self
779 attr_accessor :promoted, :sente, :x, :y, :board
781 def room_of_head?(x, y, name)
786 return adjacent_movable_grids + far_movable_grids
789 def far_movable_grids
794 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
795 if ((@board.array[x][y] == nil) || # dst is empty
796 (@board.array[x][y].sente != @sente)) # dst is enemy
804 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
805 if (@board.array[x][y] == nil) # dst is empty?
812 def adjacent_movable_grids
815 moves = @promoted_moves
817 moves = @normal_moves
819 moves.each do |(dx, dy)|
826 if (jump_to?(cand_x, cand_y))
827 grids.push([cand_x, cand_y])
833 def move_to?(x, y, name)
834 return false if (! room_of_head?(x, y, name))
835 return false if ((name != @name) && (name != @promoted_name))
836 return false if (@promoted && (name != @promoted_name)) # can't un-promote
839 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
841 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
843 return false if ((6 >= @y) && (6 >= y) && (name != @name))
847 if ((@x == 0) || (@y == 0))
848 return jump_to?(x, y)
850 return movable_grids.include?([x, y])
855 if ((@x == 0) || (@y == 0))
857 @board.sente_hands.delete(self)
859 @board.gote_hands.delete(self)
861 @board.array[x][y] = self
862 elsif ((x == 0) || (y == 0))
863 @promoted = false # clear promoted flag before moving to hands
865 @board.sente_hands.push(self)
867 @board.gote_hands.push(self)
869 @board.array[@x][@y] = nil
871 @board.array[@x][@y] = nil
872 @board.array[x][y] = self
905 class PieceFU < Piece
908 @normal_moves = [[0, +1]]
909 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
911 @promoted_name = "TO"
914 def room_of_head?(x, y, name)
917 return false if (y == 1)
919 return false if (y == 9)
925 if ((iy != @y) && # not source position
926 @board.array[x][iy] &&
927 (@board.array[x][iy].sente == @sente) && # mine
928 (@board.array[x][iy].name == "FU") &&
929 (@board.array[x][iy].promoted == false))
939 class PieceKY < Piece
943 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
945 @promoted_name = "NY"
948 def room_of_head?(x, y, name)
951 return false if (y == 1)
953 return false if (y == 9)
958 def far_movable_grids
966 while (jump_to?(cand_x, cand_y))
967 grids.push([cand_x, cand_y])
968 break if (! put_to?(cand_x, cand_y))
974 while (jump_to?(cand_x, cand_y))
975 grids.push([cand_x, cand_y])
976 break if (! put_to?(cand_x, cand_y))
984 class PieceKE < Piece
987 @normal_moves = [[+1, +2], [-1, +2]]
988 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
990 @promoted_name = "NK"
993 def room_of_head?(x, y, name)
996 return false if ((y == 1) || (y == 2))
998 return false if ((y == 9) || (y == 8))
1004 class PieceGI < Piece
1005 def initialize(*arg)
1007 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1008 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1010 @promoted_name = "NG"
1014 class PieceKI < Piece
1015 def initialize(*arg)
1017 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1018 @promoted_moves = []
1020 @promoted_name = nil
1024 class PieceKA < Piece
1025 def initialize(*arg)
1028 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
1030 @promoted_name = "UM"
1033 def far_movable_grids
1038 while (jump_to?(cand_x, cand_y))
1039 grids.push([cand_x, cand_y])
1040 break if (! put_to?(cand_x, cand_y))
1047 while (jump_to?(cand_x, cand_y))
1048 grids.push([cand_x, cand_y])
1049 break if (! put_to?(cand_x, cand_y))
1056 while (jump_to?(cand_x, cand_y))
1057 grids.push([cand_x, cand_y])
1058 break if (! put_to?(cand_x, cand_y))
1065 while (jump_to?(cand_x, cand_y))
1066 grids.push([cand_x, cand_y])
1067 break if (! put_to?(cand_x, cand_y))
1074 class PieceHI < Piece
1075 def initialize(*arg)
1078 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1080 @promoted_name = "RY"
1083 def far_movable_grids
1088 while (jump_to?(cand_x, cand_y))
1089 grids.push([cand_x, cand_y])
1090 break if (! put_to?(cand_x, cand_y))
1096 while (jump_to?(cand_x, cand_y))
1097 grids.push([cand_x, cand_y])
1098 break if (! put_to?(cand_x, cand_y))
1104 while (jump_to?(cand_x, cand_y))
1105 grids.push([cand_x, cand_y])
1106 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))
1120 class PieceOU < Piece
1121 def initialize(*arg)
1123 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1124 @promoted_moves = []
1126 @promoted_name = nil
1133 @sente_hands = Array::new
1134 @gote_hands = Array::new
1135 @history = Hash::new(0)
1136 @sente_history = Hash::new(0)
1137 @gote_history = Hash::new(0)
1138 @array = [[], [], [], [], [], [], [], [], [], []]
1140 @teban = nil # black => true, white => false
1142 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1143 attr_reader :move_count
1146 PieceKY::new(self, 1, 1, false)
1147 PieceKE::new(self, 2, 1, false)
1148 PieceGI::new(self, 3, 1, false)
1149 PieceKI::new(self, 4, 1, false)
1150 PieceOU::new(self, 5, 1, false)
1151 PieceKI::new(self, 6, 1, false)
1152 PieceGI::new(self, 7, 1, false)
1153 PieceKE::new(self, 8, 1, false)
1154 PieceKY::new(self, 9, 1, false)
1155 PieceKA::new(self, 2, 2, false)
1156 PieceHI::new(self, 8, 2, false)
1158 PieceFU::new(self, i, 3, false)
1161 PieceKY::new(self, 1, 9, true)
1162 PieceKE::new(self, 2, 9, true)
1163 PieceGI::new(self, 3, 9, true)
1164 PieceKI::new(self, 4, 9, true)
1165 PieceOU::new(self, 5, 9, true)
1166 PieceKI::new(self, 6, 9, true)
1167 PieceGI::new(self, 7, 9, true)
1168 PieceKE::new(self, 8, 9, true)
1169 PieceKY::new(self, 9, 9, true)
1170 PieceKA::new(self, 8, 8, true)
1171 PieceHI::new(self, 2, 8, true)
1173 PieceFU::new(self, i, 7, true)
1178 def have_piece?(hands, name)
1179 piece = hands.find { |i|
1185 def move_to(x0, y0, x1, y1, name, sente)
1187 hands = @sente_hands
1192 if ((x0 == 0) || (y0 == 0))
1193 piece = have_piece?(hands, name)
1194 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1195 piece.move_to(x1, y1)
1197 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1198 if (@array[x0][y0].name != name) # promoted ?
1199 @array[x0][y0].promoted = true
1201 if (@array[x1][y1]) # capture
1202 if (@array[x1][y1].name == "OU")
1203 return :outori # return board update
1205 @array[x1][y1].sente = @array[x0][y0].sente
1206 @array[x1][y1].move_to(0, 0)
1207 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1211 @array[x0][y0].move_to(x1, y1)
1214 @teban = @teban ? false : true
1218 def look_for_ou(sente)
1224 (@array[x][y].name == "OU") &&
1225 (@array[x][y].sente == sente))
1232 raise "can't find ou"
1235 # note checkmate, but check. sente is checked.
1236 def checkmated?(sente) # sente is loosing
1237 ou = look_for_ou(sente)
1243 (@array[x][y].sente != sente))
1244 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1255 def uchifuzume?(sente)
1256 rival_ou = look_for_ou(! sente) # rival's ou
1257 if (sente) # rival is gote
1258 if ((rival_ou.y != 9) &&
1259 (@array[rival_ou.x][rival_ou.y + 1]) &&
1260 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1261 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1263 fu_y = rival_ou.y + 1
1268 if ((rival_ou.y != 1) &&
1269 (@array[rival_ou.x][rival_ou.y - 1]) &&
1270 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1271 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1273 fu_y = rival_ou.y - 1
1279 ## case: rival_ou is moving
1280 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1281 tmp_board = Marshal.load(Marshal.dump(self))
1282 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1283 raise "internal error" if (s != true)
1284 if (! tmp_board.checkmated?(! sente)) # good move
1289 ## case: rival is capturing fu
1295 (@array[x][y].sente != sente) &&
1296 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1299 if (@array[x][y].promoted)
1300 names << @array[x][y].promoted_name
1302 names << @array[x][y].name
1303 if @array[x][y].promoted_name &&
1304 @array[x][y].move_to?(fu_x, fu_y, @array[x][y].promoted_name)
1305 names << @array[x][y].promoted_name
1308 names.map! do |name|
1309 tmp_board = Marshal.load(Marshal.dump(self))
1310 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1314 tmp_board.checkmated?(! sente) # result
1317 all_illegal = names.find {|a| a != :illegal}
1318 raise "internal error: legal move not found" if all_illegal == nil
1319 r = names.find {|a| a == false} # good move
1320 return false if r == false # found good move
1329 # @[sente|gote]_history has at least one item while the player is checking the other or
1330 # the other escapes.
1331 def update_sennichite(player)
1334 if checkmated?(!player)
1336 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
1338 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
1342 @sente_history.clear # no more continuous check
1344 @gote_history.clear # no more continuous check
1347 if @sente_history.size > 0 # possible for Sente's or Gote's turn
1348 @sente_history[str] += 1
1350 if @gote_history.size > 0 # possible for Sente's or Gote's turn
1351 @gote_history[str] += 1
1355 def oute_sennichite?(player)
1356 if (@sente_history[to_s] >= 4)
1357 return :oute_sennichite_sente_lose
1358 elsif (@gote_history[to_s] >= 4)
1359 return :oute_sennichite_gote_lose
1365 def sennichite?(sente)
1366 if (@history[to_s] >= 4) # already 3 times
1372 def good_kachi?(sente)
1373 if (checkmated?(sente))
1374 puts "'NG: Checkmating." if $DEBUG
1378 ou = look_for_ou(sente)
1379 if (sente && (ou.y >= 4))
1380 puts "'NG: Black's OU does not enter yet." if $DEBUG
1383 if (! sente && (ou.y <= 6))
1384 puts "'NG: White's OU does not enter yet." if $DEBUG
1392 hands = @sente_hands
1402 (@array[x][y].sente == sente) &&
1403 (@array[x][y].point > 0))
1404 point = point + @array[x][y].point
1410 hands.each do |piece|
1411 point = point + piece.point
1415 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1420 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1425 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1430 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1434 # sente is nil only if tests in test_board run
1435 def handle_one_move(str, sente=nil)
1436 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1443 elsif (str =~ /^%KACHI/)
1444 raise ArgumentError, "sente is null", caller if sente == nil
1445 if (good_kachi?(sente))
1450 elsif (str =~ /^%TORYO/)
1456 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1457 ((x0 != 0) || (y0 != 0)))
1459 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1464 sente = true if sente == nil # deprecated
1465 return :illegal unless sente == true # black player's move must be black
1466 hands = @sente_hands
1468 sente = false if sente == nil # deprecated
1469 return :illegal unless sente == false # white player's move must be white
1474 if ((x0 == 0) && (y0 == 0))
1475 return :illegal if (! have_piece?(hands, name))
1476 elsif (! @array[x0][y0])
1477 return :illegal # no piece
1478 elsif (@array[x0][y0].sente != sente)
1479 return :illegal # this is not mine
1480 elsif (@array[x0][y0].name != name)
1481 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1484 ## destination check
1485 if (@array[x1][y1] &&
1486 (@array[x1][y1].sente == sente)) # can't capture mine
1488 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1489 return :illegal # can't put on existing piece
1492 tmp_board = Marshal.load(Marshal.dump(self))
1493 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1494 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1495 tmp_board.update_sennichite(sente)
1496 os_result = tmp_board.oute_sennichite?(sente)
1497 return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
1498 return :sennichite if tmp_board.sennichite?(sente)
1500 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1504 move_to(x0, y0, x1, y1, name, sente)
1506 update_sennichite(sente)
1514 a.push(sprintf("P%d", y))
1517 piece = @array[x][y]
1526 a.push(sprintf("\n"))
1529 if (! sente_hands.empty?)
1531 sente_hands.each do |p|
1532 a.push("00" + p.name)
1536 if (! gote_hands.empty?)
1538 gote_hands.each do |p|
1539 a.push("00" + p.name)
1543 a.push("%s\n" % [@teban ? "+" : "-"])
1549 attr_reader :players, :black, :white
1551 def initialize(p1, p2)
1553 if p1.sente && !p2.sente
1554 @black, @white = p1, p2
1555 elsif !p1.sente && p2.sente
1556 @black, @white = p2, p1
1558 raise "Never reached!"
1563 class GameResultWin < GameResult
1564 attr_reader :winner, :loser
1566 def initialize(winner, loser)
1568 @winner, @loser = winner, loser
1569 @winner.last_game_win = true
1570 @loser.last_game_win = false
1574 black_name = @black.id || @black.name
1575 white_name = @white.id || @white.name
1576 "%s:%s" % [black_name, white_name]
1580 class GameResultDraw < GameResult
1581 def initialize(p1, p2)
1583 p1.last_game_win = false
1584 p2.last_game_win = false
1592 def initialize(game_name, player0, player1)
1593 @monitors = Array::new
1594 @game_name = game_name
1595 if (@game_name =~ /-(\d+)-(\d+)$/)
1596 @total_time = $1.to_i
1601 @sente, @gote = player0, player1
1603 @sente, @gote = player1, player0
1605 @sente.socket_buffer.clear
1606 @gote.socket_buffer.clear
1607 @current_player, @next_player = @sente, @gote
1614 @sente.status = "agree_waiting"
1615 @gote.status = "agree_waiting"
1617 @id = sprintf("%s+%s+%s+%s+%s",
1618 LEAGUE.event, @game_name,
1619 @sente.name, @gote.name, issue_current_time)
1620 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1622 LEAGUE.games[@id] = self
1624 log_message(sprintf("game created %s", @id))
1634 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1635 attr_accessor :last_move, :current_turn
1639 @sente.rated? && @gote.rated?
1642 def monitoron(monitor)
1643 @monitors.delete(monitor)
1644 @monitors.push(monitor)
1647 def monitoroff(monitor)
1648 @monitors.delete(monitor)
1651 def reject(rejector)
1652 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1653 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1658 if ["agree_waiting", "start_waiting"].include?(@sente.status)
1660 elsif (@current_player == killer)
1667 log_message(sprintf("game finished %s", @id))
1668 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1673 @sente.status = "connected"
1674 @gote.status = "connected"
1676 if (@current_player.protocol == LoginCSA::PROTOCOL)
1677 @current_player.finish
1679 if (@next_player.protocol == LoginCSA::PROTOCOL)
1682 @monitors = Array::new
1685 @current_player = nil
1687 LEAGUE.games.delete(@id)
1691 def handle_one_move(str, player)
1692 unless @current_player == player
1693 @fh.puts("'Skipped %s" % [str])
1694 log_warning("Skipped a move [%s] scince it is not %s 's turn." %
1696 player.socket_buffer.unshift(str)
1702 @end_time = Time::new
1703 t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
1706 if ((@current_player.mytime - t <= -@byoyomi) &&
1707 ((@total_time > 0) || (@byoyomi > 0)))
1709 elsif (str == :timeout)
1710 return false # time isn't expired. players aren't swapped. continue game
1712 @current_player.mytime -= t
1713 if (@current_player.mytime < 0)
1714 @current_player.mytime = 0
1717 move_status = @board.handle_one_move(str, @sente == @current_player)
1719 if [:illegal, :uchifuzme, :oute_kaihimore].include?(move_status)
1720 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1722 if [:normal, :outori, :sennichite, :oute_sennichite_sente_lose, :oute_sennichite_gote_lose].include?(move_status)
1723 # Thinking time includes network traffic
1724 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1725 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1726 @fh.printf("%s\nT%d\n", str, t)
1727 @last_move = sprintf("%s,T%d", str, t)
1731 @monitors.each do |monitor|
1732 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1733 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1738 if (@next_player.status != "game") # rival is logout or disconnected
1740 elsif (status == :timeout)
1742 elsif (move_status == :illegal)
1744 elsif (move_status == :kachi_win)
1746 elsif (move_status == :kachi_lose)
1748 elsif (move_status == :toryo)
1750 elsif (move_status == :outori)
1752 elsif (move_status == :oute_sennichite_sente_lose)
1753 oute_sennichite_win_lose(@gote, @sente) # Sente is checking
1754 elsif (move_status == :oute_sennichite_gote_lose)
1755 oute_sennichite_win_lose(@sente, @gote) # Gote is checking
1756 elsif (move_status == :sennichite)
1758 elsif (move_status == :uchifuzume)
1760 elsif (move_status == :oute_kaihimore)
1761 oute_kaihimore_lose()
1765 finish() if finish_flag
1766 @current_player, @next_player = @next_player, @current_player
1767 @start_time = Time::new
1772 @current_player.status = "connected"
1773 @next_player.status = "connected"
1774 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1775 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1776 @fh.printf("%%TORYO\n")
1777 @fh.print(@board.to_s.gsub(/^/, "\'"))
1778 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1779 @result = GameResultWin.new(@current_player, @next_player)
1780 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1781 @monitors.each do |monitor|
1782 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1787 @current_player.status = "connected"
1788 @next_player.status = "connected"
1789 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1790 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1791 @fh.printf("%%TORYO\n")
1792 @fh.print(@board.to_s.gsub(/^/, "\'"))
1793 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1794 @result = GameResultWin.new(@next_player, @current_player)
1795 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1796 @monitors.each do |monitor|
1797 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1802 @current_player.status = "connected"
1803 @next_player.status = "connected"
1804 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1805 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1806 @fh.print(@board.to_s.gsub(/^/, "\'"))
1807 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1808 @result = GameResultDraw.new(@current_player, @next_player)
1809 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1810 @monitors.each do |monitor|
1811 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @id))
1815 def oute_sennichite_win_lose(winner, loser)
1816 @current_player.status = "connected"
1817 @next_player.status = "connected"
1818 loser.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1819 winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1820 @fh.print(@board.to_s.gsub(/^/, "\'"))
1821 if loser == @current_player
1822 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1824 @fh.printf("'summary:oute_sennichite:%s win:%s lose\n", @current_player.name, @next_player.name)
1826 @result = GameResultWin.new(winner, loser)
1827 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1828 @monitors.each do |monitor|
1829 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1834 @current_player.status = "connected"
1835 @next_player.status = "connected"
1836 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1837 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1838 @fh.print(@board.to_s.gsub(/^/, "\'"))
1839 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1840 @result = GameResultWin.new(@next_player, @current_player)
1841 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1842 @monitors.each do |monitor|
1843 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1848 @current_player.status = "connected"
1849 @next_player.status = "connected"
1850 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1851 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1852 @fh.print(@board.to_s.gsub(/^/, "\'"))
1853 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1854 @result = GameResultWin.new(@next_player, @current_player)
1855 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1856 @monitors.each do |monitor|
1857 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1861 def oute_kaihimore_lose
1862 @current_player.status = "connected"
1863 @next_player.status = "connected"
1864 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1865 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1866 @fh.print(@board.to_s.gsub(/^/, "\'"))
1867 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1868 @result = GameResultWin.new(@next_player, @current_player)
1869 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1870 @monitors.each do |monitor|
1871 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1876 @current_player.status = "connected"
1877 @next_player.status = "connected"
1878 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1879 @next_player.write_safe("#TIME_UP\n#WIN\n")
1880 @fh.print(@board.to_s.gsub(/^/, "\'"))
1881 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1882 @result = GameResultWin.new(@next_player, @current_player)
1883 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1884 @monitors.each do |monitor|
1885 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
1890 @current_player.status = "connected"
1891 @next_player.status = "connected"
1892 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1893 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1894 @fh.printf("%%KACHI\n")
1895 @fh.print(@board.to_s.gsub(/^/, "\'"))
1896 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1897 @result = GameResultWin.new(@current_player, @next_player)
1898 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1899 @monitors.each do |monitor|
1900 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1905 @current_player.status = "connected"
1906 @next_player.status = "connected"
1907 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1908 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1909 @fh.printf("%%KACHI\n")
1910 @fh.print(@board.to_s.gsub(/^/, "\'"))
1911 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1912 @result = GameResultWin.new(@next_player, @current_player)
1913 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1914 @monitors.each do |monitor|
1915 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1920 @current_player.status = "connected"
1921 @next_player.status = "connected"
1922 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1923 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1924 @fh.printf("%%TORYO\n")
1925 @fh.print(@board.to_s.gsub(/^/, "\'"))
1926 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1927 @result = GameResultWin.new(@next_player, @current_player)
1928 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1929 @monitors.each do |monitor|
1930 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1935 @current_player.status = "connected"
1936 @next_player.status = "connected"
1937 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1938 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1939 @fh.print(@board.to_s.gsub(/^/, "\'"))
1940 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1941 @result = GameResultWin.new(@current_player, @next_player)
1942 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1943 @monitors.each do |monitor|
1944 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1949 log_message(sprintf("game started %s", @id))
1950 @sente.write_safe(sprintf("START:%s\n", @id))
1951 @gote.write_safe(sprintf("START:%s\n", @id))
1952 @sente.mytime = @total_time
1953 @gote.mytime = @total_time
1954 @start_time = Time::new
1958 @fh = open(@logfile, "w")
1962 @fh.puts("N+#{@sente.name}")
1963 @fh.puts("N-#{@gote.name}")
1964 @fh.puts("$EVENT:#{@id}")
1966 @sente.write_safe(propose_message("+"))
1967 @gote.write_safe(propose_message("-"))
1969 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
1970 @fh.puts("$START_TIME:#{now}")
1972 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1973 P2 * -HI * * * * * -KA *
1974 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1975 P4 * * * * * * * * *
1976 P5 * * * * * * * * *
1977 P6 * * * * * * * * *
1978 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1979 P8 * +KA * * * * * +HI *
1980 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1988 Protocol_Version:1.1
1989 Protocol_Mode:Server
1991 Declaration:Jishogi 1.1
1993 Name+:#{@sente.name}
1999 Total_Time:#{@total_time}
2001 Least_Time_Per_Move:#{Least_Time_Per_Move}
2002 Remaining_Time+:#{@sente.mytime}
2003 Remaining_Time-:#{@gote.mytime}
2004 Last_Move:#{@last_move}
2005 Current_Turn:#{@current_turn}
2015 return str0 + @board.to_s + str1
2018 def propose_message(sg_flag)
2021 Protocol_Version:1.1
2022 Protocol_Mode:Server
2024 Declaration:Jishogi 1.1
2026 Name+:#{@sente.name}
2028 Your_Turn:#{sg_flag}
2033 Total_Time:#{@total_time}
2035 Least_Time_Per_Move:#{Least_Time_Per_Move}
2038 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2039 P2 * -HI * * * * * -KA *
2040 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2041 P4 * * * * * * * * *
2042 P5 * * * * * * * * *
2043 P6 * * * * * * * * *
2044 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2045 P8 * +KA * * * * * +HI *
2046 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2058 def issue_current_time
2059 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
2060 @@mutex.synchronize do
2061 while time <= @@time do
2068 end # module ShogiServer
2070 #################################################
2077 shogi-server - server for CSA server protocol
2080 shogi-server [OPTIONS] event_name port_number
2083 server for CSA server protocol
2087 specify filename for logging process ID
2089 run as a daemon. Log files will be put in dir.
2092 this file is distributed under GPL version2 and might be compiled by Exerb
2097 #{ShogiServer::Release}
2100 #{ShogiServer::Revision}
2108 def log_message(str)
2112 def log_warning(str)
2121 def parse_command_line
2123 parser = GetoptLong.new(
2124 ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2125 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT])
2128 parser.each_option do |name, arg|
2129 name.sub!(/^--/, '')
2130 options[name] = arg.dup
2134 raise parser.error_message
2139 def write_pid_file(file)
2140 open(file, "w") do |fh|
2145 def mutex_watchdog(mutex, sec)
2157 log_error("mutex watchdog timeout")
2163 def login_loop(client)
2164 player = login = nil
2166 while r = select([client], nil, nil, ShogiServer::Login_Time) do
2167 break unless str = r[0].first.gets
2168 $mutex.lock # guards LEAGUE
2172 if (ShogiServer::Login::good_login?(str))
2173 player = ShogiServer::Player::new(str, client, eol)
2174 login = ShogiServer::Login::factory(str, player)
2175 if (current_player = LEAGUE.find(player.name))
2176 if (current_player.password == player.password &&
2177 current_player.status != "game")
2178 log_message(sprintf("user %s login forcely", player.name))
2181 login.incorrect_duplicated_player(str)
2189 client.write("LOGIN:incorrect" + eol)
2190 client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2196 return [player, login]
2204 mutex_watchdog($mutex, 10)
2207 $options = parse_command_line
2208 if (ARGV.length != 2)
2213 LEAGUE.event = ARGV.shift
2216 dir = $options["daemon"]
2217 dir = File.expand_path(dir) if dir
2218 if dir && ! File.exist?(dir)
2219 FileUtils.mkdir(dir)
2221 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2222 $logger = WEBrick::Log.new(log_file) # thread safe
2224 LEAGUE.dir = dir || File.dirname(__FILE__)
2225 LEAGUE.setup_players_database
2228 config[:Port] = port
2229 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2230 config[:Logger] = $logger
2231 if $options["pid-file"]
2232 pid_file = File.expand_path($options["pid-file"])
2233 config[:StartCallback] = Proc.new do
2234 write_pid_file(pid_file)
2236 config[:StopCallback] = Proc.new do
2237 FileUtils.rm(pid_file, :force => true)
2241 server = WEBrick::GenericServer.new(config)
2242 ["INT", "TERM"].each do |signal|
2248 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2249 log_message("server started [Revision: #{ShogiServer::Revision}]")
2251 server.start do |client|
2252 # client.sync = true # this is already set in WEBrick
2253 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2254 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2255 player, login = login_loop(client) # loop
2258 log_message(sprintf("user %s login", player.name))
2260 player.run(login.csa_1st_str) # loop
2264 player.game.kill(player)
2266 player.finish # socket has been closed
2267 LEAGUE.delete(player)
2268 log_message(sprintf("user %s logout", player.name))
2279 TCPSocket.do_not_reverse_lookup = true
2280 Thread.abort_on_exception = $DEBUG ? true : false
2282 LEAGUE = ShogiServer::League::new