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)
106 cmd = SpaceCommand.new(str, player)
108 # TODO: just ignore commands specific to 81Dojo.
109 # Need to discuss with 81Dojo people.
110 cmd = VoidCommand.new(str, player)
112 cmd = ErrorCommand.new(str, player)
119 def initialize(str, player)
122 @time = Time.now # this should be replaced later with a real time
127 # Dummy command which does nothing.
129 class VoidCommand < Command
130 def initialize(str, player)
139 # Application-level protocol for Keep-Alive.
140 # If the server receives an LF, it sends back an LF. Note that the 30 sec
141 # rule (client may not send LF again within 30 sec) is not implemented
144 class KeepAliveCommand < Command
145 def initialize(str, player)
150 @player.write_safe("\n")
155 # Command of moving a piece.
157 class MoveCommand < Command
158 def initialize(str, player)
163 if (@player.status == "game")
164 array_str = @str.split(",")
165 move = array_str.shift
166 if @player.game.last_move &&
167 @player.game.last_move.split(",").first == move
168 log_warning("Received two sequencial identical moves [#{move}] from #{@player.name}. The last one was ignored.")
171 additional = array_str.shift
173 if /^'(.*)/ =~ additional
174 comment = array_str.unshift("'*#{$1.toeuc}")
176 s = @player.game.handle_one_move(move, @player, @time)
177 @player.game.log_game(Kconv.toeuc(comment.first)) if (comment && comment.first && !s)
178 return :return if (s && @player.protocol == LoginCSA::PROTOCOL)
184 # Command like "%TORYO" or :timeout
186 class SpecialCommand < Command
187 def initialize(str, player)
193 if (@player.status == "game")
194 rc = in_game_status()
195 elsif ["agree_waiting", "start_waiting"].include?(@player.status)
196 rc = in_waiting_status()
198 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].") unless @str == :timeout
206 s = @player.game.handle_one_move(@str, @player, @time)
207 rc = :return if (s && @player.protocol == LoginCSA::PROTOCOL)
212 def in_waiting_status
215 if @player.game.prepared_expire?
216 log_warning("#{@player.status} lasted too long. This play has been expired: %s" % [@player.game.game_id])
217 @player.game.reject("the Server (timed out)")
218 rc = :return if (@player.protocol == LoginCSA::PROTOCOL)
225 # Command of :exception
227 class ExceptionCommand < Command
228 def initialize(str, player)
233 log_error("Failed to receive a message from #{@player.name}.")
240 class RejectCommand < Command
241 def initialize(str, player)
246 if (@player.status == "agree_waiting")
247 @player.game.reject(@player.name)
248 return :return if (@player.protocol == LoginCSA::PROTOCOL)
250 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].")
251 @player.write_safe(sprintf("##[ERROR] you are in %s status. REJECT is valid in agree_waiting status\n", @player.status))
259 class AgreeCommand < Command
260 def initialize(str, player)
265 if (@player.status == "agree_waiting")
266 @player.status = "start_waiting"
267 if (@player.game.is_startable_status?)
271 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].")
272 @player.write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @player.status))
278 # Base Command calss requiring a game instance
280 class BaseCommandForGame < Command
281 def initialize(str, player, game)
284 @game_id = game ? game.game_id : nil
290 class ShowCommand < BaseCommandForGame
291 def initialize(str, player, game)
297 @player.write_safe(@game.show.gsub(/^/, '##[SHOW] '))
299 @player.write_safe("##[SHOW] +OK\n")
305 def initialize(player)
310 attr_reader :player, :type, :header
314 rhs.is_a?(MonitorHandler) &&
315 @player == rhs.player &&
319 def write_safe(game_id, str)
320 str.chomp.split("\n").each do |line|
321 @player.write_safe("##[%s][%s] %s\n" % [@header, game_id, line.chomp])
323 @player.write_safe("##[%s][%s] %s\n" % [@header, game_id, "+OK"])
327 class MonitorHandler1 < MonitorHandler
328 def initialize(player)
334 def write_one_move(game_id, game)
335 write_safe(game_id, game.show.chomp)
339 class MonitorHandler2 < MonitorHandler
340 def initialize(player)
346 def write_one_move(game_id, game)
347 write_safe(game_id, game.last_move.gsub(",", "\n"))
351 # Command of MONITORON
353 class MonitorOnCommand < BaseCommandForGame
354 def initialize(str, player, game)
360 monitor_handler = MonitorHandler1.new(@player)
361 @game.monitoron(monitor_handler)
362 monitor_handler.write_safe(@game_id, @game.show)
368 # Command of MONITOROFF
370 class MonitorOffCommand < BaseCommandForGame
371 def initialize(str, player, game)
377 @game.monitoroff(MonitorHandler1.new(@player))
383 # Command of MONITOR2ON
385 class Monitor2OnCommand < BaseCommandForGame
386 def initialize(str, player, game)
392 monitor_handler = MonitorHandler2.new(@player)
393 @game.monitoron(monitor_handler)
394 lines = IO::readlines(@game.logfile).join("")
395 monitor_handler.write_safe(@game_id, lines)
401 class Monitor2OffCommand < MonitorOffCommand
402 def initialize(str, player, game)
408 @game.monitoroff(MonitorHandler2.new(@player))
416 class HelpCommand < Command
417 def initialize(str, player)
423 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
430 class RatingCommand < Command
431 def initialize(str, player, rated_players)
433 @rated_players = rated_players
437 @rated_players.sort {|a,b| b.rate <=> a.rate}.each do |p|
438 @player.write_safe("##[RATING] %s \t %4d @%s\n" %
439 [p.simple_player_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
441 @player.write_safe("##[RATING] +OK\n")
448 class VersionCommand < Command
449 def initialize(str, player)
454 @player.write_safe "##[VERSION] Shogi Server revision #{ShogiServer::Revision}\n"
455 @player.write_safe("##[VERSION] +OK\n")
462 class GameCommand < Command
463 def initialize(str, player)
468 if ((@player.status == "connected") || (@player.status == "game_waiting"))
469 @player.status = "connected"
470 @player.game_name = ""
472 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
478 # Commando of game challenge
479 # TODO make a test case
481 class GameChallengeCommand < Command
482 def initialize(str, player, command_name, game_name, my_sente_str)
484 @command_name = command_name
485 @game_name = game_name
486 @my_sente_str = my_sente_str
487 player.set_sente_from_str(@my_sente_str)
491 if (! Login::good_game_name?(@game_name))
492 @player.write_safe(sprintf("##[ERROR] bad game name\n"))
494 elsif ((@player.status == "connected") || (@player.status == "game_waiting"))
497 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
502 if (League::Floodgate.game_name?(@game_name))
503 if (@my_sente_str != "*")
504 @player.write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", @my_sente_str, @game_name))
509 rival = $league.find_rival(@player, @game_name)
510 if rival.instance_of?(Symbol)
511 # An error happened. rival is not a player instance, but an error
512 # symobl that must be returned to the main routine immediately.
518 @player.game_name = @game_name
519 Game::decide_turns(@player, @my_sente_str, rival)
521 if (Buoy.game_name?(@game_name))
522 buoy = Buoy.new # TODO config
523 if buoy.is_new_game?(@game_name)
524 # The buoy game is not ready yet.
525 # When the game is set, it will be started.
526 @player.status = "game_waiting"
528 buoy_game = buoy.get_game(@game_name)
529 if buoy_game.instance_of? NilBuoyGame
533 moves_array = Board::split_moves(buoy_game.moves)
536 board.set_from_moves(moves_array)
538 # it will never happen since moves have already been checked
539 log_error "Failed to set up a buoy game: #{moves}"
542 buoy.decrement_count(buoy_game)
543 Game::new(@player.game_name, @player, rival, board)
546 klass = Login.handicapped_game_name?(@game_name) || Board
549 Game::new(@player.game_name, @player, rival, board)
551 else # rival not found
552 if (@command_name == "GAME")
553 @player.status = "game_waiting"
554 @player.game_name = @game_name
556 @player.write_safe(sprintf("##[ERROR] can't find rival for %s\n", @game_name))
557 @player.status = "connected"
558 @player.game_name = ""
568 class ChatCommand < Command
570 # players array of [name, player]
572 def initialize(str, player, message, players)
579 @players.each do |name, p| # TODO player change name
580 if (p.protocol != LoginCSA::PROTOCOL)
581 p.write_safe(sprintf("##[CHAT][%s] %s\n", @player.name, @message))
590 class ListCommand < Command
592 # games array of [game_id, game]
594 def initialize(str, player, games)
601 @games.each do |id, game|
602 buf.push(sprintf("##[LIST] %s\n", id))
604 buf.push("##[LIST] +OK\n")
605 @player.write_safe(buf.join)
612 class WhoCommand < Command
614 # players array of [[name, player]]
616 def initialize(str, player, players)
623 @players.each do |name, p|
624 buf.push(sprintf("##[WHO] %s\n", p.to_s))
626 buf.push("##[WHO] +OK\n")
627 @player.write_safe(buf.join)
634 class LogoutCommand < Command
635 def initialize(str, player)
640 @player.status = "connected"
641 @player.write_safe("LOGOUT:completed\n")
646 # Command of CHALLENGE
648 class ChallengeCommand < Command
649 def initialize(str, player)
654 # This command is only available for CSA's official testing server.
655 # So, this means nothing for this program.
656 @player.write_safe("CHALLENGE ACCEPTED\n")
661 # Command for a space
663 class SpaceCommand < Command
664 def initialize(str, player)
669 ## ignore null string
674 # Command for an error
676 class ErrorCommand < Command
677 def initialize(str, player)
685 # Aim to hide a possible password
686 cmd.gsub!(/LOGIN\s*(\w+)\s+.*/i, 'LOGIN \1...')
687 @msg = "##[ERROR] unknown command %s\n" % [cmd]
688 @player.write_safe(@msg)
696 class SetBuoyCommand < Command
698 def initialize(str, player, game_name, moves, count)
700 @game_name = game_name
706 unless (Buoy.game_name?(@game_name))
707 @player.write_safe(sprintf("##[ERROR] wrong buoy game name: %s\n", @game_name))
708 log_error "Received a wrong buoy game name: %s from %s." % [@game_name, @player.name]
712 unless buoy.is_new_game?(@game_name)
713 @player.write_safe(sprintf("##[ERROR] duplicated buoy game name: %s\n", @game_name))
714 log_error "Received duplicated buoy game name: %s from %s." % [@game_name, @player.name]
718 @player.write_safe(sprintf("##[ERROR] invalid count: %s\n", @count))
719 log_error "Received an invalid count for a buoy game: %s, %s from %s." % [@count, @game_name, @player.name]
724 moves_array = Board::split_moves(@moves)
727 board.set_from_moves(moves_array)
732 buoy_game = BuoyGame.new(@game_name, @moves, @player.name, @count)
733 buoy.add_game(buoy_game)
734 @player.write_safe(sprintf("##[SETBUOY] +OK\n"))
735 log_info("A buoy game was created: %s by %s" % [@game_name, @player.name])
737 # if two players are waiting for this buoy game, start it
738 candidates = $league.find_all_players do |player|
739 player.status == "game_waiting" &&
740 player.game_name == @game_name &&
741 player.name != @player.name
744 log_info("No players found for a buoy game. Wait for players: %s" % [@game_name])
747 p1 = candidates.first
748 p2 = $league.find_rival(p1, @game_name)
750 log_info("No opponent found for a buoy game. Wait for the opponent: %s by %s" % [@game_name, p1.name])
752 elsif p2.instance_of?(Symbol)
753 # An error happened. rival is not a player instance, but an error
754 # symobl that must be returned to the main routine immediately.
757 # found two players: p1 and p2
758 log_info("Starting a buoy game: %s with %s and %s" % [@game_name, p1.name, p2.name])
759 buoy.decrement_count(buoy_game)
760 game = Game::new(@game_name, p1, p2, board)
763 rescue WrongMoves => e
764 @player.write_safe(sprintf("##[ERROR] wrong moves: %s\n", @moves))
765 log_error "Received wrong moves: %s from %s. [%s]" % [@moves, @player.name, e.message]
772 class DeleteBuoyCommand < Command
773 def initialize(str, player, game_name)
775 @game_name = game_name
780 buoy_game = buoy.get_game(@game_name)
781 if buoy_game.instance_of?(NilBuoyGame)
782 @player.write_safe(sprintf("##[ERROR] buoy game not found: %s\n", @game_name))
783 log_error "Game name not found: %s by %s" % [@game_name, @player.name]
787 if buoy_game.owner != @player.name
788 @player.write_safe(sprintf("##[ERROR] you are not allowed to delete a buoy game that you did not set: %s\n", @game_name))
789 log_error "%s are not allowed to delete a game: %s" % [@player.name, @game_name]
793 buoy.delete_game(buoy_game)
794 @player.write_safe(sprintf("##[DELETEBUOY] +OK\n"))
795 log_info("A buoy game was deleted: %s" % [@game_name])
802 class GetBuoyCountCommand < Command
803 def initialize(str, player, game_name)
805 @game_name = game_name
810 buoy_game = buoy.get_game(@game_name)
811 if buoy_game.instance_of?(NilBuoyGame)
812 @player.write_safe("##[GETBUOYCOUNT] -1\n")
814 @player.write_safe("##[GETBUOYCOUNT] %s\n" % [buoy_game.count])
816 @player.write_safe("##[GETBUOYCOUNT] +OK\n")
820 # %%FORK <source_game> <new_buoy_game> [<nth-move>]
821 # Fork a new game from the posistion where the n-th (starting from 1) move
822 # of a source game is played. The new game should be a valid buoy game
823 # name. The default value of n is the position where the previous position
826 class ForkCommand < Command
827 def initialize(str, player, source_game, new_buoy_game, nth_move)
829 @source_game = source_game
830 @new_buoy_game = new_buoy_game
831 @nth_move = nth_move # may be nil
835 game = $league.games[@source_game]
837 @player.write_safe(sprintf("##[ERROR] wrong source game name: %s\n", @source_game))
838 log_error "Received a wrong source game name: %s from %s." % [@source_game, @player.name]
842 moves = game.read_moves # [["+7776FU","T2"],["-3334FU","T5"]]
843 @nth_move = moves.size - 1 unless @nth_move
844 if @nth_move > moves.size or @nth_move < 1
845 @player.write_safe(sprintf("##[ERROR] number of moves to fork is out of range: %s.\n", moves.size))
846 log_error "Number of moves to fork is out of range: %s [%s]" % [@nth_move, @player.name]
850 moves[0...@nth_move].each do |m|
851 new_moves_str << m.join(",")
853 buoy_cmd = SetBuoyCommand.new(@str, @player, @new_buoy_game, new_moves_str, 1)
858 end # module ShogiServer