4 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
5 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ## GNU General Public License for more details.
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, write to the Free Software
19 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33 def gets_timeout(t = Default_Timeout)
44 def gets_safe(t = nil)
52 rescue Exception => ex
53 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
66 return self.write(str)
74 module ShogiServer # for a namespace
76 Max_Write_Queue_Size = 1000
77 Max_Identifier_Length = 32
78 Default_Timeout = 60 # for single socket operation
80 Default_Game_Name = "default-1500-0"
83 Least_Time_Per_Move = 1
84 Login_Time = 300 # time for LOGIN
86 Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
87 Release.concat("-") if (Release == "")
88 Revision = "$Revision$".gsub(/[^\.\d]/, '')
95 log_message("Floodgate: too few players [%d]" % [players.size])
97 log_message("Floodgate: found %d players. Making games..." % [players.size])
101 def start_game(p1, p2)
104 Game.new(p1.game_name, p1, p2)
107 def delete_most_playing_player(players)
108 max_player = players.max {|a,b| a.win + a.loss <=> b.win + b.loss}
109 return players.delete(max_player)
112 def delete_least_rate_player(players)
113 min_player = players.min {|a,b| a.rate <=> b.rate}
114 return players.delete(min_player)
117 def pairing_and_start_game(players)
118 return if players.size < 2
119 if players.size % 2 == 1
120 log_warning("#Players should be even: %d" % [players.size])
123 sorted = players.sort{ rand < 0.5 ? 1 : -1 }
125 pairs = [[sorted.shift]]
126 while !sorted.empty? do
127 if pairs.last.size < 2
128 pairs.last << sorted.shift
130 pairs << [sorted.shift]
134 start_game(pair.first, pair.last)
139 class RandomPairing < Pairing
142 return if players.size < 2
144 if players.size % 2 == 1
145 delete_most_playing_player(players)
147 pairing_and_start_game(players)
151 class SwissPairing < Pairing
154 return if players.size < 2
156 win_players = players.find_all {|a| a.last_game_win?}
157 remains = players - win_players
158 if win_players.size >= 2
159 if win_players.size % 2 == 1
160 remains << delete_least_rate_player(win_players)
162 pairing_and_start_game(win_players)
164 remains.concat(win_players)
166 return if remains.size < 2
167 if remains.size % 2 == 1
168 delete_most_playing_player(remains)
170 pairing_and_start_game(remains)
177 return /^floodgate-\d+-\d+$/.match(str) ? true : false
181 def initialize(league)
184 @pairing = SwissPairing.new
189 @thread = Thread.new do
194 next if Time.now < @next_time
198 rescue Exception => ex
200 log_error("[in Floodgate's thread] #{ex}")
207 @thread.kill if @thread
215 @next_time = Time.mktime(now.year, now.month, now.day, now.hour, 30)
217 @next_time = Time.mktime(now.year, now.month, now.day, now.hour) + 3600
221 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min, 30)
223 # @next_time = Time.mktime(now.year, now.month, now.day, now.hour, now.min) + 60
228 players = @league.find_all_players do |pl|
229 pl.status == "game_waiting" &&
230 Floodgate.game_name?(pl.game_name) &&
233 @pairing.match(players)
235 end # class Floodgate
238 @mutex = Mutex.new # guard @players
242 @dir = File.dirname(__FILE__)
243 @floodgate = Floodgate.new(self)
246 attr_accessor :players, :games, :event, :dir
249 @mutex.synchronize do
250 @players.each {|a| save(a)}
255 # this should be called just after instanciating a League object.
256 def setup_players_database
257 @db = YAML::Store.new(File.join(@dir, "players.yaml"))
261 self.load(player) if player.id
262 @mutex.synchronize do
263 @players[player.name] = player
268 @mutex.synchronize do
270 @players.delete(player.name)
275 @mutex.synchronize do
276 @players.each {|player| load(player)}
282 @mutex.synchronize do
283 found = @players.find_all do |name, player|
287 return found.map {|a| a.last}
290 def get_player(status, game_name, sente, searcher)
292 @mutex.synchronize do
293 found = @players.find do |name, player|
294 (player.status == status) &&
295 (player.game_name == game_name) &&
297 (player.sente == nil) ||
298 (player.sente == sente) ) &&
299 (player.name != searcher.name)
302 return found ? found.last : nil
306 hash = search(player.id)
310 player.name = hash['name']
311 player.rate = hash['rate'] || 0
312 player.modified_at = hash['last_modified']
313 player.rating_group = hash['rating_group']
314 player.win = hash['win'] || 0
315 player.loss = hash['loss'] || 0
316 player.last_game_win = hash['last_game_win'] || false
321 break unless @db["players"]
322 @db["players"].each do |group, players|
323 hash = players[player.id]
325 hash['last_game_win'] = player.last_game_win
334 @db.transaction(true) do
335 break unless @db["players"]
336 @db["players"].each do |group, players|
346 @db.transaction(true) do
347 break unless @db["players"]
348 @db["players"].each do |group, players_hash|
349 players << players_hash.keys
352 return players.flatten.collect do |id|
362 ######################################################
363 # Processes the LOGIN command.
366 def Login.good_login?(str)
368 if (((tokens.length == 3) || ((tokens.length == 4) && tokens[3] == "x1")) &&
369 (tokens[0] == "LOGIN") &&
370 (good_identifier?(tokens[1])))
377 def Login.good_game_name?(str)
378 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
385 def Login.good_identifier?(str)
386 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
393 def Login.factory(str, player)
394 (login, player.name, password, ext) = str.chomp.split
396 return Loginx1.new(player, password)
398 return LoginCSA.new(player, password)
404 # the first command that will be executed just after LOGIN.
405 # If it is nil, the default process will be started.
406 attr_reader :csa_1st_str
408 def initialize(player, password)
411 parse_password(password)
415 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
416 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
419 def incorrect_duplicated_player(str)
420 @player.write_safe("LOGIN:incorrect\n")
421 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
422 sleep 3 # wait for sending the above messages.
423 @player.name = "%s [duplicated]" % [@player.name]
428 ######################################################
429 # Processes LOGIN for the CSA standard mode.
431 class LoginCSA < Login
434 def initialize(player, password)
437 @player.protocol = PROTOCOL
440 def parse_password(password)
441 if Login.good_game_name?(password)
443 @player.set_password(nil)
444 elsif password.split(",").size > 1
445 @gamename, *trip = password.split(",")
446 @player.set_password(trip.join(","))
448 @player.set_password(password)
449 @gamename = Default_Game_Name
451 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
456 @csa_1st_str = "%%GAME #{@gamename} *"
460 ######################################################
461 # Processes LOGIN for the extented mode.
463 class Loginx1 < Login
466 def initialize(player, password)
468 @player.protocol = PROTOCOL
471 def parse_password(password)
472 @player.set_password(password)
477 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
487 @last_game_win = false
490 # Idetifier of the player in the rating system
496 # Password of the player, which does not include a trip
497 attr_accessor :password
499 # Score in the rating sysem
502 # Number of games for win and loss in the rating system
503 attr_accessor :win, :loss
505 # Group in the rating system
506 attr_accessor :rating_group
508 # Last timestamp when the rate was modified
509 attr_accessor :modified_at
511 # Whether win the previous game or not
512 attr_accessor :last_game_win
515 @modified_at || Time.now
521 @modified_at = Time.now
530 return @last_game_win
535 simple_name = @name.gsub(/@.*?$/, '')
536 "%s+%s" % [simple_name, @trip[0..8]]
543 # Parses str in the LOGIN command, sets up @id and @trip
545 def set_password(str)
546 if str && !str.empty?
547 @password = str.strip
548 @id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
550 @id = @password = nil
556 class Player < BasicPlayer
557 def initialize(str, socket)
560 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
562 @protocol = nil # CSA or x1
563 @eol = "\m" # favorite eol code
566 @mytime = 0 # set in start method also
568 @write_queue = Queue::new
569 @main_thread = Thread::current
570 @writer_thread = Thread::start do
576 attr_accessor :socket, :status
577 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
578 attr_accessor :main_thread, :writer_thread, :write_queue
581 log_message(sprintf("user %s killed", @name))
586 Thread::kill(@main_thread) if @main_thread
590 if (@status != "finished")
592 log_message(sprintf("user %s finish", @name))
593 # TODO you should confirm that there is no message in the queue.
594 Thread::kill(@writer_thread) if @writer_thread
596 # @socket.close if (! @socket.closed?)
598 log_message(sprintf("user %s finish failed", @name))
604 @write_queue.push(str.gsub(/[\r\n]+/, @eol))
608 while (str = @write_queue.pop)
611 rescue Exception => ex
612 log_error("Failed to send a message to #{@name}.")
613 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
620 if ((status == "game_waiting") ||
621 (status == "start_waiting") ||
622 (status == "agree_waiting") ||
625 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
626 elsif (@sente == false)
627 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
628 elsif (@sente == nil)
629 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
632 return sprintf("%s %s %s", @name, @protocol, @status)
636 def run(csa_1st_str=nil)
637 while (csa_1st_str || (str = @socket.gets_safe(Default_Timeout)))
641 if (@writer_thread == nil || @writer_thread.status == false)
642 # The writer_thread has been killed because of socket errors.
650 if (@write_queue.size > Max_Write_Queue_Size)
651 log_warning(sprintf("write_queue of %s is %d", @name, @write_queue.size))
655 if (@status == "finished")
658 str.chomp! if (str.class == String) # may be strip! ?
659 log_message(str) if $DEBUG
662 # Application-level protocol for Keep-Alive
663 # If the server gets LF, it sends back LF.
664 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
667 if (@status == "game")
668 array_str = str.split(",")
669 move = array_str.shift
670 additional = array_str.shift
671 if /^'(.*)/ =~ additional
672 comment = array_str.unshift("'*#{$1}")
674 s = @game.handle_one_move(move, self)
675 @game.fh.print("#{comment}\n") if (comment && !s)
676 return if (s && @protocol == LoginCSA::PROTOCOL)
678 when /^%[^%]/, :timeout
679 if (@status == "game")
680 s = @game.handle_one_move(str, self)
681 return if (s && @protocol == LoginCSA::PROTOCOL)
684 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
685 # rescue Exception => ex
686 # log_error("Failed to send a keepalive to #{@name}.")
687 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
692 log_error("Failed to receive a message from #{@name}.")
695 if (@status == "agree_waiting")
697 return if (@protocol == LoginCSA::PROTOCOL)
699 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
702 if (@status == "agree_waiting")
703 @status = "start_waiting"
704 if ((@game.sente.status == "start_waiting") &&
705 (@game.gote.status == "start_waiting"))
707 @game.sente.status = "game"
708 @game.gote.status = "game"
711 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
713 when /^%%SHOW\s+(\S+)/
715 if (LEAGUE.games[game_id])
716 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
718 write_safe("##[SHOW] +OK\n")
719 when /^%%MONITORON\s+(\S+)/
721 if (LEAGUE.games[game_id])
722 LEAGUE.games[game_id].monitoron(self)
723 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
724 write_safe("##[MONITOR][#{game_id}] +OK\n")
726 when /^%%MONITOROFF\s+(\S+)/
728 if (LEAGUE.games[game_id])
729 LEAGUE.games[game_id].monitoroff(self)
733 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
735 players = LEAGUE.rated_players
736 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
737 write_safe("##[RATING] %s \t %4d @%s\n" %
738 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
740 write_safe("##[RATING] +OK\n")
742 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
743 write_safe("##[VERSION] +OK\n")
745 if ((@status == "connected") || (@status == "game_waiting"))
746 @status = "connected"
749 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
751 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
755 if (! Login::good_game_name?(game_name))
756 write_safe(sprintf("##[ERROR] bad game name\n"))
758 elsif ((@status == "connected") || (@status == "game_waiting"))
761 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
766 if (League::Floodgate.game_name?(game_name))
767 if (my_sente_str != "*")
768 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n"), my_sente_str, game_name)
773 if (my_sente_str == "*")
774 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
775 elsif (my_sente_str == "+")
776 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
777 elsif (my_sente_str == "-")
778 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
781 write_safe(sprintf("##[ERROR] bad game option\n"))
787 @game_name = game_name
788 if ((my_sente_str == "*") && (rival.sente == nil))
796 elsif (rival.sente == true) # rival has higher priority
798 elsif (rival.sente == false)
800 elsif (my_sente_str == "+")
803 elsif (my_sente_str == "-")
809 Game::new(@game_name, self, rival)
810 else # rival not found
811 if (command_name == "GAME")
812 @status = "game_waiting"
813 @game_name = game_name
814 if (my_sente_str == "+")
816 elsif (my_sente_str == "-")
822 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
823 @status = "connected"
828 when /^%%CHAT\s+(.+)/
830 LEAGUE.players.each do |name, player|
831 if (player.protocol != LoginCSA::PROTOCOL)
832 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
837 LEAGUE.games.each do |id, game|
838 buf.push(sprintf("##[LIST] %s\n", id))
840 buf.push("##[LIST] +OK\n")
844 LEAGUE.players.each do |name, player|
845 buf.push(sprintf("##[WHO] %s\n", player.to_s))
847 buf.push("##[WHO] +OK\n")
850 @status = "connected"
851 write_safe("LOGOUT:completed\n")
854 # This command is only available for CSA's official testing server.
855 # So, this means nothing for this program.
856 write_safe("CHALLENGE ACCEPTED\n")
858 ## ignore null string
860 msg = "##[ERROR] unknown command %s\n" % [str]
872 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
873 def initialize(board, x, y, sente, promoted=false)
880 if ((x == 0) || (y == 0))
882 hands = board.sente_hands
884 hands = board.gote_hands
891 @board.array[x][y] = self
894 attr_accessor :promoted, :sente, :x, :y, :board
896 def room_of_head?(x, y, name)
901 return adjacent_movable_grids + far_movable_grids
904 def far_movable_grids
909 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
910 if ((@board.array[x][y] == nil) || # dst is empty
911 (@board.array[x][y].sente != @sente)) # dst is enemy
919 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
920 if (@board.array[x][y] == nil) # dst is empty?
927 def adjacent_movable_grids
930 moves = @promoted_moves
932 moves = @normal_moves
934 moves.each do |(dx, dy)|
941 if (jump_to?(cand_x, cand_y))
942 grids.push([cand_x, cand_y])
948 def move_to?(x, y, name)
949 return false if (! room_of_head?(x, y, name))
950 return false if ((name != @name) && (name != @promoted_name))
951 return false if (@promoted && (name != @promoted_name)) # can't un-promote
954 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
956 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
958 return false if ((6 >= @y) && (6 >= y) && (name != @name))
962 if ((@x == 0) || (@y == 0))
963 return jump_to?(x, y)
965 return movable_grids.include?([x, y])
970 if ((@x == 0) || (@y == 0))
972 @board.sente_hands.delete(self)
974 @board.gote_hands.delete(self)
976 @board.array[x][y] = self
977 elsif ((x == 0) || (y == 0))
978 @promoted = false # clear promoted flag before moving to hands
980 @board.sente_hands.push(self)
982 @board.gote_hands.push(self)
984 @board.array[@x][@y] = nil
986 @board.array[@x][@y] = nil
987 @board.array[x][y] = self
1020 class PieceFU < Piece
1021 def initialize(*arg)
1023 @normal_moves = [[0, +1]]
1024 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1026 @promoted_name = "TO"
1029 def room_of_head?(x, y, name)
1032 return false if (y == 1)
1034 return false if (y == 9)
1040 if ((iy != @y) && # not source position
1041 @board.array[x][iy] &&
1042 (@board.array[x][iy].sente == @sente) && # mine
1043 (@board.array[x][iy].name == "FU") &&
1044 (@board.array[x][iy].promoted == false))
1054 class PieceKY < Piece
1055 def initialize(*arg)
1058 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1060 @promoted_name = "NY"
1063 def room_of_head?(x, y, name)
1066 return false if (y == 1)
1068 return false if (y == 9)
1073 def far_movable_grids
1081 while (jump_to?(cand_x, cand_y))
1082 grids.push([cand_x, cand_y])
1083 break if (! put_to?(cand_x, cand_y))
1089 while (jump_to?(cand_x, cand_y))
1090 grids.push([cand_x, cand_y])
1091 break if (! put_to?(cand_x, cand_y))
1099 class PieceKE < Piece
1100 def initialize(*arg)
1102 @normal_moves = [[+1, +2], [-1, +2]]
1103 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1105 @promoted_name = "NK"
1108 def room_of_head?(x, y, name)
1111 return false if ((y == 1) || (y == 2))
1113 return false if ((y == 9) || (y == 8))
1119 class PieceGI < Piece
1120 def initialize(*arg)
1122 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1123 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1125 @promoted_name = "NG"
1129 class PieceKI < Piece
1130 def initialize(*arg)
1132 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
1133 @promoted_moves = []
1135 @promoted_name = nil
1139 class PieceKA < Piece
1140 def initialize(*arg)
1143 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
1145 @promoted_name = "UM"
1148 def far_movable_grids
1153 while (jump_to?(cand_x, cand_y))
1154 grids.push([cand_x, cand_y])
1155 break if (! put_to?(cand_x, cand_y))
1162 while (jump_to?(cand_x, cand_y))
1163 grids.push([cand_x, cand_y])
1164 break if (! put_to?(cand_x, cand_y))
1171 while (jump_to?(cand_x, cand_y))
1172 grids.push([cand_x, cand_y])
1173 break if (! put_to?(cand_x, cand_y))
1180 while (jump_to?(cand_x, cand_y))
1181 grids.push([cand_x, cand_y])
1182 break if (! put_to?(cand_x, cand_y))
1189 class PieceHI < Piece
1190 def initialize(*arg)
1193 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
1195 @promoted_name = "RY"
1198 def far_movable_grids
1203 while (jump_to?(cand_x, cand_y))
1204 grids.push([cand_x, cand_y])
1205 break if (! put_to?(cand_x, cand_y))
1211 while (jump_to?(cand_x, cand_y))
1212 grids.push([cand_x, cand_y])
1213 break if (! put_to?(cand_x, cand_y))
1219 while (jump_to?(cand_x, cand_y))
1220 grids.push([cand_x, cand_y])
1221 break if (! put_to?(cand_x, cand_y))
1227 while (jump_to?(cand_x, cand_y))
1228 grids.push([cand_x, cand_y])
1229 break if (! put_to?(cand_x, cand_y))
1235 class PieceOU < Piece
1236 def initialize(*arg)
1238 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1239 @promoted_moves = []
1241 @promoted_name = nil
1248 @sente_hands = Array::new
1249 @gote_hands = Array::new
1250 @history = Hash::new(0)
1251 @sente_history = Hash::new(0)
1252 @gote_history = Hash::new(0)
1253 @array = [[], [], [], [], [], [], [], [], [], []]
1256 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1257 attr_reader :move_count
1260 PieceKY::new(self, 1, 1, false)
1261 PieceKE::new(self, 2, 1, false)
1262 PieceGI::new(self, 3, 1, false)
1263 PieceKI::new(self, 4, 1, false)
1264 PieceOU::new(self, 5, 1, false)
1265 PieceKI::new(self, 6, 1, false)
1266 PieceGI::new(self, 7, 1, false)
1267 PieceKE::new(self, 8, 1, false)
1268 PieceKY::new(self, 9, 1, false)
1269 PieceKA::new(self, 2, 2, false)
1270 PieceHI::new(self, 8, 2, false)
1272 PieceFU::new(self, i, 3, false)
1275 PieceKY::new(self, 1, 9, true)
1276 PieceKE::new(self, 2, 9, true)
1277 PieceGI::new(self, 3, 9, true)
1278 PieceKI::new(self, 4, 9, true)
1279 PieceOU::new(self, 5, 9, true)
1280 PieceKI::new(self, 6, 9, true)
1281 PieceGI::new(self, 7, 9, true)
1282 PieceKE::new(self, 8, 9, true)
1283 PieceKY::new(self, 9, 9, true)
1284 PieceKA::new(self, 8, 8, true)
1285 PieceHI::new(self, 2, 8, true)
1287 PieceFU::new(self, i, 7, true)
1291 def have_piece?(hands, name)
1292 piece = hands.find { |i|
1298 def move_to(x0, y0, x1, y1, name, sente)
1300 hands = @sente_hands
1305 if ((x0 == 0) || (y0 == 0))
1306 piece = have_piece?(hands, name)
1307 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1308 piece.move_to(x1, y1)
1310 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1311 if (@array[x0][y0].name != name) # promoted ?
1312 @array[x0][y0].promoted = true
1314 if (@array[x1][y1]) # capture
1315 if (@array[x1][y1].name == "OU")
1316 return :outori # return board update
1318 @array[x1][y1].sente = @array[x0][y0].sente
1319 @array[x1][y1].move_to(0, 0)
1320 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1324 @array[x0][y0].move_to(x1, y1)
1330 def look_for_ou(sente)
1336 (@array[x][y].name == "OU") &&
1337 (@array[x][y].sente == sente))
1344 raise "can't find ou"
1347 # note checkmate, but check. sente is checked.
1348 def checkmated?(sente) # sente is loosing
1349 ou = look_for_ou(sente)
1355 (@array[x][y].sente != sente))
1356 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1367 def uchifuzume?(sente)
1368 rival_ou = look_for_ou(! sente) # rival's ou
1369 if (sente) # rival is gote
1370 if ((rival_ou.y != 9) &&
1371 (@array[rival_ou.x][rival_ou.y + 1]) &&
1372 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1373 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1375 fu_y = rival_ou.y + 1
1380 if ((rival_ou.y != 0) &&
1381 (@array[rival_ou.x][rival_ou.y - 1]) &&
1382 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1383 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1385 fu_y = rival_ou.y - 1
1391 ## case: rival_ou is moving
1393 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1394 tmp_board = Marshal.load(Marshal.dump(self))
1395 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1396 raise "internal error" if (s != true)
1397 if (! tmp_board.checkmated?(! sente)) # good move
1402 ## case: rival is capturing fu
1408 (@array[x][y].sente != sente) &&
1409 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1410 if (@array[x][y].promoted)
1411 name = @array[x][y].promoted_name
1413 name = @array[x][y].name
1415 tmp_board = Marshal.load(Marshal.dump(self))
1416 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1417 raise "internal error" if (s != true)
1418 if (! tmp_board.checkmated?(! sente)) # good move
1429 # @[sente|gote]_history has at least one item while the player is checking the other or
1430 # the other escapes.
1431 def update_sennichite(player)
1434 if checkmated?(!player)
1436 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
1438 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
1442 @sente_history.clear # no more continuous check
1444 @gote_history.clear # no more continuous check
1447 if @sente_history.size > 0 # possible for Sente's or Gote's turn
1448 @sente_history[str] += 1
1450 if @gote_history.size > 0 # possible for Sente's or Gote's turn
1451 @gote_history[str] += 1
1455 def oute_sennichite?(player)
1456 if (@sente_history[to_s] >= 4)
1457 return :oute_sennichite_sente_lose
1458 elsif (@gote_history[to_s] >= 4)
1459 return :oute_sennichite_gote_lose
1465 def sennichite?(sente)
1466 if (@history[to_s] >= 4) # already 3 times
1472 def good_kachi?(sente)
1473 if (checkmated?(sente))
1474 puts "'NG: Checkmating." if $DEBUG
1478 ou = look_for_ou(sente)
1479 if (sente && (ou.y >= 4))
1480 puts "'NG: Black's OU does not enter yet." if $DEBUG
1483 if (! sente && (ou.y <= 6))
1484 puts "'NG: White's OU does not enter yet." if $DEBUG
1492 hands = @sente_hands
1502 (@array[x][y].sente == sente) &&
1503 (@array[x][y].point > 0))
1504 point = point + @array[x][y].point
1510 hands.each do |piece|
1511 point = point + piece.point
1515 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1520 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1525 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1530 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1534 # sente is nil only if tests in test_board run
1535 def handle_one_move(str, sente=nil)
1536 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1543 elsif (str =~ /^%KACHI/)
1544 raise ArgumentError, "sente is null", caller if sente == nil
1545 if (good_kachi?(sente))
1550 elsif (str =~ /^%TORYO/)
1556 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1557 ((x0 != 0) || (y0 != 0)))
1559 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1565 sente = true if sente == nil # deprecated
1566 return :illegal unless sente == true # black player's move must be black
1567 hands = @sente_hands
1569 sente = false if sente == nil # deprecated
1570 return :illegal unless sente == false # white player's move must be white
1575 if ((x0 == 0) && (y0 == 0))
1576 return :illegal if (! have_piece?(hands, name))
1577 elsif (! @array[x0][y0])
1578 return :illegal # no piece
1579 elsif (@array[x0][y0].sente != sente)
1580 return :illegal # this is not mine
1581 elsif (@array[x0][y0].name != name)
1582 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1585 ## destination check
1586 if (@array[x1][y1] &&
1587 (@array[x1][y1].sente == sente)) # can't capture mine
1589 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1590 return :illegal # can't put on existing piece
1593 tmp_board = Marshal.load(Marshal.dump(self))
1594 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1595 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1596 tmp_board.update_sennichite(sente)
1597 os_result = tmp_board.oute_sennichite?(sente)
1598 return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
1599 return :sennichite if tmp_board.sennichite?(sente)
1601 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1605 move_to(x0, y0, x1, y1, name, sente)
1608 update_sennichite(sente)
1616 a.push(sprintf("P%d", y))
1619 piece = @array[x][y]
1628 a.push(sprintf("\n"))
1631 if (! sente_hands.empty?)
1633 sente_hands.each do |p|
1634 a.push("00" + p.name)
1638 if (! gote_hands.empty?)
1640 gote_hands.each do |p|
1641 a.push("00" + p.name)
1651 attr_reader :players, :black, :white
1653 def initialize(p1, p2)
1655 if p1.sente && !p2.sente
1656 @black, @white = p1, p2
1657 elsif !p1.sente && p2.sente
1658 @black, @white = p2, p1
1660 raise "Never reached!"
1665 class GameResultWin < GameResult
1666 attr_reader :winner, :loser
1668 def initialize(winner, loser)
1670 @winner, @loser = winner, loser
1671 @winner.last_game_win = true
1672 @loser.last_game_win = false
1676 black_name = @black.id || @black.name
1677 white_name = @white.id || @white.name
1678 "%s:%s" % [black_name, white_name]
1682 class GameResultDraw < GameResult
1683 def initialize(p1, p2)
1685 p1.last_game_win = false
1686 p2.last_game_win = false
1694 def initialize(game_name, player0, player1)
1695 @monitors = Array::new
1696 @game_name = game_name
1697 if (@game_name =~ /-(\d+)-(\d+)$/)
1698 @total_time = $1.to_i
1709 @current_player = @sente
1710 @next_player = @gote
1718 @sente.status = "agree_waiting"
1719 @gote.status = "agree_waiting"
1721 @id = sprintf("%s+%s+%s+%s+%s",
1722 LEAGUE.event, @game_name, @sente.name, @gote.name, issue_current_time)
1723 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1725 LEAGUE.games[@id] = self
1727 log_message(sprintf("game created %s", @id))
1737 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1738 attr_accessor :last_move, :current_turn
1742 @sente.rated? && @gote.rated?
1745 def monitoron(monitor)
1746 @monitors.delete(monitor)
1747 @monitors.push(monitor)
1750 def monitoroff(monitor)
1751 @monitors.delete(monitor)
1754 def reject(rejector)
1755 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1756 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1761 if ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
1763 elsif (@current_player == killer)
1770 log_message(sprintf("game finished %s", @id))
1771 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1776 @sente.status = "connected"
1777 @gote.status = "connected"
1779 if (@current_player.protocol == LoginCSA::PROTOCOL)
1780 @current_player.finish
1782 if (@next_player.protocol == LoginCSA::PROTOCOL)
1785 @monitors = Array::new
1788 @current_player = nil
1790 LEAGUE.games.delete(@id)
1793 def handle_one_move(str, player)
1795 if (@current_player == player)
1796 @end_time = Time::new
1797 t = (@end_time - @start_time).floor
1798 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
1801 if ((@current_player.mytime - t <= -@byoyomi) && ((@total_time > 0) || (@byoyomi > 0)))
1803 elsif (str == :timeout)
1804 return false # time isn't expired. players aren't swapped. continue game
1806 @current_player.mytime = @current_player.mytime - t
1807 if (@current_player.mytime < 0)
1808 @current_player.mytime = 0
1812 move_status = @board.handle_one_move(str, @sente == @current_player)
1814 # log_error("handle_one_move raise exception for #{str}")
1815 # move_status = :illegal
1818 if ((move_status == :illegal) || (move_status == :uchifuzme) || (move_status == :oute_kaihimore))
1819 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1821 if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite_sente_lose) || (move_status == :oute_sennichite_gote_lose))
1822 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1823 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1824 @fh.printf("%s\nT%d\n", str, t)
1825 @last_move = sprintf("%s,T%d", str, t)
1826 @current_turn = @current_turn + 1
1829 @monitors.each do |monitor|
1830 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1831 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1836 if (@next_player.status != "game") # rival is logout or disconnected
1838 elsif (status == :timeout)
1840 elsif (move_status == :illegal)
1842 elsif (move_status == :kachi_win)
1844 elsif (move_status == :kachi_lose)
1846 elsif (move_status == :toryo)
1848 elsif (move_status == :outori)
1850 elsif (move_status == :oute_sennichite_sente_lose)
1851 oute_sennichite_win_lose(@gote, @sente) # Sente is checking
1852 elsif (move_status == :oute_sennichite_gote_lose)
1853 oute_sennichite_win_lose(@sente, @gote) # Gote is checking
1854 elsif (move_status == :sennichite)
1856 elsif (move_status == :uchifuzume)
1858 elsif (move_status == :oute_kaihimore)
1859 oute_kaihimore_lose()
1863 finish() if finish_flag
1864 (@current_player, @next_player) = [@next_player, @current_player]
1865 @start_time = Time::new
1871 @current_player.status = "connected"
1872 @next_player.status = "connected"
1873 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1874 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1875 @fh.printf("%%TORYO\n")
1876 @fh.print(@board.to_s.gsub(/^/, "\'"))
1877 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1878 @result = GameResultWin.new(@current_player, @next_player)
1879 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1880 @monitors.each do |monitor|
1881 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1886 @current_player.status = "connected"
1887 @next_player.status = "connected"
1888 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1889 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1890 @fh.printf("%%TORYO\n")
1891 @fh.print(@board.to_s.gsub(/^/, "\'"))
1892 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1893 @result = GameResultWin.new(@next_player, @current_player)
1894 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1895 @monitors.each do |monitor|
1896 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1901 @current_player.status = "connected"
1902 @next_player.status = "connected"
1903 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1904 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1905 @fh.print(@board.to_s.gsub(/^/, "\'"))
1906 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1907 @result = GameResultDraw.new(@current_player, @next_player)
1908 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1909 @monitors.each do |monitor|
1910 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @id))
1914 def oute_sennichite_win_lose(winner, loser)
1915 @current_player.status = "connected"
1916 @next_player.status = "connected"
1917 loser.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1918 winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1919 @fh.print(@board.to_s.gsub(/^/, "\'"))
1920 if loser == @current_player
1921 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1923 @fh.printf("'summary:oute_sennichite:%s win:%s lose\n", @current_player.name, @next_player.name)
1925 @result = GameResultWin.new(winner, loser)
1926 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1927 @monitors.each do |monitor|
1928 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1933 @current_player.status = "connected"
1934 @next_player.status = "connected"
1935 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1936 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1937 @fh.print(@board.to_s.gsub(/^/, "\'"))
1938 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1939 @result = GameResultWin.new(@next_player, @current_player)
1940 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1941 @monitors.each do |monitor|
1942 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1947 @current_player.status = "connected"
1948 @next_player.status = "connected"
1949 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1950 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1951 @fh.print(@board.to_s.gsub(/^/, "\'"))
1952 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1953 @result = GameResultWin.new(@next_player, @current_player)
1954 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1955 @monitors.each do |monitor|
1956 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1960 def oute_kaihimore_lose
1961 @current_player.status = "connected"
1962 @next_player.status = "connected"
1963 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1964 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1965 @fh.print(@board.to_s.gsub(/^/, "\'"))
1966 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1967 @result = GameResultWin.new(@next_player, @current_player)
1968 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1969 @monitors.each do |monitor|
1970 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1975 @current_player.status = "connected"
1976 @next_player.status = "connected"
1977 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1978 @next_player.write_safe("#TIME_UP\n#WIN\n")
1979 @fh.print(@board.to_s.gsub(/^/, "\'"))
1980 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1981 @result = GameResultWin.new(@next_player, @current_player)
1982 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1983 @monitors.each do |monitor|
1984 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
1989 @current_player.status = "connected"
1990 @next_player.status = "connected"
1991 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1992 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1993 @fh.printf("%%KACHI\n")
1994 @fh.print(@board.to_s.gsub(/^/, "\'"))
1995 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1996 @result = GameResultWin.new(@current_player, @next_player)
1997 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1998 @monitors.each do |monitor|
1999 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
2004 @current_player.status = "connected"
2005 @next_player.status = "connected"
2006 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
2007 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
2008 @fh.printf("%%KACHI\n")
2009 @fh.print(@board.to_s.gsub(/^/, "\'"))
2010 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
2011 @result = GameResultWin.new(@next_player, @current_player)
2012 @fh.printf("'rating:#{@result.to_s}\n") if rated?
2013 @monitors.each do |monitor|
2014 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
2019 @current_player.status = "connected"
2020 @next_player.status = "connected"
2021 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
2022 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
2023 @fh.printf("%%TORYO\n")
2024 @fh.print(@board.to_s.gsub(/^/, "\'"))
2025 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
2026 @result = GameResultWin.new(@next_player, @current_player)
2027 @fh.printf("'rating:#{@result.to_s}\n") if rated?
2028 @monitors.each do |monitor|
2029 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
2034 @current_player.status = "connected"
2035 @next_player.status = "connected"
2036 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
2037 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
2038 @fh.print(@board.to_s.gsub(/^/, "\'"))
2039 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
2040 @result = GameResultWin.new(@current_player, @next_player)
2041 @fh.printf("'rating:#{@result.to_s}\n") if rated?
2042 @monitors.each do |monitor|
2043 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
2048 log_message(sprintf("game started %s", @id))
2049 @sente.write_safe(sprintf("START:%s\n", @id))
2050 @gote.write_safe(sprintf("START:%s\n", @id))
2051 @sente.mytime = @total_time
2052 @gote.mytime = @total_time
2053 @start_time = Time::new
2057 @fh = open(@logfile, "w")
2061 @fh.puts("N+#{@sente.name}")
2062 @fh.puts("N-#{@gote.name}")
2063 @fh.puts("$EVENT:#{@id}")
2065 @sente.write_safe(propose_message("+"))
2066 @gote.write_safe(propose_message("-"))
2068 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
2069 @fh.puts("$START_TIME:#{now}")
2071 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2072 P2 * -HI * * * * * -KA *
2073 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2074 P4 * * * * * * * * *
2075 P5 * * * * * * * * *
2076 P6 * * * * * * * * *
2077 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2078 P8 * +KA * * * * * +HI *
2079 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2087 Protocol_Version:1.1
2088 Protocol_Mode:Server
2090 Declaration:Jishogi 1.1
2092 Name+:#{@sente.name}
2098 Total_Time:#{@total_time}
2100 Least_Time_Per_Move:#{Least_Time_Per_Move}
2101 Remaining_Time+:#{@sente.mytime}
2102 Remaining_Time-:#{@gote.mytime}
2103 Last_Move:#{@last_move}
2104 Current_Turn:#{@current_turn}
2114 return str0 + @board.to_s + str1
2117 def propose_message(sg_flag)
2120 Protocol_Version:1.1
2121 Protocol_Mode:Server
2123 Declaration:Jishogi 1.1
2125 Name+:#{@sente.name}
2127 Your_Turn:#{sg_flag}
2132 Total_Time:#{@total_time}
2134 Least_Time_Per_Move:#{Least_Time_Per_Move}
2137 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
2138 P2 * -HI * * * * * -KA *
2139 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
2140 P4 * * * * * * * * *
2141 P5 * * * * * * * * *
2142 P6 * * * * * * * * *
2143 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
2144 P8 * +KA * * * * * +HI *
2145 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
2157 def issue_current_time
2158 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
2159 @@mutex.synchronize do
2160 while time <= @@time do
2167 end # module ShogiServer
2169 #################################################
2176 shogi-server - server for CSA server protocol
2179 shogi-server [OPTIONS] event_name port_number
2182 server for CSA server protocol
2186 specify filename for logging process ID
2188 run as a daemon. Log files will be put in dir.
2191 this file is distributed under GPL version2 and might be compiled by Exerb
2196 #{ShogiServer::Release}
2199 #{ShogiServer::Revision}
2207 def log_message(str)
2211 def log_warning(str)
2220 def parse_command_line
2222 parser = GetoptLong.new( ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2223 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT]
2227 parser.each_option do |name, arg|
2228 name.sub!(/^--/, '')
2229 options[name] = arg.dup
2233 raise parser.error_message
2238 def write_pid_file(file)
2239 open(file, "w") do |fh|
2244 def mutex_watchdog(mutex, sec)
2256 log_error("mutex watchdog timeout")
2267 mutex_watchdog($mutex, 10)
2270 $options = parse_command_line
2271 if (ARGV.length != 2)
2276 LEAGUE.event = ARGV.shift
2279 dir = $options["daemon"]
2280 dir = File.expand_path(dir) if dir
2281 if dir && ! File.exist?(dir)
2282 FileUtils.mkdir(dir)
2284 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2285 $logger = WEBrick::Log.new(log_file)
2287 LEAGUE.dir = dir || File.dirname(__FILE__)
2288 LEAGUE.setup_players_database
2291 config[:Port] = port
2292 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2293 config[:Logger] = $logger
2294 if $options["pid-file"]
2295 pid_file = File.expand_path($options["pid-file"])
2296 config[:StartCallback] = Proc.new do
2297 write_pid_file(pid_file)
2299 config[:StopCallback] = Proc.new do
2300 FileUtils.rm(pid_file, :force => true)
2304 server = WEBrick::GenericServer.new(config)
2305 ["INT", "TERM"].each do |signal|
2311 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2312 log_message("server started [Revision: #{ShogiServer::Revision}]")
2314 server.start do |client|
2315 # client.sync = true # this is already set in WEBrick
2316 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2317 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2320 while (str = client.gets_timeout(ShogiServer::Login_Time))
2325 if (ShogiServer::Login::good_login?(str))
2326 player = ShogiServer::Player::new(str, client)
2328 login = ShogiServer::Login::factory(str, player)
2329 if (LEAGUE.players[player.name])
2330 if ((LEAGUE.players[player.name].password == player.password) &&
2331 (LEAGUE.players[player.name].status != "game"))
2332 log_message(sprintf("user %s login forcely", player.name))
2333 LEAGUE.players[player.name].kill
2335 login.incorrect_duplicated_player(str)
2346 client.write_safe("LOGIN:incorrect" + eol)
2347 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2359 log_message(sprintf("user %s login", player.name))
2361 player.run(login.csa_1st_str)
2365 player.game.kill(player)
2367 player.finish # socket has been closed
2368 LEAGUE.delete(player)
2369 log_message(sprintf("user %s logout", player.name))
2380 TCPSocket.do_not_reverse_lookup = true
2381 Thread.abort_on_exception = true
2383 LEAGUE = ShogiServer::League::new