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 ## ignore null string
644 msg = "##[ERROR] unknown command %s\n" % [str]
656 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
657 def initialize(board, x, y, sente, promoted=false)
664 if ((x == 0) || (y == 0))
666 hands = board.sente_hands
668 hands = board.gote_hands
675 @board.array[x][y] = self
678 attr_accessor :promoted, :sente, :x, :y, :board
680 def room_of_head?(x, y, name)
685 return adjacent_movable_grids + far_movable_grids
688 def far_movable_grids
693 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
694 if ((@board.array[x][y] == nil) || # dst is empty
695 (@board.array[x][y].sente != @sente)) # dst is enemy
703 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
704 if (@board.array[x][y] == nil) # dst is empty?
711 def adjacent_movable_grids
714 moves = @promoted_moves
716 moves = @normal_moves
718 moves.each do |(dx, dy)|
725 if (jump_to?(cand_x, cand_y))
726 grids.push([cand_x, cand_y])
732 def move_to?(x, y, name)
733 return false if (! room_of_head?(x, y, name))
734 return false if ((name != @name) && (name != @promoted_name))
735 return false if (@promoted && (name != @promoted_name)) # can't un-promote
738 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
740 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
742 return false if ((6 >= @y) && (6 >= y) && (name != @name))
746 if ((@x == 0) || (@y == 0))
747 return jump_to?(x, y)
749 return movable_grids.include?([x, y])
754 if ((@x == 0) || (@y == 0))
756 @board.sente_hands.delete(self)
758 @board.gote_hands.delete(self)
760 @board.array[x][y] = self
761 elsif ((x == 0) || (y == 0))
762 @promoted = false # clear promoted flag before moving to hands
764 @board.sente_hands.push(self)
766 @board.gote_hands.push(self)
768 @board.array[@x][@y] = nil
770 @board.array[@x][@y] = nil
771 @board.array[x][y] = self
804 class PieceFU < Piece
807 @normal_moves = [[0, +1]]
808 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
810 @promoted_name = "TO"
813 def room_of_head?(x, y, name)
816 return false if (y == 1)
818 return false if (y == 9)
824 if ((iy != @y) && # not source position
825 @board.array[x][iy] &&
826 (@board.array[x][iy].sente == @sente) && # mine
827 (@board.array[x][iy].name == "FU") &&
828 (@board.array[x][iy].promoted == false))
838 class PieceKY < Piece
842 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
844 @promoted_name = "NY"
847 def room_of_head?(x, y, name)
850 return false if (y == 1)
852 return false if (y == 9)
857 def far_movable_grids
865 while (jump_to?(cand_x, cand_y))
866 grids.push([cand_x, cand_y])
867 break if (! put_to?(cand_x, cand_y))
873 while (jump_to?(cand_x, cand_y))
874 grids.push([cand_x, cand_y])
875 break if (! put_to?(cand_x, cand_y))
883 class PieceKE < Piece
886 @normal_moves = [[+1, +2], [-1, +2]]
887 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
889 @promoted_name = "NK"
892 def room_of_head?(x, y, name)
895 return false if ((y == 1) || (y == 2))
897 return false if ((y == 9) || (y == 8))
903 class PieceGI < Piece
906 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
907 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
909 @promoted_name = "NG"
913 class PieceKI < Piece
916 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
923 class PieceKA < Piece
927 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
929 @promoted_name = "UM"
932 def far_movable_grids
937 while (jump_to?(cand_x, cand_y))
938 grids.push([cand_x, cand_y])
939 break if (! put_to?(cand_x, cand_y))
946 while (jump_to?(cand_x, cand_y))
947 grids.push([cand_x, cand_y])
948 break if (! put_to?(cand_x, cand_y))
955 while (jump_to?(cand_x, cand_y))
956 grids.push([cand_x, cand_y])
957 break if (! put_to?(cand_x, cand_y))
964 while (jump_to?(cand_x, cand_y))
965 grids.push([cand_x, cand_y])
966 break if (! put_to?(cand_x, cand_y))
973 class PieceHI < Piece
977 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
979 @promoted_name = "RY"
982 def far_movable_grids
987 while (jump_to?(cand_x, cand_y))
988 grids.push([cand_x, cand_y])
989 break if (! put_to?(cand_x, cand_y))
995 while (jump_to?(cand_x, cand_y))
996 grids.push([cand_x, cand_y])
997 break if (! put_to?(cand_x, cand_y))
1003 while (jump_to?(cand_x, cand_y))
1004 grids.push([cand_x, cand_y])
1005 break if (! put_to?(cand_x, cand_y))
1011 while (jump_to?(cand_x, cand_y))
1012 grids.push([cand_x, cand_y])
1013 break if (! put_to?(cand_x, cand_y))
1019 class PieceOU < Piece
1020 def initialize(*arg)
1022 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1023 @promoted_moves = []
1025 @promoted_name = nil
1032 @sente_hands = Array::new
1033 @gote_hands = Array::new
1034 @history = Hash::new
1035 @sente_history = Hash::new
1036 @gote_history = Hash::new
1037 @array = [[], [], [], [], [], [], [], [], [], []]
1040 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1041 attr_reader :move_count
1044 PieceKY::new(self, 1, 1, false)
1045 PieceKE::new(self, 2, 1, false)
1046 PieceGI::new(self, 3, 1, false)
1047 PieceKI::new(self, 4, 1, false)
1048 PieceOU::new(self, 5, 1, false)
1049 PieceKI::new(self, 6, 1, false)
1050 PieceGI::new(self, 7, 1, false)
1051 PieceKE::new(self, 8, 1, false)
1052 PieceKY::new(self, 9, 1, false)
1053 PieceKA::new(self, 2, 2, false)
1054 PieceHI::new(self, 8, 2, false)
1055 PieceFU::new(self, 1, 3, false)
1056 PieceFU::new(self, 2, 3, false)
1057 PieceFU::new(self, 3, 3, false)
1058 PieceFU::new(self, 4, 3, false)
1059 PieceFU::new(self, 5, 3, false)
1060 PieceFU::new(self, 6, 3, false)
1061 PieceFU::new(self, 7, 3, false)
1062 PieceFU::new(self, 8, 3, false)
1063 PieceFU::new(self, 9, 3, false)
1065 PieceKY::new(self, 1, 9, true)
1066 PieceKE::new(self, 2, 9, true)
1067 PieceGI::new(self, 3, 9, true)
1068 PieceKI::new(self, 4, 9, true)
1069 PieceOU::new(self, 5, 9, true)
1070 PieceKI::new(self, 6, 9, true)
1071 PieceGI::new(self, 7, 9, true)
1072 PieceKE::new(self, 8, 9, true)
1073 PieceKY::new(self, 9, 9, true)
1074 PieceKA::new(self, 8, 8, true)
1075 PieceHI::new(self, 2, 8, true)
1076 PieceFU::new(self, 1, 7, true)
1077 PieceFU::new(self, 2, 7, true)
1078 PieceFU::new(self, 3, 7, true)
1079 PieceFU::new(self, 4, 7, true)
1080 PieceFU::new(self, 5, 7, true)
1081 PieceFU::new(self, 6, 7, true)
1082 PieceFU::new(self, 7, 7, true)
1083 PieceFU::new(self, 8, 7, true)
1084 PieceFU::new(self, 9, 7, true)
1087 def have_piece?(hands, name)
1088 piece = hands.find { |i|
1094 def move_to(x0, y0, x1, y1, name, sente)
1096 hands = @sente_hands
1101 if ((x0 == 0) || (y0 == 0))
1102 piece = have_piece?(hands, name)
1103 return :illegal if (! piece.move_to?(x1, y1, name))
1104 piece.move_to(x1, y1)
1106 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name))
1107 if (@array[x0][y0].name != name) # promoted ?
1108 @array[x0][y0].promoted = true
1111 if (@array[x1][y1].name == "OU")
1112 return :outori # return board update
1114 @array[x1][y1].sente = @array[x0][y0].sente
1115 @array[x1][y1].move_to(0, 0)
1120 @array[x0][y0].move_to(x1, y1)
1126 def look_for_ou(sente)
1132 (@array[x][y].name == "OU") &&
1133 (@array[x][y].sente == sente))
1140 raise "can't find ou"
1143 def checkmated?(sente) # sente is loosing
1144 ou = look_for_ou(sente)
1150 (@array[x][y].sente != sente))
1151 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1162 def uchifuzume?(sente)
1163 rival_ou = look_for_ou(! sente) # rival's ou
1164 if (sente) # rival is gote
1165 if ((rival_ou.y != 9) &&
1166 (@array[rival_ou.x][rival_ou.y + 1]) &&
1167 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1168 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1170 fu_y = rival_ou.y + 1
1175 if ((rival_ou.y != 0) &&
1176 (@array[rival_ou.x][rival_ou.y - 1]) &&
1177 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1178 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1180 fu_y = rival_ou.y - 1
1186 ## case: rival_ou is moving
1188 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1189 tmp_board = Marshal.load(Marshal.dump(self))
1190 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1191 raise "internal error" if (s != true)
1192 if (! tmp_board.checkmated?(! sente)) # good move
1197 ## case: rival is capturing fu
1203 (@array[x][y].sente != sente) &&
1204 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1205 if (@array[x][y].promoted)
1206 name = @array[x][y].promoted_name
1208 name = @array[x][y].name
1210 tmp_board = Marshal.load(Marshal.dump(self))
1211 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1212 raise "internal error" if (s != true)
1213 if (! tmp_board.checkmated?(! sente)) # good move
1224 def oute_sennichite?(sente)
1225 if (checkmated?(! sente))
1228 if (@sente_history[str] && (@sente_history[str] >= 3)) # already 3 times
1232 if (@gote_history[str] && (@gote_history[str] >= 3)) # already 3 times
1240 def sennichite?(sente)
1242 if (@history[str] && (@history[str] >= 3)) # already 3 times
1248 def good_kachi?(sente)
1249 if (checkmated?(sente))
1250 puts "'NG: Checkmating." if $DEBUG
1254 ou = look_for_ou(sente)
1255 if (sente && (ou.y >= 4))
1256 puts "'NG: Black's OU does not enter yet." if $DEBUG
1259 if (! sente && (ou.y <= 6))
1260 puts "'NG: White's OU does not enter yet." if $DEBUG
1268 hands = @sente_hands
1278 (@array[x][y].sente == sente) &&
1279 (@array[x][y].point > 0))
1280 point = point + @array[x][y].point
1286 hands.each do |piece|
1287 point = point + piece.point
1291 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1296 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1301 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1306 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1310 # sente is nil only if tests in test_board run
1311 def handle_one_move(str, sente=nil)
1312 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1319 elsif (str =~ /^%KACHI/)
1320 raise ArgumentError, "sente is null", caller if sente == nil
1321 if (good_kachi?(sente))
1326 elsif (str =~ /^%TORYO/)
1332 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1333 ((x0 != 0) || (y0 != 0)))
1335 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1341 sente = true if sente == nil # deprecated
1342 return :illegal unless sente == true # black player's move must be black
1343 hands = @sente_hands
1345 sente = false if sente == nil # deprecated
1346 return :illegal unless sente == false # white player's move must be white
1351 if ((x0 == 0) && (y0 == 0))
1352 return :illegal if (! have_piece?(hands, name))
1353 elsif (! @array[x0][y0])
1354 return :illegal # no piece
1355 elsif (@array[x0][y0].sente != sente)
1356 return :illegal # this is not mine
1357 elsif (@array[x0][y0].name != name)
1358 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1361 ## destination check
1362 if (@array[x1][y1] &&
1363 (@array[x1][y1].sente == sente)) # can't capture mine
1365 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1366 return :illegal # can't put on existing piece
1369 tmp_board = Marshal.load(Marshal.dump(self))
1370 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1371 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1372 return :oute_sennichite if tmp_board.oute_sennichite?(sente)
1373 return :sennichite if tmp_board.sennichite?(sente)
1375 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1379 move_to(x0, y0, x1, y1, name, sente)
1382 if (checkmated?(! sente))
1384 @sente_history[str] = (@sente_history[str] || 0) + 1
1386 @gote_history[str] = (@gote_history[str] || 0) + 1
1390 @sente_history.clear
1395 @history[str] = (@history[str] || 0) + 1
1403 a.push(sprintf("P%d", y))
1406 piece = @array[x][y]
1415 a.push(sprintf("\n"))
1418 if (! sente_hands.empty?)
1420 sente_hands.each do |p|
1421 a.push("00" + p.name)
1425 if (! gote_hands.empty?)
1427 gote_hands.each do |p|
1428 a.push("00" + p.name)
1438 attr_reader :players, :black, :white
1440 def initialize(p1, p2)
1444 if p1.sente && !p2.sente
1445 @black, @white = p1, p2
1446 elsif !p1.sente && p2.sente
1447 @black, @white = p2, p1
1449 raise "Never reached!"
1454 class GameResultWin < GameResult
1455 attr_reader :winner, :loser
1457 def initialize(winner, loser)
1459 @winner, @loser = winner, loser
1463 black_name = @black.id || @black.name
1464 white_name = @white.id || @white.name
1465 "%s:%s" % [black_name, white_name]
1469 class GameResultDraw < GameResult
1477 def initialize(game_name, player0, player1)
1478 @monitors = Array::new
1479 @game_name = game_name
1480 if (@game_name =~ /-(\d+)-(\d+)$/)
1481 @total_time = $1.to_i
1492 @current_player = @sente
1493 @next_player = @gote
1501 @sente.status = "agree_waiting"
1502 @gote.status = "agree_waiting"
1504 @id = sprintf("%s+%s+%s+%s+%s",
1505 LEAGUE.event, @game_name, @sente.name, @gote.name, issue_current_time)
1506 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1508 LEAGUE.games[@id] = self
1510 log_message(sprintf("game created %s", @id))
1520 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1521 attr_accessor :last_move, :current_turn
1525 @sente.rated? && @gote.rated?
1528 def monitoron(monitor)
1529 @monitors.delete(monitor)
1530 @monitors.push(monitor)
1533 def monitoroff(monitor)
1534 @monitors.delete(monitor)
1537 def reject(rejector)
1538 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1539 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1544 if ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
1546 elsif (@current_player == killer)
1553 log_message(sprintf("game finished %s", @id))
1554 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1559 @sente.status = "connected"
1560 @gote.status = "connected"
1562 if (@current_player.protocol == LoginCSA::PROTOCOL)
1563 @current_player.finish
1565 if (@next_player.protocol == LoginCSA::PROTOCOL)
1568 @monitors = Array::new
1571 @current_player = nil
1573 LEAGUE.games.delete(@id)
1576 def handle_one_move(str, player)
1578 if (@current_player == player)
1579 @end_time = Time::new
1580 t = (@end_time - @start_time).floor
1581 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
1584 if ((@current_player.mytime - t <= -@byoyomi) && ((@total_time > 0) || (@byoyomi > 0)))
1586 elsif (str == :timeout)
1587 return false # time isn't expired. players aren't swapped. continue game
1589 @current_player.mytime = @current_player.mytime - t
1590 if (@current_player.mytime < 0)
1591 @current_player.mytime = 0
1595 move_status = @board.handle_one_move(str, @sente == @current_player)
1597 # log_error("handle_one_move raise exception for #{str}")
1598 # move_status = :illegal
1601 if ((move_status == :illegal) || (move_status == :uchifuzme) || (move_status == :oute_kaihimore))
1602 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1604 if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite))
1605 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1606 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1607 @fh.printf("%s\nT%d\n", str, t)
1608 @last_move = sprintf("%s,T%d", str, t)
1609 @current_turn = @current_turn + 1
1612 @monitors.each do |monitor|
1613 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1614 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1619 if (@next_player.status != "game") # rival is logout or disconnected
1621 elsif (status == :timeout)
1623 elsif (move_status == :illegal)
1625 elsif (move_status == :kachi_win)
1627 elsif (move_status == :kachi_lose)
1629 elsif (move_status == :toryo)
1631 elsif (move_status == :outori)
1633 elsif (move_status == :sennichite)
1635 elsif (move_status == :oute_sennichite)
1636 oute_sennichite_lose()
1637 elsif (move_status == :uchifuzume)
1639 elsif (move_status == :oute_kaihimore)
1640 oute_kaihimore_lose()
1644 finish() if finish_flag
1645 (@current_player, @next_player) = [@next_player, @current_player]
1646 @start_time = Time::new
1652 @current_player.status = "connected"
1653 @next_player.status = "connected"
1654 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1655 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1656 @fh.printf("%%TORYO\n")
1657 @fh.print(@board.to_s.gsub(/^/, "\'"))
1658 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1659 @result = GameResultWin.new(@current_player, @next_player)
1660 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1661 @monitors.each do |monitor|
1662 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1667 @current_player.status = "connected"
1668 @next_player.status = "connected"
1669 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1670 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1671 @fh.printf("%%TORYO\n")
1672 @fh.print(@board.to_s.gsub(/^/, "\'"))
1673 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1674 @result = GameResultWin.new(@next_player, @current_player)
1675 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1676 @monitors.each do |monitor|
1677 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1682 @current_player.status = "connected"
1683 @next_player.status = "connected"
1684 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1685 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1686 @fh.print(@board.to_s.gsub(/^/, "\'"))
1687 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1688 @result = GameResultDraw.new(@current_player, @next_player)
1689 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1690 @monitors.each do |monitor|
1691 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @id))
1695 def oute_sennichite_lose
1696 @current_player.status = "connected"
1697 @next_player.status = "connected"
1698 @current_player.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1699 @next_player.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1700 @fh.print(@board.to_s.gsub(/^/, "\'"))
1701 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1702 @result = GameResultWin.new(@next_player, @current_player)
1703 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1704 @monitors.each do |monitor|
1705 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1710 @current_player.status = "connected"
1711 @next_player.status = "connected"
1712 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1713 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1714 @fh.print(@board.to_s.gsub(/^/, "\'"))
1715 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1716 @result = GameResultWin.new(@next_player, @current_player)
1717 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1718 @monitors.each do |monitor|
1719 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1724 @current_player.status = "connected"
1725 @next_player.status = "connected"
1726 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1727 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1728 @fh.print(@board.to_s.gsub(/^/, "\'"))
1729 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1730 @result = GameResultWin.new(@next_player, @current_player)
1731 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1732 @monitors.each do |monitor|
1733 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1737 def oute_kaihimore_lose
1738 @current_player.status = "connected"
1739 @next_player.status = "connected"
1740 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1741 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1742 @fh.print(@board.to_s.gsub(/^/, "\'"))
1743 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1744 @result = GameResultWin.new(@next_player, @current_player)
1745 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1746 @monitors.each do |monitor|
1747 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1752 @current_player.status = "connected"
1753 @next_player.status = "connected"
1754 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1755 @next_player.write_safe("#TIME_UP\n#WIN\n")
1756 @fh.print(@board.to_s.gsub(/^/, "\'"))
1757 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1758 @result = GameResultWin.new(@next_player, @current_player)
1759 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1760 @monitors.each do |monitor|
1761 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
1766 @current_player.status = "connected"
1767 @next_player.status = "connected"
1768 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1769 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1770 @fh.printf("%%KACHI\n")
1771 @fh.print(@board.to_s.gsub(/^/, "\'"))
1772 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1773 @result = GameResultWin.new(@current_player, @next_player)
1774 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1775 @monitors.each do |monitor|
1776 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1781 @current_player.status = "connected"
1782 @next_player.status = "connected"
1783 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1784 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1785 @fh.printf("%%KACHI\n")
1786 @fh.print(@board.to_s.gsub(/^/, "\'"))
1787 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1788 @result = GameResultWin.new(@next_player, @current_player)
1789 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1790 @monitors.each do |monitor|
1791 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1796 @current_player.status = "connected"
1797 @next_player.status = "connected"
1798 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1799 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1800 @fh.printf("%%TORYO\n")
1801 @fh.print(@board.to_s.gsub(/^/, "\'"))
1802 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1803 @result = GameResultWin.new(@next_player, @current_player)
1804 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1805 @monitors.each do |monitor|
1806 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1811 @current_player.status = "connected"
1812 @next_player.status = "connected"
1813 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1814 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1815 @fh.print(@board.to_s.gsub(/^/, "\'"))
1816 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1817 @result = GameResultWin.new(@current_player, @next_player)
1818 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1819 @monitors.each do |monitor|
1820 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1825 log_message(sprintf("game started %s", @id))
1826 @sente.write_safe(sprintf("START:%s\n", @id))
1827 @gote.write_safe(sprintf("START:%s\n", @id))
1828 @sente.mytime = @total_time
1829 @gote.mytime = @total_time
1830 @start_time = Time::new
1835 @fh = open(@logfile, "w")
1839 @fh.printf("N+%s\n", @sente.name)
1840 @fh.printf("N-%s\n", @gote.name)
1841 @fh.printf("$EVENT:%s\n", @id)
1843 @sente.write_safe(propose_message("+"))
1844 @gote.write_safe(propose_message("-"))
1846 @fh.printf("$START_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1848 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1849 P2 * -HI * * * * * -KA *
1850 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1851 P4 * * * * * * * * *
1852 P5 * * * * * * * * *
1853 P6 * * * * * * * * *
1854 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1855 P8 * +KA * * * * * +HI *
1856 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1865 Protocol_Version:1.1
1866 Protocol_Mode:Server
1868 Declaration:Jishogi 1.1
1870 Name+:#{@sente.name}
1876 Total_Time:#{@total_time}
1878 Least_Time_Per_Move:#{Least_Time_Per_Move}
1879 Remaining_Time+:#{@sente.mytime}
1880 Remaining_Time-:#{@gote.mytime}
1881 Last_Move:#{@last_move}
1882 Current_Turn:#{@current_turn}
1892 return str0 + @board.to_s + str1
1895 def propose_message(sg_flag)
1898 Protocol_Version:1.1
1899 Protocol_Mode:Server
1901 Declaration:Jishogi 1.1
1903 Name+:#{@sente.name}
1905 Your_Turn:#{sg_flag}
1910 Total_Time:#{@total_time}
1912 Least_Time_Per_Move:#{Least_Time_Per_Move}
1915 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1916 P2 * -HI * * * * * -KA *
1917 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1918 P4 * * * * * * * * *
1919 P5 * * * * * * * * *
1920 P6 * * * * * * * * *
1921 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1922 P8 * +KA * * * * * +HI *
1923 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1935 def issue_current_time
1936 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
1937 @@mutex.synchronize do
1938 while time <= @@time do
1945 end # module ShogiServer
1947 #################################################
1954 shogi-server - server for CSA server protocol
1957 shogi-server [OPTIONS] event_name port_number
1960 server for CSA server protocol
1964 specify filename for logging process ID
1966 run as a daemon. Log files will be put in dir.
1969 this file is distributed under GPL version2 and might be compiled by Exerb
1974 #{ShogiServer::Release}
1977 #{ShogiServer::Revision}
1981 def log_message(str)
1985 def log_warning(str)
1994 def parse_command_line
1996 parser = GetoptLong.new( ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
1997 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT]
2001 parser.each_option do |name, arg|
2002 name.sub!(/^--/, '')
2003 options[name] = arg.dup
2007 raise parser.error_message
2012 def write_pid_file(file)
2013 open(file, "w") do |fh|
2014 fh.print Process::pid, "\n"
2018 def mutex_watchdog(mutex, sec)
2030 log_error("mutex watchdog timeout")
2041 mutex_watchdog($mutex, 10)
2044 $options = parse_command_line
2045 if (ARGV.length != 2)
2050 LEAGUE.event = ARGV.shift
2053 write_pid_file($options["pid-file"]) if ($options["pid-file"])
2055 dir = $options["daemon"] || nil
2056 if dir && ! File.exist?(dir)
2057 FileUtils.mkdir(dir)
2059 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2060 $logger = WEBrick::Log.new(log_file)
2062 LEAGUE.dir = dir || File.dirname(__FILE__)
2063 LEAGUE.setup_players_database
2066 config[:Port] = port
2067 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2068 config[:Logger] = $logger
2070 server = WEBrick::GenericServer.new(config)
2071 ["INT", "TERM"].each {|signal| trap(signal){ server.shutdown } }
2072 $stderr.puts("server started as a deamon") if $options["daemon"]
2073 log_message("server started")
2075 server.start do |client|
2076 # client.sync = true # this is already set in WEBrick
2077 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
2078 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
2081 while (str = client.gets_timeout(ShogiServer::Login_Time))
2086 if (ShogiServer::Login::good_login?(str))
2087 player = ShogiServer::Player::new(str, client)
2089 login = ShogiServer::Login::factory(str, player)
2090 if (LEAGUE.players[player.name])
2091 if ((LEAGUE.players[player.name].password == player.password) &&
2092 (LEAGUE.players[player.name].status != "game"))
2093 log_message(sprintf("user %s login forcely", player.name))
2094 LEAGUE.players[player.name].kill
2096 login.incorrect_duplicated_player(str)
2107 client.write_safe("LOGIN:incorrect" + eol)
2108 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2120 log_message(sprintf("user %s login", player.name))
2122 player.run(login.csa_1st_str)
2126 player.game.kill(player)
2128 player.finish # socket has been closed
2129 LEAGUE.delete(player)
2130 log_message(sprintf("user %s logout", player.name))
2141 TCPSocket.do_not_reverse_lookup = true
2142 Thread.abort_on_exception = true
2144 LEAGUE = ShogiServer::League::new