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)
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)
106 def initialize(str, player)
112 # Application-level protocol for Keep-Alive.
113 # If the server receives an LF, it sends back an LF. Note that the 30 sec
114 # rule (client may not send LF again within 30 sec) is not implemented
117 class KeepAliveCommand < Command
118 def initialize(str, player)
123 @player.write_safe("\n")
128 # Command of moving a piece.
130 class MoveCommand < Command
131 def initialize(str, player)
136 if (@player.status == "game")
137 array_str = @str.split(",")
138 move = array_str.shift
139 additional = array_str.shift
141 if /^'(.*)/ =~ additional
142 comment = array_str.unshift("'*#{$1.toeuc}")
144 s = @player.game.handle_one_move(move, @player)
145 @player.game.log_game(Kconv.toeuc(comment.first)) if (comment && comment.first && !s)
146 return :return if (s && @player.protocol == LoginCSA::PROTOCOL)
152 # Command like "%TORYO" or :timeout
154 class SpecialCommand < Command
155 def initialize(str, player)
161 if (@player.status == "game")
162 rc = in_game_status()
163 elsif ["agree_waiting", "start_waiting"].include?(@player.status)
164 rc = in_waiting_status()
166 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].") unless @str == :timeout
174 s = @player.game.handle_one_move(@str, @player)
175 rc = :return if (s && @player.protocol == LoginCSA::PROTOCOL)
180 def in_waiting_status
183 if @player.game.prepared_expire?
184 log_warning("#{@player.status} lasted too long. This play has been expired: %s" % [@player.game.game_id])
185 @player.game.reject("the Server (timed out)")
186 rc = :return if (@player.protocol == LoginCSA::PROTOCOL)
193 # Command of :exception
195 class ExceptionCommand < Command
196 def initialize(str, player)
201 log_error("Failed to receive a message from #{@player.name}.")
208 class RejectCommand < Command
209 def initialize(str, player)
214 if (@player.status == "agree_waiting")
215 @player.game.reject(@player.name)
216 return :return if (@player.protocol == LoginCSA::PROTOCOL)
218 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].")
219 @player.write_safe(sprintf("##[ERROR] you are in %s status. REJECT is valid in agree_waiting status\n", @player.status))
227 class AgreeCommand < Command
228 def initialize(str, player)
233 if (@player.status == "agree_waiting")
234 @player.status = "start_waiting"
235 if (@player.game.is_startable_status?)
239 log_error("Received a command [#{@str}] from #{@player.name} in an inappropriate status [#{@player.status}].")
240 @player.write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @player.status))
246 # Base Command calss requiring a game instance
248 class BaseCommandForGame < Command
249 def initialize(str, player, game)
252 @game_id = game ? game.game_id : nil
258 class ShowCommand < BaseCommandForGame
259 def initialize(str, player, game)
265 @player.write_safe(@game.show.gsub(/^/, '##[SHOW] '))
267 @player.write_safe("##[SHOW] +OK\n")
273 def initialize(player)
278 attr_reader :player, :type, :header
282 rhs.is_a?(MonitorHandler) &&
283 @player = rhs.player &&
287 def write_safe(game_id, str)
288 str.chomp.split("\n").each do |line|
289 @player.write_safe("##[%s][%s] %s\n" % [@header, game_id, line.chomp])
291 @player.write_safe("##[%s][%s] %s\n" % [@header, game_id, "+OK"])
295 class MonitorHandler1 < MonitorHandler
296 def initialize(player)
302 def write_one_move(game_id, game)
303 write_safe(game_id, game.show.chomp)
307 class MonitorHandler2 < MonitorHandler
308 def initialize(player)
314 def write_one_move(game_id, game)
315 write_safe(game_id, game.last_move.gsub(",", "\n"))
319 # Command of MONITORON
321 class MonitorOnCommand < BaseCommandForGame
322 def initialize(str, player, game)
328 monitor_handler = MonitorHandler1.new(@player)
329 @game.monitoron(monitor_handler)
330 monitor_handler.write_safe(@game_id, @game.show)
336 # Command of MONITOROFF
338 class MonitorOffCommand < BaseCommandForGame
339 def initialize(str, player, game)
345 @game.monitoroff(MonitorHandler1.new(@player))
351 # Command of MONITOR2ON
353 class Monitor2OnCommand < BaseCommandForGame
354 def initialize(str, player, game)
360 monitor_handler = MonitorHandler2.new(@player)
361 @game.monitoron(monitor_handler)
362 lines = IO::readlines(@game.logfile).join("")
363 monitor_handler.write_safe(@game_id, lines)
369 class Monitor2OffCommand < MonitorOffCommand # same
370 def initialize(str, player, game)
377 class HelpCommand < Command
378 def initialize(str, player)
384 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
391 class RatingCommand < Command
392 def initialize(str, player, rated_players)
394 @rated_players = rated_players
398 @rated_players.sort {|a,b| b.rate <=> a.rate}.each do |p|
399 @player.write_safe("##[RATING] %s \t %4d @%s\n" %
400 [p.simple_player_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
402 @player.write_safe("##[RATING] +OK\n")
409 class VersionCommand < Command
410 def initialize(str, player)
415 @player.write_safe "##[VERSION] Shogi Server revision #{ShogiServer::Revision}\n"
416 @player.write_safe("##[VERSION] +OK\n")
423 class GameCommand < Command
424 def initialize(str, player)
429 if ((@player.status == "connected") || (@player.status == "game_waiting"))
430 @player.status = "connected"
431 @player.game_name = ""
433 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
439 # Commando of game challenge
440 # TODO make a test case
442 class GameChallengeCommand < Command
443 def initialize(str, player, command_name, game_name, my_sente_str)
445 @command_name = command_name
446 @game_name = game_name
447 @my_sente_str = my_sente_str
451 if (! Login::good_game_name?(@game_name))
452 @player.write_safe(sprintf("##[ERROR] bad game name\n"))
454 elsif ((@player.status == "connected") || (@player.status == "game_waiting"))
457 @player.write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @player.status))
462 if (Buoy.game_name?(@game_name))
463 if (@my_sente_str != "*")
464 @player.write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", @my_sente_str, @game_name))
470 if (League::Floodgate.game_name?(@game_name))
471 if (@my_sente_str != "*")
472 @player.write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", @my_sente_str, @game_name))
477 if (@my_sente_str == "*") && !Login.handicapped_game_name?(@game_name)
478 rival = $league.get_player("game_waiting", @game_name, nil, @player) # no preference
479 elsif (@my_sente_str == "+")
480 rival = $league.get_player("game_waiting", @game_name, false, @player) # rival must be gote
481 elsif (@my_sente_str == "-")
482 rival = $league.get_player("game_waiting", @game_name, true, @player) # rival must be sente
484 @player.write_safe(sprintf("##[ERROR] bad game option\n"))
490 @player.game_name = @game_name
492 if ((@my_sente_str == "*") && (rival.sente == nil))
497 @player.sente = false
500 elsif (rival.sente == true) # rival has higher priority
501 @player.sente = false
502 elsif (rival.sente == false)
504 elsif (@my_sente_str == "+")
507 elsif (@my_sente_str == "-")
508 @player.sente = false
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
547 if (@my_sente_str == "+")
549 elsif (@my_sente_str == "-")
550 @player.sente = false
555 @player.write_safe(sprintf("##[ERROR] can't find rival for %s\n", @game_name))
556 @player.status = "connected"
557 @player.game_name = ""
567 class ChatCommand < Command
569 # players array of [name, player]
571 def initialize(str, player, message, players)
578 @players.each do |name, p| # TODO player change name
579 if (p.protocol != LoginCSA::PROTOCOL)
580 p.write_safe(sprintf("##[CHAT][%s] %s\n", @player.name, @message))
589 class ListCommand < Command
591 # games array of [game_id, game]
593 def initialize(str, player, games)
600 @games.each do |id, game|
601 buf.push(sprintf("##[LIST] %s\n", id))
603 buf.push("##[LIST] +OK\n")
604 @player.write_safe(buf.join)
611 class WhoCommand < Command
613 # players array of [[name, player]]
615 def initialize(str, player, players)
622 @players.each do |name, p|
623 buf.push(sprintf("##[WHO] %s\n", p.to_s))
625 buf.push("##[WHO] +OK\n")
626 @player.write_safe(buf.join)
633 class LogoutCommand < Command
634 def initialize(str, player)
639 @player.status = "connected"
640 @player.write_safe("LOGOUT:completed\n")
645 # Command of CHALLENGE
647 class ChallengeCommand < Command
648 def initialize(str, player)
653 # This command is only available for CSA's official testing server.
654 # So, this means nothing for this program.
655 @player.write_safe("CHALLENGE ACCEPTED\n")
660 # Command for a space
662 class SpaceCommand < Command
663 def initialize(str, player)
668 ## ignore null string
673 # Command for an error
675 class ErrorCommand < Command
676 def initialize(str, player)
681 msg = "##[ERROR] unknown command %s\n" % [@str]
682 @player.write_safe(msg)
690 class SetBuoyCommand < Command
692 def initialize(str, player, game_name, moves, count)
694 @game_name = game_name
700 unless (Buoy.game_name?(@game_name))
701 @player.write_safe(sprintf("##[ERROR] wrong buoy game name: %s\n", @game_name))
702 log_error "Received a wrong buoy game name: %s from %s." % [@game_name, @player.name]
706 unless buoy.is_new_game?(@game_name)
707 @player.write_safe(sprintf("##[ERROR] duplicated buoy game name: %s\n", @game_name))
708 log_error "Received duplicated buoy game name: %s from %s." % [@game_name, @player.name]
712 @player.write_safe(sprintf("##[ERROR] invalid count: %s\n", @count))
713 log_error "Received an invalid count for a buoy game: %s, %s from %s." % [@count, @game_name, @player.name]
718 moves_array = Board::split_moves(@moves)
721 board.set_from_moves(moves_array)
726 buoy_game = BuoyGame.new(@game_name, @moves, @player.name, @count)
727 buoy.add_game(buoy_game)
728 @player.write_safe(sprintf("##[SETBUOY] +OK\n"))
729 log_info("A buoy game was created: %s by %s" % [@game_name, @player.name])
731 # if two players, who are not @player, are waiting for a new game, start it
732 p1 = $league.get_player("game_waiting", @game_name, true, @player)
733 return :continue unless p1
734 p2 = $league.get_player("game_waiting", @game_name, false, @player)
735 return :continue unless p2
737 buoy.decrement_count(buoy_game)
738 game = Game::new(@game_name, p1, p2, board)
740 rescue WrongMoves => e
741 @player.write_safe(sprintf("##[ERROR] wrong moves: %s\n", @moves))
742 log_error "Received wrong moves: %s from %s. [%s]" % [@moves, @player.name, e.message]
749 class DeleteBuoyCommand < Command
750 def initialize(str, player, game_name)
752 @game_name = game_name
757 buoy_game = buoy.get_game(@game_name)
758 if buoy_game.instance_of?(NilBuoyGame)
759 @player.write_safe(sprintf("##[ERROR] buoy game not found: %s\n", @game_name))
760 log_error "Game name not found: %s by %s" % [@game_name, @player.name]
764 if buoy_game.owner != @player.name
765 @player.write_safe(sprintf("##[ERROR] you are not allowed to delete a buoy game that you did not set: %s\n", @game_name))
766 log_error "%s are not allowed to delete a game: %s" % [@player.name, @game_name]
770 buoy.delete_game(buoy_game)
771 @player.write_safe(sprintf("##[DELETEBUOY] +OK\n"))
772 log_info("A buoy game was deleted: %s" % [@game_name])
779 class GetBuoyCountCommand < Command
780 def initialize(str, player, game_name)
782 @game_name = game_name
787 buoy_game = buoy.get_game(@game_name)
788 if buoy_game.instance_of?(NilBuoyGame)
789 @player.write_safe("##[GETBUOYCOUNT] -1\n")
791 @player.write_safe("##[GETBUOYCOUNT] %s\n" % [buoy_game.count])
793 @player.write_safe("##[GETBUOYCOUNT] +OK\n")
797 end # module ShogiServer