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 cmd = ErrorCommand.new(str, player)
107 def initialize(str, player)
110 @time = Time.now # this should be replaced later with a real time
115 # Application-level protocol for Keep-Alive.
116 # If the server receives an LF, it sends back an LF. Note that the 30 sec
117 # rule (client may not send LF again within 30 sec) is not implemented
120 class KeepAliveCommand < Command
121 def initialize(str, player)
126 @player.write_safe("\n")
131 # Command of moving a piece.
133 class MoveCommand < Command
134 def initialize(str, player)
139 if (@player.status == "game")
140 array_str = @str.split(",")
141 move = array_str.shift
142 if @player.game.last_move &&
143 @player.game.last_move.split(",").first == move
144 log_warning("Received two sequencial identical moves [#{move}] from #{@player.name}. The last one was ignored.")
147 additional = array_str.shift
149 if /^'(.*)/ =~ additional
150 comment = array_str.unshift("'*#{$1.toeuc}")
152 s = @player.game.handle_one_move(move, @player, @time)
153 @player.game.log_game(Kconv.toeuc(comment.first)) if (comment && comment.first && !s)
154 return :return if (s && @player.protocol == LoginCSA::PROTOCOL)
160 # Command like "%TORYO" or :timeout
162 class SpecialCommand < Command
163 def initialize(str, player)
169 if (@player.status == "game")
170 rc = in_game_status()
171 elsif ["agree_waiting", "start_waiting"].include?(@player.status)
172 rc = in_waiting_status()
174 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].") unless @str == :timeout
182 s = @player.game.handle_one_move(@str, @player, @time)
183 rc = :return if (s && @player.protocol == LoginCSA::PROTOCOL)
188 def in_waiting_status
191 if @player.game.prepared_expire?
192 log_warning("#{@player.status} lasted too long. This play has been expired: %s" % [@player.game.game_id])
193 @player.game.reject("the Server (timed out)")
194 rc = :return if (@player.protocol == LoginCSA::PROTOCOL)
201 # Command of :exception
203 class ExceptionCommand < Command
204 def initialize(str, player)
209 log_error("Failed to receive a message from #{@player.name}.")
216 class RejectCommand < Command
217 def initialize(str, player)
222 if (@player.status == "agree_waiting")
223 @player.game.reject(@player.name)
224 return :return if (@player.protocol == LoginCSA::PROTOCOL)
226 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].")
227 @player.write_safe(sprintf("##[ERROR] you are in %s status. REJECT is valid in agree_waiting status\n", @player.status))
235 class AgreeCommand < Command
236 def initialize(str, player)
241 if (@player.status == "agree_waiting")
242 @player.status = "start_waiting"
243 if (@player.game.is_startable_status?)
247 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].")
248 @player.write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @player.status))
254 # Base Command calss requiring a game instance
256 class BaseCommandForGame < Command
257 def initialize(str, player, game)
260 @game_id = game ? game.game_id : nil
266 class ShowCommand < BaseCommandForGame
267 def initialize(str, player, game)
273 @player.write_safe(@game.show.gsub(/^/, '##[SHOW] '))
275 @player.write_safe("##[SHOW] +OK\n")
281 def initialize(player)
286 attr_reader :player, :type, :header
290 rhs.is_a?(MonitorHandler) &&
291 @player == rhs.player &&
295 def write_safe(game_id, str)
296 str.chomp.split("\n").each do |line|
297 @player.write_safe("##[%s][%s] %s\n" % [@header, game_id, line.chomp])
299 @player.write_safe("##[%s][%s] %s\n" % [@header, game_id, "+OK"])
303 class MonitorHandler1 < MonitorHandler
304 def initialize(player)
310 def write_one_move(game_id, game)
311 write_safe(game_id, game.show.chomp)
315 class MonitorHandler2 < MonitorHandler
316 def initialize(player)
322 def write_one_move(game_id, game)
323 write_safe(game_id, game.last_move.gsub(",", "\n"))
327 # Command of MONITORON
329 class MonitorOnCommand < BaseCommandForGame
330 def initialize(str, player, game)
336 monitor_handler = MonitorHandler1.new(@player)
337 @game.monitoron(monitor_handler)
338 monitor_handler.write_safe(@game_id, @game.show)
344 # Command of MONITOROFF
346 class MonitorOffCommand < BaseCommandForGame
347 def initialize(str, player, game)
353 @game.monitoroff(MonitorHandler1.new(@player))
359 # Command of MONITOR2ON
361 class Monitor2OnCommand < BaseCommandForGame
362 def initialize(str, player, game)
368 monitor_handler = MonitorHandler2.new(@player)
369 @game.monitoron(monitor_handler)
370 lines = IO::readlines(@game.logfile).join("")
371 monitor_handler.write_safe(@game_id, lines)
377 class Monitor2OffCommand < MonitorOffCommand
378 def initialize(str, player, game)
384 @game.monitoroff(MonitorHandler2.new(@player))
392 class HelpCommand < Command
393 def initialize(str, player)
399 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
406 class RatingCommand < Command
407 def initialize(str, player, rated_players)
409 @rated_players = rated_players
413 @rated_players.sort {|a,b| b.rate <=> a.rate}.each do |p|
414 @player.write_safe("##[RATING] %s \t %4d @%s\n" %
415 [p.simple_player_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
417 @player.write_safe("##[RATING] +OK\n")
424 class VersionCommand < Command
425 def initialize(str, player)
430 @player.write_safe "##[VERSION] Shogi Server revision #{ShogiServer::Revision}\n"
431 @player.write_safe("##[VERSION] +OK\n")
438 class GameCommand < Command
439 def initialize(str, player)
444 if ((@player.status == "connected") || (@player.status == "game_waiting"))
445 @player.status = "connected"
446 @player.game_name = ""
448 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
454 # Commando of game challenge
455 # TODO make a test case
457 class GameChallengeCommand < Command
458 def initialize(str, player, command_name, game_name, my_sente_str)
460 @command_name = command_name
461 @game_name = game_name
462 @my_sente_str = my_sente_str
466 if (! Login::good_game_name?(@game_name))
467 @player.write_safe(sprintf("##[ERROR] bad game name\n"))
469 elsif ((@player.status == "connected") || (@player.status == "game_waiting"))
472 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
477 if (Buoy.game_name?(@game_name))
478 if (@my_sente_str != "*")
479 @player.write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", @my_sente_str, @game_name))
485 if (League::Floodgate.game_name?(@game_name))
486 if (@my_sente_str != "*")
487 @player.write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", @my_sente_str, @game_name))
492 if (@my_sente_str == "*") && !Login.handicapped_game_name?(@game_name)
493 rival = $league.get_player("game_waiting", @game_name, nil, @player) # no preference
494 elsif (@my_sente_str == "+")
495 rival = $league.get_player("game_waiting", @game_name, false, @player) # rival must be gote
496 elsif (@my_sente_str == "-")
497 rival = $league.get_player("game_waiting", @game_name, true, @player) # rival must be sente
499 @player.write_safe(sprintf("##[ERROR] bad game option\n"))
505 @player.game_name = @game_name
507 if ((@my_sente_str == "*") && (rival.sente == nil))
512 @player.sente = false
515 elsif (rival.sente == true) # rival has higher priority
516 @player.sente = false
517 elsif (rival.sente == false)
519 elsif (@my_sente_str == "+")
522 elsif (@my_sente_str == "-")
523 @player.sente = false
528 if (Buoy.game_name?(@game_name))
529 buoy = Buoy.new # TODO config
530 if buoy.is_new_game?(@game_name)
531 # The buoy game is not ready yet.
532 # When the game is set, it will be started.
533 @player.status = "game_waiting"
535 buoy_game = buoy.get_game(@game_name)
536 if buoy_game.instance_of? NilBuoyGame
540 moves_array = Board::split_moves(buoy_game.moves)
543 board.set_from_moves(moves_array)
545 # it will never happen since moves have already been checked
546 log_error "Failed to set up a buoy game: #{moves}"
549 buoy.decrement_count(buoy_game)
550 Game::new(@player.game_name, @player, rival, board)
553 klass = Login.handicapped_game_name?(@game_name) || Board
556 Game::new(@player.game_name, @player, rival, board)
558 else # rival not found
559 if (@command_name == "GAME")
560 @player.status = "game_waiting"
561 @player.game_name = @game_name
562 if (@my_sente_str == "+")
564 elsif (@my_sente_str == "-")
565 @player.sente = false
570 @player.write_safe(sprintf("##[ERROR] can't find rival for %s\n", @game_name))
571 @player.status = "connected"
572 @player.game_name = ""
582 class ChatCommand < Command
584 # players array of [name, player]
586 def initialize(str, player, message, players)
593 @players.each do |name, p| # TODO player change name
594 if (p.protocol != LoginCSA::PROTOCOL)
595 p.write_safe(sprintf("##[CHAT][%s] %s\n", @player.name, @message))
604 class ListCommand < Command
606 # games array of [game_id, game]
608 def initialize(str, player, games)
615 @games.each do |id, game|
616 buf.push(sprintf("##[LIST] %s\n", id))
618 buf.push("##[LIST] +OK\n")
619 @player.write_safe(buf.join)
626 class WhoCommand < Command
628 # players array of [[name, player]]
630 def initialize(str, player, players)
637 @players.each do |name, p|
638 buf.push(sprintf("##[WHO] %s\n", p.to_s))
640 buf.push("##[WHO] +OK\n")
641 @player.write_safe(buf.join)
648 class LogoutCommand < Command
649 def initialize(str, player)
654 @player.status = "connected"
655 @player.write_safe("LOGOUT:completed\n")
660 # Command of CHALLENGE
662 class ChallengeCommand < Command
663 def initialize(str, player)
668 # This command is only available for CSA's official testing server.
669 # So, this means nothing for this program.
670 @player.write_safe("CHALLENGE ACCEPTED\n")
675 # Command for a space
677 class SpaceCommand < Command
678 def initialize(str, player)
683 ## ignore null string
688 # Command for an error
690 class ErrorCommand < Command
691 def initialize(str, player)
696 msg = "##[ERROR] unknown command %s\n" % [@str]
697 @player.write_safe(msg)
705 class SetBuoyCommand < Command
707 def initialize(str, player, game_name, moves, count)
709 @game_name = game_name
715 unless (Buoy.game_name?(@game_name))
716 @player.write_safe(sprintf("##[ERROR] wrong buoy game name: %s\n", @game_name))
717 log_error "Received a wrong buoy game name: %s from %s." % [@game_name, @player.name]
721 unless buoy.is_new_game?(@game_name)
722 @player.write_safe(sprintf("##[ERROR] duplicated buoy game name: %s\n", @game_name))
723 log_error "Received duplicated buoy game name: %s from %s." % [@game_name, @player.name]
727 @player.write_safe(sprintf("##[ERROR] invalid count: %s\n", @count))
728 log_error "Received an invalid count for a buoy game: %s, %s from %s." % [@count, @game_name, @player.name]
733 moves_array = Board::split_moves(@moves)
736 board.set_from_moves(moves_array)
741 buoy_game = BuoyGame.new(@game_name, @moves, @player.name, @count)
742 buoy.add_game(buoy_game)
743 @player.write_safe(sprintf("##[SETBUOY] +OK\n"))
744 log_info("A buoy game was created: %s by %s" % [@game_name, @player.name])
746 # if two players, who are not @player, are waiting for a new game, start it
747 p1 = $league.get_player("game_waiting", @game_name, true, @player)
748 return :continue unless p1
749 p2 = $league.get_player("game_waiting", @game_name, false, @player)
750 return :continue unless p2
752 buoy.decrement_count(buoy_game)
753 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")
812 end # module ShogiServer