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)
98 cmd = SpaceCommand.new(str, player)
100 # TODO: just ignore commands specific to 81Dojo.
101 # Need to discuss with 81Dojo people.
102 cmd = VoidCommand.new(str, player)
104 cmd = ErrorCommand.new(str, player)
111 def initialize(str, player)
114 @time = Time.now # this should be replaced later with a real time
119 # Dummy command which does nothing.
121 class VoidCommand < Command
122 def initialize(str, player)
131 # Application-level protocol for Keep-Alive.
132 # If the server receives an LF, it sends back an LF. Note that the 30 sec
133 # rule (client may not send LF again within 30 sec) is not implemented
136 class KeepAliveCommand < Command
137 def initialize(str, player)
142 @player.write_safe("\n")
147 # Command of moving a piece.
149 class MoveCommand < Command
150 def initialize(str, player)
155 if (@player.status == "game")
156 array_str = @str.split(",")
157 move = array_str.shift
158 if @player.game.last_move &&
159 @player.game.last_move.split(",").first == move
160 log_warning("Received two sequencial identical moves [#{move}] from #{@player.name}. The last one was ignored.")
163 additional = array_str.shift
165 if /^'(.*)/ =~ additional
166 comment = array_str.unshift("'*#{$1.toeuc}")
168 s = @player.game.handle_one_move(move, @player, @time)
169 @player.game.log_game(Kconv.toeuc(comment.first)) if (comment && comment.first && !s)
170 return :return if (s && @player.protocol == LoginCSA::PROTOCOL)
176 # Command like "%TORYO" or :timeout
178 class SpecialCommand < Command
179 def initialize(str, player)
185 if (@player.status == "game")
186 rc = in_game_status()
187 elsif ["agree_waiting", "start_waiting"].include?(@player.status)
188 rc = in_waiting_status()
190 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].") unless @str == :timeout
198 s = @player.game.handle_one_move(@str, @player, @time)
199 rc = :return if (s && @player.protocol == LoginCSA::PROTOCOL)
204 def in_waiting_status
207 if @player.game.prepared_expire?
208 log_warning("#{@player.status} lasted too long. This play has been expired: %s" % [@player.game.game_id])
209 @player.game.reject("the Server (timed out)")
210 rc = :return if (@player.protocol == LoginCSA::PROTOCOL)
217 # Command of :exception
219 class ExceptionCommand < Command
220 def initialize(str, player)
225 log_error("Failed to receive a message from #{@player.name}.")
232 class RejectCommand < Command
233 def initialize(str, player)
238 if (@player.status == "agree_waiting")
239 @player.game.reject(@player.name)
240 return :return if (@player.protocol == LoginCSA::PROTOCOL)
242 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].")
243 @player.write_safe(sprintf("##[ERROR] you are in %s status. REJECT is valid in agree_waiting status\n", @player.status))
251 class AgreeCommand < Command
252 def initialize(str, player)
257 if (@player.status == "agree_waiting")
258 @player.status = "start_waiting"
259 if (@player.game.is_startable_status?)
263 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].")
264 @player.write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @player.status))
270 # Base Command calss requiring a game instance
272 class BaseCommandForGame < Command
273 def initialize(str, player, game)
276 @game_id = game ? game.game_id : nil
282 class ShowCommand < BaseCommandForGame
283 def initialize(str, player, game)
289 @player.write_safe(@game.show.gsub(/^/, '##[SHOW] '))
291 @player.write_safe("##[SHOW] +OK\n")
297 def initialize(player)
302 attr_reader :player, :type, :header
306 rhs.is_a?(MonitorHandler) &&
307 @player == rhs.player &&
311 def write_safe(game_id, str)
312 str.chomp.split("\n").each do |line|
313 @player.write_safe("##[%s][%s] %s\n" % [@header, game_id, line.chomp])
315 @player.write_safe("##[%s][%s] %s\n" % [@header, game_id, "+OK"])
319 class MonitorHandler1 < MonitorHandler
320 def initialize(player)
326 def write_one_move(game_id, game)
327 write_safe(game_id, game.show.chomp)
331 class MonitorHandler2 < MonitorHandler
332 def initialize(player)
338 def write_one_move(game_id, game)
339 write_safe(game_id, game.last_move.gsub(",", "\n"))
343 # Command of MONITORON
345 class MonitorOnCommand < BaseCommandForGame
346 def initialize(str, player, game)
352 monitor_handler = MonitorHandler1.new(@player)
353 @game.monitoron(monitor_handler)
354 monitor_handler.write_safe(@game_id, @game.show)
360 # Command of MONITOROFF
362 class MonitorOffCommand < BaseCommandForGame
363 def initialize(str, player, game)
369 @game.monitoroff(MonitorHandler1.new(@player))
375 # Command of MONITOR2ON
377 class Monitor2OnCommand < BaseCommandForGame
378 def initialize(str, player, game)
384 monitor_handler = MonitorHandler2.new(@player)
385 @game.monitoron(monitor_handler)
386 lines = IO::readlines(@game.logfile).join("")
387 monitor_handler.write_safe(@game_id, lines)
393 class Monitor2OffCommand < MonitorOffCommand
394 def initialize(str, player, game)
400 @game.monitoroff(MonitorHandler2.new(@player))
408 class HelpCommand < Command
409 def initialize(str, player)
415 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
422 class RatingCommand < Command
423 def initialize(str, player, rated_players)
425 @rated_players = rated_players
429 @rated_players.sort {|a,b| b.rate <=> a.rate}.each do |p|
430 @player.write_safe("##[RATING] %s \t %4d @%s\n" %
431 [p.simple_player_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
433 @player.write_safe("##[RATING] +OK\n")
440 class VersionCommand < Command
441 def initialize(str, player)
446 @player.write_safe "##[VERSION] Shogi Server revision #{ShogiServer::Revision}\n"
447 @player.write_safe("##[VERSION] +OK\n")
454 class GameCommand < Command
455 def initialize(str, player)
460 if ((@player.status == "connected") || (@player.status == "game_waiting"))
461 @player.status = "connected"
462 @player.game_name = ""
464 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
470 # Commando of game challenge
471 # TODO make a test case
473 class GameChallengeCommand < Command
474 def initialize(str, player, command_name, game_name, my_sente_str)
476 @command_name = command_name
477 @game_name = game_name
478 @my_sente_str = my_sente_str
479 player.set_sente_from_str(@my_sente_str)
483 if (! Login::good_game_name?(@game_name))
484 @player.write_safe(sprintf("##[ERROR] bad game name\n"))
486 elsif ((@player.status == "connected") || (@player.status == "game_waiting"))
489 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
494 if (League::Floodgate.game_name?(@game_name))
495 if (@my_sente_str != "*")
496 @player.write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", @my_sente_str, @game_name))
501 rival = $league.find_rival(@player, @game_name)
502 if rival.instance_of?(Symbol)
503 # An error happened. rival is not a player instance, but an error
504 # symobl that must be returned to the main routine immediately.
510 @player.game_name = @game_name
511 Game::decide_turns(@player, @my_sente_str, rival)
513 if (Buoy.game_name?(@game_name))
514 buoy = Buoy.new # TODO config
515 if buoy.is_new_game?(@game_name)
516 # The buoy game is not ready yet.
517 # When the game is set, it will be started.
518 @player.status = "game_waiting"
520 buoy_game = buoy.get_game(@game_name)
521 if buoy_game.instance_of? NilBuoyGame
525 moves_array = Board::split_moves(buoy_game.moves)
528 board.set_from_moves(moves_array)
530 # it will never happen since moves have already been checked
531 log_error "Failed to set up a buoy game: #{moves}"
534 buoy.decrement_count(buoy_game)
535 Game::new(@player.game_name, @player, rival, board)
538 klass = Login.handicapped_game_name?(@game_name) || Board
541 Game::new(@player.game_name, @player, rival, board)
543 else # rival not found
544 if (@command_name == "GAME")
545 @player.status = "game_waiting"
546 @player.game_name = @game_name
548 @player.write_safe(sprintf("##[ERROR] can't find rival for %s\n", @game_name))
549 @player.status = "connected"
550 @player.game_name = ""
560 class ChatCommand < Command
562 # players array of [name, player]
564 def initialize(str, player, message, players)
571 @players.each do |name, p| # TODO player change name
572 if (p.protocol != LoginCSA::PROTOCOL)
573 p.write_safe(sprintf("##[CHAT][%s] %s\n", @player.name, @message))
582 class ListCommand < Command
584 # games array of [game_id, game]
586 def initialize(str, player, games)
593 @games.each do |id, game|
594 buf.push(sprintf("##[LIST] %s\n", id))
596 buf.push("##[LIST] +OK\n")
597 @player.write_safe(buf.join)
604 class WhoCommand < Command
606 # players array of [[name, player]]
608 def initialize(str, player, players)
615 @players.each do |name, p|
616 buf.push(sprintf("##[WHO] %s\n", p.to_s))
618 buf.push("##[WHO] +OK\n")
619 @player.write_safe(buf.join)
626 class LogoutCommand < Command
627 def initialize(str, player)
632 @player.status = "connected"
633 @player.write_safe("LOGOUT:completed\n")
638 # Command of CHALLENGE
640 class ChallengeCommand < Command
641 def initialize(str, player)
646 # This command is only available for CSA's official testing server.
647 # So, this means nothing for this program.
648 @player.write_safe("CHALLENGE ACCEPTED\n")
653 # Command for a space
655 class SpaceCommand < Command
656 def initialize(str, player)
661 ## ignore null string
666 # Command for an error
668 class ErrorCommand < Command
669 def initialize(str, player)
677 # Aim to hide a possible password
678 cmd.gsub!(/LOGIN\s*(\w+)\s+.*/i, 'LOGIN \1...')
679 @msg = "##[ERROR] unknown command %s\n" % [cmd]
680 @player.write_safe(@msg)
688 class SetBuoyCommand < Command
690 def initialize(str, player, game_name, moves, count)
692 @game_name = game_name
698 unless (Buoy.game_name?(@game_name))
699 @player.write_safe(sprintf("##[ERROR] wrong buoy game name: %s\n", @game_name))
700 log_error "Received a wrong buoy game name: %s from %s." % [@game_name, @player.name]
704 unless buoy.is_new_game?(@game_name)
705 @player.write_safe(sprintf("##[ERROR] duplicated buoy game name: %s\n", @game_name))
706 log_error "Received duplicated buoy game name: %s from %s." % [@game_name, @player.name]
710 @player.write_safe(sprintf("##[ERROR] invalid count: %s\n", @count))
711 log_error "Received an invalid count for a buoy game: %s, %s from %s." % [@count, @game_name, @player.name]
716 moves_array = Board::split_moves(@moves)
719 board.set_from_moves(moves_array)
724 buoy_game = BuoyGame.new(@game_name, @moves, @player.name, @count)
725 buoy.add_game(buoy_game)
726 @player.write_safe(sprintf("##[SETBUOY] +OK\n"))
727 log_info("A buoy game was created: %s by %s" % [@game_name, @player.name])
729 # if two players are waiting for this buoy game, start it
730 candidates = $league.find_all_players do |player|
731 player.status == "game_waiting" &&
732 player.game_name == @game_name &&
733 player.name != @player.name
736 log_info("No players found for a buoy game. Wait for players: %s" % [@game_name])
739 p1 = candidates.first
740 p2 = $league.find_rival(p1, @game_name)
742 log_info("No opponent found for a buoy game. Wait for the opponent: %s by %s" % [@game_name, p1.name])
744 elsif p2.instance_of?(Symbol)
745 # An error happened. rival is not a player instance, but an error
746 # symobl that must be returned to the main routine immediately.
749 # found two players: p1 and p2
750 log_info("Starting a buoy game: %s with %s and %s" % [@game_name, p1.name, p2.name])
751 buoy.decrement_count(buoy_game)
752 game = Game::new(@game_name, p1, p2, board)
755 rescue WrongMoves => e
756 @player.write_safe(sprintf("##[ERROR] wrong moves: %s\n", @moves))
757 log_error "Received wrong moves: %s from %s. [%s]" % [@moves, @player.name, e.message]
764 class DeleteBuoyCommand < Command
765 def initialize(str, player, game_name)
767 @game_name = game_name
772 buoy_game = buoy.get_game(@game_name)
773 if buoy_game.instance_of?(NilBuoyGame)
774 @player.write_safe(sprintf("##[ERROR] buoy game not found: %s\n", @game_name))
775 log_error "Game name not found: %s by %s" % [@game_name, @player.name]
779 if buoy_game.owner != @player.name
780 @player.write_safe(sprintf("##[ERROR] you are not allowed to delete a buoy game that you did not set: %s\n", @game_name))
781 log_error "%s are not allowed to delete a game: %s" % [@player.name, @game_name]
785 buoy.delete_game(buoy_game)
786 @player.write_safe(sprintf("##[DELETEBUOY] +OK\n"))
787 log_info("A buoy game was deleted: %s" % [@game_name])
794 class GetBuoyCountCommand < Command
795 def initialize(str, player, game_name)
797 @game_name = game_name
802 buoy_game = buoy.get_game(@game_name)
803 if buoy_game.instance_of?(NilBuoyGame)
804 @player.write_safe("##[GETBUOYCOUNT] -1\n")
806 @player.write_safe("##[GETBUOYCOUNT] %s\n" % [buoy_game.count])
808 @player.write_safe("##[GETBUOYCOUNT] +OK\n")
813 end # module ShogiServer