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)))
431 if (@writer_thread == nil || @writer_thread.status == false)
432 # The writer_thread has been killed because of socket errors.
441 if (@write_queue.size > Max_Write_Queue_Size)
442 log_warning(sprintf("write_queue of %s is %d", @name, @write_queue.size))
446 if (@status == "finished")
449 str.chomp! if (str.class == String) # may be strip! ?
452 # Application-level protocol for Keep-Alive
453 # If the server gets LF, it sends back LF.
454 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
457 if (@status == "game")
458 array_str = str.split(",")
459 move = array_str.shift
460 additional = array_str.shift
461 if /^'(.*)/ =~ additional
462 comment = array_str.unshift("'*#{$1}")
464 s = @game.handle_one_move(move, self)
465 @game.fh.print("#{comment}\n") if (comment && !s)
466 return if (s && @protocol == LoginCSA::PROTOCOL)
468 when /^%[^%]/, :timeout
469 if (@status == "game")
470 s = @game.handle_one_move(str, self)
471 return if (s && @protocol == LoginCSA::PROTOCOL)
474 # @socket.write("##[KEEPALIVE] #{Time.now}\n")
475 # rescue Exception => ex
476 # log_error("Failed to send a keepalive to #{@name}.")
477 # log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
482 log_error("Failed to receive a message from #{@name}.")
485 if (@status == "agree_waiting")
487 return if (@protocol == LoginCSA::PROTOCOL)
489 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
492 if (@status == "agree_waiting")
493 @status = "start_waiting"
494 if ((@game.sente.status == "start_waiting") &&
495 (@game.gote.status == "start_waiting"))
497 @game.sente.status = "game"
498 @game.gote.status = "game"
501 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
503 when /^%%SHOW\s+(\S+)/
505 if (LEAGUE.games[game_id])
506 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
508 write_safe("##[SHOW] +OK\n")
509 when /^%%MONITORON\s+(\S+)/
511 if (LEAGUE.games[game_id])
512 LEAGUE.games[game_id].monitoron(self)
513 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
514 write_safe("##[MONITOR][#{game_id}] +OK\n")
516 when /^%%MONITOROFF\s+(\S+)/
518 if (LEAGUE.games[game_id])
519 LEAGUE.games[game_id].monitoroff(self)
523 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
525 players = LEAGUE.rated_players
526 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
527 write_safe("##[RATING] %s \t %4d @%s\n" %
528 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
530 write_safe("##[RATING] +OK\n")
532 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
533 write_safe("##[VERSION] +OK\n")
535 if ((@status == "connected") || (@status == "game_waiting"))
536 @status = "connected"
539 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
541 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
545 if (! Login::good_game_name?(game_name))
546 write_safe(sprintf("##[ERROR] bad game name\n"))
548 elsif ((@status == "connected") || (@status == "game_waiting"))
551 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
554 if ((my_sente_str == "*") ||
555 (my_sente_str == "+") ||
556 (my_sente_str == "-"))
559 write_safe(sprintf("##[ERROR] bad game option\n"))
563 if (my_sente_str == "*")
564 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
565 elsif (my_sente_str == "+")
566 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
567 elsif (my_sente_str == "-")
568 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
573 @game_name = game_name
574 if ((my_sente_str == "*") && (rival.sente == nil))
582 elsif (rival.sente == true) # rival has higher priority
584 elsif (rival.sente == false)
586 elsif (my_sente_str == "+")
589 elsif (my_sente_str == "-")
595 Game::new(@game_name, self, rival)
596 self.status = "agree_waiting"
597 rival.status = "agree_waiting"
598 else # rival not found
599 if (command_name == "GAME")
600 @status = "game_waiting"
601 @game_name = game_name
602 if (my_sente_str == "+")
604 elsif (my_sente_str == "-")
610 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
611 @status = "connected"
616 when /^%%CHAT\s+(.+)/
618 LEAGUE.players.each do |name, player|
619 if (player.protocol != LoginCSA::PROTOCOL)
620 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
625 LEAGUE.games.each do |id, game|
626 buf.push(sprintf("##[LIST] %s\n", id))
628 buf.push("##[LIST] +OK\n")
632 LEAGUE.players.each do |name, player|
633 buf.push(sprintf("##[WHO] %s\n", player.to_s))
635 buf.push("##[WHO] +OK\n")
638 @status = "connected"
639 write_safe("LOGOUT:completed\n")
642 # This command is only available for CSA's official testing server.
643 # So, this means nothing for this program.
644 write_safe("CHALLENGE ACCEPTED\n")
646 ## ignore null string
648 msg = "##[ERROR] unknown command %s\n" % [str]
660 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
661 def initialize(board, x, y, sente, promoted=false)
668 if ((x == 0) || (y == 0))
670 hands = board.sente_hands
672 hands = board.gote_hands
679 @board.array[x][y] = self
682 attr_accessor :promoted, :sente, :x, :y, :board
684 def room_of_head?(x, y, name)
689 return adjacent_movable_grids + far_movable_grids
692 def far_movable_grids
697 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
698 if ((@board.array[x][y] == nil) || # dst is empty
699 (@board.array[x][y].sente != @sente)) # dst is enemy
707 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
708 if (@board.array[x][y] == nil) # dst is empty?
715 def adjacent_movable_grids
718 moves = @promoted_moves
720 moves = @normal_moves
722 moves.each do |(dx, dy)|
729 if (jump_to?(cand_x, cand_y))
730 grids.push([cand_x, cand_y])
736 def move_to?(x, y, name)
737 return false if (! room_of_head?(x, y, name))
738 return false if ((name != @name) && (name != @promoted_name))
739 return false if (@promoted && (name != @promoted_name)) # can't un-promote
742 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
744 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
746 return false if ((6 >= @y) && (6 >= y) && (name != @name))
750 if ((@x == 0) || (@y == 0))
751 return jump_to?(x, y)
753 return movable_grids.include?([x, y])
758 if ((@x == 0) || (@y == 0))
760 @board.sente_hands.delete(self)
762 @board.gote_hands.delete(self)
764 @board.array[x][y] = self
765 elsif ((x == 0) || (y == 0))
766 @promoted = false # clear promoted flag before moving to hands
768 @board.sente_hands.push(self)
770 @board.gote_hands.push(self)
772 @board.array[@x][@y] = nil
774 @board.array[@x][@y] = nil
775 @board.array[x][y] = self
808 class PieceFU < Piece
811 @normal_moves = [[0, +1]]
812 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
814 @promoted_name = "TO"
817 def room_of_head?(x, y, name)
820 return false if (y == 1)
822 return false if (y == 9)
828 if ((iy != @y) && # not source position
829 @board.array[x][iy] &&
830 (@board.array[x][iy].sente == @sente) && # mine
831 (@board.array[x][iy].name == "FU") &&
832 (@board.array[x][iy].promoted == false))
842 class PieceKY < Piece
846 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
848 @promoted_name = "NY"
851 def room_of_head?(x, y, name)
854 return false if (y == 1)
856 return false if (y == 9)
861 def far_movable_grids
869 while (jump_to?(cand_x, cand_y))
870 grids.push([cand_x, cand_y])
871 break if (! put_to?(cand_x, cand_y))
877 while (jump_to?(cand_x, cand_y))
878 grids.push([cand_x, cand_y])
879 break if (! put_to?(cand_x, cand_y))
887 class PieceKE < Piece
890 @normal_moves = [[+1, +2], [-1, +2]]
891 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
893 @promoted_name = "NK"
896 def room_of_head?(x, y, name)
899 return false if ((y == 1) || (y == 2))
901 return false if ((y == 9) || (y == 8))
907 class PieceGI < Piece
910 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
911 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
913 @promoted_name = "NG"
917 class PieceKI < Piece
920 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
927 class PieceKA < Piece
931 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
933 @promoted_name = "UM"
936 def far_movable_grids
941 while (jump_to?(cand_x, cand_y))
942 grids.push([cand_x, cand_y])
943 break if (! put_to?(cand_x, cand_y))
950 while (jump_to?(cand_x, cand_y))
951 grids.push([cand_x, cand_y])
952 break if (! put_to?(cand_x, cand_y))
959 while (jump_to?(cand_x, cand_y))
960 grids.push([cand_x, cand_y])
961 break if (! put_to?(cand_x, cand_y))
968 while (jump_to?(cand_x, cand_y))
969 grids.push([cand_x, cand_y])
970 break if (! put_to?(cand_x, cand_y))
977 class PieceHI < Piece
981 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
983 @promoted_name = "RY"
986 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))
1007 while (jump_to?(cand_x, cand_y))
1008 grids.push([cand_x, cand_y])
1009 break if (! put_to?(cand_x, cand_y))
1015 while (jump_to?(cand_x, cand_y))
1016 grids.push([cand_x, cand_y])
1017 break if (! put_to?(cand_x, cand_y))
1023 class PieceOU < Piece
1024 def initialize(*arg)
1026 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1027 @promoted_moves = []
1029 @promoted_name = nil
1036 @sente_hands = Array::new
1037 @gote_hands = Array::new
1038 @history = Hash::new
1039 @sente_history = Hash::new
1040 @gote_history = Hash::new
1041 @array = [[], [], [], [], [], [], [], [], [], []]
1044 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1045 attr_reader :move_count
1048 PieceKY::new(self, 1, 1, false)
1049 PieceKE::new(self, 2, 1, false)
1050 PieceGI::new(self, 3, 1, false)
1051 PieceKI::new(self, 4, 1, false)
1052 PieceOU::new(self, 5, 1, false)
1053 PieceKI::new(self, 6, 1, false)
1054 PieceGI::new(self, 7, 1, false)
1055 PieceKE::new(self, 8, 1, false)
1056 PieceKY::new(self, 9, 1, false)
1057 PieceKA::new(self, 2, 2, false)
1058 PieceHI::new(self, 8, 2, false)
1059 PieceFU::new(self, 1, 3, false)
1060 PieceFU::new(self, 2, 3, false)
1061 PieceFU::new(self, 3, 3, false)
1062 PieceFU::new(self, 4, 3, false)
1063 PieceFU::new(self, 5, 3, false)
1064 PieceFU::new(self, 6, 3, false)
1065 PieceFU::new(self, 7, 3, false)
1066 PieceFU::new(self, 8, 3, false)
1067 PieceFU::new(self, 9, 3, false)
1069 PieceKY::new(self, 1, 9, true)
1070 PieceKE::new(self, 2, 9, true)
1071 PieceGI::new(self, 3, 9, true)
1072 PieceKI::new(self, 4, 9, true)
1073 PieceOU::new(self, 5, 9, true)
1074 PieceKI::new(self, 6, 9, true)
1075 PieceGI::new(self, 7, 9, true)
1076 PieceKE::new(self, 8, 9, true)
1077 PieceKY::new(self, 9, 9, true)
1078 PieceKA::new(self, 8, 8, true)
1079 PieceHI::new(self, 2, 8, true)
1080 PieceFU::new(self, 1, 7, true)
1081 PieceFU::new(self, 2, 7, true)
1082 PieceFU::new(self, 3, 7, true)
1083 PieceFU::new(self, 4, 7, true)
1084 PieceFU::new(self, 5, 7, true)
1085 PieceFU::new(self, 6, 7, true)
1086 PieceFU::new(self, 7, 7, true)
1087 PieceFU::new(self, 8, 7, true)
1088 PieceFU::new(self, 9, 7, true)
1091 def have_piece?(hands, name)
1092 piece = hands.find { |i|
1098 def move_to(x0, y0, x1, y1, name, sente)
1100 hands = @sente_hands
1105 if ((x0 == 0) || (y0 == 0))
1106 piece = have_piece?(hands, name)
1107 return :illegal if (! piece.move_to?(x1, y1, name))
1108 piece.move_to(x1, y1)
1110 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name))
1111 if (@array[x0][y0].name != name) # promoted ?
1112 @array[x0][y0].promoted = true
1115 if (@array[x1][y1].name == "OU")
1116 return :outori # return board update
1118 @array[x1][y1].sente = @array[x0][y0].sente
1119 @array[x1][y1].move_to(0, 0)
1124 @array[x0][y0].move_to(x1, y1)
1130 def look_for_ou(sente)
1136 (@array[x][y].name == "OU") &&
1137 (@array[x][y].sente == sente))
1144 raise "can't find ou"
1147 def checkmated?(sente) # sente is loosing
1148 ou = look_for_ou(sente)
1154 (@array[x][y].sente != sente))
1155 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1166 def uchifuzume?(sente)
1167 rival_ou = look_for_ou(! sente) # rival's ou
1168 if (sente) # rival is gote
1169 if ((rival_ou.y != 9) &&
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
1179 if ((rival_ou.y != 0) &&
1180 (@array[rival_ou.x][rival_ou.y - 1]) &&
1181 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1182 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1184 fu_y = rival_ou.y - 1
1190 ## case: rival_ou is moving
1192 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1193 tmp_board = Marshal.load(Marshal.dump(self))
1194 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1195 raise "internal error" if (s != true)
1196 if (! tmp_board.checkmated?(! sente)) # good move
1201 ## case: rival is capturing fu
1207 (@array[x][y].sente != sente) &&
1208 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1209 if (@array[x][y].promoted)
1210 name = @array[x][y].promoted_name
1212 name = @array[x][y].name
1214 tmp_board = Marshal.load(Marshal.dump(self))
1215 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1216 raise "internal error" if (s != true)
1217 if (! tmp_board.checkmated?(! sente)) # good move
1228 def oute_sennichite?(sente)
1229 if (checkmated?(! sente))
1232 if (@sente_history[str] && (@sente_history[str] >= 3)) # already 3 times
1236 if (@gote_history[str] && (@gote_history[str] >= 3)) # already 3 times
1244 def sennichite?(sente)
1246 if (@history[str] && (@history[str] >= 3)) # already 3 times
1252 def good_kachi?(sente)
1253 if (checkmated?(sente))
1254 puts "'NG: Checkmating." if $DEBUG
1258 ou = look_for_ou(sente)
1259 if (sente && (ou.y >= 4))
1260 puts "'NG: Black's OU does not enter yet." if $DEBUG
1263 if (! sente && (ou.y <= 6))
1264 puts "'NG: White's OU does not enter yet." if $DEBUG
1272 hands = @sente_hands
1282 (@array[x][y].sente == sente) &&
1283 (@array[x][y].point > 0))
1284 point = point + @array[x][y].point
1290 hands.each do |piece|
1291 point = point + piece.point
1295 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1300 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1305 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1310 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1314 # sente is nil only if tests in test_board run
1315 def handle_one_move(str, sente=nil)
1316 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1323 elsif (str =~ /^%KACHI/)
1324 raise ArgumentError, "sente is null", caller if sente == nil
1325 if (good_kachi?(sente))
1330 elsif (str =~ /^%TORYO/)
1336 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1337 ((x0 != 0) || (y0 != 0)))
1339 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1345 sente = true if sente == nil # deprecated
1346 return :illegal unless sente == true # black player's move must be black
1347 hands = @sente_hands
1349 sente = false if sente == nil # deprecated
1350 return :illegal unless sente == false # white player's move must be white
1355 if ((x0 == 0) && (y0 == 0))
1356 return :illegal if (! have_piece?(hands, name))
1357 elsif (! @array[x0][y0])
1358 return :illegal # no piece
1359 elsif (@array[x0][y0].sente != sente)
1360 return :illegal # this is not mine
1361 elsif (@array[x0][y0].name != name)
1362 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1365 ## destination check
1366 if (@array[x1][y1] &&
1367 (@array[x1][y1].sente == sente)) # can't capture mine
1369 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1370 return :illegal # can't put on existing piece
1373 tmp_board = Marshal.load(Marshal.dump(self))
1374 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1375 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1376 return :oute_sennichite if tmp_board.oute_sennichite?(sente)
1377 return :sennichite if tmp_board.sennichite?(sente)
1379 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1383 move_to(x0, y0, x1, y1, name, sente)
1386 if (checkmated?(! sente))
1388 @sente_history[str] = (@sente_history[str] || 0) + 1
1390 @gote_history[str] = (@gote_history[str] || 0) + 1
1394 @sente_history.clear
1399 @history[str] = (@history[str] || 0) + 1
1407 a.push(sprintf("P%d", y))
1410 piece = @array[x][y]
1419 a.push(sprintf("\n"))
1422 if (! sente_hands.empty?)
1424 sente_hands.each do |p|
1425 a.push("00" + p.name)
1429 if (! gote_hands.empty?)
1431 gote_hands.each do |p|
1432 a.push("00" + p.name)
1442 attr_reader :players, :black, :white
1444 def initialize(p1, p2)
1448 if p1.sente && !p2.sente
1449 @black, @white = p1, p2
1450 elsif !p1.sente && p2.sente
1451 @black, @white = p2, p1
1453 raise "Never reached!"
1458 class GameResultWin < GameResult
1459 attr_reader :winner, :loser
1461 def initialize(winner, loser)
1463 @winner, @loser = winner, loser
1467 black_name = @black.id || @black.name
1468 white_name = @white.id || @white.name
1469 "%s:%s" % [black_name, white_name]
1473 class GameResultDraw < GameResult
1481 def initialize(game_name, player0, player1)
1482 @monitors = Array::new
1483 @game_name = game_name
1484 if (@game_name =~ /-(\d+)-(\d+)$/)
1485 @total_time = $1.to_i
1496 @current_player = @sente
1497 @next_player = @gote
1505 @sente.status = "agree_waiting"
1506 @gote.status = "agree_waiting"
1508 @id = sprintf("%s+%s+%s+%s+%s",
1509 LEAGUE.event, @game_name, @sente.name, @gote.name, issue_current_time)
1510 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1512 LEAGUE.games[@id] = self
1514 log_message(sprintf("game created %s", @id))
1524 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1525 attr_accessor :last_move, :current_turn
1529 @sente.rated? && @gote.rated?
1532 def monitoron(monitor)
1533 @monitors.delete(monitor)
1534 @monitors.push(monitor)
1537 def monitoroff(monitor)
1538 @monitors.delete(monitor)
1541 def reject(rejector)
1542 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1543 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1548 if ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
1550 elsif (@current_player == killer)
1557 log_message(sprintf("game finished %s", @id))
1558 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1563 @sente.status = "connected"
1564 @gote.status = "connected"
1566 if (@current_player.protocol == LoginCSA::PROTOCOL)
1567 @current_player.finish
1569 if (@next_player.protocol == LoginCSA::PROTOCOL)
1572 @monitors = Array::new
1575 @current_player = nil
1577 LEAGUE.games.delete(@id)
1580 def handle_one_move(str, player)
1582 if (@current_player == player)
1583 @end_time = Time::new
1584 t = (@end_time - @start_time).floor
1585 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
1588 if ((@current_player.mytime - t <= -@byoyomi) && ((@total_time > 0) || (@byoyomi > 0)))
1590 elsif (str == :timeout)
1591 return false # time isn't expired. players aren't swapped. continue game
1593 @current_player.mytime = @current_player.mytime - t
1594 if (@current_player.mytime < 0)
1595 @current_player.mytime = 0
1599 move_status = @board.handle_one_move(str, @sente == @current_player)
1601 # log_error("handle_one_move raise exception for #{str}")
1602 # move_status = :illegal
1605 if ((move_status == :illegal) || (move_status == :uchifuzme) || (move_status == :oute_kaihimore))
1606 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1608 if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite))
1609 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1610 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1611 @fh.printf("%s\nT%d\n", str, t)
1612 @last_move = sprintf("%s,T%d", str, t)
1613 @current_turn = @current_turn + 1
1616 @monitors.each do |monitor|
1617 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1618 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1623 if (@next_player.status != "game") # rival is logout or disconnected
1625 elsif (status == :timeout)
1627 elsif (move_status == :illegal)
1629 elsif (move_status == :kachi_win)
1631 elsif (move_status == :kachi_lose)
1633 elsif (move_status == :toryo)
1635 elsif (move_status == :outori)
1637 elsif (move_status == :sennichite)
1639 elsif (move_status == :oute_sennichite)
1640 oute_sennichite_lose()
1641 elsif (move_status == :uchifuzume)
1643 elsif (move_status == :oute_kaihimore)
1644 oute_kaihimore_lose()
1648 finish() if finish_flag
1649 (@current_player, @next_player) = [@next_player, @current_player]
1650 @start_time = Time::new
1656 @current_player.status = "connected"
1657 @next_player.status = "connected"
1658 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1659 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1660 @fh.printf("%%TORYO\n")
1661 @fh.print(@board.to_s.gsub(/^/, "\'"))
1662 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1663 @result = GameResultWin.new(@current_player, @next_player)
1664 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1665 @monitors.each do |monitor|
1666 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1671 @current_player.status = "connected"
1672 @next_player.status = "connected"
1673 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1674 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1675 @fh.printf("%%TORYO\n")
1676 @fh.print(@board.to_s.gsub(/^/, "\'"))
1677 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1678 @result = GameResultWin.new(@next_player, @current_player)
1679 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1680 @monitors.each do |monitor|
1681 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1686 @current_player.status = "connected"
1687 @next_player.status = "connected"
1688 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1689 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1690 @fh.print(@board.to_s.gsub(/^/, "\'"))
1691 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1692 @result = GameResultDraw.new(@current_player, @next_player)
1693 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1694 @monitors.each do |monitor|
1695 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @id))
1699 def oute_sennichite_lose
1700 @current_player.status = "connected"
1701 @next_player.status = "connected"
1702 @current_player.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1703 @next_player.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1704 @fh.print(@board.to_s.gsub(/^/, "\'"))
1705 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1706 @result = GameResultWin.new(@next_player, @current_player)
1707 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1708 @monitors.each do |monitor|
1709 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1714 @current_player.status = "connected"
1715 @next_player.status = "connected"
1716 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1717 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1718 @fh.print(@board.to_s.gsub(/^/, "\'"))
1719 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1720 @result = GameResultWin.new(@next_player, @current_player)
1721 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1722 @monitors.each do |monitor|
1723 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1728 @current_player.status = "connected"
1729 @next_player.status = "connected"
1730 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1731 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1732 @fh.print(@board.to_s.gsub(/^/, "\'"))
1733 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1734 @result = GameResultWin.new(@next_player, @current_player)
1735 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1736 @monitors.each do |monitor|
1737 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1741 def oute_kaihimore_lose
1742 @current_player.status = "connected"
1743 @next_player.status = "connected"
1744 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1745 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1746 @fh.print(@board.to_s.gsub(/^/, "\'"))
1747 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1748 @result = GameResultWin.new(@next_player, @current_player)
1749 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1750 @monitors.each do |monitor|
1751 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1756 @current_player.status = "connected"
1757 @next_player.status = "connected"
1758 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1759 @next_player.write_safe("#TIME_UP\n#WIN\n")
1760 @fh.print(@board.to_s.gsub(/^/, "\'"))
1761 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1762 @result = GameResultWin.new(@next_player, @current_player)
1763 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1764 @monitors.each do |monitor|
1765 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
1770 @current_player.status = "connected"
1771 @next_player.status = "connected"
1772 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1773 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1774 @fh.printf("%%KACHI\n")
1775 @fh.print(@board.to_s.gsub(/^/, "\'"))
1776 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1777 @result = GameResultWin.new(@current_player, @next_player)
1778 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1779 @monitors.each do |monitor|
1780 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1785 @current_player.status = "connected"
1786 @next_player.status = "connected"
1787 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1788 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1789 @fh.printf("%%KACHI\n")
1790 @fh.print(@board.to_s.gsub(/^/, "\'"))
1791 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1792 @result = GameResultWin.new(@next_player, @current_player)
1793 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1794 @monitors.each do |monitor|
1795 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1800 @current_player.status = "connected"
1801 @next_player.status = "connected"
1802 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1803 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1804 @fh.printf("%%TORYO\n")
1805 @fh.print(@board.to_s.gsub(/^/, "\'"))
1806 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1807 @result = GameResultWin.new(@next_player, @current_player)
1808 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1809 @monitors.each do |monitor|
1810 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1815 @current_player.status = "connected"
1816 @next_player.status = "connected"
1817 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1818 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1819 @fh.print(@board.to_s.gsub(/^/, "\'"))
1820 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1821 @result = GameResultWin.new(@current_player, @next_player)
1822 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1823 @monitors.each do |monitor|
1824 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1829 log_message(sprintf("game started %s", @id))
1830 @sente.write_safe(sprintf("START:%s\n", @id))
1831 @gote.write_safe(sprintf("START:%s\n", @id))
1832 @sente.mytime = @total_time
1833 @gote.mytime = @total_time
1834 @start_time = Time::new
1839 @fh = open(@logfile, "w")
1843 @fh.printf("N+%s\n", @sente.name)
1844 @fh.printf("N-%s\n", @gote.name)
1845 @fh.printf("$EVENT:%s\n", @id)
1847 @sente.write_safe(propose_message("+"))
1848 @gote.write_safe(propose_message("-"))
1850 @fh.printf("$START_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1852 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1853 P2 * -HI * * * * * -KA *
1854 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1855 P4 * * * * * * * * *
1856 P5 * * * * * * * * *
1857 P6 * * * * * * * * *
1858 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1859 P8 * +KA * * * * * +HI *
1860 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1869 Protocol_Version:1.1
1870 Protocol_Mode:Server
1872 Declaration:Jishogi 1.1
1874 Name+:#{@sente.name}
1880 Total_Time:#{@total_time}
1882 Least_Time_Per_Move:#{Least_Time_Per_Move}
1883 Remaining_Time+:#{@sente.mytime}
1884 Remaining_Time-:#{@gote.mytime}
1885 Last_Move:#{@last_move}
1886 Current_Turn:#{@current_turn}
1896 return str0 + @board.to_s + str1
1899 def propose_message(sg_flag)
1902 Protocol_Version:1.1
1903 Protocol_Mode:Server
1905 Declaration:Jishogi 1.1
1907 Name+:#{@sente.name}
1909 Your_Turn:#{sg_flag}
1914 Total_Time:#{@total_time}
1916 Least_Time_Per_Move:#{Least_Time_Per_Move}
1919 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1920 P2 * -HI * * * * * -KA *
1921 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1922 P4 * * * * * * * * *
1923 P5 * * * * * * * * *
1924 P6 * * * * * * * * *
1925 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1926 P8 * +KA * * * * * +HI *
1927 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1939 def issue_current_time
1940 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
1941 @@mutex.synchronize do
1942 while time <= @@time do
1949 end # module ShogiServer
1951 #################################################
1958 shogi-server - server for CSA server protocol
1961 shogi-server [OPTIONS] event_name port_number
1964 server for CSA server protocol
1968 specify filename for logging process ID
1970 run as a daemon. Log files will be put in dir.
1973 this file is distributed under GPL version2 and might be compiled by Exerb
1978 #{ShogiServer::Release}
1981 #{ShogiServer::Revision}
1985 def log_message(str)
1989 def log_warning(str)
1998 def parse_command_line
2000 parser = GetoptLong.new( ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
2001 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT]
2005 parser.each_option do |name, arg|
2006 name.sub!(/^--/, '')
2007 options[name] = arg.dup
2011 raise parser.error_message
2016 def write_pid_file(file)
2017 open(file, "w") do |fh|
2018 fh.print Process::pid, "\n"
2022 def mutex_watchdog(mutex, sec)
2034 log_error("mutex watchdog timeout")
2045 mutex_watchdog($mutex, 10)
2048 $options = parse_command_line
2049 if (ARGV.length != 2)
2054 LEAGUE.event = ARGV.shift
2057 write_pid_file($options["pid-file"]) if ($options["pid-file"])
2059 dir = $options["daemon"] || nil
2060 if dir && ! File.exist?(dir)
2061 FileUtils.mkdir(dir)
2063 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2064 $logger = WEBrick::Log.new(log_file)
2066 LEAGUE.dir = dir || File.dirname(__FILE__)
2067 LEAGUE.setup_players_database
2070 config[:Port] = port
2071 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2072 config[:Logger] = $logger
2074 server = WEBrick::GenericServer.new(config)
2075 ["INT", "TERM"].each {|signal| trap(signal){ server.shutdown } }
2076 $stderr.puts("server started as a deamon") if $options["daemon"]
2077 log_message("server started")
2079 server.start do |client|
2080 # client.sync = true # this is already set in WEBrick
2081 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2082 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2085 while (str = client.gets_timeout(ShogiServer::Login_Time))
2090 if (ShogiServer::Login::good_login?(str))
2091 player = ShogiServer::Player::new(str, client)
2093 login = ShogiServer::Login::factory(str, player)
2094 if (LEAGUE.players[player.name])
2095 if ((LEAGUE.players[player.name].password == player.password) &&
2096 (LEAGUE.players[player.name].status != "game"))
2097 log_message(sprintf("user %s login forcely", player.name))
2098 LEAGUE.players[player.name].kill
2100 login.incorrect_duplicated_player(str)
2111 client.write_safe("LOGIN:incorrect" + eol)
2112 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2124 log_message(sprintf("user %s login", player.name))
2126 player.run(login.csa_1st_str)
2130 player.game.kill(player)
2132 player.finish # socket has been closed
2133 LEAGUE.delete(player)
2134 log_message(sprintf("user %s logout", player.name))
2145 TCPSocket.do_not_reverse_lookup = true
2146 Thread.abort_on_exception = true
2148 LEAGUE = ShogiServer::League::new