3 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
4 ## Copyright (C) 2007-2012 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/time_clock'
23 require 'shogi_server/util'
25 module ShogiServer # for a namespace
28 # When this duration passes after this object instanciated (i.e.
29 # the agree_waiting or start_waiting state lasts too long),
30 # the game will be rejected by the Server.
31 WAITING_EXPIRATION = 120 # seconds
36 # Decide an actual turn of each player according to their turn preferences.
37 # p2 is a rival player of the p1 player.
38 # p1_sente_string must be "*", "+" or "-".
39 # After this call, the sente value of each player is always true or false, not
42 def Game.decide_turns(p1, p1_sente_string, p2)
43 if ((p1_sente_string == "*") && (p2.sente == nil))
51 elsif (p2.sente == true) # rival has higher priority
53 elsif (p2.sente == false)
55 elsif (p1_sente_string == "+")
58 elsif (p1_sente_string == "-")
67 def initialize(game_name, player0, player1, board)
68 @monitors = Array::new # array of MonitorHandler*
69 @game_name = game_name
70 if (@game_name =~ /-(\d+)-(\d+)$/)
74 @time_clock = TimeClock::factory(Least_Time_Per_Move, @game_name)
78 @sente, @gote = player0, player1
80 @sente, @gote = player1, player0
82 @sente.socket_buffer.clear
83 @gote.socket_buffer.clear
86 @current_player, @next_player = @sente, @gote
88 @current_player, @next_player = @gote, @sente
94 unless @board.initial_moves.empty?
95 last_move = @board.initial_moves.last
98 @last_move = last_move.join(",")
100 @last_move = "%s,T1" % [last_move]
103 @current_turn = @board.initial_moves.size
105 @sente.status = "agree_waiting"
106 @gote.status = "agree_waiting"
108 @game_id = sprintf("%s+%s+%s+%s+%s",
109 $league.event, @game_name,
110 @sente.name, @gote.name, issue_current_time)
112 # The time when this Game instance was created.
113 # Don't be confused with @start_time when the game was started to play.
114 @prepared_time = Time.now
115 log_dir_name = File.join($league.dir,
116 @prepared_time.strftime("%Y"),
117 @prepared_time.strftime("%m"),
118 @prepared_time.strftime("%d"))
119 @logfile = File.join(log_dir_name, @game_id + ".csa")
120 Mkdir.mkdir_for(@logfile)
122 $league.games[@game_id] = self
124 log_message(sprintf("game created %s", @game_id))
125 log_message(" " + @time_clock.to_s)
128 @fh = open(@logfile, "w")
134 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors, :time_clock
135 attr_accessor :last_move, :current_turn
136 attr_reader :result, :prepared_time
138 # Path of a log file for this game.
142 @sente.rated? && @gote.rated?
146 return player.status == "game" && @current_player == player
149 def monitoron(monitor_handler)
150 monitoroff(monitor_handler)
151 @monitors.push(monitor_handler)
154 def monitoroff(monitor_handler)
155 @monitors.delete_if {|mon| mon == monitor_handler}
159 @monitors.each do |monitor_handler|
160 yield monitor_handler
166 log_error("Failed to write to Game[%s]'s log file: %s" %
169 @fh.printf("%s\n", str)
173 @sente.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
174 @gote.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
179 [@sente, @gote].each do |player|
180 if ["agree_waiting", "start_waiting"].include?(player.status)
182 return # return from this method
186 if (@current_player == killer)
187 @result = GameResultAbnormalWin.new(self, @next_player, @current_player)
194 log_message(sprintf("game finished %s", @game_id))
196 # In a case where a player in agree_waiting or start_waiting status is
197 # rejected, a GameResult object is not yet instanciated.
198 # See test/TC_before_agree.rb.
199 end_time = @result ? @result.end_time : Time.now
200 @fh.printf("'$END_TIME:%s\n", end_time.strftime("%Y/%m/%d %H:%M:%S"))
205 @sente.status = "connected"
206 @gote.status = "connected"
208 if (@current_player.protocol == LoginCSA::PROTOCOL)
209 @current_player.finish
211 if (@next_player.protocol == LoginCSA::PROTOCOL)
214 @monitors = Array::new
217 @current_player = nil
219 $league.games.delete(@game_id)
223 def handle_one_move(str, player, end_time)
225 return false if str == :timeout
227 @fh.puts("'Deferred %s" % [str])
228 log_warning("Deferred a move [%s] scince it is not %s 's turn." %
230 player.socket_buffer << str # always in the player's thread
238 if (@time_clock.timeout?(@current_player, @start_time, @end_time))
240 elsif (str == :timeout)
241 return false # time isn't expired. players aren't swapped. continue game
243 t = @time_clock.process_time(@current_player, @start_time, @end_time)
244 move_status = @board.handle_one_move(str, @sente == @current_player)
245 # log_debug("move_status: %s for %s's %s" % [move_status, @sente == @current_player ? "BLACK" : "WHITE", str])
247 if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
248 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
250 if :toryo != move_status
251 # Thinking time includes network traffic
252 @sente.write_safe(sprintf("%s,T%d\n", str, t))
253 @gote.write_safe(sprintf("%s,T%d\n", str, t))
254 @fh.printf("%s\nT%d\n", str, t)
255 @last_move = sprintf("%s,T%d", str, t)
258 @monitors.each do |monitor_handler|
259 monitor_handler.write_one_move(@game_id, self)
262 # if move_status is :toryo then a GameResult message will be sent to monitors
267 if (@next_player.status != "game") # rival is logout or disconnected
268 @result = GameResultAbnormalWin.new(self, @current_player, @next_player)
269 elsif (status == :timeout)
270 # current_player losed
271 @result = GameResultTimeoutWin.new(self, @next_player, @current_player)
272 elsif (move_status == :illegal)
273 @result = GameResultIllegalMoveWin.new(self, @next_player, @current_player)
274 elsif (move_status == :kachi_win)
275 @result = GameResultKachiWin.new(self, @current_player, @next_player)
276 elsif (move_status == :kachi_lose)
277 @result = GameResultIllegalKachiWin.new(self, @next_player, @current_player)
278 elsif (move_status == :toryo)
279 @result = GameResultToryoWin.new(self, @next_player, @current_player)
280 elsif (move_status == :outori)
281 # The current player captures the next player's king
282 @result = GameResultOutoriWin.new(self, @current_player, @next_player)
283 elsif (move_status == :oute_sennichite_sente_lose)
284 @result = GameResultOuteSennichiteWin.new(self, @gote, @sente) # Sente is checking
285 elsif (move_status == :oute_sennichite_gote_lose)
286 @result = GameResultOuteSennichiteWin.new(self, @sente, @gote) # Gote is checking
287 elsif (move_status == :sennichite)
288 @result = GameResultSennichiteDraw.new(self, @current_player, @next_player)
289 elsif (move_status == :uchifuzume)
290 # the current player losed
291 @result = GameResultUchifuzumeWin.new(self, @next_player, @current_player)
292 elsif (move_status == :oute_kaihimore)
293 # the current player losed
294 @result = GameResultOuteKaihiMoreWin.new(self, @next_player, @current_player)
298 @result.process if @result
299 finish() if finish_flag
300 @current_player, @next_player = @next_player, @current_player
301 @start_time = Time.now
305 def is_startable_status?
306 return (@sente && @gote &&
307 (@sente.status == "start_waiting") &&
308 (@gote.status == "start_waiting"))
312 log_message(sprintf("game started %s", @game_id))
313 @sente.status = "game"
314 @gote.status = "game"
315 @sente.write_safe(sprintf("START:%s\n", @game_id))
316 @gote.write_safe(sprintf("START:%s\n", @game_id))
317 @sente.mytime = @total_time
318 @gote.mytime = @total_time
319 @start_time = Time.now
324 @fh.puts("N+#{@sente.name}")
325 @fh.puts("N-#{@gote.name}")
326 @fh.puts("$EVENT:#{@game_id}")
328 @sente.write_safe(propose_message("+"))
329 @gote.write_safe(propose_message("-"))
331 now = Time.now.strftime("%Y/%m/%d %H:%M:%S")
332 @fh.puts("$START_TIME:#{now}")
333 @fh.print(@board.initial_string)
335 black_name = @sente.rated? ? @sente.player_id : @sente.name
336 white_name = @gote.rated? ? @gote.player_id : @gote.name
337 @fh.puts("'rating:%s:%s" % [black_name, white_name])
339 unless @board.initial_moves.empty?
340 @fh.puts "'buoy game starting with %d moves" % [@board.initial_moves.size]
341 @board.initial_moves.each do |move|
360 Declaration:Jishogi 1.1
367 Time_Unit:#{@time_clock.time_unit}
368 Total_Time:#{@total_time}
370 Least_Time_Per_Move:#{Least_Time_Per_Move}
371 Remaining_Time+:#{@sente.mytime}
372 Remaining_Time-:#{@gote.mytime}
373 Last_Move:#{@last_move}
374 Current_Turn:#{@current_turn}
384 return str0 + @board.to_s + str1
387 def propose_message(sg_flag)
393 Declaration:Jishogi 1.1
399 To_Move:#{@board.teban ? "+" : "-"}
401 Time_Unit:#{@time_clock.time_unit}
402 Total_Time:#{@total_time}
404 Least_Time_Per_Move:#{Least_Time_Per_Move}
407 #{@board.initial_string.chomp}
408 #{@board.initial_moves.collect do |m|
419 # An empty @board.initial_moves causes an empty line, which should be
421 return str.gsub("\n\n", "\n")
425 if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
432 # Read the .csa file and returns an array of moves and times.
433 # ex. [["+7776FU","T2"], ["-3334FU","T5"]]
437 IO.foreach(@logfile) do |line|
438 if /^[\+\-]\d{4}[A-Z]{2}/ =~ line
440 elsif /^T\d*/ =~ line
441 ret[-1] << line.chomp
449 def issue_current_time
450 time = Time.now.strftime("%Y%m%d%H%M%S").to_i
451 @@mutex.synchronize do
452 while time <= @@time do