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
30 def gets_timeout(t = Default_Timeout)
41 def gets_safe(t = nil)
62 return self.write(str)
70 module ShogiServer # for a namespace
72 Max_Write_Queue_Size = 1000
73 Max_Identifier_Length = 32
74 Default_Timeout = 60 # for single socket operation
76 Default_Game_Name = "default-1500-0"
79 Least_Time_Per_Move = 1
80 Login_Time = 300 # time for LOGIN
82 Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
83 Release.concat("-") if (Release == "")
84 Revision = "$Revision$".gsub(/[^\.\d]/, '')
92 @db = YAML::Store.new( File.join(File.dirname(__FILE__), "players.yaml") )
94 attr_accessor :players, :games, :event
97 self.load(player) if player.id
98 @players[player.name] = player
102 @players.delete(player.name)
105 def get_player(status, game_name, sente, searcher=nil)
106 @players.each do |name, player|
107 if ((player.status == status) &&
108 (player.game_name == game_name) &&
109 ((sente == nil) || (player.sente == nil) || (player.sente == sente)) &&
110 ((searcher == nil) || (player != searcher)))
118 hash = search(player.id)
121 player.name = hash['name']
122 player.rate = hash['rate']
123 player.modified_at = hash['last_modified']
124 player.rating_group = hash['rating_group']
131 break unless @db["players"]
132 @db["players"].each do |group, players|
142 @db.transaction(true) do
143 break unless @db["players"]
144 @db["players"].each do |group, players_hash|
145 players << players_hash.keys
148 return players.flatten.collect do |id|
158 ######################################################
159 # Processes the LOGIN command.
162 def Login.good_login?(str)
164 if (((tokens.length == 3) || ((tokens.length == 4) && tokens[3] == "x1")) &&
165 (tokens[0] == "LOGIN") &&
166 (good_identifier?(tokens[1])))
173 def Login.good_game_name?(str)
174 if ((str =~ /^(.+)-\d+-\d+$/) && (good_identifier?($1)))
181 def Login.good_identifier?(str)
182 if str =~ /\A[\w\d_@\-\.]{1,#{Max_Identifier_Length}}\z/
189 def Login.factory(str, player)
190 (login, player.name, password, ext) = str.chomp.split
192 return Loginx1.new(player, password)
194 return LoginCSA.new(player, password)
200 # the first command that will be executed just after LOGIN.
201 # If it is nil, the default process will be started.
202 attr_reader :csa_1st_str
204 def initialize(player, password)
207 parse_password(password)
211 @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
212 log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
215 def incorrect_duplicated_player(str)
216 @player.write_safe("LOGIN:incorrect\n")
217 @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
218 sleep 3 # wait for sending the above messages.
219 @player.name = "%s [duplicated]" % [@player.name]
224 ######################################################
225 # Processes LOGIN for the CSA standard mode.
227 class LoginCSA < Login
230 def initialize(player, password)
233 @player.protocol = PROTOCOL
236 def parse_password(password)
237 if Login.good_game_name?(password)
239 @player.set_password(nil)
240 elsif password.split(",").size > 1
241 @gamename, *trip = password.split(",")
242 @player.set_password(trip.join(","))
244 @player.set_password(password)
245 @gamename = Default_Game_Name
247 @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
252 @csa_1st_str = "%%GAME #{@gamename} *"
256 ######################################################
257 # Processes LOGIN for the extented mode.
259 class Loginx1 < Login
262 def initialize(player, password)
264 @player.protocol = PROTOCOL
267 def parse_password(password)
268 @player.set_password(password)
273 @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
279 # Idetifier of the player in the rating system
285 # Password of the player, which does not include a trip
286 attr_accessor :password
288 # Score in the rating sysem
291 # Group in the rating system
292 attr_accessor :rating_group
294 # Last timestamp when the rate was modified
295 attr_accessor :modified_at
303 @modified_at || Time.now
309 @modified_at = Time.now
319 simple_name = @name.gsub(/@.*?$/, '')
320 "%s+%s" % [simple_name, @trip[0..8]]
327 # Parses str in the LOGIN command, sets up @id and @trip
329 def set_password(str)
330 if str && !str.empty?
331 @password = str.strip
332 @id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
334 @id = @password = nil
340 class Player < BasicPlayer
341 def initialize(str, socket)
344 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
346 @protocol = nil # CSA or x1
347 @eol = "\m" # favorite eol code
350 @mytime = 0 # set in start method also
352 @write_queue = Queue::new
353 @main_thread = Thread::current
354 @writer_thread = Thread::start do
360 attr_accessor :socket, :status
361 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
362 attr_accessor :main_thread, :writer_thread, :write_queue
365 log_message(sprintf("user %s killed", @name))
370 Thread::kill(@main_thread) if @main_thread
374 if (@status != "finished")
376 log_message(sprintf("user %s finish", @name))
377 # TODO you should confirm that there is no message in the queue.
378 Thread::kill(@writer_thread) if @writer_thread
380 @socket.close if (! @socket.closed?)
382 log_message(sprintf("user %s finish failed", @name))
388 @write_queue.push(str.gsub(/[\r\n]+/, @eol))
392 while (str = @write_queue.pop)
393 @socket.write_safe(str)
398 if ((status == "game_waiting") ||
399 (status == "start_waiting") ||
400 (status == "agree_waiting") ||
403 return sprintf("%s %s %s %s +", @name, @protocol, @status, @game_name)
404 elsif (@sente == false)
405 return sprintf("%s %s %s %s -", @name, @protocol, @status, @game_name)
406 elsif (@sente == nil)
407 return sprintf("%s %s %s %s *", @name, @protocol, @status, @game_name)
410 return sprintf("%s %s %s", @name, @protocol, @status)
415 @socket.write_safe('##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"')
418 def run(csa_1st_str=nil)
419 while (csa_1st_str || (str = @socket.gets_safe(Default_Timeout)))
426 if (@write_queue.size > Max_Write_Queue_Size)
427 log_warning(sprintf("write_queue of %s is %d", @name, @write_queue.size))
431 if (@status == "finished")
434 str.chomp! if (str.class == String)
437 if (@status == "game")
438 array_str = str.split(",")
439 move = array_str.shift
440 additional = array_str.shift
441 if /^'(.*)/ =~ additional
442 comment = array_str.unshift("'*#{$1}")
444 s = @game.handle_one_move(move, self)
445 @game.fh.print("#{comment}\n") if (comment && !s)
446 return if (s && @protocol == LoginCSA::PROTOCOL)
448 when /^%[^%]/, :timeout
449 if (@status == "game")
450 s = @game.handle_one_move(str, self)
451 return if (s && @protocol == LoginCSA::PROTOCOL)
454 if (@status == "agree_waiting")
456 return if (@protocol == LoginCSA::PROTOCOL)
458 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
461 if (@status == "agree_waiting")
462 @status = "start_waiting"
463 if ((@game.sente.status == "start_waiting") &&
464 (@game.gote.status == "start_waiting"))
466 @game.sente.status = "game"
467 @game.gote.status = "game"
470 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
472 when /^%%SHOW\s+(\S+)/
474 if (LEAGUE.games[game_id])
475 write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
477 write_safe("##[SHOW] +OK\n")
478 when /^%%MONITORON\s+(\S+)/
480 if (LEAGUE.games[game_id])
481 LEAGUE.games[game_id].monitoron(self)
482 write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
483 write_safe("##[MONITOR][#{game_id}] +OK\n")
485 when /^%%MONITOROFF\s+(\S+)/
487 if (LEAGUE.games[game_id])
488 LEAGUE.games[game_id].monitoroff(self)
493 players = LEAGUE.rated_players
494 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
495 write_safe("##[RATING] %s \t %4d @%s\n" %
496 [p.simple_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
498 write_safe("##[RATING] +OK\n")
500 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
501 write_safe("##[VERSION] +OK\n")
503 if ((@status == "connected") || (@status == "game_waiting"))
504 @status = "connected"
507 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
509 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
513 if (! Login::good_game_name?(game_name))
514 write_safe(sprintf("##[ERROR] bad game name\n"))
516 elsif ((@status == "connected") || (@status == "game_waiting"))
519 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
522 if ((my_sente_str == "*") ||
523 (my_sente_str == "+") ||
524 (my_sente_str == "-"))
527 write_safe(sprintf("##[ERROR] bad game option\n"))
531 if (my_sente_str == "*")
532 rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
533 elsif (my_sente_str == "+")
534 rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
535 elsif (my_sente_str == "-")
536 rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
541 @game_name = game_name
542 if ((my_sente_str == "*") && (rival.sente == nil))
550 elsif (rival.sente == true) # rival has higher priority
552 elsif (rival.sente == false)
554 elsif (my_sente_str == "+")
557 elsif (my_sente_str == "-")
563 Game::new(@game_name, self, rival)
564 self.status = "agree_waiting"
565 rival.status = "agree_waiting"
566 else # rival not found
567 if (command_name == "GAME")
568 @status = "game_waiting"
569 @game_name = game_name
570 if (my_sente_str == "+")
572 elsif (my_sente_str == "-")
578 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
579 @status = "connected"
584 when /^%%CHAT\s+(.+)/
586 LEAGUE.players.each do |name, player|
587 if (player.protocol != LoginCSA::PROTOCOL)
588 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
593 LEAGUE.games.each do |id, game|
594 buf.push(sprintf("##[LIST] %s\n", id))
596 buf.push("##[LIST] +OK\n")
600 LEAGUE.players.each do |name, player|
601 buf.push(sprintf("##[WHO] %s\n", player.to_s))
603 buf.push("##[WHO] +OK\n")
606 @status = "connected"
607 write_safe("LOGOUT:completed\n")
610 ## ignore null string
612 write_safe(sprintf("##[ERROR] unknown command %s\n", str))
622 PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
623 def initialize(board, x, y, sente, promoted=false)
630 if ((x == 0) || (y == 0))
632 hands = board.sente_hands
634 hands = board.gote_hands
641 @board.array[x][y] = self
644 attr_accessor :promoted, :sente, :x, :y, :board
646 def room_of_head?(x, y, name)
651 return adjacent_movable_grids + far_movable_grids
654 def far_movable_grids
659 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
660 if ((@board.array[x][y] == nil) || # dst is empty
661 (@board.array[x][y].sente != @sente)) # dst is enemy
669 if ((1 <= x) && (x <= 9) && (1 <= y) && (y <= 9))
670 if (@board.array[x][y] == nil) # dst is empty?
677 def adjacent_movable_grids
680 moves = @promoted_moves
682 moves = @normal_moves
684 moves.each do |(dx, dy)|
691 if (jump_to?(cand_x, cand_y))
692 grids.push([cand_x, cand_y])
698 def move_to?(x, y, name)
699 return false if (! room_of_head?(x, y, name))
700 return false if ((name != @name) && (name != @promoted_name))
701 return false if (@promoted && (name != @promoted_name)) # can't un-promote
704 return false if (((@x == 0) || (@y == 0)) && (name != @name)) # can't put promoted piece
706 return false if ((4 <= @y) && (4 <= y) && (name != @name)) # can't promote
708 return false if ((6 >= @y) && (6 >= y) && (name != @name))
712 if ((@x == 0) || (@y == 0))
713 return jump_to?(x, y)
715 return movable_grids.include?([x, y])
720 if ((@x == 0) || (@y == 0))
722 @board.sente_hands.delete(self)
724 @board.gote_hands.delete(self)
726 @board.array[x][y] = self
727 elsif ((x == 0) || (y == 0))
728 @promoted = false # clear promoted flag before moving to hands
730 @board.sente_hands.push(self)
732 @board.gote_hands.push(self)
734 @board.array[@x][@y] = nil
736 @board.array[@x][@y] = nil
737 @board.array[x][y] = self
770 class PieceFU < Piece
773 @normal_moves = [[0, +1]]
774 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
776 @promoted_name = "TO"
779 def room_of_head?(x, y, name)
782 return false if (y == 1)
784 return false if (y == 9)
790 if ((iy != @y) && # not source position
791 @board.array[x][iy] &&
792 (@board.array[x][iy].sente == @sente) && # mine
793 (@board.array[x][iy].name == "FU") &&
794 (@board.array[x][iy].promoted == false))
804 class PieceKY < Piece
808 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
810 @promoted_name = "NY"
813 def room_of_head?(x, y, name)
816 return false if (y == 1)
818 return false if (y == 9)
823 def far_movable_grids
831 while (jump_to?(cand_x, cand_y))
832 grids.push([cand_x, cand_y])
833 break if (! put_to?(cand_x, cand_y))
839 while (jump_to?(cand_x, cand_y))
840 grids.push([cand_x, cand_y])
841 break if (! put_to?(cand_x, cand_y))
849 class PieceKE < Piece
852 @normal_moves = [[+1, +2], [-1, +2]]
853 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
855 @promoted_name = "NK"
858 def room_of_head?(x, y, name)
861 return false if ((y == 1) || (y == 2))
863 return false if ((y == 9) || (y == 8))
869 class PieceGI < Piece
872 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, -1], [-1, -1]]
873 @promoted_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
875 @promoted_name = "NG"
879 class PieceKI < Piece
882 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1]]
889 class PieceKA < Piece
893 @promoted_moves = [[0, +1], [+1, 0], [-1, 0], [0, -1]]
895 @promoted_name = "UM"
898 def far_movable_grids
903 while (jump_to?(cand_x, cand_y))
904 grids.push([cand_x, cand_y])
905 break if (! put_to?(cand_x, cand_y))
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 class PieceHI < Piece
943 @promoted_moves = [[+1, +1], [-1, +1], [+1, -1], [-1, -1]]
945 @promoted_name = "RY"
948 def far_movable_grids
953 while (jump_to?(cand_x, cand_y))
954 grids.push([cand_x, cand_y])
955 break if (! put_to?(cand_x, cand_y))
961 while (jump_to?(cand_x, cand_y))
962 grids.push([cand_x, cand_y])
963 break if (! put_to?(cand_x, cand_y))
969 while (jump_to?(cand_x, cand_y))
970 grids.push([cand_x, cand_y])
971 break if (! put_to?(cand_x, cand_y))
977 while (jump_to?(cand_x, cand_y))
978 grids.push([cand_x, cand_y])
979 break if (! put_to?(cand_x, cand_y))
985 class PieceOU < Piece
988 @normal_moves = [[0, +1], [+1, +1], [-1, +1], [+1, +0], [-1, +0], [0, -1], [+1, -1], [-1, -1]]
998 @sente_hands = Array::new
999 @gote_hands = Array::new
1000 @history = Hash::new
1001 @sente_history = Hash::new
1002 @gote_history = Hash::new
1003 @array = [[], [], [], [], [], [], [], [], [], []]
1006 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history
1007 attr_reader :move_count
1010 PieceKY::new(self, 1, 1, false)
1011 PieceKE::new(self, 2, 1, false)
1012 PieceGI::new(self, 3, 1, false)
1013 PieceKI::new(self, 4, 1, false)
1014 PieceOU::new(self, 5, 1, false)
1015 PieceKI::new(self, 6, 1, false)
1016 PieceGI::new(self, 7, 1, false)
1017 PieceKE::new(self, 8, 1, false)
1018 PieceKY::new(self, 9, 1, false)
1019 PieceKA::new(self, 2, 2, false)
1020 PieceHI::new(self, 8, 2, false)
1021 PieceFU::new(self, 1, 3, false)
1022 PieceFU::new(self, 2, 3, false)
1023 PieceFU::new(self, 3, 3, false)
1024 PieceFU::new(self, 4, 3, false)
1025 PieceFU::new(self, 5, 3, false)
1026 PieceFU::new(self, 6, 3, false)
1027 PieceFU::new(self, 7, 3, false)
1028 PieceFU::new(self, 8, 3, false)
1029 PieceFU::new(self, 9, 3, false)
1031 PieceKY::new(self, 1, 9, true)
1032 PieceKE::new(self, 2, 9, true)
1033 PieceGI::new(self, 3, 9, true)
1034 PieceKI::new(self, 4, 9, true)
1035 PieceOU::new(self, 5, 9, true)
1036 PieceKI::new(self, 6, 9, true)
1037 PieceGI::new(self, 7, 9, true)
1038 PieceKE::new(self, 8, 9, true)
1039 PieceKY::new(self, 9, 9, true)
1040 PieceKA::new(self, 8, 8, true)
1041 PieceHI::new(self, 2, 8, true)
1042 PieceFU::new(self, 1, 7, true)
1043 PieceFU::new(self, 2, 7, true)
1044 PieceFU::new(self, 3, 7, true)
1045 PieceFU::new(self, 4, 7, true)
1046 PieceFU::new(self, 5, 7, true)
1047 PieceFU::new(self, 6, 7, true)
1048 PieceFU::new(self, 7, 7, true)
1049 PieceFU::new(self, 8, 7, true)
1050 PieceFU::new(self, 9, 7, true)
1053 def have_piece?(hands, name)
1054 piece = hands.find { |i|
1060 def move_to(x0, y0, x1, y1, name, sente)
1062 hands = @sente_hands
1067 if ((x0 == 0) || (y0 == 0))
1068 piece = have_piece?(hands, name)
1069 return :illegal if (! piece.move_to?(x1, y1, name))
1070 piece.move_to(x1, y1)
1072 return :illegal if (! @array[x0][y0].move_to?(x1, y1, name))
1073 if (@array[x0][y0].name != name) # promoted ?
1074 @array[x0][y0].promoted = true
1077 if (@array[x1][y1].name == "OU")
1078 return :outori # return board update
1080 @array[x1][y1].sente = @array[x0][y0].sente
1081 @array[x1][y1].move_to(0, 0)
1086 @array[x0][y0].move_to(x1, y1)
1092 def look_for_ou(sente)
1098 (@array[x][y].name == "OU") &&
1099 (@array[x][y].sente == sente))
1106 raise "can't find ou"
1109 def checkmated?(sente) # sente is loosing
1110 ou = look_for_ou(sente)
1116 (@array[x][y].sente != sente))
1117 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
1128 def uchifuzume?(sente)
1129 rival_ou = look_for_ou(! sente) # rival's ou
1130 if (sente) # rival is gote
1131 if ((rival_ou.y != 9) &&
1132 (@array[rival_ou.x][rival_ou.y + 1]) &&
1133 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
1134 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
1136 fu_y = rival_ou.y + 1
1141 if ((rival_ou.y != 0) &&
1142 (@array[rival_ou.x][rival_ou.y - 1]) &&
1143 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
1144 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
1146 fu_y = rival_ou.y - 1
1152 ## case: rival_ou is moving
1154 rival_ou.movable_grids.each do |(cand_x, cand_y)|
1155 tmp_board = Marshal.load(Marshal.dump(self))
1156 s = tmp_board.move_to(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente)
1157 raise "internal error" if (s != true)
1158 if (! tmp_board.checkmated?(! sente)) # good move
1163 ## case: rival is capturing fu
1169 (@array[x][y].sente != sente) &&
1170 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
1171 if (@array[x][y].promoted)
1172 name = @array[x][y].promoted_name
1174 name = @array[x][y].name
1176 tmp_board = Marshal.load(Marshal.dump(self))
1177 s = tmp_board.move_to(x, y, fu_x, fu_y, name, ! sente)
1178 raise "internal error" if (s != true)
1179 if (! tmp_board.checkmated?(! sente)) # good move
1190 def oute_sennichite?(sente)
1191 if (checkmated?(! sente))
1194 if (@sente_history[str] && (@sente_history[str] >= 3)) # already 3 times
1198 if (@gote_history[str] && (@gote_history[str] >= 3)) # already 3 times
1206 def sennichite?(sente)
1208 if (@history[str] && (@history[str] >= 3)) # already 3 times
1214 def good_kachi?(sente)
1215 if (checkmated?(sente))
1216 puts "'NG: Checkmating." if $DEBUG
1220 ou = look_for_ou(sente)
1221 if (sente && (ou.y >= 4))
1222 puts "'NG: Black's OU does not enter yet." if $DEBUG
1225 if (! sente && (ou.y <= 6))
1226 puts "'NG: White's OU does not enter yet." if $DEBUG
1234 hands = @sente_hands
1244 (@array[x][y].sente == sente) &&
1245 (@array[x][y].point > 0))
1246 point = point + @array[x][y].point
1252 hands.each do |piece|
1253 point = point + piece.point
1257 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
1262 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
1267 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
1272 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
1276 # sente is nil only if tests in test_board run
1277 def handle_one_move(str, sente=nil)
1278 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
1285 elsif (str =~ /^%KACHI/)
1286 raise ArgumentError, "sente is null", caller if sente == nil
1287 if (good_kachi?(sente))
1292 elsif (str =~ /^%TORYO/)
1298 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
1299 ((x0 != 0) || (y0 != 0)))
1301 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
1307 sente = true if sente == nil # deprecated
1308 return :illegal unless sente == true # black player's move must be black
1309 hands = @sente_hands
1311 sente = false if sente == nil # deprecated
1312 return :illegal unless sente == false # white player's move must be white
1317 if ((x0 == 0) && (y0 == 0))
1318 return :illegal if (! have_piece?(hands, name))
1319 elsif (! @array[x0][y0])
1320 return :illegal # no piece
1321 elsif (@array[x0][y0].sente != sente)
1322 return :illegal # this is not mine
1323 elsif (@array[x0][y0].name != name)
1324 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
1327 ## destination check
1328 if (@array[x1][y1] &&
1329 (@array[x1][y1].sente == sente)) # can't capture mine
1331 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
1332 return :illegal # can't put on existing piece
1335 tmp_board = Marshal.load(Marshal.dump(self))
1336 return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
1337 return :oute_kaihimore if (tmp_board.checkmated?(sente))
1338 return :oute_sennichite if tmp_board.oute_sennichite?(sente)
1339 return :sennichite if tmp_board.sennichite?(sente)
1341 if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
1345 move_to(x0, y0, x1, y1, name, sente)
1348 if (checkmated?(! sente))
1350 @sente_history[str] = (@sente_history[str] || 0) + 1
1352 @gote_history[str] = (@gote_history[str] || 0) + 1
1356 @sente_history.clear
1361 @history[str] = (@history[str] || 0) + 1
1369 a.push(sprintf("P%d", y))
1372 piece = @array[x][y]
1381 a.push(sprintf("\n"))
1384 if (! sente_hands.empty?)
1386 sente_hands.each do |p|
1387 a.push("00" + p.name)
1391 if (! gote_hands.empty?)
1393 gote_hands.each do |p|
1394 a.push("00" + p.name)
1404 attr_reader :players, :black, :white
1406 def initialize(p1, p2)
1410 if p1.sente && !p2.sente
1411 @black, @white = p1, p2
1412 elsif !p1.sente && p2.sente
1413 @black, @white = p2, p1
1415 raise "Never reached!"
1420 class GameResultWin < GameResult
1421 attr_reader :winner, :loser
1423 def initialize(winner, loser)
1425 @winner, @loser = winner, loser
1429 black_name = @black.id || @black.name
1430 white_name = @white.id || @white.name
1431 "%s:%s" % [black_name, white_name]
1435 class GameResultDraw < GameResult
1443 def initialize(game_name, player0, player1)
1444 @monitors = Array::new
1445 @game_name = game_name
1446 if (@game_name =~ /-(\d+)-(\d+)$/)
1447 @total_time = $1.to_i
1458 @current_player = @sente
1459 @next_player = @gote
1467 @sente.status = "agree_waiting"
1468 @gote.status = "agree_waiting"
1470 @id = sprintf("%s+%s+%s+%s+%s",
1471 LEAGUE.event, @game_name, @sente.name, @gote.name, issue_current_time)
1472 @logfile = @id + ".csa"
1474 LEAGUE.games[@id] = self
1476 log_message(sprintf("game created %s", @id))
1486 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :id, :board, :current_player, :next_player, :fh, :monitors
1487 attr_accessor :last_move, :current_turn
1491 @sente.rated? && @gote.rated?
1494 def monitoron(monitor)
1495 @monitors.delete(monitor)
1496 @monitors.push(monitor)
1499 def monitoroff(monitor)
1500 @monitors.delete(monitor)
1503 def reject(rejector)
1504 @sente.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1505 @gote.write_safe(sprintf("REJECT:%s by %s\n", @id, rejector))
1510 if ((@sente.status == "agree_waiting") || (@sente.status == "start_waiting"))
1512 elsif (@current_player == killer)
1519 log_message(sprintf("game finished %s", @id))
1520 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1525 @sente.status = "connected"
1526 @gote.status = "connected"
1528 if (@current_player.protocol == LoginCSA::PROTOCOL)
1529 @current_player.finish
1531 if (@next_player.protocol == LoginCSA::PROTOCOL)
1534 @monitors = Array::new
1537 @current_player = nil
1539 LEAGUE.games.delete(@id)
1542 def handle_one_move(str, player)
1544 if (@current_player == player)
1545 @end_time = Time::new
1546 t = (@end_time - @start_time).floor
1547 t = Least_Time_Per_Move if (t < Least_Time_Per_Move)
1550 if ((@current_player.mytime - t <= -@byoyomi) && ((@total_time > 0) || (@byoyomi > 0)))
1552 elsif (str == :timeout)
1553 return false # time isn't expired. players aren't swapped. continue game
1555 @current_player.mytime = @current_player.mytime - t
1556 if (@current_player.mytime < 0)
1557 @current_player.mytime = 0
1561 move_status = @board.handle_one_move(str, @sente == @current_player)
1563 # log_error("handle_one_move raise exception for #{str}")
1564 # move_status = :illegal
1567 if ((move_status == :illegal) || (move_status == :uchifuzme) || (move_status == :oute_kaihimore))
1568 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
1570 if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite))
1571 @sente.write_safe(sprintf("%s,T%d\n", str, t))
1572 @gote.write_safe(sprintf("%s,T%d\n", str, t))
1573 @fh.printf("%s\nT%d\n", str, t)
1574 @last_move = sprintf("%s,T%d", str, t)
1575 @current_turn = @current_turn + 1
1578 @monitors.each do |monitor|
1579 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@id}] "))
1580 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @id))
1585 if (@next_player.status != "game") # rival is logout or disconnected
1587 elsif (status == :timeout)
1589 elsif (move_status == :illegal)
1591 elsif (move_status == :kachi_win)
1593 elsif (move_status == :kachi_lose)
1595 elsif (move_status == :toryo)
1597 elsif (move_status == :outori)
1599 elsif (move_status == :sennichite)
1601 elsif (move_status == :oute_sennichite)
1602 oute_sennichite_lose()
1603 elsif (move_status == :uchifuzume)
1605 elsif (move_status == :oute_kaihimore)
1606 oute_kaihimore_lose()
1610 finish() if finish_flag
1611 (@current_player, @next_player) = [@next_player, @current_player]
1612 @start_time = Time::new
1618 @current_player.status = "connected"
1619 @next_player.status = "connected"
1620 @current_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1621 @next_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1622 @fh.printf("%%TORYO\n")
1623 @fh.print(@board.to_s.gsub(/^/, "\'"))
1624 @fh.printf("'summary:abnormal:%s win:%s lose\n", @current_player.name, @next_player.name)
1625 @result = GameResultWin.new(@current_player, @next_player)
1626 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1627 @monitors.each do |monitor|
1628 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1633 @current_player.status = "connected"
1634 @next_player.status = "connected"
1635 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1636 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1637 @fh.printf("%%TORYO\n")
1638 @fh.print(@board.to_s.gsub(/^/, "\'"))
1639 @fh.printf("'summary:abnormal:%s lose:%s win\n", @current_player.name, @next_player.name)
1640 @result = GameResultWin.new(@next_player, @current_player)
1641 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1642 @monitors.each do |monitor|
1643 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1648 @current_player.status = "connected"
1649 @next_player.status = "connected"
1650 @current_player.write_safe("#SENNICHITE\n#DRAW\n")
1651 @next_player.write_safe("#SENNICHITE\n#DRAW\n")
1652 @fh.print(@board.to_s.gsub(/^/, "\'"))
1653 @fh.printf("'summary:sennichite:%s draw:%s draw\n", @current_player.name, @next_player.name)
1654 @result = GameResultDraw.new(@current_player, @next_player)
1655 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1656 @monitors.each do |monitor|
1657 monitor.write_safe(sprintf("##[MONITOR][%s] #SENNICHITE\n", @id))
1661 def oute_sennichite_lose
1662 @current_player.status = "connected"
1663 @next_player.status = "connected"
1664 @current_player.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
1665 @next_player.write_safe("#OUTE_SENNICHITE\n#WIN\n")
1666 @fh.print(@board.to_s.gsub(/^/, "\'"))
1667 @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
1668 @result = GameResultWin.new(@next_player, @current_player)
1669 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1670 @monitors.each do |monitor|
1671 monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
1676 @current_player.status = "connected"
1677 @next_player.status = "connected"
1678 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1679 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1680 @fh.print(@board.to_s.gsub(/^/, "\'"))
1681 @fh.printf("'summary:illegal move:%s lose:%s win\n", @current_player.name, @next_player.name)
1682 @result = GameResultWin.new(@next_player, @current_player)
1683 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1684 @monitors.each do |monitor|
1685 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1690 @current_player.status = "connected"
1691 @next_player.status = "connected"
1692 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1693 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1694 @fh.print(@board.to_s.gsub(/^/, "\'"))
1695 @fh.printf("'summary:uchifuzume:%s lose:%s win\n", @current_player.name, @next_player.name)
1696 @result = GameResultWin.new(@next_player, @current_player)
1697 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1698 @monitors.each do |monitor|
1699 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1703 def oute_kaihimore_lose
1704 @current_player.status = "connected"
1705 @next_player.status = "connected"
1706 @current_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1707 @next_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1708 @fh.print(@board.to_s.gsub(/^/, "\'"))
1709 @fh.printf("'summary:oute_kaihimore:%s lose:%s win\n", @current_player.name, @next_player.name)
1710 @result = GameResultWin.new(@next_player, @current_player)
1711 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1712 @monitors.each do |monitor|
1713 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1718 @current_player.status = "connected"
1719 @next_player.status = "connected"
1720 @current_player.write_safe("#TIME_UP\n#LOSE\n")
1721 @next_player.write_safe("#TIME_UP\n#WIN\n")
1722 @fh.print(@board.to_s.gsub(/^/, "\'"))
1723 @fh.printf("'summary:time up:%s lose:%s win\n", @current_player.name, @next_player.name)
1724 @result = GameResultWin.new(@next_player, @current_player)
1725 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1726 @monitors.each do |monitor|
1727 monitor.write_safe(sprintf("##[MONITOR][%s] #TIME_UP\n", @id))
1732 @current_player.status = "connected"
1733 @next_player.status = "connected"
1734 @current_player.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
1735 @next_player.write_safe("%KACHI\n#JISHOGI\n#LOSE\n")
1736 @fh.printf("%%KACHI\n")
1737 @fh.print(@board.to_s.gsub(/^/, "\'"))
1738 @fh.printf("'summary:kachi:%s win:%s lose\n", @current_player.name, @next_player.name)
1739 @result = GameResultWin.new(@current_player, @next_player)
1740 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1741 @monitors.each do |monitor|
1742 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1747 @current_player.status = "connected"
1748 @next_player.status = "connected"
1749 @current_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
1750 @next_player.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
1751 @fh.printf("%%KACHI\n")
1752 @fh.print(@board.to_s.gsub(/^/, "\'"))
1753 @fh.printf("'summary:illegal kachi:%s lose:%s win\n", @current_player.name, @next_player.name)
1754 @result = GameResultWin.new(@next_player, @current_player)
1755 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1756 @monitors.each do |monitor|
1757 monitor.write_safe(sprintf("##[MONITOR][%s] %%KACHI\n", @id))
1762 @current_player.status = "connected"
1763 @next_player.status = "connected"
1764 @current_player.write_safe("%TORYO\n#RESIGN\n#LOSE\n")
1765 @next_player.write_safe("%TORYO\n#RESIGN\n#WIN\n")
1766 @fh.printf("%%TORYO\n")
1767 @fh.print(@board.to_s.gsub(/^/, "\'"))
1768 @fh.printf("'summary:toryo:%s lose:%s win\n", @current_player.name, @next_player.name)
1769 @result = GameResultWin.new(@next_player, @current_player)
1770 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1771 @monitors.each do |monitor|
1772 monitor.write_safe(sprintf("##[MONITOR][%s] %%TORYO\n", @id))
1777 @current_player.status = "connected"
1778 @next_player.status = "connected"
1779 @current_player.write_safe("#ILLEGAL_MOVE\n#WIN\n")
1780 @next_player.write_safe("#ILLEGAL_MOVE\n#LOSE\n")
1781 @fh.print(@board.to_s.gsub(/^/, "\'"))
1782 @fh.printf("'summary:outori:%s win:%s lose\n", @current_player.name, @next_player.name)
1783 @result = GameResultWin.new(@current_player, @next_player)
1784 @fh.printf("'rating:#{@result.to_s}\n") if rated?
1785 @monitors.each do |monitor|
1786 monitor.write_safe(sprintf("##[MONITOR][%s] #ILLEGAL_MOVE\n", @id))
1791 log_message(sprintf("game started %s", @id))
1792 @sente.write_safe(sprintf("START:%s\n", @id))
1793 @gote.write_safe(sprintf("START:%s\n", @id))
1794 @sente.mytime = @total_time
1795 @gote.mytime = @total_time
1796 @start_time = Time::new
1801 @fh = open(@logfile, "w")
1805 @fh.printf("N+%s\n", @sente.name)
1806 @fh.printf("N-%s\n", @gote.name)
1807 @fh.printf("$EVENT:%s\n", @id)
1809 @sente.write_safe(propose_message("+"))
1810 @gote.write_safe(propose_message("-"))
1812 @fh.printf("$START_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
1814 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1815 P2 * -HI * * * * * -KA *
1816 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1817 P4 * * * * * * * * *
1818 P5 * * * * * * * * *
1819 P6 * * * * * * * * *
1820 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1821 P8 * +KA * * * * * +HI *
1822 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1831 Protocol_Version:1.1
1832 Protocol_Mode:Server
1834 Declaration:Jishogi 1.1
1836 Name+:#{@sente.name}
1842 Total_Time:#{@total_time}
1844 Least_Time_Per_Move:#{Least_Time_Per_Move}
1845 Remaining_Time+:#{@sente.mytime}
1846 Remaining_Time-:#{@gote.mytime}
1847 Last_Move:#{@last_move}
1848 Current_Turn:#{@current_turn}
1858 return str0 + @board.to_s + str1
1861 def propose_message(sg_flag)
1864 Protocol_Version:1.1
1865 Protocol_Mode:Server
1867 Declaration:Jishogi 1.1
1869 Name+:#{@sente.name}
1871 Your_Turn:#{sg_flag}
1876 Total_Time:#{@total_time}
1878 Least_Time_Per_Move:#{Least_Time_Per_Move}
1881 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
1882 P2 * -HI * * * * * -KA *
1883 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
1884 P4 * * * * * * * * *
1885 P5 * * * * * * * * *
1886 P6 * * * * * * * * *
1887 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
1888 P8 * +KA * * * * * +HI *
1889 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
1901 def issue_current_time
1902 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
1903 @@mutex.synchronize do
1904 while time <= @@time do
1911 end # module ShogiServer
1913 #################################################
1920 shogi-server - server for CSA server protocol
1923 shogi-server event_name port_number
1926 server for CSA server protocol
1930 specify filename for logging process ID
1933 this file is distributed under GPL version2 and might be compiled by Exerb
1938 #{ShogiServer::Release}
1941 #{ShogiServer::Revision}
1945 def log_message(str)
1946 printf("%s message: %s\n", Time::new.to_s, str)
1949 def log_warning(str)
1950 printf("%s warning: %s\n", Time::new.to_s, str)
1954 printf("%s error: %s\n", Time::new.to_s, str)
1958 def parse_command_line
1960 parser = GetoptLong.new
1961 parser.ordering = GetoptLong::REQUIRE_ORDER
1963 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT])
1967 parser.each_option do |name, arg|
1968 name.sub!(/^--/, '')
1969 options[name] = arg.dup
1973 raise parser.error_message
1978 def write_pid_file(file)
1979 open(file, "w") do |fh|
1980 fh.print Process::pid, "\n"
1984 def mutex_watchdog(mutex, sec)
1996 log_error("mutex watchdog timeout")
2007 mutex_watchdog($mutex, 10)
2010 $options = parse_command_line
2011 if (ARGV.length != 2)
2016 LEAGUE.event = ARGV.shift
2019 write_pid_file($options["pid-file"]) if ($options["pid-file"])
2021 server = TCPserver.open(port)
2022 log_message("server started")
2025 Thread::start(server.accept) do |client|
2030 while (str = client.gets_timeout(ShogiServer::Login_Time))
2035 if (ShogiServer::Login::good_login?(str))
2036 player = ShogiServer::Player::new(str, client)
2038 login = ShogiServer::Login::factory(str, player)
2039 if (LEAGUE.players[player.name])
2040 if ((LEAGUE.players[player.name].password == player.password) &&
2041 (LEAGUE.players[player.name].status != "game"))
2042 log_message(sprintf("user %s login forcely", player.name))
2043 LEAGUE.players[player.name].kill
2045 login.incorrect_duplicated_player(str)
2053 client.write_safe("LOGIN:incorrect" + eol)
2054 client.write_safe("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
2065 log_message(sprintf("user %s login", player.name))
2067 player.run(login.csa_1st_str)
2071 player.game.kill(player)
2073 player.finish # socket has been closed
2074 LEAGUE.delete(player)
2075 log_message(sprintf("user %s logout", player.name))
2087 TCPSocket.do_not_reverse_lookup = true
2088 Thread.abort_on_exception = true
2090 LEAGUE = ShogiServer::League::new