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
20 require 'shogi_server/league/floodgate'
21 require 'shogi_server/game_result'
22 require 'shogi_server/util'
24 module ShogiServer # for a namespace
27 # When this duration passes after this object instanciated (i.e.
28 # the agree_waiting or start_waiting state lasts too long),
29 # the game will be rejected by the Server.
30 WAITING_EXPIRATION = 120 # seconds
35 # Decide an actual turn of each player according to their turn preferences.
36 # p2 is a rival player of the p1 player.
37 # p1_sente_string must be "*", "+" or "-".
38 # After this call, the sente value of each player is always true or false, not
41 def Game.decide_turns(p1, p1_sente_string, p2)
42 if ((p1_sente_string == "*") && (p2.sente == nil))
50 elsif (p2.sente == true) # rival has higher priority
52 elsif (p2.sente == false)
54 elsif (p1_sente_string == "+")
57 elsif (p1_sente_string == "-")
66 def initialize(game_name, player0, player1, board)
67 @monitors = Array::new # array of MonitorHandler*
68 @game_name = game_name
69 if (@game_name =~ /-(\d+)-(\d+)$/)
75 @sente, @gote = player0, player1
77 @sente, @gote = player1, player0
79 @sente.socket_buffer.clear
80 @gote.socket_buffer.clear
83 @current_player, @next_player = @sente, @gote
85 @current_player, @next_player = @gote, @sente
90 @last_move = @board.initial_moves.empty? ? "" : "%s,T1" % [@board.initial_moves.last]
91 @current_turn = @board.initial_moves.size
93 @sente.status = "agree_waiting"
94 @gote.status = "agree_waiting"
96 @game_id = sprintf("%s+%s+%s+%s+%s",
97 $league.event, @game_name,
98 @sente.name, @gote.name, issue_current_time)
100 # The time when this Game instance was created.
101 # Don't be confused with @start_time when the game was started to play.
102 @prepared_time = Time.now
103 log_dir_name = File.join($league.dir,
104 @prepared_time.strftime("%Y"),
105 @prepared_time.strftime("%m"),
106 @prepared_time.strftime("%d"))
107 @logfile = File.join(log_dir_name, @game_id + ".csa")
108 Mkdir.mkdir_for(@logfile)
110 $league.games[@game_id] = self
112 log_message(sprintf("game created %s", @game_id))
115 @fh = open(@logfile, "w")
121 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors
122 attr_accessor :last_move, :current_turn
123 attr_reader :result, :prepared_time
125 # Path of a log file for this game.
129 @sente.rated? && @gote.rated?
133 return player.status == "game" && @current_player == player
136 def monitoron(monitor_handler)
137 monitoroff(monitor_handler)
138 @monitors.push(monitor_handler)
141 def monitoroff(monitor_handler)
142 @monitors.delete_if {|mon| mon == monitor_handler}
146 @monitors.each do |monitor_handler|
147 yield monitor_handler
153 log_error("Failed to write to Game[%s]'s log file: %s" %
156 @fh.printf("%s\n", str)
160 @sente.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
161 @gote.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
166 [@sente, @gote].each do |player|
167 if ["agree_waiting", "start_waiting"].include?(player.status)
169 return # return from this method
173 if (@current_player == killer)
174 @result = GameResultAbnormalWin.new(self, @next_player, @current_player)
181 log_message(sprintf("game finished %s", @game_id))
183 # In a case where a player in agree_waiting or start_waiting status is
184 # rejected, a GameResult object is not yet instanciated.
185 # See test/TC_before_agree.rb.
186 end_time = @result ? @result.end_time : Time.now
187 @fh.printf("'$END_TIME:%s\n", end_time.strftime("%Y/%m/%d %H:%M:%S"))
192 @sente.status = "connected"
193 @gote.status = "connected"
195 if (@current_player.protocol == LoginCSA::PROTOCOL)
196 @current_player.finish
198 if (@next_player.protocol == LoginCSA::PROTOCOL)
201 @monitors = Array::new
204 @current_player = nil
206 $league.games.delete(@game_id)
210 def handle_one_move(str, player, end_time)
212 return false if str == :timeout
214 @fh.puts("'Deferred %s" % [str])
215 log_warning("Deferred a move [%s] scince it is not %s 's turn." %
217 player.socket_buffer << str # always in the player's thread
223 t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
226 if ((@current_player.mytime - t <= -@byoyomi) &&
227 ((@total_time > 0) || (@byoyomi > 0)))
229 elsif (str == :timeout)
230 return false # time isn't expired. players aren't swapped. continue game
232 @current_player.mytime -= t
233 if (@current_player.mytime < 0)
234 @current_player.mytime = 0
237 move_status = @board.handle_one_move(str, @sente == @current_player)
238 # log_debug("move_status: %s for %s's %s" % [move_status, @sente == @current_player ? "BLACK" : "WHITE", str])
240 if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
241 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
243 if :toryo != move_status
244 # Thinking time includes network traffic
245 @sente.write_safe(sprintf("%s,T%d\n", str, t))
246 @gote.write_safe(sprintf("%s,T%d\n", str, t))
247 @fh.printf("%s\nT%d\n", str, t)
248 @last_move = sprintf("%s,T%d", str, t)
251 @monitors.each do |monitor_handler|
252 monitor_handler.write_one_move(@game_id, self)
255 # if move_status is :toryo then a GameResult message will be sent to monitors
260 if (@next_player.status != "game") # rival is logout or disconnected
261 @result = GameResultAbnormalWin.new(self, @current_player, @next_player)
262 elsif (status == :timeout)
263 # current_player losed
264 @result = GameResultTimeoutWin.new(self, @next_player, @current_player)
265 elsif (move_status == :illegal)
266 @result = GameResultIllegalMoveWin.new(self, @next_player, @current_player)
267 elsif (move_status == :kachi_win)
268 @result = GameResultKachiWin.new(self, @current_player, @next_player)
269 elsif (move_status == :kachi_lose)
270 @result = GameResultIllegalKachiWin.new(self, @next_player, @current_player)
271 elsif (move_status == :toryo)
272 @result = GameResultToryoWin.new(self, @next_player, @current_player)
273 elsif (move_status == :outori)
274 # The current player captures the next player's king
275 @result = GameResultOutoriWin.new(self, @current_player, @next_player)
276 elsif (move_status == :oute_sennichite_sente_lose)
277 @result = GameResultOuteSennichiteWin.new(self, @gote, @sente) # Sente is checking
278 elsif (move_status == :oute_sennichite_gote_lose)
279 @result = GameResultOuteSennichiteWin.new(self, @sente, @gote) # Gote is checking
280 elsif (move_status == :sennichite)
281 @result = GameResultSennichiteDraw.new(self, @current_player, @next_player)
282 elsif (move_status == :uchifuzume)
283 # the current player losed
284 @result = GameResultUchifuzumeWin.new(self, @next_player, @current_player)
285 elsif (move_status == :oute_kaihimore)
286 # the current player losed
287 @result = GameResultOuteKaihiMoreWin.new(self, @next_player, @current_player)
291 @result.process if @result
292 finish() if finish_flag
293 @current_player, @next_player = @next_player, @current_player
294 @start_time = Time.now
298 def is_startable_status?
299 return (@sente && @gote &&
300 (@sente.status == "start_waiting") &&
301 (@gote.status == "start_waiting"))
305 log_message(sprintf("game started %s", @game_id))
306 @sente.status = "game"
307 @gote.status = "game"
308 @sente.write_safe(sprintf("START:%s\n", @game_id))
309 @gote.write_safe(sprintf("START:%s\n", @game_id))
310 @sente.mytime = @total_time
311 @gote.mytime = @total_time
312 @start_time = Time.now
317 @fh.puts("N+#{@sente.name}")
318 @fh.puts("N-#{@gote.name}")
319 @fh.puts("$EVENT:#{@game_id}")
321 @sente.write_safe(propose_message("+"))
322 @gote.write_safe(propose_message("-"))
324 now = Time.now.strftime("%Y/%m/%d %H:%M:%S")
325 @fh.puts("$START_TIME:#{now}")
326 @fh.print(@board.initial_string)
328 black_name = @sente.rated? ? @sente.player_id : @sente.name
329 white_name = @gote.rated? ? @gote.player_id : @gote.name
330 @fh.puts("'rating:%s:%s" % [black_name, white_name])
332 unless @board.initial_moves.empty?
333 @fh.puts "'buoy game starting with %d moves" % [@board.initial_moves.size]
334 @board.initial_moves.each do |move|
347 Declaration:Jishogi 1.1
355 Total_Time:#{@total_time}
357 Least_Time_Per_Move:#{Least_Time_Per_Move}
358 Remaining_Time+:#{@sente.mytime}
359 Remaining_Time-:#{@gote.mytime}
360 Last_Move:#{@last_move}
361 Current_Turn:#{@current_turn}
371 return str0 + @board.to_s + str1
374 def propose_message(sg_flag)
380 Declaration:Jishogi 1.1
386 To_Move:#{@board.teban ? "+" : "-"}
389 Total_Time:#{@total_time}
391 Least_Time_Per_Move:#{Least_Time_Per_Move}
394 #{@board.initial_string.chomp}
395 #{@board.initial_moves.collect {|m| m + ",T1"}.join("\n")}
399 # An empty @board.initial_moves causes an empty line, which should be
401 return str.gsub("\n\n", "\n")
405 if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
414 def issue_current_time
415 time = Time.now.strftime("%Y%m%d%H%M%S").to_i
416 @@mutex.synchronize do
417 while time <= @@time do