4 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, write to the Free Software
18 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32 def gets_timeout(t = Default_Timeout)
43 def gets_safe(t = nil)
51 rescue Exception => ex
52 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
65 return self.write(str)
73 module ShogiServer # for a namespace
75 Max_Write_Queue_Size = 1000
76 Max_Identifier_Length = 32
77 Default_Timeout = 60 # for single socket operation
79 Default_Game_Name = "default-1500-0"
82 Least_Time_Per_Move = 1
83 Login_Time = 300 # time for LOGIN
85 Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
86 Release.concat("-") if (Release == "")
87 Revision = "$Revision$".gsub(/[^\.\d]/, '')
95 @dir = File.dirname(__FILE__)
97 attr_accessor :players, :games, :event, :dir
99 # this should be called just after instanciating a League object.
100 def setup_players_database
101 @db = YAML::Store.new(File.join(@dir, "players.yaml"))
105 self.load(player) if player.id
106 @players[player.name] = player
110 @players.delete(player.name)
113 def get_player(status, game_name, sente, searcher=nil)
114 @players.each do |name, player|
115 if ((player.status == status) &&
116 (player.game_name == game_name) &&
117 ((sente == nil) || (player.sente == nil) || (player.sente == sente)) &&
118 ((searcher == nil) || (player != searcher)))
126 hash = search(player.id)
129 player.name = hash['name']
130 player.rate = hash['rate']
131 player.modified_at = hash['last_modified']
132 player.rating_group = hash['rating_group']
139 break unless @db["players"]
140 @db["players"].each do |group, players|
150 @db.transaction(true) do
151 break unless @db["players"]
152 @db["players"].each do |group, players_hash|
153 players << players_hash.keys
156 return players.flatten.collect do |id|
166 ######################################################
167 # Processes the LOGIN command.
170 def Login.good_login?(str)
172 if (((tokens.length == 3) || ((tokens.length == 4) && tokens[3] == "x1")) &&
173 (tokens[0] == "LOGIN") &&
174 (good_identifier?(tokens[1])))
181 def Login.good_game_name?(str)
182 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
189 def Login.good_identifier?(str)
190 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
197 def Login.factory(str, player)
198 (login, player.name, password, ext) = str.chomp.split
200 return Loginx1.new(player, password)
202 return LoginCSA.new(player, password)
208 # the first command that will be executed just after LOGIN.
209 # If it is nil, the default process will be started.
210 attr_reader :csa_1st_str
212 def initialize(player, password)
215 parse_password(password)
219 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
220 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
223 def incorrect_duplicated_player(str)
224 @player.write_safe("LOGIN:incorrect\n")
225 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
226 sleep 3 # wait for sending the above messages.
227 @player.name = "%s [duplicated]" % [@player.name]
232 ######################################################
233 # Processes LOGIN for the CSA standard mode.
235 class LoginCSA < Login
238 def initialize(player, password)
241 @player.protocol = PROTOCOL
244 def parse_password(password)
245 if Login.good_game_name?(password)
247 @player.set_password(nil)
248 elsif password.split(",").size > 1
249 @gamename, *trip = password.split(",")
250 @player.set_password(trip.join(","))
252 @player.set_password(password)
253 @gamename = Default_Game_Name
255 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
260 @csa_1st_str = "%%GAME #{@gamename} *"
264 ######################################################
265 # Processes LOGIN for the extented mode.
267 class Loginx1 < Login
270 def initialize(player, password)
272 @player.protocol = PROTOCOL
275 def parse_password(password)
276 @player.set_password(password)
281 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
287 # Idetifier of the player in the rating system
293 # Password of the player, which does not include a trip
294 attr_accessor :password
296 # Score in the rating sysem
299 # Group in the rating system
300 attr_accessor :rating_group
302 # Last timestamp when the rate was modified
303 attr_accessor :modified_at
311 @modified_at || Time.now
317 @modified_at = Time.now
327 simple_name = @name.gsub(/@.*?$/, '')
328 "%s+%s" % [simple_name, @trip[0..8]]
335 # Parses str in the LOGIN command, sets up @id and @trip
337 def set_password(str)
338 if str && !str.empty?
339 @password = str.strip
340 @id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
342 @id = @password = nil
348 class Player < BasicPlayer
349 def initialize(str, socket)
352 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
354 @protocol = nil # CSA or x1
355 @eol = "\m" # favorite eol code
358 @mytime = 0 # set in start method also
360 @write_queue = Queue::new
361 @main_thread = Thread::current
362 @writer_thread = Thread::start do
368 attr_accessor :socket, :status
369 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
370 attr_accessor :main_thread, :writer_thread, :write_queue
373 log_message(sprintf("user %s killed", @name))
378 Thread::kill(@main_thread) if @main_thread
382 if (@status != "finished")
384 log_message(sprintf("user %s finish", @name))
385 # TODO you should confirm that there is no message in the queue.
386 Thread::kill(@writer_thread) if @writer_thread
388 # @socket.close if (! @socket.closed?)
390 log_message(sprintf("user %s finish failed", @name))
396 @write_queue.push(str.gsub(/[\r\n]+/, @eol))
400 while (str = @write_queue.pop)
403 rescue Exception => ex
404 log_error("Failed to send a message to #{@name}.")
405 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
412 if ((status == "game_waiting") ||
413 (status == "start_waiting") ||
414 (status == "agree_waiting") ||
417 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
418 elsif (@sente == false)
419 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
420 elsif (@sente == nil)
421 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
424 return sprintf("%s %s %s", @name, @protocol, @status)
428 def run(csa_1st_str=nil)
429 while (csa_1st_str || (str = @socket.gets_safe(Default_Timeout)))
433 if (@writer_thread == nil || @writer_thread.status == false)
434 # The writer_thread has been killed because of socket errors.
442 if (@write_queue.size > Max_Write_Queue_Size)
443 log_warning(sprintf("write_queue of %s is %d", @name, @write_queue.size))
447 if (@status == "finished")
450 str.chomp! if (str.class == String) # may be strip! ?
453 # Application-level protocol for Keep-Alive
454 # If the server gets LF, it sends back LF.
455 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
458 if (@status == "game")
459 array_str = str.split(",")
460 move = array_str.shift
461 additional = array_str.shift
462 if /^'(.*)/ =~ additional
463 comment = array_str.unshift("'*#{$1}")
465 s = @game.handle_one_move(move, self)
466 @game.fh.print("#{comment}\n") if (comment && !s)
467 return if (s && @protocol == LoginCSA::PROTOCOL)
469 when /^%[^%]/, :timeout
470 if (@status == "game")
471 s = @game.handle_one_move(str, self)
472 return if (s && @protocol == LoginCSA::PROTOCOL)
475 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
476 # rescue Exception => ex
477 # log_error("Failed to send a keepalive to #{@name}.")
478 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
483 log_error("Failed to receive a message from #{@name}.")
486 if (@status == "agree_waiting")
488 return if (@protocol == LoginCSA::PROTOCOL)
490 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
493 if (@status == "agree_waiting")
494 @status = "start_waiting"
495 if ((@game.sente.status == "start_waiting") &&
496 (@game.gote.status == "start_waiting"))
498 @game.sente.status = "game"
499 @game.gote.status = "game"
502 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
504 when /^%%SHOW\s+(\S+)/
506 if (LEAGUE.games[game_id])
507 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
509 write_safe("##[SHOW] +OK\n")
510 when /^%%MONITORON\s+(\S+)/
512 if (LEAGUE.games[game_id])
513 LEAGUE.games[game_id].monitoron(self)
514 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
515 write_safe("##[MONITOR][#{game_id}] +OK\n")
517 when /^%%MONITOROFF\s+(\S+)/
519 if (LEAGUE.games[game_id])
520 LEAGUE.games[game_id].monitoroff(self)
524 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
526 players = LEAGUE.rated_players
527 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
528 write_safe("##[RATING] %s \t %4d @%s\n" %
529 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
531 write_safe("##[RATING] +OK\n")
533 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
534 write_safe("##[VERSION] +OK\n")
536 if ((@status == "connected") || (@status == "game_waiting"))
537 @status = "connected"
540 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
542 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
546 if (! Login::good_game_name?(game_name))
547 write_safe(sprintf("##[ERROR] bad game name\n"))
549 elsif ((@status == "connected") || (@status == "game_waiting"))
552 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
555 if ((my_sente_str == "*") ||
556 (my_sente_str == "+") ||
557 (my_sente_str == "-"))
560 write_safe(sprintf("##[ERROR] bad game option\n"))
564 if (my_sente_str == "*")
565 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
566 elsif (my_sente_str == "+")
567 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
568 elsif (my_sente_str == "-")
569 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
574 @game_name = game_name
575 if ((my_sente_str == "*") && (rival.sente == nil))
583 elsif (rival.sente == true) # rival has higher priority
585 elsif (rival.sente == false)
587 elsif (my_sente_str == "+")
590 elsif (my_sente_str == "-")
596 Game::new(@game_name, self, rival)
597 self.status = "agree_waiting"
598 rival.status = "agree_waiting"
599 else # rival not found
600 if (command_name == "GAME")
601 @status = "game_waiting"
602 @game_name = game_name
603 if (my_sente_str == "+")
605 elsif (my_sente_str == "-")
611 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
612 @status = "connected"
617 when /^%%CHAT\s+(.+)/
619 LEAGUE.players.each do |name, player|
620 if (player.protocol != LoginCSA::PROTOCOL)
621 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
626 LEAGUE.games.each do |id, game|
627 buf.push(sprintf("##[LIST] %s\n", id))
629 buf.push("##[LIST] +OK\n")
633 LEAGUE.players.each do |name, player|
634 buf.push(sprintf("##[WHO] %s\n", player.to_s))
636 buf.push("##[WHO] +OK\n")
639 @status = "connected"
640 write_safe("LOGOUT:completed\n")
643 # This command is only available for CSA's official testing server.
644 # So, this means nothing for this program.
645 write_safe("CHALLENGE ACCEPTED\n")
647 ## ignore null string
649 msg = "##[ERROR] unknown command %s\n" % [str]
661 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
662 def initialize(board, x, y, sente, promoted=false)
669 if ((x == 0) || (y == 0))
671 hands = board.sente_hands
673 hands = board.gote_hands
680 @board.array[x][y] = self
683 attr_accessor :promoted, :sente, :x, :y, :board
685 def room_of_head?(x, y, name)
690 return adjacent_movable_grids + far_movable_grids
693 def far_movable_grids
698 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
699 if ((@board.array[x][y] == nil) || # dst is empty
700 (@board.array[x][y].sente != @sente)) # dst is enemy
708 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
709 if (@board.array[x][y] == nil) # dst is empty?
716 def adjacent_movable_grids
719 moves = @promoted_moves
721 moves = @normal_moves
723 moves.each do |(dx, dy)|
730 if (jump_to?(cand_x, cand_y))
731 grids.push([cand_x, cand_y])
737 def move_to?(x, y, name)
738 return false if (! room_of_head?(x, y, name))
739 return false if ((name != @name) && (name != @promoted_name))
740 return false if (@promoted && (name != @promoted_name)) # can't un-promote
743 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
745 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
747 return false if ((6 >= @y) && (6 >= y) && (name != @name))
751 if ((@x == 0) || (@y == 0))
752 return jump_to?(x, y)
754 return movable_grids.include?([x, y])
759 if ((@x == 0) || (@y == 0))
761 @board.sente_hands.delete(self)
763 @board.gote_hands.delete(self)
765 @board.array[x][y] = self
766 elsif ((x == 0) || (y == 0))
767 @promoted = false # clear promoted flag before moving to hands
769 @board.sente_hands.push(self)
771 @board.gote_hands.push(self)
773 @board.array[@x][@y] = nil
775 @board.array[@x][@y] = nil
776 @board.array[x][y] = self
809 class PieceFU < Piece
812 @normal_moves = [[0, +1]]
813 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
815 @promoted_name = "TO"
818 def room_of_head?(x, y, name)
821 return false if (y == 1)
823 return false if (y == 9)
829 if ((iy != @y) && # not source position
830 @board.array[x][iy] &&
831 (@board.array[x][iy].sente == @sente) && # mine
832 (@board.array[x][iy].name == "FU") &&
833 (@board.array[x][iy].promoted == false))
843 class PieceKY < Piece
847 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
849 @promoted_name = "NY"
852 def room_of_head?(x, y, name)
855 return false if (y == 1)
857 return false if (y == 9)
862 def far_movable_grids
870 while (jump_to?(cand_x, cand_y))
871 grids.push([cand_x, cand_y])
872 break if (! put_to?(cand_x, cand_y))
878 while (jump_to?(cand_x, cand_y))
879 grids.push([cand_x, cand_y])
880 break if (! put_to?(cand_x, cand_y))
888 class PieceKE < Piece
891 @normal_moves = [[+1, +2], [-1, +2]]
892 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
894 @promoted_name = "NK"
897 def room_of_head?(x, y, name)
900 return false if ((y == 1) || (y == 2))
902 return false if ((y == 9) || (y == 8))
908 class PieceGI < Piece
911 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
912 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
914 @promoted_name = "NG"
918 class PieceKI < Piece
921 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
928 class PieceKA < Piece
932 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
934 @promoted_name = "UM"
937 def far_movable_grids
942 while (jump_to?(cand_x, cand_y))
943 grids.push([cand_x, cand_y])
944 break if (! put_to?(cand_x, cand_y))
951 while (jump_to?(cand_x, cand_y))
952 grids.push([cand_x, cand_y])
953 break if (! put_to?(cand_x, cand_y))
960 while (jump_to?(cand_x, cand_y))
961 grids.push([cand_x, cand_y])
962 break if (! put_to?(cand_x, cand_y))
969 while (jump_to?(cand_x, cand_y))
970 grids.push([cand_x, cand_y])
971 break if (! put_to?(cand_x, cand_y))
978 class PieceHI < Piece
982 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
984 @promoted_name = "RY"
987 def far_movable_grids
992 while (jump_to?(cand_x, cand_y))
993 grids.push([cand_x, cand_y])
994 break if (! put_to?(cand_x, cand_y))
1000 while (jump_to?(cand_x, cand_y))
1001 grids.push([cand_x, cand_y])
1002 break if (! put_to?(cand_x, cand_y))
1008 while (jump_to?(cand_x, cand_y))
1009 grids.push([cand_x, cand_y])
1010 break if (! put_to?(cand_x, cand_y))
1016 while (jump_to?(cand_x, cand_y))
1017 grids.push([cand_x, cand_y])
1018 break if (! put_to?(cand_x, cand_y))
1024 class PieceOU < Piece
1025 def initialize(*arg)
1027 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1028 @promoted_moves = []
1030 @promoted_name = nil
1037 @sente_hands = Array::new
1038 @gote_hands = Array::new
1039 @history = Hash::new
1040 @sente_history = Hash::new
1041 @gote_history = Hash::new
1042 @array = [[], [], [], [], [], [], [], [], [], []]
1045 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1046 attr_reader :move_count
1049 PieceKY::new(self, 1, 1, false)
1050 PieceKE::new(self, 2, 1, false)
1051 PieceGI::new(self, 3, 1, false)
1052 PieceKI::new(self, 4, 1, false)
1053 PieceOU::new(self, 5, 1, false)
1054 PieceKI::new(self, 6, 1, false)
1055 PieceGI::new(self, 7, 1, false)
1056 PieceKE::new(self, 8, 1, false)
1057 PieceKY::new(self, 9, 1, false)
1058 PieceKA::new(self, 2, 2, false)
1059 PieceHI::new(self, 8, 2, false)
1061 PieceFU::new(self, i, 3, false)
1064 PieceKY::new(self, 1, 9, true)
1065 PieceKE::new(self, 2, 9, true)
1066 PieceGI::new(self, 3, 9, true)
1067 PieceKI::new(self, 4, 9, true)
1068 PieceOU::new(self, 5, 9, true)
1069 PieceKI::new(self, 6, 9, true)
1070 PieceGI::new(self, 7, 9, true)
1071 PieceKE::new(self, 8, 9, true)
1072 PieceKY::new(self, 9, 9, true)
1073 PieceKA::new(self, 8, 8, true)
1074 PieceHI::new(self, 2, 8, true)
1076 PieceFU::new(self, i, 7, true)
1080 def have_piece?(hands, name)
1081 piece = hands.find { |i|
1087 def move_to(x0, y0, x1, y1, name, sente)
1089 hands = @sente_hands
1094 if ((x0 == 0) || (y0 == 0))
1095 piece = have_piece?(hands, name)
1096 return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
1097 piece.move_to(x1, y1)
1099 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name)) # TODO null check?
1100 if (@array[x0][y0].name != name) # promoted ?
1101 @array[x0][y0].promoted = true
1103 if (@array[x1][y1]) # capture
1104 if (@array[x1][y1].name == "OU")
1105 return :outori # return board update
1107 @array[x1][y1].sente = @array[x0][y0].sente
1108 @array[x1][y1].move_to(0, 0)
1109 hands.sort! {|a, b| # TODO refactor. Move to Piece class
1113 @array[x0][y0].move_to(x1, y1)
1119 def look_for_ou(sente)
1125 (@array[x][y].name == "OU") &&
1126 (@array[x][y].sente == sente))
1133 raise "can't find ou"
1136 # note checkmate, but check. sente is checked.
1137 def checkmated?(sente) # sente is loosing
1138 ou = look_for_ou(sente)
1144 (@array[x][y].sente != sente))
1145 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1156 def uchifuzume?(sente)
1157 rival_ou = look_for_ou(! sente) # rival's ou
1158 if (sente) # rival is gote
1159 if ((rival_ou.y != 9) &&
1160 (@array[rival_ou.x][rival_ou.y + 1]) &&
1161 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1162 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1164 fu_y = rival_ou.y + 1
1169 if ((rival_ou.y != 0) &&
1170 (@array[rival_ou.x][rival_ou.y - 1]) &&
1171 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1172 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1174 fu_y = rival_ou.y - 1
1180 ## case: rival_ou is moving
1182 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1183 tmp_board = Marshal.load(Marshal.dump(self))
1184 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1185 raise "internal error" if (s != true)
1186 if (! tmp_board.checkmated?(! sente)) # good move
1191 ## case: rival is capturing fu
1197 (@array[x][y].sente != sente) &&
1198 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1199 if (@array[x][y].promoted)
1200 name = @array[x][y].promoted_name
1202 name = @array[x][y].name
1204 tmp_board = Marshal.load(Marshal.dump(self))
1205 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1206 raise "internal error" if (s != true)
1207 if (! tmp_board.checkmated?(! sente)) # good move
1218 def oute_sennichite?(sente)
1219 if (checkmated?(! sente))
1222 if (@sente_history[str] && (@sente_history[str] >= 3)) # already 3 times
1226 if (@gote_history[str] && (@gote_history[str] >= 3)) # already 3 times
1234 def sennichite?(sente)
1236 if (@history[str] && (@history[str] >= 3)) # already 3 times
1242 def good_kachi?(sente)
1243 if (checkmated?(sente))
1244 puts "'NG: Checkmating." if $DEBUG
1248 ou = look_for_ou(sente)
1249 if (sente && (ou.y >= 4))
1250 puts "'NG: Black's OU does not enter yet." if $DEBUG
1253 if (! sente && (ou.y <= 6))
1254 puts "'NG: White's OU does not enter yet." if $DEBUG
1262 hands = @sente_hands
1272 (@array[x][y].sente == sente) &&
1273 (@array[x][y].point > 0))
1274 point = point + @array[x][y].point
1280 hands.each do |piece|
1281 point = point + piece.point
1285 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1290 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1295 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1300 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1304 # sente is nil only if tests in test_board run
1305 def handle_one_move(str, sente=nil)
1306 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1313 elsif (str =~ /^%KACHI/)
1314 raise ArgumentError, "sente is null", caller if sente == nil
1315 if (good_kachi?(sente))
1320 elsif (str =~ /^%TORYO/)
1326 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1327 ((x0 != 0) || (y0 != 0)))
1329 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1335 sente = true if sente == nil # deprecated
1336 return :illegal unless sente == true # black player's move must be black
1337 hands = @sente_hands
1339 sente = false if sente == nil # deprecated
1340 return :illegal unless sente == false # white player's move must be white
1345 if ((x0 == 0) && (y0 == 0))
1346 return :illegal if (! have_piece?(hands, name))
1347 elsif (! @array[x0][y0])
1348 return :illegal # no piece
1349 elsif (@array[x0][y0].sente != sente)
1350 return :illegal # this is not mine
1351 elsif (@array[x0][y0].name != name)
1352 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1355 ## destination check
1356 if (@array[x1][y1] &&
1357 (@array[x1][y1].sente == sente)) # can't capture mine
1359 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1360 return :illegal # can't put on existing piece
1363 tmp_board = Marshal.load(Marshal.dump(self))
1364 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1365 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1366 return :oute_sennichite if tmp_board.oute_sennichite?(sente)
1367 return :sennichite if tmp_board.sennichite?(sente)
1369 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1373 move_to(x0, y0, x1, y1, name, sente)
1376 if (checkmated?(! sente))
1378 @sente_history[str] = (@sente_history[str] || 0) + 1
1380 @gote_history[str] = (@gote_history[str] || 0) + 1
1384 @sente_history.clear
1389 @history[str] = (@history[str] || 0) + 1
1397 a.push(sprintf("P%d", y))
1400 piece = @array[x][y]
1409 a.push(sprintf("\n"))
1412 if (! sente_hands.empty?)
1414 sente_hands.each do |p|
1415 a.push("00" + p.name)
1419 if (! gote_hands.empty?)
1421 gote_hands.each do |p|
1422 a.push("00" + p.name)
1432 attr_reader :players, :black, :white
1434 def initialize(p1, p2)
1438 if p1.sente && !p2.sente
1439 @black, @white = p1, p2
1440 elsif !p1.sente && p2.sente
1441 @black, @white = p2, p1
1443 raise "Never reached!"
1448 class GameResultWin < GameResult
1449 attr_reader :winner, :loser
1451 def initialize(winner, loser)
1453 @winner, @loser = winner, loser
1457 black_name = @black.id || @black.name
1458 white_name = @white.id || @white.name
1459 "%s:%s" % [black_name, white_name]
1463 class GameResultDraw < GameResult
1471 def initialize(game_name, player0, player1)
1472 @monitors = Array::new
1473 @game_name = game_name
1474 if (@game_name =~ /-(\d+)-(\d+)$/)
1475 @total_time = $1.to_i
1486 @current_player = @sente
1487 @next_player = @gote
1495 @sente.status = "agree_waiting"
1496 @gote.status = "agree_waiting"
1498 @id = sprintf("%s+%s+%s+%s+%s",
1499 LEAGUE.event, @game_name, @sente.name, @gote.name, issue_current_time)
1500 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1502 LEAGUE.games[@id] = self
1504 log_message(sprintf("game created %s", @id))
1514 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1515 attr_accessor :last_move, :current_turn
1519 @sente.rated? && @gote.rated?
1522 def monitoron(monitor)
1523 @monitors.delete(monitor)
1524 @monitors.push(monitor)
1527 def monitoroff(monitor)
1528 @monitors.delete(monitor)
1531 def reject(rejector)
1532 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1533 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1538 if ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
1540 elsif (@current_player == killer)
1547 log_message(sprintf("game finished %s", @id))
1548 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1553 @sente.status = "connected"
1554 @gote.status = "connected"
1556 if (@current_player.protocol == LoginCSA::PROTOCOL)
1557 @current_player.finish
1559 if (@next_player.protocol == LoginCSA::PROTOCOL)
1562 @monitors = Array::new
1565 @current_player = nil
1567 LEAGUE.games.delete(@id)
1570 def handle_one_move(str, player)
1572 if (@current_player == player)
1573 @end_time = Time::new
1574 t = (@end_time - @start_time).floor
1575 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
1578 if ((@current_player.mytime - t <= -@byoyomi) && ((@total_time > 0) || (@byoyomi > 0)))
1580 elsif (str == :timeout)
1581 return false # time isn't expired. players aren't swapped. continue game
1583 @current_player.mytime = @current_player.mytime - t
1584 if (@current_player.mytime < 0)
1585 @current_player.mytime = 0
1589 move_status = @board.handle_one_move(str, @sente == @current_player)
1591 # log_error("handle_one_move raise exception for #{str}")
1592 # move_status = :illegal
1595 if ((move_status == :illegal) || (move_status == :uchifuzme) || (move_status == :oute_kaihimore))
1596 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1598 if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite))
1599 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1600 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1601 @fh.printf("%s\nT%d\n", str, t)
1602 @last_move = sprintf("%s,T%d", str, t)
1603 @current_turn = @current_turn + 1
1606 @monitors.each do |monitor|
1607 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1608 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1613 if (@next_player.status != "game") # rival is logout or disconnected
1615 elsif (status == :timeout)
1617 elsif (move_status == :illegal)
1619 elsif (move_status == :kachi_win)
1621 elsif (move_status == :kachi_lose)
1623 elsif (move_status == :toryo)
1625 elsif (move_status == :outori)
1627 elsif (move_status == :sennichite)
1629 elsif (move_status == :oute_sennichite)
1630 oute_sennichite_lose()
1631 elsif (move_status == :uchifuzume)
1633 elsif (move_status == :oute_kaihimore)
1634 oute_kaihimore_lose()
1638 finish() if finish_flag
1639 (@current_player, @next_player) = [@next_player, @current_player]
1640 @start_time = Time::new
1646 @current_player.status = "connected"
1647 @next_player.status = "connected"
1648 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1649 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1650 @fh.printf("%%TORYO\n")
1651 @fh.print(@board.to_s.gsub(/^/, "\'"))
1652 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1653 @result = GameResultWin.new(@current_player, @next_player)
1654 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1655 @monitors.each do |monitor|
1656 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1661 @current_player.status = "connected"
1662 @next_player.status = "connected"
1663 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1664 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1665 @fh.printf("%%TORYO\n")
1666 @fh.print(@board.to_s.gsub(/^/, "\'"))
1667 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1668 @result = GameResultWin.new(@next_player, @current_player)
1669 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1670 @monitors.each do |monitor|
1671 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1676 @current_player.status = "connected"
1677 @next_player.status = "connected"
1678 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1679 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1680 @fh.print(@board.to_s.gsub(/^/, "\'"))
1681 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1682 @result = GameResultDraw.new(@current_player, @next_player)
1683 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1684 @monitors.each do |monitor|
1685 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @id))
1689 def oute_sennichite_lose
1690 @current_player.status = "connected"
1691 @next_player.status = "connected"
1692 @current_player.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1693 @next_player.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1694 @fh.print(@board.to_s.gsub(/^/, "\'"))
1695 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1696 @result = GameResultWin.new(@next_player, @current_player)
1697 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1698 @monitors.each do |monitor|
1699 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1704 @current_player.status = "connected"
1705 @next_player.status = "connected"
1706 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1707 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1708 @fh.print(@board.to_s.gsub(/^/, "\'"))
1709 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1710 @result = GameResultWin.new(@next_player, @current_player)
1711 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1712 @monitors.each do |monitor|
1713 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1718 @current_player.status = "connected"
1719 @next_player.status = "connected"
1720 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1721 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1722 @fh.print(@board.to_s.gsub(/^/, "\'"))
1723 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1724 @result = GameResultWin.new(@next_player, @current_player)
1725 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1726 @monitors.each do |monitor|
1727 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1731 def oute_kaihimore_lose
1732 @current_player.status = "connected"
1733 @next_player.status = "connected"
1734 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1735 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1736 @fh.print(@board.to_s.gsub(/^/, "\'"))
1737 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1738 @result = GameResultWin.new(@next_player, @current_player)
1739 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1740 @monitors.each do |monitor|
1741 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1746 @current_player.status = "connected"
1747 @next_player.status = "connected"
1748 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1749 @next_player.write_safe("#TIME_UP\n#WIN\n")
1750 @fh.print(@board.to_s.gsub(/^/, "\'"))
1751 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1752 @result = GameResultWin.new(@next_player, @current_player)
1753 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1754 @monitors.each do |monitor|
1755 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
1760 @current_player.status = "connected"
1761 @next_player.status = "connected"
1762 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1763 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1764 @fh.printf("%%KACHI\n")
1765 @fh.print(@board.to_s.gsub(/^/, "\'"))
1766 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1767 @result = GameResultWin.new(@current_player, @next_player)
1768 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1769 @monitors.each do |monitor|
1770 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1775 @current_player.status = "connected"
1776 @next_player.status = "connected"
1777 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1778 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1779 @fh.printf("%%KACHI\n")
1780 @fh.print(@board.to_s.gsub(/^/, "\'"))
1781 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1782 @result = GameResultWin.new(@next_player, @current_player)
1783 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1784 @monitors.each do |monitor|
1785 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1790 @current_player.status = "connected"
1791 @next_player.status = "connected"
1792 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1793 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1794 @fh.printf("%%TORYO\n")
1795 @fh.print(@board.to_s.gsub(/^/, "\'"))
1796 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1797 @result = GameResultWin.new(@next_player, @current_player)
1798 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1799 @monitors.each do |monitor|
1800 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1805 @current_player.status = "connected"
1806 @next_player.status = "connected"
1807 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1808 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1809 @fh.print(@board.to_s.gsub(/^/, "\'"))
1810 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1811 @result = GameResultWin.new(@current_player, @next_player)
1812 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1813 @monitors.each do |monitor|
1814 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1819 log_message(sprintf("game started %s", @id))
1820 @sente.write_safe(sprintf("START:%s\n", @id))
1821 @gote.write_safe(sprintf("START:%s\n", @id))
1822 @sente.mytime = @total_time
1823 @gote.mytime = @total_time
1824 @start_time = Time::new
1829 @fh = open(@logfile, "w")
1833 @fh.printf("N+%s\n", @sente.name)
1834 @fh.printf("N-%s\n", @gote.name)
1835 @fh.printf("$EVENT:%s\n", @id)
1837 @sente.write_safe(propose_message("+"))
1838 @gote.write_safe(propose_message("-"))
1840 @fh.printf("$START_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1842 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1843 P2 * -HI * * * * * -KA *
1844 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1845 P4 * * * * * * * * *
1846 P5 * * * * * * * * *
1847 P6 * * * * * * * * *
1848 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1849 P8 * +KA * * * * * +HI *
1850 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1859 Protocol_Version:1.1
1860 Protocol_Mode:Server
1862 Declaration:Jishogi 1.1
1864 Name+:#{@sente.name}
1870 Total_Time:#{@total_time}
1872 Least_Time_Per_Move:#{Least_Time_Per_Move}
1873 Remaining_Time+:#{@sente.mytime}
1874 Remaining_Time-:#{@gote.mytime}
1875 Last_Move:#{@last_move}
1876 Current_Turn:#{@current_turn}
1886 return str0 + @board.to_s + str1
1889 def propose_message(sg_flag)
1892 Protocol_Version:1.1
1893 Protocol_Mode:Server
1895 Declaration:Jishogi 1.1
1897 Name+:#{@sente.name}
1899 Your_Turn:#{sg_flag}
1904 Total_Time:#{@total_time}
1906 Least_Time_Per_Move:#{Least_Time_Per_Move}
1909 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1910 P2 * -HI * * * * * -KA *
1911 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1912 P4 * * * * * * * * *
1913 P5 * * * * * * * * *
1914 P6 * * * * * * * * *
1915 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1916 P8 * +KA * * * * * +HI *
1917 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1929 def issue_current_time
1930 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
1931 @@mutex.synchronize do
1932 while time <= @@time do
1939 end # module ShogiServer
1941 #################################################
1948 shogi-server - server for CSA server protocol
1951 shogi-server [OPTIONS] event_name port_number
1954 server for CSA server protocol
1958 specify filename for logging process ID
1960 run as a daemon. Log files will be put in dir.
1963 this file is distributed under GPL version2 and might be compiled by Exerb
1968 #{ShogiServer::Release}
1971 #{ShogiServer::Revision}
1975 def log_message(str)
1979 def log_warning(str)
1988 def parse_command_line
1990 parser = GetoptLong.new( ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
1991 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT]
1995 parser.each_option do |name, arg|
1996 name.sub!(/^--/, '')
1997 options[name] = arg.dup
2001 raise parser.error_message
2006 def write_pid_file(file)
2007 open(file, "w") do |fh|
2008 fh.print Process::pid, "\n"
2012 def mutex_watchdog(mutex, sec)
2024 log_error("mutex watchdog timeout")
2035 mutex_watchdog($mutex, 10)
2038 $options = parse_command_line
2039 if (ARGV.length != 2)
2044 LEAGUE.event = ARGV.shift
2047 write_pid_file($options["pid-file"]) if ($options["pid-file"])
2049 dir = $options["daemon"] || nil
2050 if dir && ! File.exist?(dir)
2051 FileUtils.mkdir(dir)
2053 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2054 $logger = WEBrick::Log.new(log_file)
2056 LEAGUE.dir = dir || File.dirname(__FILE__)
2057 LEAGUE.setup_players_database
2060 config[:Port] = port
2061 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2062 config[:Logger] = $logger
2064 server = WEBrick::GenericServer.new(config)
2065 ["INT", "TERM"].each {|signal| trap(signal){ server.shutdown } }
2066 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
2067 log_message("server started [Revision: #{ShogiServer::Revision}]")
2069 server.start do |client|
2070 # client.sync = true # this is already set in WEBrick
2071 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2072 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2075 while (str = client.gets_timeout(ShogiServer::Login_Time))
2080 if (ShogiServer::Login::good_login?(str))
2081 player = ShogiServer::Player::new(str, client)
2083 login = ShogiServer::Login::factory(str, player)
2084 if (LEAGUE.players[player.name])
2085 if ((LEAGUE.players[player.name].password == player.password) &&
2086 (LEAGUE.players[player.name].status != "game"))
2087 log_message(sprintf("user %s login forcely", player.name))
2088 LEAGUE.players[player.name].kill
2090 login.incorrect_duplicated_player(str)
2101 client.write_safe("LOGIN:incorrect" + eol)
2102 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2114 log_message(sprintf("user %s login", player.name))
2116 player.run(login.csa_1st_str)
2120 player.game.kill(player)
2122 player.finish # socket has been closed
2123 LEAGUE.delete(player)
2124 log_message(sprintf("user %s logout", player.name))
2135 TCPSocket.do_not_reverse_lookup = true
2136 Thread.abort_on_exception = true
2138 LEAGUE = ShogiServer::League::new