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
91 unless @board.initial_moves.empty?
92 last_move = @board.initial_moves.last
95 @last_move = last_move.join(",")
97 @last_move = "%s,T1" % [last_move]
100 @current_turn = @board.initial_moves.size
102 @sente.status = "agree_waiting"
103 @gote.status = "agree_waiting"
105 @game_id = sprintf("%s+%s+%s+%s+%s",
106 $league.event, @game_name,
107 @sente.name, @gote.name, issue_current_time)
109 # The time when this Game instance was created.
110 # Don't be confused with @start_time when the game was started to play.
111 @prepared_time = Time.now
112 log_dir_name = File.join($league.dir,
113 @prepared_time.strftime("%Y"),
114 @prepared_time.strftime("%m"),
115 @prepared_time.strftime("%d"))
116 @logfile = File.join(log_dir_name, @game_id + ".csa")
117 Mkdir.mkdir_for(@logfile)
119 $league.games[@game_id] = self
121 log_message(sprintf("game created %s", @game_id))
124 @fh = open(@logfile, "w")
130 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors
131 attr_accessor :last_move, :current_turn
132 attr_reader :result, :prepared_time
134 # Path of a log file for this game.
138 @sente.rated? && @gote.rated?
142 return player.status == "game" && @current_player == player
145 def monitoron(monitor_handler)
146 monitoroff(monitor_handler)
147 @monitors.push(monitor_handler)
150 def monitoroff(monitor_handler)
151 @monitors.delete_if {|mon| mon == monitor_handler}
155 @monitors.each do |monitor_handler|
156 yield monitor_handler
162 log_error("Failed to write to Game[%s]'s log file: %s" %
165 @fh.printf("%s\n", str)
169 @sente.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
170 @gote.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
175 [@sente, @gote].each do |player|
176 if ["agree_waiting", "start_waiting"].include?(player.status)
178 return # return from this method
182 if (@current_player == killer)
183 @result = GameResultAbnormalWin.new(self, @next_player, @current_player)
190 log_message(sprintf("game finished %s", @game_id))
192 # In a case where a player in agree_waiting or start_waiting status is
193 # rejected, a GameResult object is not yet instanciated.
194 # See test/TC_before_agree.rb.
195 end_time = @result ? @result.end_time : Time.now
196 @fh.printf("'$END_TIME:%s\n", end_time.strftime("%Y/%m/%d %H:%M:%S"))
201 @sente.status = "connected"
202 @gote.status = "connected"
204 if (@current_player.protocol == LoginCSA::PROTOCOL)
205 @current_player.finish
207 if (@next_player.protocol == LoginCSA::PROTOCOL)
210 @monitors = Array::new
213 @current_player = nil
215 $league.games.delete(@game_id)
219 def handle_one_move(str, player, end_time)
221 return false if str == :timeout
223 @fh.puts("'Deferred %s" % [str])
224 log_warning("Deferred a move [%s] scince it is not %s 's turn." %
226 player.socket_buffer << str # always in the player's thread
232 t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
235 if ((@current_player.mytime - t <= -@byoyomi) &&
236 ((@total_time > 0) || (@byoyomi > 0)))
238 elsif (str == :timeout)
239 return false # time isn't expired. players aren't swapped. continue game
241 @current_player.mytime -= t
242 if (@current_player.mytime < 0)
243 @current_player.mytime = 0
246 move_status = @board.handle_one_move(str, @sente == @current_player)
247 # log_debug("move_status: %s for %s's %s" % [move_status, @sente == @current_player ? "BLACK" : "WHITE", str])
249 if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
250 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
252 if :toryo != move_status
253 # Thinking time includes network traffic
254 @sente.write_safe(sprintf("%s,T%d\n", str, t))
255 @gote.write_safe(sprintf("%s,T%d\n", str, t))
256 @fh.printf("%s\nT%d\n", str, t)
257 @last_move = sprintf("%s,T%d", str, t)
260 @monitors.each do |monitor_handler|
261 monitor_handler.write_one_move(@game_id, self)
264 # if move_status is :toryo then a GameResult message will be sent to monitors
269 if (@next_player.status != "game") # rival is logout or disconnected
270 @result = GameResultAbnormalWin.new(self, @current_player, @next_player)
271 elsif (status == :timeout)
272 # current_player losed
273 @result = GameResultTimeoutWin.new(self, @next_player, @current_player)
274 elsif (move_status == :illegal)
275 @result = GameResultIllegalMoveWin.new(self, @next_player, @current_player)
276 elsif (move_status == :kachi_win)
277 @result = GameResultKachiWin.new(self, @current_player, @next_player)
278 elsif (move_status == :kachi_lose)
279 @result = GameResultIllegalKachiWin.new(self, @next_player, @current_player)
280 elsif (move_status == :toryo)
281 @result = GameResultToryoWin.new(self, @next_player, @current_player)
282 elsif (move_status == :outori)
283 # The current player captures the next player's king
284 @result = GameResultOutoriWin.new(self, @current_player, @next_player)
285 elsif (move_status == :oute_sennichite_sente_lose)
286 @result = GameResultOuteSennichiteWin.new(self, @gote, @sente) # Sente is checking
287 elsif (move_status == :oute_sennichite_gote_lose)
288 @result = GameResultOuteSennichiteWin.new(self, @sente, @gote) # Gote is checking
289 elsif (move_status == :sennichite)
290 @result = GameResultSennichiteDraw.new(self, @current_player, @next_player)
291 elsif (move_status == :uchifuzume)
292 # the current player losed
293 @result = GameResultUchifuzumeWin.new(self, @next_player, @current_player)
294 elsif (move_status == :oute_kaihimore)
295 # the current player losed
296 @result = GameResultOuteKaihiMoreWin.new(self, @next_player, @current_player)
300 @result.process if @result
301 finish() if finish_flag
302 @current_player, @next_player = @next_player, @current_player
303 @start_time = Time.now
307 def is_startable_status?
308 return (@sente && @gote &&
309 (@sente.status == "start_waiting") &&
310 (@gote.status == "start_waiting"))
314 log_message(sprintf("game started %s", @game_id))
315 @sente.status = "game"
316 @gote.status = "game"
317 @sente.write_safe(sprintf("START:%s\n", @game_id))
318 @gote.write_safe(sprintf("START:%s\n", @game_id))
319 @sente.mytime = @total_time
320 @gote.mytime = @total_time
321 @start_time = Time.now
326 @fh.puts("N+#{@sente.name}")
327 @fh.puts("N-#{@gote.name}")
328 @fh.puts("$EVENT:#{@game_id}")
330 @sente.write_safe(propose_message("+"))
331 @gote.write_safe(propose_message("-"))
333 now = Time.now.strftime("%Y/%m/%d %H:%M:%S")
334 @fh.puts("$START_TIME:#{now}")
335 @fh.print(@board.initial_string)
337 black_name = @sente.rated? ? @sente.player_id : @sente.name
338 white_name = @gote.rated? ? @gote.player_id : @gote.name
339 @fh.puts("'rating:%s:%s" % [black_name, white_name])
341 unless @board.initial_moves.empty?
342 @fh.puts "'buoy game starting with %d moves" % [@board.initial_moves.size]
343 @board.initial_moves.each do |move|
362 Declaration:Jishogi 1.1
370 Total_Time:#{@total_time}
372 Least_Time_Per_Move:#{Least_Time_Per_Move}
373 Remaining_Time+:#{@sente.mytime}
374 Remaining_Time-:#{@gote.mytime}
375 Last_Move:#{@last_move}
376 Current_Turn:#{@current_turn}
386 return str0 + @board.to_s + str1
389 def propose_message(sg_flag)
395 Declaration:Jishogi 1.1
401 To_Move:#{@board.teban ? "+" : "-"}
404 Total_Time:#{@total_time}
406 Least_Time_Per_Move:#{Least_Time_Per_Move}
409 #{@board.initial_string.chomp}
410 #{@board.initial_moves.collect do |m|
421 # An empty @board.initial_moves causes an empty line, which should be
423 return str.gsub("\n\n", "\n")
427 if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
434 # Read the .csa file and returns an array of moves and times.
435 # ex. [["+7776FU","T2"], ["-3334FU","T5"]]
439 IO.foreach(@logfile) do |line|
440 if /^[\+\-]\d{4}[A-Z]{2}/ =~ line
442 elsif /^T\d*/ =~ line
443 ret[-1] << line.chomp
451 def issue_current_time
452 time = Time.now.strftime("%Y%m%d%H%M%S").to_i
453 @@mutex.synchronize do
454 while time <= @@time do