3 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
4 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
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
21 require 'shogi_server'
28 def Command.factory(str, player, time=Time.now)
32 cmd = KeepAliveCommand.new(str, player)
34 cmd = MoveCommand.new(str, player)
35 when /^%[^%]/, :timeout
36 cmd = SpecialCommand.new(str, player)
38 cmd = ExceptionCommand.new(str, player)
40 cmd = RejectCommand.new(str, player)
42 cmd = AgreeCommand.new(str, player)
43 when /^%%SHOW\s+(\S+)/
45 cmd = ShowCommand.new(str, player, $league.games[game_id])
46 when /^%%MONITORON\s+(\S+)/
48 cmd = MonitorOnCommand.new(str, player, $league.games[game_id])
49 when /^%%MONITOROFF\s+(\S+)/
51 cmd = MonitorOffCommand.new(str, player, $league.games[game_id])
52 when /^%%MONITOR2ON\s+(\S+)/
54 cmd = Monitor2OnCommand.new(str, player, $league.games[game_id])
55 when /^%%MONITOR2OFF\s+(\S+)/
57 cmd = Monitor2OffCommand.new(str, player, $league.games[game_id])
59 cmd = HelpCommand.new(str, player)
61 cmd = RatingCommand.new(str, player, $league.rated_players)
63 cmd = VersionCommand.new(str, player)
65 cmd = GameCommand.new(str, player)
66 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
70 cmd = GameChallengeCommand.new(str, player,
71 command_name, game_name, my_sente_str)
74 cmd = ChatCommand.new(str, player, message, $league.players)
76 cmd = ListCommand.new(str, player, $league.games)
78 cmd = WhoCommand.new(str, player, $league.players)
80 cmd = LogoutCommand.new(str, player)
82 cmd = ChallengeCommand.new(str, player)
83 when /^%%SETBUOY\s+(\S+)\s+(\S+)(.*)/
87 if $3 && /^\s+(\d*)/ =~ $3
90 cmd = SetBuoyCommand.new(str, player, game_name, moves, count)
91 when /^%%DELETEBUOY\s+(\S+)/
93 cmd = DeleteBuoyCommand.new(str, player, game_name)
94 when /^%%GETBUOYCOUNT\s+(\S+)/
96 cmd = GetBuoyCountCommand.new(str, player, game_name)
97 when /^%%FORK\s+(\S+)\s+(\S+)(.*)/
101 if $3 && /^\s+(\d+)/ =~ $3
104 cmd = ForkCommand.new(str, player, source_game, new_buoy_game, nth_move)
105 when /^%%FORK\s+(\S+)$/
109 cmd = ForkCommand.new(str, player, source_game, new_buoy_game, nth_move)
111 cmd = SpaceCommand.new(str, player)
113 # TODO: just ignore commands specific to 81Dojo.
114 # Need to discuss with 81Dojo people.
115 cmd = VoidCommand.new(str, player)
117 cmd = ErrorCommand.new(str, player)
124 def initialize(str, player)
127 @time = Time.now # this should be replaced later with a real time
132 # Dummy command which does nothing.
134 class VoidCommand < Command
135 def initialize(str, player)
144 # Application-level protocol for Keep-Alive.
145 # If the server receives an LF, it sends back an LF. Note that the 30 sec
146 # rule (client may not send LF again within 30 sec) is not implemented
149 class KeepAliveCommand < Command
150 def initialize(str, player)
155 @player.write_safe("\n")
160 # Command of moving a piece.
162 class MoveCommand < Command
163 def initialize(str, player)
168 if (@player.status == "game")
169 array_str = @str.split(",")
170 move = array_str.shift
171 if @player.game.last_move &&
172 @player.game.last_move.split(",").first == move
173 log_warning("Received two sequencial identical moves [#{move}] from #{@player.name}. The last one was ignored.")
176 additional = array_str.shift
178 if /^'(.*)/ =~ additional
179 comment = array_str.unshift("'*#{$1.toeuc}")
181 s = @player.game.handle_one_move(move, @player, @time)
182 @player.game.log_game(Kconv.toeuc(comment.first)) if (comment && comment.first && !s)
183 return :return if (s && @player.protocol == LoginCSA::PROTOCOL)
189 # Command like "%TORYO" or :timeout
191 class SpecialCommand < Command
192 def initialize(str, player)
198 if (@player.status == "game")
199 rc = in_game_status()
200 elsif ["agree_waiting", "start_waiting"].include?(@player.status)
201 rc = in_waiting_status()
203 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].") unless @str == :timeout
211 s = @player.game.handle_one_move(@str, @player, @time)
212 rc = :return if (s && @player.protocol == LoginCSA::PROTOCOL)
217 def in_waiting_status
220 if @player.game.prepared_expire?
221 log_warning("#{@player.status} lasted too long. This play has been expired: %s" % [@player.game.game_id])
222 @player.game.reject("the Server (timed out)")
223 rc = :return if (@player.protocol == LoginCSA::PROTOCOL)
230 # Command of :exception
232 class ExceptionCommand < Command
233 def initialize(str, player)
238 log_error("Failed to receive a message from #{@player.name}.")
245 class RejectCommand < Command
246 def initialize(str, player)
251 if (@player.status == "agree_waiting")
252 @player.game.reject(@player.name)
253 return :return if (@player.protocol == LoginCSA::PROTOCOL)
255 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].")
256 @player.write_safe(sprintf("##[ERROR] you are in %s status. REJECT is valid in agree_waiting status\n", @player.status))
264 class AgreeCommand < Command
265 def initialize(str, player)
270 if (@player.status == "agree_waiting")
271 @player.status = "start_waiting"
272 if (@player.game.is_startable_status?)
276 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].")
277 @player.write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @player.status))
283 # Base Command calss requiring a game instance
285 class BaseCommandForGame < Command
286 def initialize(str, player, game)
289 @game_id = game ? game.game_id : nil
295 class ShowCommand < BaseCommandForGame
296 def initialize(str, player, game)
302 @player.write_safe(@game.show.gsub(/^/, '##[SHOW] '))
304 @player.write_safe("##[SHOW] +OK\n")
310 def initialize(player)
315 attr_reader :player, :type, :header
319 rhs.is_a?(MonitorHandler) &&
320 @player == rhs.player &&
324 def write_safe(game_id, str)
325 str.chomp.split("\n").each do |line|
326 @player.write_safe("##[%s][%s] %s\n" % [@header, game_id, line.chomp])
328 @player.write_safe("##[%s][%s] %s\n" % [@header, game_id, "+OK"])
332 class MonitorHandler1 < MonitorHandler
333 def initialize(player)
339 def write_one_move(game_id, game)
340 write_safe(game_id, game.show.chomp)
344 class MonitorHandler2 < MonitorHandler
345 def initialize(player)
351 def write_one_move(game_id, game)
352 write_safe(game_id, game.last_move.gsub(",", "\n"))
356 # Command of MONITORON
358 class MonitorOnCommand < BaseCommandForGame
359 def initialize(str, player, game)
365 monitor_handler = MonitorHandler1.new(@player)
366 @game.monitoron(monitor_handler)
367 monitor_handler.write_safe(@game_id, @game.show)
373 # Command of MONITOROFF
375 class MonitorOffCommand < BaseCommandForGame
376 def initialize(str, player, game)
382 @game.monitoroff(MonitorHandler1.new(@player))
388 # Command of MONITOR2ON
390 class Monitor2OnCommand < BaseCommandForGame
391 def initialize(str, player, game)
397 monitor_handler = MonitorHandler2.new(@player)
398 @game.monitoron(monitor_handler)
399 lines = IO::readlines(@game.logfile).join("")
400 monitor_handler.write_safe(@game_id, lines)
406 class Monitor2OffCommand < MonitorOffCommand
407 def initialize(str, player, game)
413 @game.monitoroff(MonitorHandler2.new(@player))
421 class HelpCommand < Command
422 def initialize(str, player)
428 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
435 class RatingCommand < Command
436 def initialize(str, player, rated_players)
438 @rated_players = rated_players
442 @rated_players.sort {|a,b| b.rate <=> a.rate}.each do |p|
443 @player.write_safe("##[RATING] %s \t %4d @%s\n" %
444 [p.simple_player_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
446 @player.write_safe("##[RATING] +OK\n")
453 class VersionCommand < Command
454 def initialize(str, player)
459 @player.write_safe "##[VERSION] Shogi Server revision #{ShogiServer::Revision}\n"
460 @player.write_safe("##[VERSION] +OK\n")
467 class GameCommand < Command
468 def initialize(str, player)
473 if ((@player.status == "connected") || (@player.status == "game_waiting"))
474 @player.status = "connected"
475 @player.game_name = ""
477 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
483 # Commando of game challenge
484 # TODO make a test case
486 class GameChallengeCommand < Command
487 def initialize(str, player, command_name, game_name, my_sente_str)
489 @command_name = command_name
490 @game_name = game_name
491 @my_sente_str = my_sente_str
492 player.set_sente_from_str(@my_sente_str)
496 if (! Login::good_game_name?(@game_name))
497 @player.write_safe(sprintf("##[ERROR] bad game name\n"))
499 elsif ((@player.status == "connected") || (@player.status == "game_waiting"))
502 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
507 if (League::Floodgate.game_name?(@game_name))
508 if (@my_sente_str != "*")
509 @player.write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", @my_sente_str, @game_name))
514 rival = $league.find_rival(@player, @game_name)
515 if rival.instance_of?(Symbol)
516 # An error happened. rival is not a player instance, but an error
517 # symobl that must be returned to the main routine immediately.
523 @player.game_name = @game_name
524 Game::decide_turns(@player, @my_sente_str, rival)
526 if (Buoy.game_name?(@game_name))
527 buoy = Buoy.new # TODO config
528 if buoy.is_new_game?(@game_name)
529 # The buoy game is not ready yet.
530 # When the game is set, it will be started.
531 @player.status = "game_waiting"
533 buoy_game = buoy.get_game(@game_name)
534 if buoy_game.instance_of? NilBuoyGame
538 moves_array = Board::split_moves(buoy_game.moves)
541 board.set_from_moves(moves_array)
543 # it will never happen since moves have already been checked
544 log_error "Failed to set up a buoy game: #{moves}"
547 buoy.decrement_count(buoy_game)
548 Game::new(@player.game_name, @player, rival, board)
551 klass = Login.handicapped_game_name?(@game_name) || Board
554 Game::new(@player.game_name, @player, rival, board)
556 else # rival not found
557 if (@command_name == "GAME")
558 @player.status = "game_waiting"
559 @player.game_name = @game_name
561 @player.write_safe(sprintf("##[ERROR] can't find rival for %s\n", @game_name))
562 @player.status = "connected"
563 @player.game_name = ""
573 class ChatCommand < Command
575 # players array of [name, player]
577 def initialize(str, player, message, players)
584 @players.each do |name, p| # TODO player change name
585 if (p.protocol != LoginCSA::PROTOCOL)
586 p.write_safe(sprintf("##[CHAT][%s] %s\n", @player.name, @message))
595 class ListCommand < Command
597 # games array of [game_id, game]
599 def initialize(str, player, games)
606 @games.each do |id, game|
607 buf.push(sprintf("##[LIST] %s\n", id))
609 buf.push("##[LIST] +OK\n")
610 @player.write_safe(buf.join)
617 class WhoCommand < Command
619 # players array of [[name, player]]
621 def initialize(str, player, players)
628 @players.each do |name, p|
629 buf.push(sprintf("##[WHO] %s\n", p.to_s))
631 buf.push("##[WHO] +OK\n")
632 @player.write_safe(buf.join)
639 class LogoutCommand < Command
640 def initialize(str, player)
645 @player.status = "connected"
646 @player.write_safe("LOGOUT:completed\n")
651 # Command of CHALLENGE
653 class ChallengeCommand < Command
654 def initialize(str, player)
659 # This command is only available for CSA's official testing server.
660 # So, this means nothing for this program.
661 @player.write_safe("CHALLENGE ACCEPTED\n")
666 # Command for a space
668 class SpaceCommand < Command
669 def initialize(str, player)
674 ## ignore null string
679 # Command for an error
681 class ErrorCommand < Command
682 def initialize(str, player)
690 # Aim to hide a possible password
691 cmd.gsub!(/LOGIN\s*(\w+)\s+.*/i, 'LOGIN \1...')
692 @msg = "##[ERROR] unknown command %s\n" % [cmd]
693 @player.write_safe(@msg)
701 class SetBuoyCommand < Command
703 def initialize(str, player, game_name, moves, count)
705 @game_name = game_name
711 unless (Buoy.game_name?(@game_name))
712 @player.write_safe(sprintf("##[ERROR] wrong buoy game name: %s\n", @game_name))
713 log_error "Received a wrong buoy game name: %s from %s." % [@game_name, @player.name]
717 unless buoy.is_new_game?(@game_name)
718 @player.write_safe(sprintf("##[ERROR] duplicated buoy game name: %s\n", @game_name))
719 log_error "Received duplicated buoy game name: %s from %s." % [@game_name, @player.name]
723 @player.write_safe(sprintf("##[ERROR] invalid count: %s\n", @count))
724 log_error "Received an invalid count for a buoy game: %s, %s from %s." % [@count, @game_name, @player.name]
729 moves_array = Board::split_moves(@moves)
732 board.set_from_moves(moves_array)
737 buoy_game = BuoyGame.new(@game_name, @moves, @player.name, @count)
738 buoy.add_game(buoy_game)
739 @player.write_safe(sprintf("##[SETBUOY] +OK\n"))
740 log_info("A buoy game was created: %s by %s" % [@game_name, @player.name])
742 # if two players are waiting for this buoy game, start it
743 candidates = $league.find_all_players do |player|
744 player.status == "game_waiting" &&
745 player.game_name == @game_name &&
746 player.name != @player.name
749 log_info("No players found for a buoy game. Wait for players: %s" % [@game_name])
752 p1 = candidates.first
753 p2 = $league.find_rival(p1, @game_name)
755 log_info("No opponent found for a buoy game. Wait for the opponent: %s by %s" % [@game_name, p1.name])
757 elsif p2.instance_of?(Symbol)
758 # An error happened. rival is not a player instance, but an error
759 # symobl that must be returned to the main routine immediately.
762 # found two players: p1 and p2
763 log_info("Starting a buoy game: %s with %s and %s" % [@game_name, p1.name, p2.name])
764 buoy.decrement_count(buoy_game)
765 game = Game::new(@game_name, p1, p2, board)
768 rescue WrongMoves => e
769 @player.write_safe(sprintf("##[ERROR] wrong moves: %s\n", @moves))
770 log_error "Received wrong moves: %s from %s. [%s]" % [@moves, @player.name, e.message]
777 class DeleteBuoyCommand < Command
778 def initialize(str, player, game_name)
780 @game_name = game_name
785 buoy_game = buoy.get_game(@game_name)
786 if buoy_game.instance_of?(NilBuoyGame)
787 @player.write_safe(sprintf("##[ERROR] buoy game not found: %s\n", @game_name))
788 log_error "Game name not found: %s by %s" % [@game_name, @player.name]
792 if buoy_game.owner != @player.name
793 @player.write_safe(sprintf("##[ERROR] you are not allowed to delete a buoy game that you did not set: %s\n", @game_name))
794 log_error "%s are not allowed to delete a game: %s" % [@player.name, @game_name]
798 buoy.delete_game(buoy_game)
799 @player.write_safe(sprintf("##[DELETEBUOY] +OK\n"))
800 log_info("A buoy game was deleted: %s" % [@game_name])
807 class GetBuoyCountCommand < Command
808 def initialize(str, player, game_name)
810 @game_name = game_name
815 buoy_game = buoy.get_game(@game_name)
816 if buoy_game.instance_of?(NilBuoyGame)
817 @player.write_safe("##[GETBUOYCOUNT] -1\n")
819 @player.write_safe("##[GETBUOYCOUNT] %s\n" % [buoy_game.count])
821 @player.write_safe("##[GETBUOYCOUNT] +OK\n")
825 # %%FORK <source_game> <new_buoy_game> [<nth-move>]
826 # Fork a new game from the posistion where the n-th (starting from 1) move
827 # of a source game is played. The new game should be a valid buoy game
828 # name. The default value of n is the position where the previous position
831 class ForkCommand < Command
832 def initialize(str, player, source_game, new_buoy_game, nth_move)
834 @source_game = source_game
835 @new_buoy_game = new_buoy_game
836 @nth_move = nth_move # may be nil
838 attr_reader :new_buoy_game
840 def decide_new_buoy_game_name
845 if @source_game.split("+").size >= 2 &&
846 /^([^-]+)-(\d+)-(\d+)/ =~ @source_game.split("+")[1]
851 if name == nil || total_time == nil || byo_time == nil
852 @player.write_safe(sprintf("##[ERROR] wrong source game name to make a new buoy game name: %s\n", @source_game))
853 log_error "Received a wrong source game name to make a new buoy game name: %s from %s." % [@source_game, @player.name]
856 @new_buoy_game = "buoy_%s_%d-%s-%s" % [name, @nth_move, total_time, byo_time]
857 @player.write_safe(sprintf("##[FORK]: new buoy game name: %s\n", @new_buoy_game))
858 @player.write_safe("##[FORK] +OK\n")
862 game = $league.games[@source_game]
864 @player.write_safe(sprintf("##[ERROR] wrong source game name: %s\n", @source_game))
865 log_error "Received a wrong source game name: %s from %s." % [@source_game, @player.name]
869 moves = game.read_moves # [["+7776FU","T2"],["-3334FU","T5"]]
870 @nth_move = moves.size - 1 unless @nth_move
871 if @nth_move > moves.size or @nth_move < 1
872 @player.write_safe(sprintf("##[ERROR] number of moves to fork is out of range: %s.\n", moves.size))
873 log_error "Number of moves to fork is out of range: %s [%s]" % [@nth_move, @player.name]
877 moves[0...@nth_move].each do |m|
878 new_moves_str << m.join(",")
881 unless @new_buoy_game
882 decide_new_buoy_game_name
885 buoy_cmd = SetBuoyCommand.new(@str, @player, @new_buoy_game, new_moves_str, 1)
890 end # module ShogiServer