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)
64 return self.write(str)
72 module ShogiServer # for a namespace
74 Max_Write_Queue_Size = 1000
75 Max_Identifier_Length = 32
76 Default_Timeout = 60 # for single socket operation
78 Default_Game_Name = "default-1500-0"
81 Least_Time_Per_Move = 1
82 Login_Time = 300 # time for LOGIN
84 Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
85 Release.concat("-") if (Release == "")
86 Revision = "$Revision$".gsub(/[^\.\d]/, '')
94 @dir = File.dirname(__FILE__)
96 attr_accessor :players, :games, :event, :dir
98 # this should be called just after instanciating a League object.
99 def setup_players_database
100 @db = YAML::Store.new(File.join(@dir, "players.yaml"))
104 self.load(player) if player.id
105 @players[player.name] = player
109 @players.delete(player.name)
112 def get_player(status, game_name, sente, searcher=nil)
113 @players.each do |name, player|
114 if ((player.status == status) &&
115 (player.game_name == game_name) &&
116 ((sente == nil) || (player.sente == nil) || (player.sente == sente)) &&
117 ((searcher == nil) || (player != searcher)))
125 hash = search(player.id)
128 player.name = hash['name']
129 player.rate = hash['rate']
130 player.modified_at = hash['last_modified']
131 player.rating_group = hash['rating_group']
138 break unless @db["players"]
139 @db["players"].each do |group, players|
149 @db.transaction(true) do
150 break unless @db["players"]
151 @db["players"].each do |group, players_hash|
152 players << players_hash.keys
155 return players.flatten.collect do |id|
165 ######################################################
166 # Processes the LOGIN command.
169 def Login.good_login?(str)
171 if (((tokens.length == 3) || ((tokens.length == 4) && tokens[3] == "x1")) &&
172 (tokens[0] == "LOGIN") &&
173 (good_identifier?(tokens[1])))
180 def Login.good_game_name?(str)
181 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
188 def Login.good_identifier?(str)
189 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
196 def Login.factory(str, player)
197 (login, player.name, password, ext) = str.chomp.split
199 return Loginx1.new(player, password)
201 return LoginCSA.new(player, password)
207 # the first command that will be executed just after LOGIN.
208 # If it is nil, the default process will be started.
209 attr_reader :csa_1st_str
211 def initialize(player, password)
214 parse_password(password)
218 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
219 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
222 def incorrect_duplicated_player(str)
223 @player.write_safe("LOGIN:incorrect\n")
224 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
225 sleep 3 # wait for sending the above messages.
226 @player.name = "%s [duplicated]" % [@player.name]
231 ######################################################
232 # Processes LOGIN for the CSA standard mode.
234 class LoginCSA < Login
237 def initialize(player, password)
240 @player.protocol = PROTOCOL
243 def parse_password(password)
244 if Login.good_game_name?(password)
246 @player.set_password(nil)
247 elsif password.split(",").size > 1
248 @gamename, *trip = password.split(",")
249 @player.set_password(trip.join(","))
251 @player.set_password(password)
252 @gamename = Default_Game_Name
254 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
259 @csa_1st_str = "%%GAME #{@gamename} *"
263 ######################################################
264 # Processes LOGIN for the extented mode.
266 class Loginx1 < Login
269 def initialize(player, password)
271 @player.protocol = PROTOCOL
274 def parse_password(password)
275 @player.set_password(password)
280 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
286 # Idetifier of the player in the rating system
292 # Password of the player, which does not include a trip
293 attr_accessor :password
295 # Score in the rating sysem
298 # Group in the rating system
299 attr_accessor :rating_group
301 # Last timestamp when the rate was modified
302 attr_accessor :modified_at
310 @modified_at || Time.now
316 @modified_at = Time.now
326 simple_name = @name.gsub(/@.*?$/, '')
327 "%s+%s" % [simple_name, @trip[0..8]]
334 # Parses str in the LOGIN command, sets up @id and @trip
336 def set_password(str)
337 if str && !str.empty?
338 @password = str.strip
339 @id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
341 @id = @password = nil
347 class Player < BasicPlayer
348 def initialize(str, socket)
351 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
353 @protocol = nil # CSA or x1
354 @eol = "\m" # favorite eol code
357 @mytime = 0 # set in start method also
359 @write_queue = Queue::new
360 @main_thread = Thread::current
361 @writer_thread = Thread::start do
367 attr_accessor :socket, :status
368 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
369 attr_accessor :main_thread, :writer_thread, :write_queue
372 log_message(sprintf("user %s killed", @name))
377 Thread::kill(@main_thread) if @main_thread
381 if (@status != "finished")
383 log_message(sprintf("user %s finish", @name))
384 # TODO you should confirm that there is no message in the queue.
385 Thread::kill(@writer_thread) if @writer_thread
387 # @socket.close if (! @socket.closed?)
389 log_message(sprintf("user %s finish failed", @name))
395 @write_queue.push(str.gsub(/[\r\n]+/, @eol))
399 while (str = @write_queue.pop)
400 @socket.write_safe(str)
405 if ((status == "game_waiting") ||
406 (status == "start_waiting") ||
407 (status == "agree_waiting") ||
410 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
411 elsif (@sente == false)
412 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
413 elsif (@sente == nil)
414 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
417 return sprintf("%s %s %s", @name, @protocol, @status)
422 @socket.write_safe('##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"')
425 def run(csa_1st_str=nil)
426 while (csa_1st_str || (str = @socket.gets_safe(Default_Timeout)))
433 if (@write_queue.size > Max_Write_Queue_Size)
434 log_warning(sprintf("write_queue of %s is %d", @name, @write_queue.size))
438 if (@status == "finished")
441 str.chomp! if (str.class == String)
444 if (@status == "game")
445 array_str = str.split(",")
446 move = array_str.shift
447 additional = array_str.shift
448 if /^'(.*)/ =~ additional
449 comment = array_str.unshift("'*#{$1}")
451 s = @game.handle_one_move(move, self)
452 @game.fh.print("#{comment}\n") if (comment && !s)
453 return if (s && @protocol == LoginCSA::PROTOCOL)
455 when /^%[^%]/, :timeout
456 if (@status == "game")
457 s = @game.handle_one_move(str, self)
458 return if (s && @protocol == LoginCSA::PROTOCOL)
461 if (@status == "agree_waiting")
463 return if (@protocol == LoginCSA::PROTOCOL)
465 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
468 if (@status == "agree_waiting")
469 @status = "start_waiting"
470 if ((@game.sente.status == "start_waiting") &&
471 (@game.gote.status == "start_waiting"))
473 @game.sente.status = "game"
474 @game.gote.status = "game"
477 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
479 when /^%%SHOW\s+(\S+)/
481 if (LEAGUE.games[game_id])
482 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
484 write_safe("##[SHOW] +OK\n")
485 when /^%%MONITORON\s+(\S+)/
487 if (LEAGUE.games[game_id])
488 LEAGUE.games[game_id].monitoron(self)
489 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
490 write_safe("##[MONITOR][#{game_id}] +OK\n")
492 when /^%%MONITOROFF\s+(\S+)/
494 if (LEAGUE.games[game_id])
495 LEAGUE.games[game_id].monitoroff(self)
500 players = LEAGUE.rated_players
501 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
502 write_safe("##[RATING] %s \t %4d @%s\n" %
503 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
505 write_safe("##[RATING] +OK\n")
507 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
508 write_safe("##[VERSION] +OK\n")
510 if ((@status == "connected") || (@status == "game_waiting"))
511 @status = "connected"
514 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
516 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
520 if (! Login::good_game_name?(game_name))
521 write_safe(sprintf("##[ERROR] bad game name\n"))
523 elsif ((@status == "connected") || (@status == "game_waiting"))
526 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
529 if ((my_sente_str == "*") ||
530 (my_sente_str == "+") ||
531 (my_sente_str == "-"))
534 write_safe(sprintf("##[ERROR] bad game option\n"))
538 if (my_sente_str == "*")
539 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
540 elsif (my_sente_str == "+")
541 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
542 elsif (my_sente_str == "-")
543 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
548 @game_name = game_name
549 if ((my_sente_str == "*") && (rival.sente == nil))
557 elsif (rival.sente == true) # rival has higher priority
559 elsif (rival.sente == false)
561 elsif (my_sente_str == "+")
564 elsif (my_sente_str == "-")
570 Game::new(@game_name, self, rival)
571 self.status = "agree_waiting"
572 rival.status = "agree_waiting"
573 else # rival not found
574 if (command_name == "GAME")
575 @status = "game_waiting"
576 @game_name = game_name
577 if (my_sente_str == "+")
579 elsif (my_sente_str == "-")
585 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
586 @status = "connected"
591 when /^%%CHAT\s+(.+)/
593 LEAGUE.players.each do |name, player|
594 if (player.protocol != LoginCSA::PROTOCOL)
595 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
600 LEAGUE.games.each do |id, game|
601 buf.push(sprintf("##[LIST] %s\n", id))
603 buf.push("##[LIST] +OK\n")
607 LEAGUE.players.each do |name, player|
608 buf.push(sprintf("##[WHO] %s\n", player.to_s))
610 buf.push("##[WHO] +OK\n")
613 @status = "connected"
614 write_safe("LOGOUT:completed\n")
617 ## ignore null string
619 msg = "##[ERROR] unknown command %s\n" % [str]
631 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
632 def initialize(board, x, y, sente, promoted=false)
639 if ((x == 0) || (y == 0))
641 hands = board.sente_hands
643 hands = board.gote_hands
650 @board.array[x][y] = self
653 attr_accessor :promoted, :sente, :x, :y, :board
655 def room_of_head?(x, y, name)
660 return adjacent_movable_grids + far_movable_grids
663 def far_movable_grids
668 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
669 if ((@board.array[x][y] == nil) || # dst is empty
670 (@board.array[x][y].sente != @sente)) # dst is enemy
678 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
679 if (@board.array[x][y] == nil) # dst is empty?
686 def adjacent_movable_grids
689 moves = @promoted_moves
691 moves = @normal_moves
693 moves.each do |(dx, dy)|
700 if (jump_to?(cand_x, cand_y))
701 grids.push([cand_x, cand_y])
707 def move_to?(x, y, name)
708 return false if (! room_of_head?(x, y, name))
709 return false if ((name != @name) && (name != @promoted_name))
710 return false if (@promoted && (name != @promoted_name)) # can't un-promote
713 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
715 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
717 return false if ((6 >= @y) && (6 >= y) && (name != @name))
721 if ((@x == 0) || (@y == 0))
722 return jump_to?(x, y)
724 return movable_grids.include?([x, y])
729 if ((@x == 0) || (@y == 0))
731 @board.sente_hands.delete(self)
733 @board.gote_hands.delete(self)
735 @board.array[x][y] = self
736 elsif ((x == 0) || (y == 0))
737 @promoted = false # clear promoted flag before moving to hands
739 @board.sente_hands.push(self)
741 @board.gote_hands.push(self)
743 @board.array[@x][@y] = nil
745 @board.array[@x][@y] = nil
746 @board.array[x][y] = self
779 class PieceFU < Piece
782 @normal_moves = [[0, +1]]
783 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
785 @promoted_name = "TO"
788 def room_of_head?(x, y, name)
791 return false if (y == 1)
793 return false if (y == 9)
799 if ((iy != @y) && # not source position
800 @board.array[x][iy] &&
801 (@board.array[x][iy].sente == @sente) && # mine
802 (@board.array[x][iy].name == "FU") &&
803 (@board.array[x][iy].promoted == false))
813 class PieceKY < Piece
817 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
819 @promoted_name = "NY"
822 def room_of_head?(x, y, name)
825 return false if (y == 1)
827 return false if (y == 9)
832 def far_movable_grids
840 while (jump_to?(cand_x, cand_y))
841 grids.push([cand_x, cand_y])
842 break if (! put_to?(cand_x, cand_y))
848 while (jump_to?(cand_x, cand_y))
849 grids.push([cand_x, cand_y])
850 break if (! put_to?(cand_x, cand_y))
858 class PieceKE < Piece
861 @normal_moves = [[+1, +2], [-1, +2]]
862 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
864 @promoted_name = "NK"
867 def room_of_head?(x, y, name)
870 return false if ((y == 1) || (y == 2))
872 return false if ((y == 9) || (y == 8))
878 class PieceGI < Piece
881 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
882 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
884 @promoted_name = "NG"
888 class PieceKI < Piece
891 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
898 class PieceKA < Piece
902 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
904 @promoted_name = "UM"
907 def far_movable_grids
912 while (jump_to?(cand_x, cand_y))
913 grids.push([cand_x, cand_y])
914 break if (! put_to?(cand_x, cand_y))
921 while (jump_to?(cand_x, cand_y))
922 grids.push([cand_x, cand_y])
923 break if (! put_to?(cand_x, cand_y))
930 while (jump_to?(cand_x, cand_y))
931 grids.push([cand_x, cand_y])
932 break if (! put_to?(cand_x, cand_y))
939 while (jump_to?(cand_x, cand_y))
940 grids.push([cand_x, cand_y])
941 break if (! put_to?(cand_x, cand_y))
948 class PieceHI < Piece
952 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
954 @promoted_name = "RY"
957 def far_movable_grids
962 while (jump_to?(cand_x, cand_y))
963 grids.push([cand_x, cand_y])
964 break if (! put_to?(cand_x, cand_y))
970 while (jump_to?(cand_x, cand_y))
971 grids.push([cand_x, cand_y])
972 break if (! put_to?(cand_x, cand_y))
978 while (jump_to?(cand_x, cand_y))
979 grids.push([cand_x, cand_y])
980 break if (! put_to?(cand_x, cand_y))
986 while (jump_to?(cand_x, cand_y))
987 grids.push([cand_x, cand_y])
988 break if (! put_to?(cand_x, cand_y))
994 class PieceOU < Piece
997 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
1000 @promoted_name = nil
1007 @sente_hands = Array::new
1008 @gote_hands = Array::new
1009 @history = Hash::new
1010 @sente_history = Hash::new
1011 @gote_history = Hash::new
1012 @array = [[], [], [], [], [], [], [], [], [], []]
1015 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1016 attr_reader :move_count
1019 PieceKY::new(self, 1, 1, false)
1020 PieceKE::new(self, 2, 1, false)
1021 PieceGI::new(self, 3, 1, false)
1022 PieceKI::new(self, 4, 1, false)
1023 PieceOU::new(self, 5, 1, false)
1024 PieceKI::new(self, 6, 1, false)
1025 PieceGI::new(self, 7, 1, false)
1026 PieceKE::new(self, 8, 1, false)
1027 PieceKY::new(self, 9, 1, false)
1028 PieceKA::new(self, 2, 2, false)
1029 PieceHI::new(self, 8, 2, false)
1030 PieceFU::new(self, 1, 3, false)
1031 PieceFU::new(self, 2, 3, false)
1032 PieceFU::new(self, 3, 3, false)
1033 PieceFU::new(self, 4, 3, false)
1034 PieceFU::new(self, 5, 3, false)
1035 PieceFU::new(self, 6, 3, false)
1036 PieceFU::new(self, 7, 3, false)
1037 PieceFU::new(self, 8, 3, false)
1038 PieceFU::new(self, 9, 3, false)
1040 PieceKY::new(self, 1, 9, true)
1041 PieceKE::new(self, 2, 9, true)
1042 PieceGI::new(self, 3, 9, true)
1043 PieceKI::new(self, 4, 9, true)
1044 PieceOU::new(self, 5, 9, true)
1045 PieceKI::new(self, 6, 9, true)
1046 PieceGI::new(self, 7, 9, true)
1047 PieceKE::new(self, 8, 9, true)
1048 PieceKY::new(self, 9, 9, true)
1049 PieceKA::new(self, 8, 8, true)
1050 PieceHI::new(self, 2, 8, true)
1051 PieceFU::new(self, 1, 7, true)
1052 PieceFU::new(self, 2, 7, true)
1053 PieceFU::new(self, 3, 7, true)
1054 PieceFU::new(self, 4, 7, true)
1055 PieceFU::new(self, 5, 7, true)
1056 PieceFU::new(self, 6, 7, true)
1057 PieceFU::new(self, 7, 7, true)
1058 PieceFU::new(self, 8, 7, true)
1059 PieceFU::new(self, 9, 7, true)
1062 def have_piece?(hands, name)
1063 piece = hands.find { |i|
1069 def move_to(x0, y0, x1, y1, name, sente)
1071 hands = @sente_hands
1076 if ((x0 == 0) || (y0 == 0))
1077 piece = have_piece?(hands, name)
1078 return :illegal if (! piece.move_to?(x1, y1, name))
1079 piece.move_to(x1, y1)
1081 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name))
1082 if (@array[x0][y0].name != name) # promoted ?
1083 @array[x0][y0].promoted = true
1086 if (@array[x1][y1].name == "OU")
1087 return :outori # return board update
1089 @array[x1][y1].sente = @array[x0][y0].sente
1090 @array[x1][y1].move_to(0, 0)
1095 @array[x0][y0].move_to(x1, y1)
1101 def look_for_ou(sente)
1107 (@array[x][y].name == "OU") &&
1108 (@array[x][y].sente == sente))
1115 raise "can't find ou"
1118 def checkmated?(sente) # sente is loosing
1119 ou = look_for_ou(sente)
1125 (@array[x][y].sente != sente))
1126 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1137 def uchifuzume?(sente)
1138 rival_ou = look_for_ou(! sente) # rival's ou
1139 if (sente) # rival is gote
1140 if ((rival_ou.y != 9) &&
1141 (@array[rival_ou.x][rival_ou.y + 1]) &&
1142 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1143 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1145 fu_y = rival_ou.y + 1
1150 if ((rival_ou.y != 0) &&
1151 (@array[rival_ou.x][rival_ou.y - 1]) &&
1152 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1153 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1155 fu_y = rival_ou.y - 1
1161 ## case: rival_ou is moving
1163 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1164 tmp_board = Marshal.load(Marshal.dump(self))
1165 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1166 raise "internal error" if (s != true)
1167 if (! tmp_board.checkmated?(! sente)) # good move
1172 ## case: rival is capturing fu
1178 (@array[x][y].sente != sente) &&
1179 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1180 if (@array[x][y].promoted)
1181 name = @array[x][y].promoted_name
1183 name = @array[x][y].name
1185 tmp_board = Marshal.load(Marshal.dump(self))
1186 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1187 raise "internal error" if (s != true)
1188 if (! tmp_board.checkmated?(! sente)) # good move
1199 def oute_sennichite?(sente)
1200 if (checkmated?(! sente))
1203 if (@sente_history[str] && (@sente_history[str] >= 3)) # already 3 times
1207 if (@gote_history[str] && (@gote_history[str] >= 3)) # already 3 times
1215 def sennichite?(sente)
1217 if (@history[str] && (@history[str] >= 3)) # already 3 times
1223 def good_kachi?(sente)
1224 if (checkmated?(sente))
1225 puts "'NG: Checkmating." if $DEBUG
1229 ou = look_for_ou(sente)
1230 if (sente && (ou.y >= 4))
1231 puts "'NG: Black's OU does not enter yet." if $DEBUG
1234 if (! sente && (ou.y <= 6))
1235 puts "'NG: White's OU does not enter yet." if $DEBUG
1243 hands = @sente_hands
1253 (@array[x][y].sente == sente) &&
1254 (@array[x][y].point > 0))
1255 point = point + @array[x][y].point
1261 hands.each do |piece|
1262 point = point + piece.point
1266 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1271 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1276 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1281 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1285 # sente is nil only if tests in test_board run
1286 def handle_one_move(str, sente=nil)
1287 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1294 elsif (str =~ /^%KACHI/)
1295 raise ArgumentError, "sente is null", caller if sente == nil
1296 if (good_kachi?(sente))
1301 elsif (str =~ /^%TORYO/)
1307 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1308 ((x0 != 0) || (y0 != 0)))
1310 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1316 sente = true if sente == nil # deprecated
1317 return :illegal unless sente == true # black player's move must be black
1318 hands = @sente_hands
1320 sente = false if sente == nil # deprecated
1321 return :illegal unless sente == false # white player's move must be white
1326 if ((x0 == 0) && (y0 == 0))
1327 return :illegal if (! have_piece?(hands, name))
1328 elsif (! @array[x0][y0])
1329 return :illegal # no piece
1330 elsif (@array[x0][y0].sente != sente)
1331 return :illegal # this is not mine
1332 elsif (@array[x0][y0].name != name)
1333 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1336 ## destination check
1337 if (@array[x1][y1] &&
1338 (@array[x1][y1].sente == sente)) # can't capture mine
1340 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1341 return :illegal # can't put on existing piece
1344 tmp_board = Marshal.load(Marshal.dump(self))
1345 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1346 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1347 return :oute_sennichite if tmp_board.oute_sennichite?(sente)
1348 return :sennichite if tmp_board.sennichite?(sente)
1350 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1354 move_to(x0, y0, x1, y1, name, sente)
1357 if (checkmated?(! sente))
1359 @sente_history[str] = (@sente_history[str] || 0) + 1
1361 @gote_history[str] = (@gote_history[str] || 0) + 1
1365 @sente_history.clear
1370 @history[str] = (@history[str] || 0) + 1
1378 a.push(sprintf("P%d", y))
1381 piece = @array[x][y]
1390 a.push(sprintf("\n"))
1393 if (! sente_hands.empty?)
1395 sente_hands.each do |p|
1396 a.push("00" + p.name)
1400 if (! gote_hands.empty?)
1402 gote_hands.each do |p|
1403 a.push("00" + p.name)
1413 attr_reader :players, :black, :white
1415 def initialize(p1, p2)
1419 if p1.sente && !p2.sente
1420 @black, @white = p1, p2
1421 elsif !p1.sente && p2.sente
1422 @black, @white = p2, p1
1424 raise "Never reached!"
1429 class GameResultWin < GameResult
1430 attr_reader :winner, :loser
1432 def initialize(winner, loser)
1434 @winner, @loser = winner, loser
1438 black_name = @black.id || @black.name
1439 white_name = @white.id || @white.name
1440 "%s:%s" % [black_name, white_name]
1444 class GameResultDraw < GameResult
1452 def initialize(game_name, player0, player1)
1453 @monitors = Array::new
1454 @game_name = game_name
1455 if (@game_name =~ /-(\d+)-(\d+)$/)
1456 @total_time = $1.to_i
1467 @current_player = @sente
1468 @next_player = @gote
1476 @sente.status = "agree_waiting"
1477 @gote.status = "agree_waiting"
1479 @id = sprintf("%s+%s+%s+%s+%s",
1480 LEAGUE.event, @game_name, @sente.name, @gote.name, issue_current_time)
1481 @logfile = File.join(LEAGUE.dir, @id + ".csa")
1483 LEAGUE.games[@id] = self
1485 log_message(sprintf("game created %s", @id))
1495 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1496 attr_accessor :last_move, :current_turn
1500 @sente.rated? && @gote.rated?
1503 def monitoron(monitor)
1504 @monitors.delete(monitor)
1505 @monitors.push(monitor)
1508 def monitoroff(monitor)
1509 @monitors.delete(monitor)
1512 def reject(rejector)
1513 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1514 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1519 if ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
1521 elsif (@current_player == killer)
1528 log_message(sprintf("game finished %s", @id))
1529 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1534 @sente.status = "connected"
1535 @gote.status = "connected"
1537 if (@current_player.protocol == LoginCSA::PROTOCOL)
1538 @current_player.finish
1540 if (@next_player.protocol == LoginCSA::PROTOCOL)
1543 @monitors = Array::new
1546 @current_player = nil
1548 LEAGUE.games.delete(@id)
1551 def handle_one_move(str, player)
1553 if (@current_player == player)
1554 @end_time = Time::new
1555 t = (@end_time - @start_time).floor
1556 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
1559 if ((@current_player.mytime - t <= -@byoyomi) && ((@total_time > 0) || (@byoyomi > 0)))
1561 elsif (str == :timeout)
1562 return false # time isn't expired. players aren't swapped. continue game
1564 @current_player.mytime = @current_player.mytime - t
1565 if (@current_player.mytime < 0)
1566 @current_player.mytime = 0
1570 move_status = @board.handle_one_move(str, @sente == @current_player)
1572 # log_error("handle_one_move raise exception for #{str}")
1573 # move_status = :illegal
1576 if ((move_status == :illegal) || (move_status == :uchifuzme) || (move_status == :oute_kaihimore))
1577 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1579 if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite))
1580 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1581 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1582 @fh.printf("%s\nT%d\n", str, t)
1583 @last_move = sprintf("%s,T%d", str, t)
1584 @current_turn = @current_turn + 1
1587 @monitors.each do |monitor|
1588 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1589 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1594 if (@next_player.status != "game") # rival is logout or disconnected
1596 elsif (status == :timeout)
1598 elsif (move_status == :illegal)
1600 elsif (move_status == :kachi_win)
1602 elsif (move_status == :kachi_lose)
1604 elsif (move_status == :toryo)
1606 elsif (move_status == :outori)
1608 elsif (move_status == :sennichite)
1610 elsif (move_status == :oute_sennichite)
1611 oute_sennichite_lose()
1612 elsif (move_status == :uchifuzume)
1614 elsif (move_status == :oute_kaihimore)
1615 oute_kaihimore_lose()
1619 finish() if finish_flag
1620 (@current_player, @next_player) = [@next_player, @current_player]
1621 @start_time = Time::new
1627 @current_player.status = "connected"
1628 @next_player.status = "connected"
1629 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1630 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1631 @fh.printf("%%TORYO\n")
1632 @fh.print(@board.to_s.gsub(/^/, "\'"))
1633 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1634 @result = GameResultWin.new(@current_player, @next_player)
1635 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1636 @monitors.each do |monitor|
1637 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1642 @current_player.status = "connected"
1643 @next_player.status = "connected"
1644 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1645 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1646 @fh.printf("%%TORYO\n")
1647 @fh.print(@board.to_s.gsub(/^/, "\'"))
1648 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1649 @result = GameResultWin.new(@next_player, @current_player)
1650 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1651 @monitors.each do |monitor|
1652 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1657 @current_player.status = "connected"
1658 @next_player.status = "connected"
1659 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1660 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1661 @fh.print(@board.to_s.gsub(/^/, "\'"))
1662 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1663 @result = GameResultDraw.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] #SENNICHITE\n", @id))
1670 def oute_sennichite_lose
1671 @current_player.status = "connected"
1672 @next_player.status = "connected"
1673 @current_player.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1674 @next_player.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1675 @fh.print(@board.to_s.gsub(/^/, "\'"))
1676 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1677 @result = GameResultWin.new(@next_player, @current_player)
1678 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1679 @monitors.each do |monitor|
1680 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1685 @current_player.status = "connected"
1686 @next_player.status = "connected"
1687 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1688 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1689 @fh.print(@board.to_s.gsub(/^/, "\'"))
1690 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1691 @result = GameResultWin.new(@next_player, @current_player)
1692 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1693 @monitors.each do |monitor|
1694 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1699 @current_player.status = "connected"
1700 @next_player.status = "connected"
1701 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1702 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1703 @fh.print(@board.to_s.gsub(/^/, "\'"))
1704 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1705 @result = GameResultWin.new(@next_player, @current_player)
1706 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1707 @monitors.each do |monitor|
1708 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1712 def oute_kaihimore_lose
1713 @current_player.status = "connected"
1714 @next_player.status = "connected"
1715 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1716 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1717 @fh.print(@board.to_s.gsub(/^/, "\'"))
1718 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1719 @result = GameResultWin.new(@next_player, @current_player)
1720 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1721 @monitors.each do |monitor|
1722 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1727 @current_player.status = "connected"
1728 @next_player.status = "connected"
1729 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1730 @next_player.write_safe("#TIME_UP\n#WIN\n")
1731 @fh.print(@board.to_s.gsub(/^/, "\'"))
1732 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1733 @result = GameResultWin.new(@next_player, @current_player)
1734 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1735 @monitors.each do |monitor|
1736 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
1741 @current_player.status = "connected"
1742 @next_player.status = "connected"
1743 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1744 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1745 @fh.printf("%%KACHI\n")
1746 @fh.print(@board.to_s.gsub(/^/, "\'"))
1747 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1748 @result = GameResultWin.new(@current_player, @next_player)
1749 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1750 @monitors.each do |monitor|
1751 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1756 @current_player.status = "connected"
1757 @next_player.status = "connected"
1758 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1759 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1760 @fh.printf("%%KACHI\n")
1761 @fh.print(@board.to_s.gsub(/^/, "\'"))
1762 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1763 @result = GameResultWin.new(@next_player, @current_player)
1764 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1765 @monitors.each do |monitor|
1766 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1771 @current_player.status = "connected"
1772 @next_player.status = "connected"
1773 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1774 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1775 @fh.printf("%%TORYO\n")
1776 @fh.print(@board.to_s.gsub(/^/, "\'"))
1777 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1778 @result = GameResultWin.new(@next_player, @current_player)
1779 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1780 @monitors.each do |monitor|
1781 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1786 @current_player.status = "connected"
1787 @next_player.status = "connected"
1788 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1789 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1790 @fh.print(@board.to_s.gsub(/^/, "\'"))
1791 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1792 @result = GameResultWin.new(@current_player, @next_player)
1793 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1794 @monitors.each do |monitor|
1795 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1800 log_message(sprintf("game started %s", @id))
1801 @sente.write_safe(sprintf("START:%s\n", @id))
1802 @gote.write_safe(sprintf("START:%s\n", @id))
1803 @sente.mytime = @total_time
1804 @gote.mytime = @total_time
1805 @start_time = Time::new
1810 @fh = open(@logfile, "w")
1814 @fh.printf("N+%s\n", @sente.name)
1815 @fh.printf("N-%s\n", @gote.name)
1816 @fh.printf("$EVENT:%s\n", @id)
1818 @sente.write_safe(propose_message("+"))
1819 @gote.write_safe(propose_message("-"))
1821 @fh.printf("$START_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1823 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1824 P2 * -HI * * * * * -KA *
1825 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1826 P4 * * * * * * * * *
1827 P5 * * * * * * * * *
1828 P6 * * * * * * * * *
1829 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1830 P8 * +KA * * * * * +HI *
1831 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1840 Protocol_Version:1.1
1841 Protocol_Mode:Server
1843 Declaration:Jishogi 1.1
1845 Name+:#{@sente.name}
1851 Total_Time:#{@total_time}
1853 Least_Time_Per_Move:#{Least_Time_Per_Move}
1854 Remaining_Time+:#{@sente.mytime}
1855 Remaining_Time-:#{@gote.mytime}
1856 Last_Move:#{@last_move}
1857 Current_Turn:#{@current_turn}
1867 return str0 + @board.to_s + str1
1870 def propose_message(sg_flag)
1873 Protocol_Version:1.1
1874 Protocol_Mode:Server
1876 Declaration:Jishogi 1.1
1878 Name+:#{@sente.name}
1880 Your_Turn:#{sg_flag}
1885 Total_Time:#{@total_time}
1887 Least_Time_Per_Move:#{Least_Time_Per_Move}
1890 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1891 P2 * -HI * * * * * -KA *
1892 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1893 P4 * * * * * * * * *
1894 P5 * * * * * * * * *
1895 P6 * * * * * * * * *
1896 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1897 P8 * +KA * * * * * +HI *
1898 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1910 def issue_current_time
1911 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
1912 @@mutex.synchronize do
1913 while time <= @@time do
1920 end # module ShogiServer
1922 #################################################
1929 shogi-server - server for CSA server protocol
1932 shogi-server [OPTIONS] event_name port_number
1935 server for CSA server protocol
1939 specify filename for logging process ID
1941 run as a daemon. Log files will be put in dir.
1944 this file is distributed under GPL version2 and might be compiled by Exerb
1949 #{ShogiServer::Release}
1952 #{ShogiServer::Revision}
1956 def log_message(str)
1960 def log_warning(str)
1969 def parse_command_line
1971 parser = GetoptLong.new( ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
1972 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT]
1976 parser.each_option do |name, arg|
1977 name.sub!(/^--/, '')
1978 options[name] = arg.dup
1982 raise parser.error_message
1987 def write_pid_file(file)
1988 open(file, "w") do |fh|
1989 fh.print Process::pid, "\n"
1993 def mutex_watchdog(mutex, sec)
2005 log_error("mutex watchdog timeout")
2016 mutex_watchdog($mutex, 10)
2019 $options = parse_command_line
2020 if (ARGV.length != 2)
2025 LEAGUE.event = ARGV.shift
2028 write_pid_file($options["pid-file"]) if ($options["pid-file"])
2030 dir = $options["daemon"] || nil
2031 if dir && ! File.exist?(dir)
2032 FileUtils.mkdir(dir)
2034 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
2035 $logger = WEBrick::Log.new(log_file)
2037 LEAGUE.dir = dir || File.dirname(__FILE__)
2038 LEAGUE.setup_players_database
2041 config[:Port] = port
2042 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
2043 config[:Logger] = $logger
2045 server = WEBrick::GenericServer.new(config)
2046 ["INT", "TERM"].each {|signal| trap(signal){ server.shutdown } }
2047 $stderr.puts("server started as a deamon") if $options["daemon"]
2048 log_message("server started")
2050 server.start do |client|
2054 while (str = client.gets_timeout(ShogiServer::Login_Time))
2059 if (ShogiServer::Login::good_login?(str))
2060 player = ShogiServer::Player::new(str, client)
2062 login = ShogiServer::Login::factory(str, player)
2063 if (LEAGUE.players[player.name])
2064 if ((LEAGUE.players[player.name].password == player.password) &&
2065 (LEAGUE.players[player.name].status != "game"))
2066 log_message(sprintf("user %s login forcely", player.name))
2067 LEAGUE.players[player.name].kill
2069 login.incorrect_duplicated_player(str)
2080 client.write_safe("LOGIN:incorrect" + eol)
2081 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2093 log_message(sprintf("user %s login", player.name))
2095 player.run(login.csa_1st_str)
2099 player.game.kill(player)
2101 player.finish # socket has been closed
2102 LEAGUE.delete(player)
2103 log_message(sprintf("user %s logout", player.name))
2114 TCPSocket.do_not_reverse_lookup = true
2115 Thread.abort_on_exception = true
2117 LEAGUE = ShogiServer::League::new