OSDN Git Service

* Return [...] +OK after %%SETBUOY and %%DELETEBUOY commands
[shogi-server/shogi-server.git] / shogi_server / game.rb
index 154db72..6225c79 100644 (file)
 ## along with this program; if not, write to the Free Software
 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
+require 'shogi_server/league/floodgate'
+require 'observer'
+
 module ShogiServer # for a namespace
 
+# MonitorObserver obserers GameResult to send messages to the monotors
+# watching the game
+#
+class MonitorObserver
+  def update(game_result)
+    game_result.game.each_monitor do |monitor|
+      monitor.write_safe("##[MONITOR][%s] %s\n" % [game_result.game.game_id, game_result.result_type])
+    end
+  end
+end
+
+# Base class for a game result
+#
 class GameResult
-  attr_reader :players, :black, :white
+  include Observable
+
+  # Game object
+  attr_reader :game
+  # Array of players
+  attr_reader :players
+  # Black player object
+  attr_reader :black
+  # White plyer object
+  attr_reader :white
+  # Command to send monitors such as '%TORYO' etc...
+  attr_reader :result_type
 
   def initialize(game, p1, p2)
     @game = game
@@ -34,27 +61,41 @@ class GameResult
     end
     @players.each do |player|
       player.status = "connected"
-      LEAGUE.save(player)
     end
+    @result_type = ""
+
+    regist_observers
+  end
+
+  def regist_observers
+    add_observer MonitorObserver.new
+
+    if League::Floodgate.game_name?(@game.game_name) &&
+       @game.sente.player_id &&
+       @game.gote.player_id &&
+       $options["floodgate-history"]
+      add_observer League::Floodgate::History.factory
+    end
+
   end
 
   def process
     raise "Implement me!"
   end
 
+  def notify
+    changed
+    notify_observers(self)
+  end
+
   def log(str)
     @game.log_game(str)
   end
 
   def log_board
-    log(@game.board.to_s.gsub(/^/, "\'"))
+    log(@game.board.to_s.gsub(/^/, "\'").chomp)
   end
 
-  def notify_monitor(type)
-    @game.each_monitor do |monitor|
-      monitor.write_safe(sprintf("##[MONITOR][%s] %s\n", @game.game_id, type))
-    end
-  end
 end
 
 class GameResultWin < GameResult
@@ -78,9 +119,9 @@ class GameResultWin < GameResult
       black_result = "lose"
       white_result = "win"
     end
-    log("'summary:%s:%s %s:%s %s\n" % [type, 
-                                       @black.name, black_result,
-                                       @white.name, white_result])
+    log("'summary:%s:%s %s:%s %s" % [type, 
+                                     @black.name, black_result,
+                                     @white.name, white_result])
 
   end
 end
@@ -89,9 +130,10 @@ class GameResultAbnormalWin < GameResultWin
   def process
     @winner.write_safe("%TORYO\n#RESIGN\n#WIN\n")
     @loser.write_safe( "%TORYO\n#RESIGN\n#LOSE\n")
-    log("%%TORYO\n")
+    log("%TORYO")
     log_summary("abnormal")
-    notify_monitor("%%TORYO")
+    @result_type = "%TORYO"
+    notify
   end
 end
 
@@ -100,7 +142,8 @@ class GameResultTimeoutWin < GameResultWin
     @winner.write_safe("#TIME_UP\n#WIN\n")
     @loser.write_safe( "#TIME_UP\n#LOSE\n")
     log_summary("time up")
-    notify_monitor("#TIME_UP")
+    @result_type = "#TIME_UP"
+    notify
   end
 end
 
@@ -109,9 +152,10 @@ class GameResultKachiWin < GameResultWin
   def process
     @winner.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
     @loser.write_safe( "%KACHI\n#JISHOGI\n#LOSE\n")
-    log("%%KACHI\n")
+    log("%KACHI")
     log_summary("kachi")
-    notify_monitor("%%KACHI")
+    @result_type = "%KACHI"
+    notify
   end
 end
 
@@ -120,9 +164,10 @@ class GameResultIllegalKachiWin < GameResultWin
   def process
     @winner.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
     @loser.write_safe( "%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
-    log("%%KACHI\n")
+    log("%KACHI")
     log_summary("illegal kachi")
-    notify_monitor("%%KACHI")
+    @result_type = "%KACHI"
+    notify
   end
 end
 
@@ -136,7 +181,8 @@ class GameResultIllegalWin < GameResultWin
     @winner.write_safe("#ILLEGAL_MOVE\n#WIN\n")
     @loser.write_safe( "#ILLEGAL_MOVE\n#LOSE\n")
     log_summary(@cause)
-    notify_monitor("#ILLEGAL_MOVE")
+    @result_type = "#ILLEGAL_MOVE"
+    notify
   end
 end
 
@@ -152,7 +198,7 @@ class GameResultUchifuzumeWin < GameResultIllegalWin
   end
 end
 
-class GameResultOuteKaihiMoreWin < GameResultWin
+class GameResultOuteKaihiMoreWin < GameResultIllegalWin
   def initialize(game, winner, loser)
     super(game, winner, loser, "oute_kaihimore")
   end
@@ -160,17 +206,18 @@ end
 
 class GameResultOutoriWin < GameResultWin
   def initialize(game, winner, loser)
-    super(game, winner, loser, "outori")
+    super(game, winner, loser)
   end
 end
 
-class GameReulstToryoWin < GameResultWin
+class GameResultToryoWin < GameResultWin
   def process
     @winner.write_safe("%TORYO\n#RESIGN\n#WIN\n")
     @loser.write_safe( "%TORYO\n#RESIGN\n#LOSE\n")
-    log("%%TORYO\n")
+    log("%TORYO")
     log_summary("toryo")
-    notify_monitor("%%TORYO")
+    @result_type = "%TORYO"
+    notify
   end
 end
 
@@ -179,7 +226,8 @@ class GameResultOuteSennichiteWin < GameResultWin
     @winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
     @loser.write_safe( "#OUTE_SENNICHITE\n#LOSE\n")
     log_summary("oute_sennichite")
-    notify_monitor("#OUTE_SENNICHITE")
+    @result_type = "#OUTE_SENNICHITE"
+    notify
   end
 end
 
@@ -192,7 +240,7 @@ class GameResultDraw < GameResult
   
   def log_summary(type)
     log_board
-    log("'summary:%s:%s draw:%s draw\n", type, @black.name, @white.name)
+    log("'summary:%s:%s draw:%s draw" % [type, @black.name, @white.name])
   end
 end
 
@@ -202,15 +250,20 @@ class GameResultSennichiteDraw < GameResultDraw
       player.write_safe("#SENNICHITE\n#DRAW\n")
     end
     log_summary("sennichite")
-    notify_monitor("#SENNICHITE")
+    @result_type = "#SENNICHITE"
+    notify
   end
 end
 
 class Game
+  # When this duration passes after this object instanciated (i.e.
+  # the agree_waiting or start_waiting state lasts too long),
+  # the game will be rejected by the Server.
+  WAITING_EXPIRATION = 120 # seconds
+
   @@mutex = Mutex.new
   @@time  = 0
-
-  def initialize(game_name, player0, player1)
+  def initialize(game_name, player0, player1, board)
     @monitors = Array::new
     @game_name = game_name
     if (@game_name =~ /-(\d+)-(\d+)$/)
@@ -225,34 +278,39 @@ class Game
     end
     @sente.socket_buffer.clear
     @gote.socket_buffer.clear
-    @current_player, @next_player = @sente, @gote
+    @board = board
+    if @board.teban
+      @current_player, @next_player = @sente, @gote
+    else
+      @current_player, @next_player = @gote, @sente
+    end
     @sente.game = self
     @gote.game  = self
 
-    @last_move = ""
-    @current_turn = 0
+    @last_move = @board.initial_moves.empty? ? "" : "%s,T1" % [@board.initial_moves.last]
+    @current_turn = @board.initial_moves.size
 
     @sente.status = "agree_waiting"
     @gote.status  = "agree_waiting"
 
     @game_id = sprintf("%s+%s+%s+%s+%s", 
-                  LEAGUE.event, @game_name, 
+                  $league.event, @game_name, 
                   @sente.name, @gote.name, issue_current_time)
     
-    now = Time.now
-    log_dir_name = File.join(LEAGUE.dir, 
-                             now.strftime("%Y"),
-                             now.strftime("%m"),
-                             now.strftime("%d"))
+    # The time when this Game instance was created.
+    # Don't be confused with @start_time when the game was started to play.
+    @prepared_time = Time.now 
+    log_dir_name = File.join($league.dir, 
+                             @prepared_time.strftime("%Y"),
+                             @prepared_time.strftime("%m"),
+                             @prepared_time.strftime("%d"))
     FileUtils.mkdir_p(log_dir_name) unless File.exist?(log_dir_name)
     @logfile = File.join(log_dir_name, @game_id + ".csa")
 
-    LEAGUE.games[@game_id] = self
+    $league.games[@game_id] = self
 
     log_message(sprintf("game created %s", @game_id))
 
-    @board = Board::new
-    @board.initial
     @start_time = nil
     @fh = open(@logfile, "w")
     @fh.sync = true
@@ -262,7 +320,10 @@ class Game
   end
   attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors
   attr_accessor :last_move, :current_turn
-  attr_reader   :result
+  attr_reader   :result, :prepared_time
+
+  # Path of a log file for this game.
+  attr_reader   :logfile
 
   def rated?
     @sente.rated? && @gote.rated?
@@ -302,9 +363,14 @@ class Game
   end
 
   def kill(killer)
-    if ["agree_waiting", "start_waiting"].include?(@sente.status)
-      reject(killer.name)
-    elsif (@current_player == killer)
+    [@sente, @gote].each do |player|
+      if ["agree_waiting", "start_waiting"].include?(player.status)
+        reject(killer.name)
+        return # return from this method
+      end
+    end
+    
+    if (@current_player == killer)
       result = GameResultAbnormalWin.new(self, @next_player, @current_player)
       result.process
       finish
@@ -332,7 +398,7 @@ class Game
     @gote = nil
     @current_player = nil
     @next_player = nil
-    LEAGUE.games.delete(@game_id)
+    $league.games.delete(@game_id)
   end
 
   # class Game
@@ -364,6 +430,7 @@ class Game
       end
 
       move_status = @board.handle_one_move(str, @sente == @current_player)
+      # log_debug("move_status: %s for %s's %s" % [move_status, @sente == @current_player ? "BLACK" : "WHITE", str])
 
       if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
         @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
@@ -397,7 +464,7 @@ class Game
     elsif (move_status == :kachi_lose)
       result = GameResultIllegalKachiWin.new(self, @next_player, @current_player)
     elsif (move_status == :toryo)
-      result = GameReulstToryoWin.new(self, @next_player, @current_player)
+      result = GameResultToryoWin.new(self, @next_player, @current_player)
     elsif (move_status == :outori)
       # The current player captures the next player's king
       result = GameResultOutoriWin.new(self, @current_player, @next_player)
@@ -423,8 +490,16 @@ class Game
     return finish_flag
   end
 
+  def is_startable_status?
+    return (@sente && @gote &&
+            (@sente.status == "start_waiting") &&
+            (@gote.status  == "start_waiting"))
+  end
+
   def start
     log_message(sprintf("game started %s", @game_id))
+    @sente.status = "game"
+    @gote.status  = "game"
     @sente.write_safe(sprintf("START:%s\n", @game_id))
     @gote.write_safe(sprintf("START:%s\n", @game_id))
     @sente.mytime = @total_time
@@ -460,6 +535,13 @@ EOM
       white_name = @gote.rated?  ? @gote.player_id  : @gote.name
       @fh.puts("'rating:%s:%s" % [black_name, white_name])
     end
+    unless @board.initial_moves.empty?
+      @fh.puts "'buoy game starting with %d moves" % [@board.initial_moves.size]
+      @board.initial_moves.each do |move|
+        @fh.puts move
+        @fh.puts "T1"
+      end
+    end
   end
 
   def show()
@@ -507,7 +589,7 @@ Name+:#{@sente.name}
 Name-:#{@gote.name}
 Your_Turn:#{sg_flag}
 Rematch_On_Draw:NO
-To_Move:+
+To_Move:#{@board.teban ? "+" : "-"}
 BEGIN Time
 Time_Unit:1sec
 Total_Time:#{@total_time}
@@ -515,23 +597,20 @@ Byoyomi:#{@byoyomi}
 Least_Time_Per_Move:#{Least_Time_Per_Move}
 END Time
 BEGIN Position
-P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
-P2 * -HI *  *  *  *  * -KA * 
-P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
-P4 *  *  *  *  *  *  *  *  * 
-P5 *  *  *  *  *  *  *  *  * 
-P6 *  *  *  *  *  *  *  *  * 
-P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
-P8 * +KA *  *  *  *  * +HI * 
-P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
-P+
-P-
-+
+#{@board.to_s.chomp}
 END Position
 END Game_Summary
 EOM
     return str
   end
+
+  def prepared_expire?
+    if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
+      return true
+    end
+
+    return false
+  end
   
   private