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)
72 when /^%%(GAME|CHALLENGE)\s+(\S+)/
73 msg = "A turn identifier is required"
74 cmd = ErrorCommand.new(str, player, msg)
77 cmd = ChatCommand.new(str, player, message, $league.players)
79 cmd = ListCommand.new(str, player, $league.games)
81 cmd = WhoCommand.new(str, player, $league.players)
83 cmd = LogoutCommand.new(str, player)
85 cmd = ChallengeCommand.new(str, player)
86 when /^%%SETBUOY\s+(\S+)\s+(\S+)(.*)/
90 if $3 && /^\s+(\d*)/ =~ $3
93 cmd = SetBuoyCommand.new(str, player, game_name, moves, count)
94 when /^%%DELETEBUOY\s+(\S+)/
96 cmd = DeleteBuoyCommand.new(str, player, game_name)
97 when /^%%GETBUOYCOUNT\s+(\S+)/
99 cmd = GetBuoyCountCommand.new(str, player, game_name)
100 when /^%%FORK\s+(\S+)\s+(\S+)(.*)/
104 if $3 && /^\s+(\d+)/ =~ $3
107 cmd = ForkCommand.new(str, player, source_game, new_buoy_game, nth_move)
108 when /^%%FORK\s+(\S+)$/
112 cmd = ForkCommand.new(str, player, source_game, new_buoy_game, nth_move)
114 cmd = SpaceCommand.new(str, player)
116 # TODO: just ignore commands specific to 81Dojo.
117 # Need to discuss with 81Dojo people.
118 cmd = VoidCommand.new(str, player)
120 cmd = ErrorCommand.new(str, player)
127 def initialize(str, player)
130 @time = Time.now # this should be replaced later with a real time
135 # Dummy command which does nothing.
137 class VoidCommand < Command
138 def initialize(str, player)
147 # Application-level protocol for Keep-Alive.
148 # If the server receives an LF, it sends back an LF. Note that the 30 sec
149 # rule (client may not send LF again within 30 sec) is not implemented
152 class KeepAliveCommand < Command
153 def initialize(str, player)
158 @player.write_safe("\n")
163 # Command of moving a piece.
165 class MoveCommand < Command
166 def initialize(str, player)
171 if (@player.status == "game")
172 array_str = @str.split(",")
173 move = array_str.shift
174 if @player.game.last_move &&
175 @player.game.last_move.split(",").first == move
176 log_warning("Received two sequencial identical moves [#{move}] from #{@player.name}. The last one was ignored.")
179 additional = array_str.shift
181 if /^'(.*)/ =~ additional
182 comment = array_str.unshift("'*#{$1.toeuc}")
184 s = @player.game.handle_one_move(move, @player, @time)
185 @player.game.log_game(Kconv.toeuc(comment.first)) if (comment && comment.first && !s)
186 return :return if (s && @player.protocol == LoginCSA::PROTOCOL)
192 # Command like "%TORYO" or :timeout
194 class SpecialCommand < Command
195 def initialize(str, player)
201 if (@player.status == "game")
202 rc = in_game_status()
203 elsif ["agree_waiting", "start_waiting"].include?(@player.status)
204 rc = in_waiting_status()
206 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].") unless @str == :timeout
214 s = @player.game.handle_one_move(@str, @player, @time)
215 rc = :return if (s && @player.protocol == LoginCSA::PROTOCOL)
220 def in_waiting_status
223 if @player.game.prepared_expire?
224 log_warning("#{@player.status} lasted too long. This play has been expired: %s" % [@player.game.game_id])
225 @player.game.reject("the Server (timed out)")
226 rc = :return if (@player.protocol == LoginCSA::PROTOCOL)
233 # Command of :exception
235 class ExceptionCommand < Command
236 def initialize(str, player)
241 log_error("Failed to receive a message from #{@player.name}.")
248 class RejectCommand < Command
249 def initialize(str, player)
254 if (@player.status == "agree_waiting")
255 @player.game.reject(@player.name)
256 return :return if (@player.protocol == LoginCSA::PROTOCOL)
258 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].")
259 @player.write_safe(sprintf("##[ERROR] you are in %s status. REJECT is valid in agree_waiting status\n", @player.status))
267 class AgreeCommand < Command
268 def initialize(str, player)
273 if (@player.status == "agree_waiting")
274 @player.status = "start_waiting"
275 if (@player.game.is_startable_status?)
279 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].")
280 @player.write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @player.status))
286 # Base Command calss requiring a game instance
288 class BaseCommandForGame < Command
289 def initialize(str, player, game)
292 @game_id = game ? game.game_id : nil
298 class ShowCommand < BaseCommandForGame
299 def initialize(str, player, game)
305 @player.write_safe(@game.show.gsub(/^/, '##[SHOW] '))
307 @player.write_safe("##[SHOW] +OK\n")
313 def initialize(player)
318 attr_reader :player, :type, :header
322 rhs.is_a?(MonitorHandler) &&
323 @player == rhs.player &&
327 def write_safe(game_id, str)
328 str.chomp.split("\n").each do |line|
329 @player.write_safe("##[%s][%s] %s\n" % [@header, game_id, line.chomp])
331 @player.write_safe("##[%s][%s] %s\n" % [@header, game_id, "+OK"])
335 class MonitorHandler1 < MonitorHandler
336 def initialize(player)
342 def write_one_move(game_id, game)
343 write_safe(game_id, game.show.chomp)
347 class MonitorHandler2 < MonitorHandler
348 def initialize(player)
354 def write_one_move(game_id, game)
355 write_safe(game_id, game.last_move.gsub(",", "\n"))
359 # Command of MONITORON
361 class MonitorOnCommand < BaseCommandForGame
362 def initialize(str, player, game)
368 monitor_handler = MonitorHandler1.new(@player)
369 @game.monitoron(monitor_handler)
370 monitor_handler.write_safe(@game_id, @game.show)
376 # Command of MONITOROFF
378 class MonitorOffCommand < BaseCommandForGame
379 def initialize(str, player, game)
385 @game.monitoroff(MonitorHandler1.new(@player))
391 # Command of MONITOR2ON
393 class Monitor2OnCommand < BaseCommandForGame
394 def initialize(str, player, game)
400 monitor_handler = MonitorHandler2.new(@player)
401 @game.monitoron(monitor_handler)
402 lines = IO::readlines(@game.logfile).join("")
403 monitor_handler.write_safe(@game_id, lines)
409 class Monitor2OffCommand < MonitorOffCommand
410 def initialize(str, player, game)
416 @game.monitoroff(MonitorHandler2.new(@player))
424 class HelpCommand < Command
425 def initialize(str, player)
431 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
438 class RatingCommand < Command
439 def initialize(str, player, rated_players)
441 @rated_players = rated_players
445 @rated_players.sort {|a,b| b.rate <=> a.rate}.each do |p|
446 @player.write_safe("##[RATING] %s \t %4d @%s\n" %
447 [p.simple_player_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
449 @player.write_safe("##[RATING] +OK\n")
456 class VersionCommand < Command
457 def initialize(str, player)
462 @player.write_safe "##[VERSION] Shogi Server revision #{ShogiServer::Revision}\n"
463 @player.write_safe("##[VERSION] +OK\n")
470 class GameCommand < Command
471 def initialize(str, player)
476 if ((@player.status == "connected") || (@player.status == "game_waiting"))
477 @player.status = "connected"
478 @player.game_name = ""
480 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
486 # Commando of game challenge
487 # TODO make a test case
489 class GameChallengeCommand < Command
490 def initialize(str, player, command_name, game_name, my_sente_str)
492 @command_name = command_name
493 @game_name = game_name
494 @my_sente_str = my_sente_str
495 player.set_sente_from_str(@my_sente_str)
499 if (! Login::good_game_name?(@game_name))
500 @player.write_safe(sprintf("##[ERROR] bad game name: %s.\n", @game_name))
501 if (/^(.+)-\d+-\d+$/ =~ @game_name)
502 if Login::good_identifier?($1)
505 @player.write_safe(sprintf("##[ERROR] invalid identifiers are found or too many characters are used.\n"))
508 @player.write_safe(sprintf("##[ERROR] game name should consist of three parts like game-1500-60.\n"))
511 elsif ((@player.status == "connected") || (@player.status == "game_waiting"))
514 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
519 if (League::Floodgate.game_name?(@game_name))
520 if (@my_sente_str != "*")
521 @player.write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", @my_sente_str, @game_name))
526 rival = $league.find_rival(@player, @game_name)
527 if rival.instance_of?(Symbol)
528 # An error happened. rival is not a player instance, but an error
529 # symobl that must be returned to the main routine immediately.
535 @player.game_name = @game_name
536 Game::decide_turns(@player, @my_sente_str, rival)
538 if (Buoy.game_name?(@game_name))
539 buoy = Buoy.new # TODO config
540 if buoy.is_new_game?(@game_name)
541 # The buoy game is not ready yet.
542 # When the game is set, it will be started.
543 @player.status = "game_waiting"
545 buoy_game = buoy.get_game(@game_name)
546 if buoy_game.instance_of? NilBuoyGame
550 moves_array = Board::split_moves(buoy_game.moves)
553 board.set_from_moves(moves_array)
555 # it will never happen since moves have already been checked
556 log_error "Failed to set up a buoy game: #{moves}"
559 buoy.decrement_count(buoy_game)
560 Game::new(@player.game_name, @player, rival, board)
563 klass = Login.handicapped_game_name?(@game_name) || Board
566 Game::new(@player.game_name, @player, rival, board)
568 else # rival not found
569 if (@command_name == "GAME")
570 @player.status = "game_waiting"
571 @player.game_name = @game_name
573 @player.write_safe(sprintf("##[ERROR] can't find rival for %s\n", @game_name))
574 @player.status = "connected"
575 @player.game_name = ""
585 class ChatCommand < Command
587 # players array of [name, player]
589 def initialize(str, player, message, players)
596 @players.each do |name, p| # TODO player change name
597 if (p.protocol != LoginCSA::PROTOCOL)
598 p.write_safe(sprintf("##[CHAT][%s] %s\n", @player.name, @message))
607 class ListCommand < Command
609 # games array of [game_id, game]
611 def initialize(str, player, games)
618 @games.each do |id, game|
619 buf.push(sprintf("##[LIST] %s\n", id))
621 buf.push("##[LIST] +OK\n")
622 @player.write_safe(buf.join)
629 class WhoCommand < Command
631 # players array of [[name, player]]
633 def initialize(str, player, players)
640 @players.each do |name, p|
641 buf.push(sprintf("##[WHO] %s\n", p.to_s))
643 buf.push("##[WHO] +OK\n")
644 @player.write_safe(buf.join)
651 class LogoutCommand < Command
652 def initialize(str, player)
657 @player.status = "connected"
658 @player.write_safe("LOGOUT:completed\n")
663 # Command of CHALLENGE
665 class ChallengeCommand < Command
666 def initialize(str, player)
671 # This command is only available for CSA's official testing server.
672 # So, this means nothing for this program.
673 @player.write_safe("CHALLENGE ACCEPTED\n")
678 # Command for a space
680 class SpaceCommand < Command
681 def initialize(str, player)
686 ## ignore null string
691 # Command for an error
693 class ErrorCommand < Command
694 def initialize(str, player, msg=nil)
696 @msg = msg || "unknown command"
702 # Aim to hide a possible password
703 cmd.gsub!(/LOGIN\s*(\w+)\s+.*/i, 'LOGIN \1...')
704 @msg = "##[ERROR] %s: %s\n" % [@msg, cmd]
705 @player.write_safe(@msg)
713 class SetBuoyCommand < Command
715 def initialize(str, player, game_name, moves, count)
717 @game_name = game_name
723 unless (Buoy.game_name?(@game_name))
724 @player.write_safe(sprintf("##[ERROR] wrong buoy game name: %s\n", @game_name))
725 log_error "Received a wrong buoy game name: %s from %s." % [@game_name, @player.name]
729 unless buoy.is_new_game?(@game_name)
730 @player.write_safe(sprintf("##[ERROR] duplicated buoy game name: %s\n", @game_name))
731 log_error "Received duplicated buoy game name: %s from %s." % [@game_name, @player.name]
735 @player.write_safe(sprintf("##[ERROR] invalid count: %s\n", @count))
736 log_error "Received an invalid count for a buoy game: %s, %s from %s." % [@count, @game_name, @player.name]
741 moves_array = Board::split_moves(@moves)
744 board.set_from_moves(moves_array)
749 buoy_game = BuoyGame.new(@game_name, @moves, @player.name, @count)
750 buoy.add_game(buoy_game)
751 @player.write_safe(sprintf("##[SETBUOY] +OK\n"))
752 log_info("A buoy game was created: %s by %s" % [@game_name, @player.name])
754 # if two players are waiting for this buoy game, start it
755 candidates = $league.find_all_players do |player|
756 player.status == "game_waiting" &&
757 player.game_name == @game_name &&
758 player.name != @player.name
761 log_info("No players found for a buoy game. Wait for players: %s" % [@game_name])
764 p1 = candidates.first
765 p2 = $league.find_rival(p1, @game_name)
767 log_info("No opponent found for a buoy game. Wait for the opponent: %s by %s" % [@game_name, p1.name])
769 elsif p2.instance_of?(Symbol)
770 # An error happened. rival is not a player instance, but an error
771 # symobl that must be returned to the main routine immediately.
774 # found two players: p1 and p2
775 log_info("Starting a buoy game: %s with %s and %s" % [@game_name, p1.name, p2.name])
776 buoy.decrement_count(buoy_game)
777 game = Game::new(@game_name, p1, p2, board)
780 rescue WrongMoves => e
781 @player.write_safe(sprintf("##[ERROR] wrong moves: %s\n", @moves))
782 log_error "Received wrong moves: %s from %s. [%s]" % [@moves, @player.name, e.message]
789 class DeleteBuoyCommand < Command
790 def initialize(str, player, game_name)
792 @game_name = game_name
797 buoy_game = buoy.get_game(@game_name)
798 if buoy_game.instance_of?(NilBuoyGame)
799 @player.write_safe(sprintf("##[ERROR] buoy game not found: %s\n", @game_name))
800 log_error "Game name not found: %s by %s" % [@game_name, @player.name]
804 if buoy_game.owner != @player.name
805 @player.write_safe(sprintf("##[ERROR] you are not allowed to delete a buoy game that you did not set: %s\n", @game_name))
806 log_error "%s are not allowed to delete a game: %s" % [@player.name, @game_name]
810 buoy.delete_game(buoy_game)
811 @player.write_safe(sprintf("##[DELETEBUOY] +OK\n"))
812 log_info("A buoy game was deleted: %s" % [@game_name])
819 class GetBuoyCountCommand < Command
820 def initialize(str, player, game_name)
822 @game_name = game_name
827 buoy_game = buoy.get_game(@game_name)
828 if buoy_game.instance_of?(NilBuoyGame)
829 @player.write_safe("##[GETBUOYCOUNT] -1\n")
831 @player.write_safe("##[GETBUOYCOUNT] %s\n" % [buoy_game.count])
833 @player.write_safe("##[GETBUOYCOUNT] +OK\n")
837 # %%FORK <source_game> <new_buoy_game> [<nth-move>]
838 # Fork a new game from the posistion where the n-th (starting from 1) move
839 # of a source game is played. The new game should be a valid buoy game
840 # name. The default value of n is the position where the previous position
843 class ForkCommand < Command
844 def initialize(str, player, source_game, new_buoy_game, nth_move)
846 @source_game = source_game
847 @new_buoy_game = new_buoy_game
848 @nth_move = nth_move # may be nil
850 attr_reader :new_buoy_game
852 def decide_new_buoy_game_name
857 if @source_game.split("+").size >= 2 &&
858 /^([^-]+)-(\d+)-(\d+)/ =~ @source_game.split("+")[1]
863 if name == nil || total_time == nil || byo_time == nil
864 @player.write_safe(sprintf("##[ERROR] wrong source game name to make a new buoy game name: %s\n", @source_game))
865 log_error "Received a wrong source game name to make a new buoy game name: %s from %s." % [@source_game, @player.name]
868 @new_buoy_game = "buoy_%s_%d-%s-%s" % [name, @nth_move, total_time, byo_time]
869 @player.write_safe(sprintf("##[FORK]: new buoy game name: %s\n", @new_buoy_game))
870 @player.write_safe("##[FORK] +OK\n")
874 game = $league.games[@source_game]
876 @player.write_safe(sprintf("##[ERROR] wrong source game name: %s\n", @source_game))
877 log_error "Received a wrong source game name: %s from %s." % [@source_game, @player.name]
881 moves = game.read_moves # [["+7776FU","T2"],["-3334FU","T5"]]
882 @nth_move = moves.size - 1 unless @nth_move
883 if @nth_move > moves.size or @nth_move < 1
884 @player.write_safe(sprintf("##[ERROR] number of moves to fork is out of range: %s.\n", moves.size))
885 log_error "Number of moves to fork is out of range: %s [%s]" % [@nth_move, @player.name]
889 moves[0...@nth_move].each do |m|
890 new_moves_str << m.join(",")
893 unless @new_buoy_game
894 decide_new_buoy_game_name
897 buoy_cmd = SetBuoyCommand.new(@str, @player, @new_buoy_game, new_moves_str, 1)
902 end # module ShogiServer