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} #{ex.backtrace}")
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 # This manages those players who have their player_id.
126 # Since mk_rate mainly updates the yaml file, basically,
127 # this only reads data. But this writes some properties.
128 # TODO Such data should be facoted out to another file
131 def initialize(filename)
132 @db = YAML::Store.new(filename)
133 @db.transaction do |pstore|
134 @db['players'] ||= Hash.new
139 # trancaction=true means read only
141 def each_group(transaction=false)
142 @db.transaction(transaction) do
143 groups = @db["players"] || Hash.new
144 groups.each do |group, players|
150 def load_player(player)
151 return unless player.player_id
154 each_group(true) do |group, players|
155 hash = players[player.player_id]
161 player.name = hash['name']
162 player.rate = hash['rate'] || 0
163 player.modified_at = hash['last_modified']
164 player.rating_group = hash['rating_group']
165 player.win = hash['win'] || 0
166 player.loss = hash['loss'] || 0
167 player.last_game_win = hash['last_game_win'] || false
171 return unless player.player_id
173 each_group do |group, players|
174 hash = players[player.player_id]
176 # write only this property.
177 # the others are updated by ./mk_rate
178 hash['last_game_win'] = player.last_game_win
186 each_group(true) do |group, players_hash|
187 players << players_hash.keys
189 return players.flatten.collect do |player_id|
191 p.player_id = player_id
196 end # class Persistent
199 @mutex = Mutex.new # guard @players
203 @dir = File.dirname(__FILE__)
204 @floodgate = Floodgate.new(self)
207 attr_accessor :players, :games, :event, :dir
210 @mutex.synchronize do
211 @players.each do |name, player|
212 @persistent.save(player)
218 # this should be called just after instanciating a League object.
219 def setup_players_database
220 filename = File.join(@dir, "players.yaml")
221 @persistent = Persistent.new(filename)
225 @persistent.load_player(player)
226 @mutex.synchronize do
227 @players[player.name] = player
232 @persistent.save(player)
233 @mutex.synchronize do
234 @players.delete(player.name)
239 @mutex.synchronize do
240 @players.each do |name, player|
241 @persistent.load_player(player)
248 @mutex.synchronize do
249 found = @players.find_all do |name, player|
253 return found.map {|a| a.last}
256 def find(player_name)
258 @mutex.synchronize do
259 found = @players[player_name]
264 def get_player(status, game_name, sente, searcher)
266 @mutex.synchronize do
267 found = @players.find do |name, player|
268 (player.status == status) &&
269 (player.game_name == game_name) &&
271 (player.sente == nil) ||
272 (player.sente == sente) ) &&
273 (player.name != searcher.name)
276 return found ? found.last : nil
280 return @persistent.get_players
285 ######################################################
286 # Processes the LOGIN command.
289 def Login.good_login?(str)
291 if (((tokens.length == 3) ||
292 ((tokens.length == 4) && tokens[3] == "x1")) &&
293 (tokens[0] == "LOGIN") &&
294 (good_identifier?(tokens[1])))
301 def Login.good_game_name?(str)
302 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
309 def Login.good_identifier?(str)
310 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
317 def Login.factory(str, player)
318 (login, player.name, password, ext) = str.chomp.split
320 return Loginx1.new(player, password)
322 return LoginCSA.new(player, password)
328 # the first command that will be executed just after LOGIN.
329 # If it is nil, the default process will be started.
330 attr_reader :csa_1st_str
332 def initialize(player, password)
335 parse_password(password)
339 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
340 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
343 def incorrect_duplicated_player(str)
344 @player.write_safe("LOGIN:incorrect\n")
345 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
346 sleep 3 # wait for sending the above messages.
347 @player.name = "%s [duplicated]" % [@player.name]
352 ######################################################
353 # Processes LOGIN for the CSA standard mode.
355 class LoginCSA < Login
358 def initialize(player, password)
361 @player.protocol = PROTOCOL
364 def parse_password(password)
365 if Login.good_game_name?(password)
367 @player.set_password(nil)
368 elsif password.split(",").size > 1
369 @gamename, *trip = password.split(",")
370 @player.set_password(trip.join(","))
372 @player.set_password(password)
373 @gamename = Default_Game_Name
375 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
380 @csa_1st_str = "%%GAME #{@gamename} *"
384 ######################################################
385 # Processes LOGIN for the extented mode.
387 class Loginx1 < Login
390 def initialize(player, password)
392 @player.protocol = PROTOCOL
395 def parse_password(password)
396 @player.set_password(password)
401 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
411 @last_game_win = false
414 # Idetifier of the player in the rating system
415 attr_accessor :player_id
420 # Password of the player, which does not include a trip
421 attr_accessor :password
423 # Score in the rating sysem
426 # Number of games for win and loss in the rating system
427 attr_accessor :win, :loss
429 # Group in the rating system
430 attr_accessor :rating_group
432 # Last timestamp when the rate was modified
433 attr_accessor :modified_at
435 # Whether win the previous game or not
436 attr_accessor :last_game_win
439 @modified_at || Time.now
445 @modified_at = Time.now
454 return @last_game_win
459 simple_name = @name.gsub(/@.*?$/, '')
460 "%s+%s" % [simple_name, @trip[0..8]]
467 # Parses str in the LOGIN command, sets up @player_id and @trip
469 def set_password(str)
470 if str && !str.empty?
471 @password = str.strip
472 @player_id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
474 @player_id = @password = nil
480 class Player < BasicPlayer
481 def initialize(str, socket, eol=nil)
484 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
486 @protocol = nil # CSA or x1
487 @eol = eol || "\m" # favorite eol code
490 @mytime = 0 # set in start method also
493 @main_thread = Thread::current
494 @mutex_write_guard = Mutex.new
497 attr_accessor :socket, :status
498 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
499 attr_accessor :main_thread
500 attr_reader :socket_buffer
503 log_message(sprintf("user %s killed", @name))
508 Thread::kill(@main_thread) if @main_thread
512 if (@status != "finished")
514 log_message(sprintf("user %s finish", @name))
516 # @socket.close if (! @socket.closed?)
518 log_message(sprintf("user %s finish failed", @name))
524 @mutex_write_guard.synchronize do
527 log_warning("%s's socket has been closed." % [@name])
530 if r = select(nil, [@socket], nil, 20)
531 r[1].first.write(str)
533 log_error("Sending a message to #{@name} timed up.")
535 rescue Exception => ex
536 log_error("Failed to send a message to #{@name}. #{ex.class}: #{ex.message}\t#{ex.backtrace[0]}")
542 if ["game_waiting", "start_waiting", "agree_waiting", "game"].include?(status)
544 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
545 elsif (@sente == false)
546 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
547 elsif (@sente == nil)
548 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
551 return sprintf("%s %s %s", @name, @protocol, @status)
555 def run(csa_1st_str=nil)
556 while ( csa_1st_str ||
557 str = gets_safe(@socket, (@socket_buffer.empty? ? Default_Timeout : 1)) )
560 if (@game && @game.turn?(self))
561 @socket_buffer << str
562 str = @socket_buffer.shift
564 log_message("%s (%s)" % [str, @socket_buffer.map {|a| String === a ? a.strip : a }.join(",")]) if $DEBUG
571 if (@status == "finished")
574 str.chomp! if (str.class == String) # may be strip! ?
577 # Application-level protocol for Keep-Alive
578 # If the server gets LF, it sends back LF.
579 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
582 if (@status == "game")
583 array_str = str.split(",")
584 move = array_str.shift
585 additional = array_str.shift
586 if /^'(.*)/ =~ additional
587 comment = array_str.unshift("'*#{$1.toeuc}")
589 s = @game.handle_one_move(move, self)
590 @game.fh.print("#{Kconv.toeuc(comment.first)}\n") if (comment && comment.first && !s)
591 return if (s && @protocol == LoginCSA::PROTOCOL)
593 when /^%[^%]/, :timeout
594 if (@status == "game")
595 s = @game.handle_one_move(str, self)
596 return if (s && @protocol == LoginCSA::PROTOCOL)
599 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
600 # rescue Exception => ex
601 # log_error("Failed to send a keepalive to #{@name}.")
602 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
607 log_error("Failed to receive a message from #{@name}.")
610 if (@status == "agree_waiting")
612 return if (@protocol == LoginCSA::PROTOCOL)
614 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
617 if (@status == "agree_waiting")
618 @status = "start_waiting"
619 if ((@game.sente.status == "start_waiting") &&
620 (@game.gote.status == "start_waiting"))
622 @game.sente.status = "game"
623 @game.gote.status = "game"
626 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
628 when /^%%SHOW\s+(\S+)/
630 if (LEAGUE.games[game_id])
631 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
633 write_safe("##[SHOW] +OK\n")
634 when /^%%MONITORON\s+(\S+)/
636 if (LEAGUE.games[game_id])
637 LEAGUE.games[game_id].monitoron(self)
638 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
639 write_safe("##[MONITOR][#{game_id}] +OK\n")
641 when /^%%MONITOROFF\s+(\S+)/
643 if (LEAGUE.games[game_id])
644 LEAGUE.games[game_id].monitoroff(self)
648 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
650 players = LEAGUE.rated_players
651 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
652 write_safe("##[RATING] %s \t %4d @%s\n" %
653 [p.simple_player_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
655 write_safe("##[RATING] +OK\n")
657 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
658 write_safe("##[VERSION] +OK\n")
660 if ((@status == "connected") || (@status == "game_waiting"))
661 @status = "connected"
664 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
666 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
670 if (! Login::good_game_name?(game_name))
671 write_safe(sprintf("##[ERROR] bad game name\n"))
673 elsif ((@status == "connected") || (@status == "game_waiting"))
676 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
681 if (League::Floodgate.game_name?(game_name))
682 if (my_sente_str != "*")
683 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", my_sente_str, game_name))
688 if (my_sente_str == "*")
689 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
690 elsif (my_sente_str == "+")
691 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
692 elsif (my_sente_str == "-")
693 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
696 write_safe(sprintf("##[ERROR] bad game option\n"))
702 @game_name = game_name
703 if ((my_sente_str == "*") && (rival.sente == nil))
711 elsif (rival.sente == true) # rival has higher priority
713 elsif (rival.sente == false)
715 elsif (my_sente_str == "+")
718 elsif (my_sente_str == "-")
724 Game::new(@game_name, self, rival)
725 else # rival not found
726 if (command_name == "GAME")
727 @status = "game_waiting"
728 @game_name = game_name
729 if (my_sente_str == "+")
731 elsif (my_sente_str == "-")
737 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
738 @status = "connected"
743 when /^%%CHAT\s+(.+)/
745 LEAGUE.players.each do |name, player|
746 if (player.protocol != LoginCSA::PROTOCOL)
747 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
752 LEAGUE.games.each do |id, game|
753 buf.push(sprintf("##[LIST] %s\n", id))
755 buf.push("##[LIST] +OK\n")
759 LEAGUE.players.each do |name, player|
760 buf.push(sprintf("##[WHO] %s\n", player.to_s))
762 buf.push("##[WHO] +OK\n")
765 @status = "connected"
766 write_safe("LOGOUT:completed\n")
769 # This command is only available for CSA's official testing server.
770 # So, this means nothing for this program.
771 write_safe("CHALLENGE ACCEPTED\n")
773 ## ignore null string
775 msg = "##[ERROR] unknown command %s\n" % [str]
787 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK",
788 "GI" => "NG", "KA" => "UM", "HI" => "RY"}
789 def initialize(board, x, y, sente, promoted=false)
796 if ((x == 0) || (y == 0))
798 hands = board.sente_hands
800 hands = board.gote_hands
807 @board.array[x][y] = self
810 attr_accessor :promoted, :sente, :x, :y, :board
812 def room_of_head?(x, y, name)
817 return adjacent_movable_grids + far_movable_grids
820 def far_movable_grids
825 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
826 if ((@board.array[x][y] == nil) || # dst is empty
827 (@board.array[x][y].sente != @sente)) # dst is enemy
835 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
836 if (@board.array[x][y] == nil) # dst is empty?
843 def adjacent_movable_grids
846 moves = @promoted_moves
848 moves = @normal_moves
850 moves.each do |(dx, dy)|
857 if (jump_to?(cand_x, cand_y))
858 grids.push([cand_x, cand_y])
864 def move_to?(x, y, name)
865 return false if (! room_of_head?(x, y, name))
866 return false if ((name != @name) && (name != @promoted_name))
867 return false if (@promoted && (name != @promoted_name)) # can't un-promote
870 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
872 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
874 return false if ((6 >= @y) && (6 >= y) && (name != @name))
878 if ((@x == 0) || (@y == 0))
879 return jump_to?(x, y)
881 return movable_grids.include?([x, y])
886 if ((@x == 0) || (@y == 0))
888 @board.sente_hands.delete(self)
890 @board.gote_hands.delete(self)
892 @board.array[x][y] = self
893 elsif ((x == 0) || (y == 0))
894 @promoted = false # clear promoted flag before moving to hands
896 @board.sente_hands.push(self)
898 @board.gote_hands.push(self)
900 @board.array[@x][@y] = nil
902 @board.array[@x][@y] = nil
903 @board.array[x][y] = self
936 class PieceFU < Piece
939 @normal_moves = [[0, +1]]
940 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
942 @promoted_name = "TO"
945 def room_of_head?(x, y, name)
948 return false if (y == 1)
950 return false if (y == 9)
956 if ((iy != @y) && # not source position
957 @board.array[x][iy] &&
958 (@board.array[x][iy].sente == @sente) && # mine
959 (@board.array[x][iy].name == "FU") &&
960 (@board.array[x][iy].promoted == false))
970 class PieceKY < Piece
974 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
976 @promoted_name = "NY"
979 def room_of_head?(x, y, name)
982 return false if (y == 1)
984 return false if (y == 9)
989 def far_movable_grids
997 while (jump_to?(cand_x, cand_y))
998 grids.push([cand_x, cand_y])
999 break if (! put_to?(cand_x, cand_y))
1005 while (jump_to?(cand_x, cand_y))
1006 grids.push([cand_x, cand_y])
1007 break if (! put_to?(cand_x, cand_y))
1015 class PieceKE < Piece
1016 def initialize(*arg)
1018 @normal_moves = [[+1, +2], [-1, +2]]
1019 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1021 @promoted_name = "NK"
1024 def room_of_head?(x, y, name)
1027 return false if ((y == 1) || (y == 2))
1029 return false if ((y == 9) || (y == 8))
1035 class PieceGI < Piece
1036 def initialize(*arg)
1038 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1039 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1041 @promoted_name = "NG"
1045 class PieceKI < Piece
1046 def initialize(*arg)
1048 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1049 @promoted_moves = []
1051 @promoted_name = nil
1055 class PieceKA < Piece
1056 def initialize(*arg)
1059 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
1061 @promoted_name = "UM"
1064 def far_movable_grids
1069 while (jump_to?(cand_x, cand_y))
1070 grids.push([cand_x, cand_y])
1071 break if (! put_to?(cand_x, cand_y))
1078 while (jump_to?(cand_x, cand_y))
1079 grids.push([cand_x, cand_y])
1080 break if (! put_to?(cand_x, cand_y))
1087 while (jump_to?(cand_x, cand_y))
1088 grids.push([cand_x, cand_y])
1089 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))
1105 class PieceHI < Piece
1106 def initialize(*arg)
1109 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1111 @promoted_name = "RY"
1114 def far_movable_grids
1119 while (jump_to?(cand_x, cand_y))
1120 grids.push([cand_x, cand_y])
1121 break if (! put_to?(cand_x, cand_y))
1127 while (jump_to?(cand_x, cand_y))
1128 grids.push([cand_x, cand_y])
1129 break if (! put_to?(cand_x, cand_y))
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 class PieceOU < Piece
1152 def initialize(*arg)
1154 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1155 @promoted_moves = []
1157 @promoted_name = nil
1164 @sente_hands = Array::new
1165 @gote_hands = Array::new
1166 @history = Hash::new(0)
1167 @sente_history = Hash::new(0)
1168 @gote_history = Hash::new(0)
1169 @array = [[], [], [], [], [], [], [], [], [], []]
1171 @teban = nil # black => true, white => false
1173 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1174 attr_reader :move_count
1177 PieceKY::new(self, 1, 1, false)
1178 PieceKE::new(self, 2, 1, false)
1179 PieceGI::new(self, 3, 1, false)
1180 PieceKI::new(self, 4, 1, false)
1181 PieceOU::new(self, 5, 1, false)
1182 PieceKI::new(self, 6, 1, false)
1183 PieceGI::new(self, 7, 1, false)
1184 PieceKE::new(self, 8, 1, false)
1185 PieceKY::new(self, 9, 1, false)
1186 PieceKA::new(self, 2, 2, false)
1187 PieceHI::new(self, 8, 2, false)
1189 PieceFU::new(self, i, 3, false)
1192 PieceKY::new(self, 1, 9, true)
1193 PieceKE::new(self, 2, 9, true)
1194 PieceGI::new(self, 3, 9, true)
1195 PieceKI::new(self, 4, 9, true)
1196 PieceOU::new(self, 5, 9, true)
1197 PieceKI::new(self, 6, 9, true)
1198 PieceGI::new(self, 7, 9, true)
1199 PieceKE::new(self, 8, 9, true)
1200 PieceKY::new(self, 9, 9, true)
1201 PieceKA::new(self, 8, 8, true)
1202 PieceHI::new(self, 2, 8, true)
1204 PieceFU::new(self, i, 7, true)
1209 def have_piece?(hands, name)
1210 piece = hands.find { |i|
1216 def move_to(x0, y0, x1, y1, name, sente)
1218 hands = @sente_hands
1223 if ((x0 == 0) || (y0 == 0))
1224 piece = have_piece?(hands, name)
1225 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1226 piece.move_to(x1, y1)
1228 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1229 if (@array[x0][y0].name != name) # promoted ?
1230 @array[x0][y0].promoted = true
1232 if (@array[x1][y1]) # capture
1233 if (@array[x1][y1].name == "OU")
1234 return :outori # return board update
1236 @array[x1][y1].sente = @array[x0][y0].sente
1237 @array[x1][y1].move_to(0, 0)
1238 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1242 @array[x0][y0].move_to(x1, y1)
1245 @teban = @teban ? false : true
1249 def look_for_ou(sente)
1255 (@array[x][y].name == "OU") &&
1256 (@array[x][y].sente == sente))
1263 raise "can't find ou"
1266 # note checkmate, but check. sente is checked.
1267 def checkmated?(sente) # sente is loosing
1268 ou = look_for_ou(sente)
1274 (@array[x][y].sente != sente))
1275 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1286 def uchifuzume?(sente)
1287 rival_ou = look_for_ou(! sente) # rival's ou
1288 if (sente) # rival is gote
1289 if ((rival_ou.y != 9) &&
1290 (@array[rival_ou.x][rival_ou.y + 1]) &&
1291 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1292 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1294 fu_y = rival_ou.y + 1
1299 if ((rival_ou.y != 1) &&
1300 (@array[rival_ou.x][rival_ou.y - 1]) &&
1301 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1302 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1304 fu_y = rival_ou.y - 1
1310 ## case: rival_ou is moving
1311 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1312 tmp_board = Marshal.load(Marshal.dump(self))
1313 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1314 raise "internal error" if (s != true)
1315 if (! tmp_board.checkmated?(! sente)) # good move
1320 ## case: rival is capturing fu
1326 (@array[x][y].sente != sente) &&
1327 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1330 if (@array[x][y].promoted)
1331 names << @array[x][y].promoted_name
1333 names << @array[x][y].name
1334 if @array[x][y].promoted_name &&
1335 @array[x][y].move_to?(fu_x, fu_y, @array[x][y].promoted_name)
1336 names << @array[x][y].promoted_name
1339 names.map! do |name|
1340 tmp_board = Marshal.load(Marshal.dump(self))
1341 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1345 tmp_board.checkmated?(! sente) # result
1348 all_illegal = names.find {|a| a != :illegal}
1349 raise "internal error: legal move not found" if all_illegal == nil
1350 r = names.find {|a| a == false} # good move
1351 return false if r == false # found good move
1360 # @[sente|gote]_history has at least one item while the player is checking the other or
1361 # the other escapes.
1362 def update_sennichite(player)
1365 if checkmated?(!player)
1367 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
1369 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
1373 @sente_history.clear # no more continuous check
1375 @gote_history.clear # no more continuous check
1378 if @sente_history.size > 0 # possible for Sente's or Gote's turn
1379 @sente_history[str] += 1
1381 if @gote_history.size > 0 # possible for Sente's or Gote's turn
1382 @gote_history[str] += 1
1386 def oute_sennichite?(player)
1387 if (@sente_history[to_s] >= 4)
1388 return :oute_sennichite_sente_lose
1389 elsif (@gote_history[to_s] >= 4)
1390 return :oute_sennichite_gote_lose
1396 def sennichite?(sente)
1397 if (@history[to_s] >= 4) # already 3 times
1403 def good_kachi?(sente)
1404 if (checkmated?(sente))
1405 puts "'NG: Checkmating." if $DEBUG
1409 ou = look_for_ou(sente)
1410 if (sente && (ou.y >= 4))
1411 puts "'NG: Black's OU does not enter yet." if $DEBUG
1414 if (! sente && (ou.y <= 6))
1415 puts "'NG: White's OU does not enter yet." if $DEBUG
1423 hands = @sente_hands
1433 (@array[x][y].sente == sente) &&
1434 (@array[x][y].point > 0))
1435 point = point + @array[x][y].point
1441 hands.each do |piece|
1442 point = point + piece.point
1446 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1451 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1456 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1461 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1465 # sente is nil only if tests in test_board run
1466 def handle_one_move(str, sente=nil)
1467 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1474 elsif (str =~ /^%KACHI/)
1475 raise ArgumentError, "sente is null", caller if sente == nil
1476 if (good_kachi?(sente))
1481 elsif (str =~ /^%TORYO/)
1487 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1488 ((x0 != 0) || (y0 != 0)))
1490 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1495 sente = true if sente == nil # deprecated
1496 return :illegal unless sente == true # black player's move must be black
1497 hands = @sente_hands
1499 sente = false if sente == nil # deprecated
1500 return :illegal unless sente == false # white player's move must be white
1505 if ((x0 == 0) && (y0 == 0))
1506 return :illegal if (! have_piece?(hands, name))
1507 elsif (! @array[x0][y0])
1508 return :illegal # no piece
1509 elsif (@array[x0][y0].sente != sente)
1510 return :illegal # this is not mine
1511 elsif (@array[x0][y0].name != name)
1512 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1515 ## destination check
1516 if (@array[x1][y1] &&
1517 (@array[x1][y1].sente == sente)) # can't capture mine
1519 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1520 return :illegal # can't put on existing piece
1523 tmp_board = Marshal.load(Marshal.dump(self))
1524 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1525 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1526 tmp_board.update_sennichite(sente)
1527 os_result = tmp_board.oute_sennichite?(sente)
1528 return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
1529 return :sennichite if tmp_board.sennichite?(sente)
1531 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1535 move_to(x0, y0, x1, y1, name, sente)
1537 update_sennichite(sente)
1545 a.push(sprintf("P%d", y))
1548 piece = @array[x][y]
1557 a.push(sprintf("\n"))
1560 if (! sente_hands.empty?)
1562 sente_hands.each do |p|
1563 a.push("00" + p.name)
1567 if (! gote_hands.empty?)
1569 gote_hands.each do |p|
1570 a.push("00" + p.name)
1574 a.push("%s\n" % [@teban ? "+" : "-"])
1580 attr_reader :players, :black, :white
1582 def initialize(p1, p2)
1584 if p1.sente && !p2.sente
1585 @black, @white = p1, p2
1586 elsif !p1.sente && p2.sente
1587 @black, @white = p2, p1
1589 raise "Never reached!"
1594 class GameResultWin < GameResult
1595 attr_reader :winner, :loser
1597 def initialize(winner, loser)
1599 @winner, @loser = winner, loser
1600 @winner.last_game_win = true
1601 @loser.last_game_win = false
1605 black_name = @black.player_id || @black.name
1606 white_name = @white.player_id || @white.name
1607 "%s:%s" % [black_name, white_name]
1611 class GameResultDraw < GameResult
1612 def initialize(p1, p2)
1614 p1.last_game_win = false
1615 p2.last_game_win = false
1623 def initialize(game_name, player0, player1)
1624 @monitors = Array::new
1625 @game_name = game_name
1626 if (@game_name =~ /-(\d+)-(\d+)$/)
1627 @total_time = $1.to_i
1632 @sente, @gote = player0, player1
1634 @sente, @gote = player1, player0
1636 @sente.socket_buffer.clear
1637 @gote.socket_buffer.clear
1638 @current_player, @next_player = @sente, @gote
1645 @sente.status = "agree_waiting"
1646 @gote.status = "agree_waiting"
1648 @game_id = sprintf("%s+%s+%s+%s+%s",
1649 LEAGUE.event, @game_name,
1650 @sente.name, @gote.name, issue_current_time)
1653 log_dir_name = File.join(LEAGUE.dir,
1657 FileUtils.mkdir_p(log_dir_name) unless File.exist?(log_dir_name)
1658 @logfile = File.join(log_dir_name, @game_id + ".csa")
1660 LEAGUE.games[@game_id] = self
1662 log_message(sprintf("game created %s", @game_id))
1672 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors
1673 attr_accessor :last_move, :current_turn
1677 @sente.rated? && @gote.rated?
1681 return player.status == "game" && @current_player == player
1684 def monitoron(monitor)
1685 @monitors.delete(monitor)
1686 @monitors.push(monitor)
1689 def monitoroff(monitor)
1690 @monitors.delete(monitor)
1693 def reject(rejector)
1694 @sente.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
1695 @gote.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
1700 if ["agree_waiting", "start_waiting"].include?(@sente.status)
1702 elsif (@current_player == killer)
1709 log_message(sprintf("game finished %s", @game_id))
1710 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1715 @sente.status = "connected"
1716 @gote.status = "connected"
1718 if (@current_player.protocol == LoginCSA::PROTOCOL)
1719 @current_player.finish
1721 if (@next_player.protocol == LoginCSA::PROTOCOL)
1724 @monitors = Array::new
1727 @current_player = nil
1729 LEAGUE.games.delete(@game_id)
1733 def handle_one_move(str, player)
1734 unless turn?(player)
1735 return false if str == :timeout
1737 @fh.puts("'Deferred %s" % [str])
1738 log_warning("Deferred a move [%s] scince it is not %s 's turn." %
1740 player.socket_buffer << str # always in the player's thread
1745 @end_time = Time::new
1746 t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
1749 if ((@current_player.mytime - t <= -@byoyomi) &&
1750 ((@total_time > 0) || (@byoyomi > 0)))
1752 elsif (str == :timeout)
1753 return false # time isn't expired. players aren't swapped. continue game
1755 @current_player.mytime -= t
1756 if (@current_player.mytime < 0)
1757 @current_player.mytime = 0
1760 move_status = @board.handle_one_move(str, @sente == @current_player)
1762 if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
1763 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1765 if [:normal, :outori, :sennichite, :oute_sennichite_sente_lose, :oute_sennichite_gote_lose].include?(move_status)
1766 # Thinking time includes network traffic
1767 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1768 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1769 @fh.printf("%s\nT%d\n", str, t)
1770 @last_move = sprintf("%s,T%d", str, t)
1774 @monitors.each do |monitor|
1775 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@game_id}] "))
1776 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @game_id))
1781 if (@next_player.status != "game") # rival is logout or disconnected
1783 elsif (status == :timeout)
1785 elsif (move_status == :illegal)
1787 elsif (move_status == :kachi_win)
1789 elsif (move_status == :kachi_lose)
1791 elsif (move_status == :toryo)
1793 elsif (move_status == :outori)
1795 elsif (move_status == :oute_sennichite_sente_lose)
1796 oute_sennichite_win_lose(@gote, @sente) # Sente is checking
1797 elsif (move_status == :oute_sennichite_gote_lose)
1798 oute_sennichite_win_lose(@sente, @gote) # Gote is checking
1799 elsif (move_status == :sennichite)
1801 elsif (move_status == :uchifuzume)
1803 elsif (move_status == :oute_kaihimore)
1804 oute_kaihimore_lose()
1808 finish() if finish_flag
1809 @current_player, @next_player = @next_player, @current_player
1810 @start_time = Time::new
1815 @current_player.status = "connected"
1816 @next_player.status = "connected"
1817 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1818 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1819 @fh.printf("%%TORYO\n")
1820 @fh.print(@board.to_s.gsub(/^/, "\'"))
1821 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1822 @result = GameResultWin.new(@current_player, @next_player)
1823 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1824 @monitors.each do |monitor|
1825 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @game_id))
1830 @current_player.status = "connected"
1831 @next_player.status = "connected"
1832 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1833 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1834 @fh.printf("%%TORYO\n")
1835 @fh.print(@board.to_s.gsub(/^/, "\'"))
1836 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1837 @result = GameResultWin.new(@next_player, @current_player)
1838 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1839 @monitors.each do |monitor|
1840 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @game_id))
1845 @current_player.status = "connected"
1846 @next_player.status = "connected"
1847 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1848 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1849 @fh.print(@board.to_s.gsub(/^/, "\'"))
1850 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1851 @result = GameResultDraw.new(@current_player, @next_player)
1852 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1853 @monitors.each do |monitor|
1854 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @game_id))
1858 def oute_sennichite_win_lose(winner, loser)
1859 @current_player.status = "connected"
1860 @next_player.status = "connected"
1861 loser.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1862 winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1863 @fh.print(@board.to_s.gsub(/^/, "\'"))
1864 if loser == @current_player
1865 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1867 @fh.printf("'summary:oute_sennichite:%s win:%s lose\n", @current_player.name, @next_player.name)
1869 @result = GameResultWin.new(winner, loser)
1870 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1871 @monitors.each do |monitor|
1872 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @game_id))
1877 @current_player.status = "connected"
1878 @next_player.status = "connected"
1879 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1880 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1881 @fh.print(@board.to_s.gsub(/^/, "\'"))
1882 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1883 @result = GameResultWin.new(@next_player, @current_player)
1884 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1885 @monitors.each do |monitor|
1886 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @game_id))
1891 @current_player.status = "connected"
1892 @next_player.status = "connected"
1893 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1894 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1895 @fh.print(@board.to_s.gsub(/^/, "\'"))
1896 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1897 @result = GameResultWin.new(@next_player, @current_player)
1898 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1899 @monitors.each do |monitor|
1900 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @game_id))
1904 def oute_kaihimore_lose
1905 @current_player.status = "connected"
1906 @next_player.status = "connected"
1907 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1908 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1909 @fh.print(@board.to_s.gsub(/^/, "\'"))
1910 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1911 @result = GameResultWin.new(@next_player, @current_player)
1912 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1913 @monitors.each do |monitor|
1914 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @game_id))
1919 @current_player.status = "connected"
1920 @next_player.status = "connected"
1921 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1922 @next_player.write_safe("#TIME_UP\n#WIN\n")
1923 @fh.print(@board.to_s.gsub(/^/, "\'"))
1924 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1925 @result = GameResultWin.new(@next_player, @current_player)
1926 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1927 @monitors.each do |monitor|
1928 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @game_id))
1933 @current_player.status = "connected"
1934 @next_player.status = "connected"
1935 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1936 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1937 @fh.printf("%%KACHI\n")
1938 @fh.print(@board.to_s.gsub(/^/, "\'"))
1939 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1940 @result = GameResultWin.new(@current_player, @next_player)
1941 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1942 @monitors.each do |monitor|
1943 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @game_id))
1948 @current_player.status = "connected"
1949 @next_player.status = "connected"
1950 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1951 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1952 @fh.printf("%%KACHI\n")
1953 @fh.print(@board.to_s.gsub(/^/, "\'"))
1954 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1955 @result = GameResultWin.new(@next_player, @current_player)
1956 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1957 @monitors.each do |monitor|
1958 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @game_id))
1963 @current_player.status = "connected"
1964 @next_player.status = "connected"
1965 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1966 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1967 @fh.printf("%%TORYO\n")
1968 @fh.print(@board.to_s.gsub(/^/, "\'"))
1969 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1970 @result = GameResultWin.new(@next_player, @current_player)
1971 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1972 @monitors.each do |monitor|
1973 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @game_id))
1978 @current_player.status = "connected"
1979 @next_player.status = "connected"
1980 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1981 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1982 @fh.print(@board.to_s.gsub(/^/, "\'"))
1983 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1984 @result = GameResultWin.new(@current_player, @next_player)
1985 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1986 @monitors.each do |monitor|
1987 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @game_id))
1992 log_message(sprintf("game started %s", @game_id))
1993 @sente.write_safe(sprintf("START:%s\n", @game_id))
1994 @gote.write_safe(sprintf("START:%s\n", @game_id))
1995 @sente.mytime = @total_time
1996 @gote.mytime = @total_time
1997 @start_time = Time::new
2001 @fh = open(@logfile, "w")
2005 @fh.puts("N+#{@sente.name}")
2006 @fh.puts("N-#{@gote.name}")
2007 @fh.puts("$EVENT:#{@game_id}")
2009 @sente.write_safe(propose_message("+"))
2010 @gote.write_safe(propose_message("-"))
2012 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
2013 @fh.puts("$START_TIME:#{now}")
2015 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2016 P2 * -HI * * * * * -KA *
2017 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2018 P4 * * * * * * * * *
2019 P5 * * * * * * * * *
2020 P6 * * * * * * * * *
2021 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2022 P8 * +KA * * * * * +HI *
2023 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2031 Protocol_Version:1.1
2032 Protocol_Mode:Server
2034 Declaration:Jishogi 1.1
2036 Name+:#{@sente.name}
2042 Total_Time:#{@total_time}
2044 Least_Time_Per_Move:#{Least_Time_Per_Move}
2045 Remaining_Time+:#{@sente.mytime}
2046 Remaining_Time-:#{@gote.mytime}
2047 Last_Move:#{@last_move}
2048 Current_Turn:#{@current_turn}
2058 return str0 + @board.to_s + str1
2061 def propose_message(sg_flag)
2064 Protocol_Version:1.1
2065 Protocol_Mode:Server
2067 Declaration:Jishogi 1.1
2069 Name+:#{@sente.name}
2071 Your_Turn:#{sg_flag}
2076 Total_Time:#{@total_time}
2078 Least_Time_Per_Move:#{Least_Time_Per_Move}
2081 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2082 P2 * -HI * * * * * -KA *
2083 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2084 P4 * * * * * * * * *
2085 P5 * * * * * * * * *
2086 P6 * * * * * * * * *
2087 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2088 P8 * +KA * * * * * +HI *
2089 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2101 def issue_current_time
2102 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
2103 @@mutex.synchronize do
2104 while time <= @@time do
2111 end # module ShogiServer
2113 #################################################
2120 shogi-server - server for CSA server protocol
2123 shogi-server [OPTIONS] event_name port_number
2126 server for CSA server protocol
2130 specify filename for logging process ID
2132 run as a daemon. Log files will be put in dir.
2135 this file is distributed under GPL version2 and might be compiled by Exerb
2140 #{ShogiServer::Release}
2143 #{ShogiServer::Revision}
2151 def log_message(str)
2155 def log_warning(str)
2164 def parse_command_line
2166 parser = GetoptLong.new(
2167 ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2168 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT])
2171 parser.each_option do |name, arg|
2172 name.sub!(/^--/, '')
2173 options[name] = arg.dup
2177 raise parser.error_message
2182 def write_pid_file(file)
2183 open(file, "w") do |fh|
2188 def mutex_watchdog(mutex, sec)
2200 log_error("mutex watchdog timeout")
2206 def login_loop(client)
2207 player = login = nil
2209 while r = select([client], nil, nil, ShogiServer::Login_Time) do
2210 break unless str = r[0].first.gets
2211 $mutex.lock # guards LEAGUE
2215 if (ShogiServer::Login::good_login?(str))
2216 player = ShogiServer::Player::new(str, client, eol)
2217 login = ShogiServer::Login::factory(str, player)
2218 if (current_player = LEAGUE.find(player.name))
2219 if (current_player.password == player.password &&
2220 current_player.status != "game")
2221 log_message(sprintf("user %s login forcely", player.name))
2224 login.incorrect_duplicated_player(str)
2232 client.write("LOGIN:incorrect" + eol)
2233 client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2239 return [player, login]
2247 mutex_watchdog($mutex, 10)
2250 $options = parse_command_line
2251 if (ARGV.length != 2)
2256 LEAGUE.event = ARGV.shift
2259 dir = $options["daemon"]
2260 dir = File.expand_path(dir) if dir
2261 if dir && ! File.exist?(dir)
2262 FileUtils.mkdir(dir)
2264 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2265 $logger = WEBrick::Log.new(log_file) # thread safe
2267 LEAGUE.dir = dir || File.dirname(__FILE__)
2268 LEAGUE.setup_players_database
2271 config[:Port] = port
2272 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2273 config[:Logger] = $logger
2274 if $options["pid-file"]
2275 pid_file = File.expand_path($options["pid-file"])
2276 config[:StartCallback] = Proc.new do
2277 write_pid_file(pid_file)
2279 config[:StopCallback] = Proc.new do
2280 FileUtils.rm(pid_file, :force => true)
2284 server = WEBrick::GenericServer.new(config)
2285 ["INT", "TERM"].each do |signal|
2291 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2292 log_message("server started [Revision: #{ShogiServer::Revision}]")
2294 server.start do |client|
2295 # client.sync = true # this is already set in WEBrick
2296 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2297 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2298 player, login = login_loop(client) # loop
2301 log_message(sprintf("user %s login", player.name))
2303 player.run(login.csa_1st_str) # loop
2307 player.game.kill(player)
2309 player.finish # socket has been closed
2310 LEAGUE.delete(player)
2311 log_message(sprintf("user %s logout", player.name))
2322 TCPSocket.do_not_reverse_lookup = true
2323 Thread.abort_on_exception = $DEBUG ? true : false
2325 LEAGUE = ShogiServer::League::new