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
482 if (! Login::good_game_name?(@game_name))
483 @player.write_safe(sprintf("##[ERROR] bad game name\n"))
485 elsif ((@player.status == "connected") || (@player.status == "game_waiting"))
488 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
493 if (League::Floodgate.game_name?(@game_name))
494 if (@my_sente_str != "*")
495 @player.write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", @my_sente_str, @game_name))
500 rival = $league.find_rival(@player, @my_sente_str, @game_name)
501 if rival.instance_of?(Symbol)
502 # An error happened. rival is not a player instance, but an error
503 # symobl that must be returned to the main routine immediately.
509 @player.game_name = @game_name
510 Game::decide_turns(@player, @my_sente_str, rival)
512 if (Buoy.game_name?(@game_name))
513 buoy = Buoy.new # TODO config
514 if buoy.is_new_game?(@game_name)
515 # The buoy game is not ready yet.
516 # When the game is set, it will be started.
517 @player.status = "game_waiting"
519 buoy_game = buoy.get_game(@game_name)
520 if buoy_game.instance_of? NilBuoyGame
524 moves_array = Board::split_moves(buoy_game.moves)
527 board.set_from_moves(moves_array)
529 # it will never happen since moves have already been checked
530 log_error "Failed to set up a buoy game: #{moves}"
533 buoy.decrement_count(buoy_game)
534 Game::new(@player.game_name, @player, rival, board)
537 klass = Login.handicapped_game_name?(@game_name) || Board
540 Game::new(@player.game_name, @player, rival, board)
542 else # rival not found
543 if (@command_name == "GAME")
544 @player.status = "game_waiting"
545 @player.game_name = @game_name
546 @player.set_sente_from_str(@my_sente_str)
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, who are not @player, are waiting for a new game, start it
730 p1 = $league.get_player("game_waiting", @game_name, true, @player)
731 return :continue unless p1
732 p2 = $league.get_player("game_waiting", @game_name, false, @player)
733 return :continue unless p2
735 buoy.decrement_count(buoy_game)
736 game = Game::new(@game_name, p1, p2, board)
738 rescue WrongMoves => e
739 @player.write_safe(sprintf("##[ERROR] wrong moves: %s\n", @moves))
740 log_error "Received wrong moves: %s from %s. [%s]" % [@moves, @player.name, e.message]
747 class DeleteBuoyCommand < Command
748 def initialize(str, player, game_name)
750 @game_name = game_name
755 buoy_game = buoy.get_game(@game_name)
756 if buoy_game.instance_of?(NilBuoyGame)
757 @player.write_safe(sprintf("##[ERROR] buoy game not found: %s\n", @game_name))
758 log_error "Game name not found: %s by %s" % [@game_name, @player.name]
762 if buoy_game.owner != @player.name
763 @player.write_safe(sprintf("##[ERROR] you are not allowed to delete a buoy game that you did not set: %s\n", @game_name))
764 log_error "%s are not allowed to delete a game: %s" % [@player.name, @game_name]
768 buoy.delete_game(buoy_game)
769 @player.write_safe(sprintf("##[DELETEBUOY] +OK\n"))
770 log_info("A buoy game was deleted: %s" % [@game_name])
777 class GetBuoyCountCommand < 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("##[GETBUOYCOUNT] -1\n")
789 @player.write_safe("##[GETBUOYCOUNT] %s\n" % [buoy_game.count])
791 @player.write_safe("##[GETBUOYCOUNT] +OK\n")
795 end # module ShogiServer