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
138 def load_player(player)
139 return unless player.player_id
142 @db.transaction(true) do
143 @db["players"].each do |group, players|
144 hash = players[player.player_id]
151 player.name = hash['name']
152 player.rate = hash['rate'] || 0
153 player.modified_at = hash['last_modified']
154 player.rating_group = hash['rating_group']
155 player.win = hash['win'] || 0
156 player.loss = hash['loss'] || 0
157 player.last_game_win = hash['last_game_win'] || false
161 return unless player.player_id
164 @db["players"].each do |group, players|
165 hash = players[player.player_id]
167 # write only this property.
168 # the others are updated by ./mk_rate
169 hash['last_game_win'] = player.last_game_win
178 @db.transaction(true) do
179 @db["players"].each do |group, players_hash|
180 players << players_hash.keys
183 return players.flatten.collect do |player_id|
185 p.player_id = player_id
193 @mutex = Mutex.new # guard @players
197 @dir = File.dirname(__FILE__)
198 @floodgate = Floodgate.new(self)
201 attr_accessor :players, :games, :event, :dir
204 @mutex.synchronize do
205 @players.each do |name, player|
206 @persistent.save(player)
212 # this should be called just after instanciating a League object.
213 def setup_players_database
214 filename = File.join(@dir, "players.yaml")
215 @persistent = Persistent.new(filename)
219 @persistent.load_player(player)
220 @mutex.synchronize do
221 @players[player.name] = player
226 @persistent.save(player)
227 @mutex.synchronize do
228 @players.delete(player.name)
233 @mutex.synchronize do
234 @players.each do |name, player|
235 @persistent.load_player(player)
242 @mutex.synchronize do
243 found = @players.find_all do |name, player|
247 return found.map {|a| a.last}
250 def find(player_name)
252 @mutex.synchronize do
253 found = @players[player_name]
258 def get_player(status, game_name, sente, searcher)
260 @mutex.synchronize do
261 found = @players.find do |name, player|
262 (player.status == status) &&
263 (player.game_name == game_name) &&
265 (player.sente == nil) ||
266 (player.sente == sente) ) &&
267 (player.name != searcher.name)
270 return found ? found.last : nil
274 return @persistent.get_players
279 ######################################################
280 # Processes the LOGIN command.
283 def Login.good_login?(str)
285 if (((tokens.length == 3) ||
286 ((tokens.length == 4) && tokens[3] == "x1")) &&
287 (tokens[0] == "LOGIN") &&
288 (good_identifier?(tokens[1])))
295 def Login.good_game_name?(str)
296 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
303 def Login.good_identifier?(str)
304 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
311 def Login.factory(str, player)
312 (login, player.name, password, ext) = str.chomp.split
314 return Loginx1.new(player, password)
316 return LoginCSA.new(player, password)
322 # the first command that will be executed just after LOGIN.
323 # If it is nil, the default process will be started.
324 attr_reader :csa_1st_str
326 def initialize(player, password)
329 parse_password(password)
333 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
334 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
337 def incorrect_duplicated_player(str)
338 @player.write_safe("LOGIN:incorrect\n")
339 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
340 sleep 3 # wait for sending the above messages.
341 @player.name = "%s [duplicated]" % [@player.name]
346 ######################################################
347 # Processes LOGIN for the CSA standard mode.
349 class LoginCSA < Login
352 def initialize(player, password)
355 @player.protocol = PROTOCOL
358 def parse_password(password)
359 if Login.good_game_name?(password)
361 @player.set_password(nil)
362 elsif password.split(",").size > 1
363 @gamename, *trip = password.split(",")
364 @player.set_password(trip.join(","))
366 @player.set_password(password)
367 @gamename = Default_Game_Name
369 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
374 @csa_1st_str = "%%GAME #{@gamename} *"
378 ######################################################
379 # Processes LOGIN for the extented mode.
381 class Loginx1 < Login
384 def initialize(player, password)
386 @player.protocol = PROTOCOL
389 def parse_password(password)
390 @player.set_password(password)
395 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
405 @last_game_win = false
408 # Idetifier of the player in the rating system
409 attr_accessor :player_id
414 # Password of the player, which does not include a trip
415 attr_accessor :password
417 # Score in the rating sysem
420 # Number of games for win and loss in the rating system
421 attr_accessor :win, :loss
423 # Group in the rating system
424 attr_accessor :rating_group
426 # Last timestamp when the rate was modified
427 attr_accessor :modified_at
429 # Whether win the previous game or not
430 attr_accessor :last_game_win
433 @modified_at || Time.now
439 @modified_at = Time.now
448 return @last_game_win
453 simple_name = @name.gsub(/@.*?$/, '')
454 "%s+%s" % [simple_name, @trip[0..8]]
461 # Parses str in the LOGIN command, sets up @player_id and @trip
463 def set_password(str)
464 if str && !str.empty?
465 @password = str.strip
466 @player_id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
468 @player_id = @password = nil
474 class Player < BasicPlayer
475 def initialize(str, socket, eol=nil)
478 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
480 @protocol = nil # CSA or x1
481 @eol = eol || "\m" # favorite eol code
484 @mytime = 0 # set in start method also
487 @main_thread = Thread::current
488 @mutex_write_guard = Mutex.new
491 attr_accessor :socket, :status
492 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
493 attr_accessor :main_thread
494 attr_reader :socket_buffer
497 log_message(sprintf("user %s killed", @name))
502 Thread::kill(@main_thread) if @main_thread
506 if (@status != "finished")
508 log_message(sprintf("user %s finish", @name))
510 # @socket.close if (! @socket.closed?)
512 log_message(sprintf("user %s finish failed", @name))
518 @mutex_write_guard.synchronize do
521 log_warning("%s's socket has been closed." % [@name])
524 if r = select(nil, [@socket], nil, 20)
525 r[1].first.write(str)
527 log_error("Sending a message to #{@name} timed up.")
529 rescue Exception => ex
530 log_error("Failed to send a message to #{@name}. #{ex.class}: #{ex.message}\t#{ex.backtrace[0]}")
536 if ["game_waiting", "start_waiting", "agree_waiting", "game"].include?(status)
538 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
539 elsif (@sente == false)
540 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
541 elsif (@sente == nil)
542 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
545 return sprintf("%s %s %s", @name, @protocol, @status)
549 def run(csa_1st_str=nil)
550 while ( csa_1st_str ||
551 str = gets_safe(@socket, (@socket_buffer.empty? ? Default_Timeout : 1)) )
554 if (@game && @game.turn?(self))
555 @socket_buffer << str
556 str = @socket_buffer.shift
558 log_message("%s (%s)" % [str, @socket_buffer.map {|a| String === a ? a.strip : a }.join(",")]) if $DEBUG
565 if (@status == "finished")
568 str.chomp! if (str.class == String) # may be strip! ?
571 # Application-level protocol for Keep-Alive
572 # If the server gets LF, it sends back LF.
573 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
576 if (@status == "game")
577 array_str = str.split(",")
578 move = array_str.shift
579 additional = array_str.shift
580 if /^'(.*)/ =~ additional
581 comment = array_str.unshift("'*#{$1.toeuc}")
583 s = @game.handle_one_move(move, self)
584 @game.fh.print("#{Kconv.toeuc(comment.first)}\n") if (comment && comment.first && !s)
585 return if (s && @protocol == LoginCSA::PROTOCOL)
587 when /^%[^%]/, :timeout
588 if (@status == "game")
589 s = @game.handle_one_move(str, self)
590 return if (s && @protocol == LoginCSA::PROTOCOL)
593 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
594 # rescue Exception => ex
595 # log_error("Failed to send a keepalive to #{@name}.")
596 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
601 log_error("Failed to receive a message from #{@name}.")
604 if (@status == "agree_waiting")
606 return if (@protocol == LoginCSA::PROTOCOL)
608 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
611 if (@status == "agree_waiting")
612 @status = "start_waiting"
613 if ((@game.sente.status == "start_waiting") &&
614 (@game.gote.status == "start_waiting"))
616 @game.sente.status = "game"
617 @game.gote.status = "game"
620 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
622 when /^%%SHOW\s+(\S+)/
624 if (LEAGUE.games[game_id])
625 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
627 write_safe("##[SHOW] +OK\n")
628 when /^%%MONITORON\s+(\S+)/
630 if (LEAGUE.games[game_id])
631 LEAGUE.games[game_id].monitoron(self)
632 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
633 write_safe("##[MONITOR][#{game_id}] +OK\n")
635 when /^%%MONITOROFF\s+(\S+)/
637 if (LEAGUE.games[game_id])
638 LEAGUE.games[game_id].monitoroff(self)
642 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
644 players = LEAGUE.rated_players
645 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
646 write_safe("##[RATING] %s \t %4d @%s\n" %
647 [p.simple_player_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
649 write_safe("##[RATING] +OK\n")
651 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
652 write_safe("##[VERSION] +OK\n")
654 if ((@status == "connected") || (@status == "game_waiting"))
655 @status = "connected"
658 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
660 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
664 if (! Login::good_game_name?(game_name))
665 write_safe(sprintf("##[ERROR] bad game name\n"))
667 elsif ((@status == "connected") || (@status == "game_waiting"))
670 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
675 if (League::Floodgate.game_name?(game_name))
676 if (my_sente_str != "*")
677 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", my_sente_str, game_name))
682 if (my_sente_str == "*")
683 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
684 elsif (my_sente_str == "+")
685 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
686 elsif (my_sente_str == "-")
687 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
690 write_safe(sprintf("##[ERROR] bad game option\n"))
696 @game_name = game_name
697 if ((my_sente_str == "*") && (rival.sente == nil))
705 elsif (rival.sente == true) # rival has higher priority
707 elsif (rival.sente == false)
709 elsif (my_sente_str == "+")
712 elsif (my_sente_str == "-")
718 Game::new(@game_name, self, rival)
719 else # rival not found
720 if (command_name == "GAME")
721 @status = "game_waiting"
722 @game_name = game_name
723 if (my_sente_str == "+")
725 elsif (my_sente_str == "-")
731 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
732 @status = "connected"
737 when /^%%CHAT\s+(.+)/
739 LEAGUE.players.each do |name, player|
740 if (player.protocol != LoginCSA::PROTOCOL)
741 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
746 LEAGUE.games.each do |id, game|
747 buf.push(sprintf("##[LIST] %s\n", id))
749 buf.push("##[LIST] +OK\n")
753 LEAGUE.players.each do |name, player|
754 buf.push(sprintf("##[WHO] %s\n", player.to_s))
756 buf.push("##[WHO] +OK\n")
759 @status = "connected"
760 write_safe("LOGOUT:completed\n")
763 # This command is only available for CSA's official testing server.
764 # So, this means nothing for this program.
765 write_safe("CHALLENGE ACCEPTED\n")
767 ## ignore null string
769 msg = "##[ERROR] unknown command %s\n" % [str]
781 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK",
782 "GI" => "NG", "KA" => "UM", "HI" => "RY"}
783 def initialize(board, x, y, sente, promoted=false)
790 if ((x == 0) || (y == 0))
792 hands = board.sente_hands
794 hands = board.gote_hands
801 @board.array[x][y] = self
804 attr_accessor :promoted, :sente, :x, :y, :board
806 def room_of_head?(x, y, name)
811 return adjacent_movable_grids + far_movable_grids
814 def far_movable_grids
819 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
820 if ((@board.array[x][y] == nil) || # dst is empty
821 (@board.array[x][y].sente != @sente)) # dst is enemy
829 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
830 if (@board.array[x][y] == nil) # dst is empty?
837 def adjacent_movable_grids
840 moves = @promoted_moves
842 moves = @normal_moves
844 moves.each do |(dx, dy)|
851 if (jump_to?(cand_x, cand_y))
852 grids.push([cand_x, cand_y])
858 def move_to?(x, y, name)
859 return false if (! room_of_head?(x, y, name))
860 return false if ((name != @name) && (name != @promoted_name))
861 return false if (@promoted && (name != @promoted_name)) # can't un-promote
864 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
866 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
868 return false if ((6 >= @y) && (6 >= y) && (name != @name))
872 if ((@x == 0) || (@y == 0))
873 return jump_to?(x, y)
875 return movable_grids.include?([x, y])
880 if ((@x == 0) || (@y == 0))
882 @board.sente_hands.delete(self)
884 @board.gote_hands.delete(self)
886 @board.array[x][y] = self
887 elsif ((x == 0) || (y == 0))
888 @promoted = false # clear promoted flag before moving to hands
890 @board.sente_hands.push(self)
892 @board.gote_hands.push(self)
894 @board.array[@x][@y] = nil
896 @board.array[@x][@y] = nil
897 @board.array[x][y] = self
930 class PieceFU < Piece
933 @normal_moves = [[0, +1]]
934 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
936 @promoted_name = "TO"
939 def room_of_head?(x, y, name)
942 return false if (y == 1)
944 return false if (y == 9)
950 if ((iy != @y) && # not source position
951 @board.array[x][iy] &&
952 (@board.array[x][iy].sente == @sente) && # mine
953 (@board.array[x][iy].name == "FU") &&
954 (@board.array[x][iy].promoted == false))
964 class PieceKY < Piece
968 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
970 @promoted_name = "NY"
973 def room_of_head?(x, y, name)
976 return false if (y == 1)
978 return false if (y == 9)
983 def far_movable_grids
991 while (jump_to?(cand_x, cand_y))
992 grids.push([cand_x, cand_y])
993 break if (! put_to?(cand_x, cand_y))
999 while (jump_to?(cand_x, cand_y))
1000 grids.push([cand_x, cand_y])
1001 break if (! put_to?(cand_x, cand_y))
1009 class PieceKE < Piece
1010 def initialize(*arg)
1012 @normal_moves = [[+1, +2], [-1, +2]]
1013 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1015 @promoted_name = "NK"
1018 def room_of_head?(x, y, name)
1021 return false if ((y == 1) || (y == 2))
1023 return false if ((y == 9) || (y == 8))
1029 class PieceGI < Piece
1030 def initialize(*arg)
1032 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1033 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1035 @promoted_name = "NG"
1039 class PieceKI < Piece
1040 def initialize(*arg)
1042 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1043 @promoted_moves = []
1045 @promoted_name = nil
1049 class PieceKA < Piece
1050 def initialize(*arg)
1053 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
1055 @promoted_name = "UM"
1058 def far_movable_grids
1063 while (jump_to?(cand_x, cand_y))
1064 grids.push([cand_x, cand_y])
1065 break if (! put_to?(cand_x, cand_y))
1072 while (jump_to?(cand_x, cand_y))
1073 grids.push([cand_x, cand_y])
1074 break if (! put_to?(cand_x, cand_y))
1081 while (jump_to?(cand_x, cand_y))
1082 grids.push([cand_x, cand_y])
1083 break if (! put_to?(cand_x, cand_y))
1090 while (jump_to?(cand_x, cand_y))
1091 grids.push([cand_x, cand_y])
1092 break if (! put_to?(cand_x, cand_y))
1099 class PieceHI < Piece
1100 def initialize(*arg)
1103 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1105 @promoted_name = "RY"
1108 def far_movable_grids
1113 while (jump_to?(cand_x, cand_y))
1114 grids.push([cand_x, cand_y])
1115 break if (! put_to?(cand_x, cand_y))
1121 while (jump_to?(cand_x, cand_y))
1122 grids.push([cand_x, cand_y])
1123 break if (! put_to?(cand_x, cand_y))
1129 while (jump_to?(cand_x, cand_y))
1130 grids.push([cand_x, cand_y])
1131 break if (! put_to?(cand_x, cand_y))
1137 while (jump_to?(cand_x, cand_y))
1138 grids.push([cand_x, cand_y])
1139 break if (! put_to?(cand_x, cand_y))
1145 class PieceOU < Piece
1146 def initialize(*arg)
1148 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1149 @promoted_moves = []
1151 @promoted_name = nil
1158 @sente_hands = Array::new
1159 @gote_hands = Array::new
1160 @history = Hash::new(0)
1161 @sente_history = Hash::new(0)
1162 @gote_history = Hash::new(0)
1163 @array = [[], [], [], [], [], [], [], [], [], []]
1165 @teban = nil # black => true, white => false
1167 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1168 attr_reader :move_count
1171 PieceKY::new(self, 1, 1, false)
1172 PieceKE::new(self, 2, 1, false)
1173 PieceGI::new(self, 3, 1, false)
1174 PieceKI::new(self, 4, 1, false)
1175 PieceOU::new(self, 5, 1, false)
1176 PieceKI::new(self, 6, 1, false)
1177 PieceGI::new(self, 7, 1, false)
1178 PieceKE::new(self, 8, 1, false)
1179 PieceKY::new(self, 9, 1, false)
1180 PieceKA::new(self, 2, 2, false)
1181 PieceHI::new(self, 8, 2, false)
1183 PieceFU::new(self, i, 3, false)
1186 PieceKY::new(self, 1, 9, true)
1187 PieceKE::new(self, 2, 9, true)
1188 PieceGI::new(self, 3, 9, true)
1189 PieceKI::new(self, 4, 9, true)
1190 PieceOU::new(self, 5, 9, true)
1191 PieceKI::new(self, 6, 9, true)
1192 PieceGI::new(self, 7, 9, true)
1193 PieceKE::new(self, 8, 9, true)
1194 PieceKY::new(self, 9, 9, true)
1195 PieceKA::new(self, 8, 8, true)
1196 PieceHI::new(self, 2, 8, true)
1198 PieceFU::new(self, i, 7, true)
1203 def have_piece?(hands, name)
1204 piece = hands.find { |i|
1210 def move_to(x0, y0, x1, y1, name, sente)
1212 hands = @sente_hands
1217 if ((x0 == 0) || (y0 == 0))
1218 piece = have_piece?(hands, name)
1219 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1220 piece.move_to(x1, y1)
1222 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1223 if (@array[x0][y0].name != name) # promoted ?
1224 @array[x0][y0].promoted = true
1226 if (@array[x1][y1]) # capture
1227 if (@array[x1][y1].name == "OU")
1228 return :outori # return board update
1230 @array[x1][y1].sente = @array[x0][y0].sente
1231 @array[x1][y1].move_to(0, 0)
1232 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1236 @array[x0][y0].move_to(x1, y1)
1239 @teban = @teban ? false : true
1243 def look_for_ou(sente)
1249 (@array[x][y].name == "OU") &&
1250 (@array[x][y].sente == sente))
1257 raise "can't find ou"
1260 # note checkmate, but check. sente is checked.
1261 def checkmated?(sente) # sente is loosing
1262 ou = look_for_ou(sente)
1268 (@array[x][y].sente != sente))
1269 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1280 def uchifuzume?(sente)
1281 rival_ou = look_for_ou(! sente) # rival's ou
1282 if (sente) # rival is gote
1283 if ((rival_ou.y != 9) &&
1284 (@array[rival_ou.x][rival_ou.y + 1]) &&
1285 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1286 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1288 fu_y = rival_ou.y + 1
1293 if ((rival_ou.y != 1) &&
1294 (@array[rival_ou.x][rival_ou.y - 1]) &&
1295 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1296 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1298 fu_y = rival_ou.y - 1
1304 ## case: rival_ou is moving
1305 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1306 tmp_board = Marshal.load(Marshal.dump(self))
1307 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1308 raise "internal error" if (s != true)
1309 if (! tmp_board.checkmated?(! sente)) # good move
1314 ## case: rival is capturing fu
1320 (@array[x][y].sente != sente) &&
1321 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1324 if (@array[x][y].promoted)
1325 names << @array[x][y].promoted_name
1327 names << @array[x][y].name
1328 if @array[x][y].promoted_name &&
1329 @array[x][y].move_to?(fu_x, fu_y, @array[x][y].promoted_name)
1330 names << @array[x][y].promoted_name
1333 names.map! do |name|
1334 tmp_board = Marshal.load(Marshal.dump(self))
1335 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1339 tmp_board.checkmated?(! sente) # result
1342 all_illegal = names.find {|a| a != :illegal}
1343 raise "internal error: legal move not found" if all_illegal == nil
1344 r = names.find {|a| a == false} # good move
1345 return false if r == false # found good move
1354 # @[sente|gote]_history has at least one item while the player is checking the other or
1355 # the other escapes.
1356 def update_sennichite(player)
1359 if checkmated?(!player)
1361 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
1363 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
1367 @sente_history.clear # no more continuous check
1369 @gote_history.clear # no more continuous check
1372 if @sente_history.size > 0 # possible for Sente's or Gote's turn
1373 @sente_history[str] += 1
1375 if @gote_history.size > 0 # possible for Sente's or Gote's turn
1376 @gote_history[str] += 1
1380 def oute_sennichite?(player)
1381 if (@sente_history[to_s] >= 4)
1382 return :oute_sennichite_sente_lose
1383 elsif (@gote_history[to_s] >= 4)
1384 return :oute_sennichite_gote_lose
1390 def sennichite?(sente)
1391 if (@history[to_s] >= 4) # already 3 times
1397 def good_kachi?(sente)
1398 if (checkmated?(sente))
1399 puts "'NG: Checkmating." if $DEBUG
1403 ou = look_for_ou(sente)
1404 if (sente && (ou.y >= 4))
1405 puts "'NG: Black's OU does not enter yet." if $DEBUG
1408 if (! sente && (ou.y <= 6))
1409 puts "'NG: White's OU does not enter yet." if $DEBUG
1417 hands = @sente_hands
1427 (@array[x][y].sente == sente) &&
1428 (@array[x][y].point > 0))
1429 point = point + @array[x][y].point
1435 hands.each do |piece|
1436 point = point + piece.point
1440 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1445 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1450 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1455 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1459 # sente is nil only if tests in test_board run
1460 def handle_one_move(str, sente=nil)
1461 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1468 elsif (str =~ /^%KACHI/)
1469 raise ArgumentError, "sente is null", caller if sente == nil
1470 if (good_kachi?(sente))
1475 elsif (str =~ /^%TORYO/)
1481 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1482 ((x0 != 0) || (y0 != 0)))
1484 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1489 sente = true if sente == nil # deprecated
1490 return :illegal unless sente == true # black player's move must be black
1491 hands = @sente_hands
1493 sente = false if sente == nil # deprecated
1494 return :illegal unless sente == false # white player's move must be white
1499 if ((x0 == 0) && (y0 == 0))
1500 return :illegal if (! have_piece?(hands, name))
1501 elsif (! @array[x0][y0])
1502 return :illegal # no piece
1503 elsif (@array[x0][y0].sente != sente)
1504 return :illegal # this is not mine
1505 elsif (@array[x0][y0].name != name)
1506 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1509 ## destination check
1510 if (@array[x1][y1] &&
1511 (@array[x1][y1].sente == sente)) # can't capture mine
1513 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1514 return :illegal # can't put on existing piece
1517 tmp_board = Marshal.load(Marshal.dump(self))
1518 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1519 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1520 tmp_board.update_sennichite(sente)
1521 os_result = tmp_board.oute_sennichite?(sente)
1522 return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
1523 return :sennichite if tmp_board.sennichite?(sente)
1525 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1529 move_to(x0, y0, x1, y1, name, sente)
1531 update_sennichite(sente)
1539 a.push(sprintf("P%d", y))
1542 piece = @array[x][y]
1551 a.push(sprintf("\n"))
1554 if (! sente_hands.empty?)
1556 sente_hands.each do |p|
1557 a.push("00" + p.name)
1561 if (! gote_hands.empty?)
1563 gote_hands.each do |p|
1564 a.push("00" + p.name)
1568 a.push("%s\n" % [@teban ? "+" : "-"])
1574 attr_reader :players, :black, :white
1576 def initialize(p1, p2)
1578 if p1.sente && !p2.sente
1579 @black, @white = p1, p2
1580 elsif !p1.sente && p2.sente
1581 @black, @white = p2, p1
1583 raise "Never reached!"
1588 class GameResultWin < GameResult
1589 attr_reader :winner, :loser
1591 def initialize(winner, loser)
1593 @winner, @loser = winner, loser
1594 @winner.last_game_win = true
1595 @loser.last_game_win = false
1599 black_name = @black.player_id || @black.name
1600 white_name = @white.player_id || @white.name
1601 "%s:%s" % [black_name, white_name]
1605 class GameResultDraw < GameResult
1606 def initialize(p1, p2)
1608 p1.last_game_win = false
1609 p2.last_game_win = false
1617 def initialize(game_name, player0, player1)
1618 @monitors = Array::new
1619 @game_name = game_name
1620 if (@game_name =~ /-(\d+)-(\d+)$/)
1621 @total_time = $1.to_i
1626 @sente, @gote = player0, player1
1628 @sente, @gote = player1, player0
1630 @sente.socket_buffer.clear
1631 @gote.socket_buffer.clear
1632 @current_player, @next_player = @sente, @gote
1639 @sente.status = "agree_waiting"
1640 @gote.status = "agree_waiting"
1642 @game_id = sprintf("%s+%s+%s+%s+%s",
1643 LEAGUE.event, @game_name,
1644 @sente.name, @gote.name, issue_current_time)
1647 log_dir_name = File.join(LEAGUE.dir,
1651 FileUtils.mkdir_p(log_dir_name) unless File.exist?(log_dir_name)
1652 @logfile = File.join(log_dir_name, @game_id + ".csa")
1654 LEAGUE.games[@game_id] = self
1656 log_message(sprintf("game created %s", @game_id))
1666 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors
1667 attr_accessor :last_move, :current_turn
1671 @sente.rated? && @gote.rated?
1675 return player.status == "game" && @current_player == player
1678 def monitoron(monitor)
1679 @monitors.delete(monitor)
1680 @monitors.push(monitor)
1683 def monitoroff(monitor)
1684 @monitors.delete(monitor)
1687 def reject(rejector)
1688 @sente.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
1689 @gote.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
1694 if ["agree_waiting", "start_waiting"].include?(@sente.status)
1696 elsif (@current_player == killer)
1703 log_message(sprintf("game finished %s", @game_id))
1704 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1709 @sente.status = "connected"
1710 @gote.status = "connected"
1712 if (@current_player.protocol == LoginCSA::PROTOCOL)
1713 @current_player.finish
1715 if (@next_player.protocol == LoginCSA::PROTOCOL)
1718 @monitors = Array::new
1721 @current_player = nil
1723 LEAGUE.games.delete(@game_id)
1727 def handle_one_move(str, player)
1728 unless turn?(player)
1729 return false if str == :timeout
1731 @fh.puts("'Deferred %s" % [str])
1732 log_warning("Deferred a move [%s] scince it is not %s 's turn." %
1734 player.socket_buffer << str # always in the player's thread
1739 @end_time = Time::new
1740 t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
1743 if ((@current_player.mytime - t <= -@byoyomi) &&
1744 ((@total_time > 0) || (@byoyomi > 0)))
1746 elsif (str == :timeout)
1747 return false # time isn't expired. players aren't swapped. continue game
1749 @current_player.mytime -= t
1750 if (@current_player.mytime < 0)
1751 @current_player.mytime = 0
1754 move_status = @board.handle_one_move(str, @sente == @current_player)
1756 if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
1757 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1759 if [:normal, :outori, :sennichite, :oute_sennichite_sente_lose, :oute_sennichite_gote_lose].include?(move_status)
1760 # Thinking time includes network traffic
1761 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1762 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1763 @fh.printf("%s\nT%d\n", str, t)
1764 @last_move = sprintf("%s,T%d", str, t)
1768 @monitors.each do |monitor|
1769 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@game_id}] "))
1770 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @game_id))
1775 if (@next_player.status != "game") # rival is logout or disconnected
1777 elsif (status == :timeout)
1779 elsif (move_status == :illegal)
1781 elsif (move_status == :kachi_win)
1783 elsif (move_status == :kachi_lose)
1785 elsif (move_status == :toryo)
1787 elsif (move_status == :outori)
1789 elsif (move_status == :oute_sennichite_sente_lose)
1790 oute_sennichite_win_lose(@gote, @sente) # Sente is checking
1791 elsif (move_status == :oute_sennichite_gote_lose)
1792 oute_sennichite_win_lose(@sente, @gote) # Gote is checking
1793 elsif (move_status == :sennichite)
1795 elsif (move_status == :uchifuzume)
1797 elsif (move_status == :oute_kaihimore)
1798 oute_kaihimore_lose()
1802 finish() if finish_flag
1803 @current_player, @next_player = @next_player, @current_player
1804 @start_time = Time::new
1809 @current_player.status = "connected"
1810 @next_player.status = "connected"
1811 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1812 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1813 @fh.printf("%%TORYO\n")
1814 @fh.print(@board.to_s.gsub(/^/, "\'"))
1815 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1816 @result = GameResultWin.new(@current_player, @next_player)
1817 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1818 @monitors.each do |monitor|
1819 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @game_id))
1824 @current_player.status = "connected"
1825 @next_player.status = "connected"
1826 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1827 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1828 @fh.printf("%%TORYO\n")
1829 @fh.print(@board.to_s.gsub(/^/, "\'"))
1830 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1831 @result = GameResultWin.new(@next_player, @current_player)
1832 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1833 @monitors.each do |monitor|
1834 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @game_id))
1839 @current_player.status = "connected"
1840 @next_player.status = "connected"
1841 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1842 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1843 @fh.print(@board.to_s.gsub(/^/, "\'"))
1844 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1845 @result = GameResultDraw.new(@current_player, @next_player)
1846 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1847 @monitors.each do |monitor|
1848 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @game_id))
1852 def oute_sennichite_win_lose(winner, loser)
1853 @current_player.status = "connected"
1854 @next_player.status = "connected"
1855 loser.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1856 winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1857 @fh.print(@board.to_s.gsub(/^/, "\'"))
1858 if loser == @current_player
1859 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1861 @fh.printf("'summary:oute_sennichite:%s win:%s lose\n", @current_player.name, @next_player.name)
1863 @result = GameResultWin.new(winner, loser)
1864 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1865 @monitors.each do |monitor|
1866 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @game_id))
1871 @current_player.status = "connected"
1872 @next_player.status = "connected"
1873 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1874 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1875 @fh.print(@board.to_s.gsub(/^/, "\'"))
1876 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1877 @result = GameResultWin.new(@next_player, @current_player)
1878 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1879 @monitors.each do |monitor|
1880 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @game_id))
1885 @current_player.status = "connected"
1886 @next_player.status = "connected"
1887 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1888 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1889 @fh.print(@board.to_s.gsub(/^/, "\'"))
1890 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1891 @result = GameResultWin.new(@next_player, @current_player)
1892 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1893 @monitors.each do |monitor|
1894 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @game_id))
1898 def oute_kaihimore_lose
1899 @current_player.status = "connected"
1900 @next_player.status = "connected"
1901 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1902 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1903 @fh.print(@board.to_s.gsub(/^/, "\'"))
1904 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1905 @result = GameResultWin.new(@next_player, @current_player)
1906 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1907 @monitors.each do |monitor|
1908 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @game_id))
1913 @current_player.status = "connected"
1914 @next_player.status = "connected"
1915 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1916 @next_player.write_safe("#TIME_UP\n#WIN\n")
1917 @fh.print(@board.to_s.gsub(/^/, "\'"))
1918 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1919 @result = GameResultWin.new(@next_player, @current_player)
1920 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1921 @monitors.each do |monitor|
1922 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @game_id))
1927 @current_player.status = "connected"
1928 @next_player.status = "connected"
1929 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1930 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1931 @fh.printf("%%KACHI\n")
1932 @fh.print(@board.to_s.gsub(/^/, "\'"))
1933 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1934 @result = GameResultWin.new(@current_player, @next_player)
1935 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1936 @monitors.each do |monitor|
1937 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @game_id))
1942 @current_player.status = "connected"
1943 @next_player.status = "connected"
1944 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1945 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1946 @fh.printf("%%KACHI\n")
1947 @fh.print(@board.to_s.gsub(/^/, "\'"))
1948 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1949 @result = GameResultWin.new(@next_player, @current_player)
1950 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1951 @monitors.each do |monitor|
1952 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @game_id))
1957 @current_player.status = "connected"
1958 @next_player.status = "connected"
1959 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1960 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1961 @fh.printf("%%TORYO\n")
1962 @fh.print(@board.to_s.gsub(/^/, "\'"))
1963 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1964 @result = GameResultWin.new(@next_player, @current_player)
1965 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1966 @monitors.each do |monitor|
1967 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @game_id))
1972 @current_player.status = "connected"
1973 @next_player.status = "connected"
1974 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1975 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1976 @fh.print(@board.to_s.gsub(/^/, "\'"))
1977 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1978 @result = GameResultWin.new(@current_player, @next_player)
1979 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1980 @monitors.each do |monitor|
1981 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @game_id))
1986 log_message(sprintf("game started %s", @game_id))
1987 @sente.write_safe(sprintf("START:%s\n", @game_id))
1988 @gote.write_safe(sprintf("START:%s\n", @game_id))
1989 @sente.mytime = @total_time
1990 @gote.mytime = @total_time
1991 @start_time = Time::new
1995 @fh = open(@logfile, "w")
1999 @fh.puts("N+#{@sente.name}")
2000 @fh.puts("N-#{@gote.name}")
2001 @fh.puts("$EVENT:#{@game_id}")
2003 @sente.write_safe(propose_message("+"))
2004 @gote.write_safe(propose_message("-"))
2006 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
2007 @fh.puts("$START_TIME:#{now}")
2009 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2010 P2 * -HI * * * * * -KA *
2011 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2012 P4 * * * * * * * * *
2013 P5 * * * * * * * * *
2014 P6 * * * * * * * * *
2015 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2016 P8 * +KA * * * * * +HI *
2017 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2025 Protocol_Version:1.1
2026 Protocol_Mode:Server
2028 Declaration:Jishogi 1.1
2030 Name+:#{@sente.name}
2036 Total_Time:#{@total_time}
2038 Least_Time_Per_Move:#{Least_Time_Per_Move}
2039 Remaining_Time+:#{@sente.mytime}
2040 Remaining_Time-:#{@gote.mytime}
2041 Last_Move:#{@last_move}
2042 Current_Turn:#{@current_turn}
2052 return str0 + @board.to_s + str1
2055 def propose_message(sg_flag)
2058 Protocol_Version:1.1
2059 Protocol_Mode:Server
2061 Declaration:Jishogi 1.1
2063 Name+:#{@sente.name}
2065 Your_Turn:#{sg_flag}
2070 Total_Time:#{@total_time}
2072 Least_Time_Per_Move:#{Least_Time_Per_Move}
2075 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2076 P2 * -HI * * * * * -KA *
2077 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2078 P4 * * * * * * * * *
2079 P5 * * * * * * * * *
2080 P6 * * * * * * * * *
2081 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2082 P8 * +KA * * * * * +HI *
2083 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2095 def issue_current_time
2096 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
2097 @@mutex.synchronize do
2098 while time <= @@time do
2105 end # module ShogiServer
2107 #################################################
2114 shogi-server - server for CSA server protocol
2117 shogi-server [OPTIONS] event_name port_number
2120 server for CSA server protocol
2124 specify filename for logging process ID
2126 run as a daemon. Log files will be put in dir.
2129 this file is distributed under GPL version2 and might be compiled by Exerb
2134 #{ShogiServer::Release}
2137 #{ShogiServer::Revision}
2145 def log_message(str)
2149 def log_warning(str)
2158 def parse_command_line
2160 parser = GetoptLong.new(
2161 ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2162 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT])
2165 parser.each_option do |name, arg|
2166 name.sub!(/^--/, '')
2167 options[name] = arg.dup
2171 raise parser.error_message
2176 def write_pid_file(file)
2177 open(file, "w") do |fh|
2182 def mutex_watchdog(mutex, sec)
2194 log_error("mutex watchdog timeout")
2200 def login_loop(client)
2201 player = login = nil
2203 while r = select([client], nil, nil, ShogiServer::Login_Time) do
2204 break unless str = r[0].first.gets
2205 $mutex.lock # guards LEAGUE
2209 if (ShogiServer::Login::good_login?(str))
2210 player = ShogiServer::Player::new(str, client, eol)
2211 login = ShogiServer::Login::factory(str, player)
2212 if (current_player = LEAGUE.find(player.name))
2213 if (current_player.password == player.password &&
2214 current_player.status != "game")
2215 log_message(sprintf("user %s login forcely", player.name))
2218 login.incorrect_duplicated_player(str)
2226 client.write("LOGIN:incorrect" + eol)
2227 client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2233 return [player, login]
2241 mutex_watchdog($mutex, 10)
2244 $options = parse_command_line
2245 if (ARGV.length != 2)
2250 LEAGUE.event = ARGV.shift
2253 dir = $options["daemon"]
2254 dir = File.expand_path(dir) if dir
2255 if dir && ! File.exist?(dir)
2256 FileUtils.mkdir(dir)
2258 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2259 $logger = WEBrick::Log.new(log_file) # thread safe
2261 LEAGUE.dir = dir || File.dirname(__FILE__)
2262 LEAGUE.setup_players_database
2265 config[:Port] = port
2266 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2267 config[:Logger] = $logger
2268 if $options["pid-file"]
2269 pid_file = File.expand_path($options["pid-file"])
2270 config[:StartCallback] = Proc.new do
2271 write_pid_file(pid_file)
2273 config[:StopCallback] = Proc.new do
2274 FileUtils.rm(pid_file, :force => true)
2278 server = WEBrick::GenericServer.new(config)
2279 ["INT", "TERM"].each do |signal|
2285 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2286 log_message("server started [Revision: #{ShogiServer::Revision}]")
2288 server.start do |client|
2289 # client.sync = true # this is already set in WEBrick
2290 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2291 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2292 player, login = login_loop(client) # loop
2295 log_message(sprintf("user %s login", player.name))
2297 player.run(login.csa_1st_str) # loop
2301 player.game.kill(player)
2303 player.finish # socket has been closed
2304 LEAGUE.delete(player)
2305 log_message(sprintf("user %s logout", player.name))
2316 TCPSocket.do_not_reverse_lookup = true
2317 Thread.abort_on_exception = $DEBUG ? true : false
2319 LEAGUE = ShogiServer::League::new