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 == "-")
66 TimeControlParams = Struct.new(:total_time, :byoyomi, :fischer, :stop_watch, :error)
68 # Parse time related parts of a game name.
70 # Return an array of a total allotted time, byoyomi seconds and fischer
71 # seconds; if it fails to parse, return nil.
72 def Game.parse_time(game_name)
73 ret = TimeControlParams.new(0, 0, 0, false, false)
75 if (game_name =~ /-(\d+)-(\d+F?)$/)
76 ret[:total_time] = $1.to_i
79 ret[:stop_watch] = true
82 ret[:fischer] = tmp.chop.to_i
84 ret[:byoyomi] = tmp.to_i
94 def initialize(game_name, player0, player1, board)
95 @monitors = Array::new # array of MonitorHandler*
96 @game_name = game_name
97 time_map = Game.parse_time @game_name
98 @total_time = time_map[:total_time]
99 @byoyomi = time_map[:byoyomi]
100 @fischer = time_map[:fischer]
101 @time_clock = TimeClock::factory(board.least_time_per_move, @game_name)
104 @sente, @gote = player0, player1
106 @sente, @gote = player1, player0
108 @sente.socket_buffer.clear
109 @gote.socket_buffer.clear
112 @current_player, @next_player = @sente, @gote
114 @current_player, @next_player = @gote, @sente
120 unless @board.initial_moves.empty?
121 last_move = @board.initial_moves.last
124 @last_move = last_move.join(",")
126 @last_move = "%s,T1" % [last_move]
129 @current_turn = @board.initial_moves.size
131 @sente.status = "agree_waiting"
132 @gote.status = "agree_waiting"
134 @game_id = sprintf("%s+%s+%s+%s+%s",
135 $league.event, @game_name,
136 @sente.name, @gote.name, issue_current_time)
138 # The time when this Game instance was created.
139 # Don't be confused with @start_time when the game was started to play.
140 @prepared_time = Time.now
141 log_dir_name = File.join($league.dir,
142 @prepared_time.strftime("%Y"),
143 @prepared_time.strftime("%m"),
144 @prepared_time.strftime("%d"))
145 @logfile = File.join(log_dir_name, @game_id + ".csa")
146 Mkdir.mkdir_for(@logfile)
148 $league.games[@game_id] = self
150 log_message(sprintf("game created %s", @game_id))
151 log_message(" " + @time_clock.to_s)
154 @fh = open(@logfile, "w")
160 attr_accessor :game_name, :total_time, :byoyomi, :fischer, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors, :time_clock
161 attr_accessor :last_move, :current_turn
162 attr_reader :result, :prepared_time
164 # Path of a log file for this game.
168 @sente.rated? && @gote.rated?
172 return player.status == "game" && @current_player == player
175 def monitoron(monitor_handler)
176 monitoroff(monitor_handler)
177 @monitors.push(monitor_handler)
180 def monitoroff(monitor_handler)
181 @monitors.delete_if {|mon| mon == monitor_handler}
185 @monitors.each do |monitor_handler|
186 yield monitor_handler
192 log_error("Failed to write to Game[%s]'s log file: %s" %
195 @fh.printf("%s\n", str)
199 @sente.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
200 @gote.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
205 [@sente, @gote].each do |player|
206 if ["agree_waiting", "start_waiting"].include?(player.status)
208 return # return from this method
212 if (@current_player == killer)
213 @result = GameResultAbnormalWin.new(self, @next_player, @current_player)
220 log_message(sprintf("game finished %s", @game_id))
222 # In a case where a player in agree_waiting or start_waiting status is
223 # rejected, a GameResult object is not yet instanciated.
224 # See test/TC_before_agree.rb.
225 end_time = @result ? @result.end_time : Time.now
226 @fh.printf("'$END_TIME:%s\n", end_time.strftime("%Y/%m/%d %H:%M:%S"))
231 @sente.status = "connected"
232 @gote.status = "connected"
234 if (@current_player.protocol == LoginCSA::PROTOCOL)
235 @current_player.finish
237 if (@next_player.protocol == LoginCSA::PROTOCOL)
240 @monitors = Array::new
243 @current_player = nil
245 $league.games.delete(@game_id)
249 def handle_one_move(str, player, end_time)
251 return false if str == :timeout
253 @fh.puts("'Deferred %s" % [str])
254 log_warning("Deferred a move [%s] scince it is not %s 's turn." %
256 player.socket_buffer << str # always in the player's thread
264 if (@time_clock.timeout?(@current_player, @start_time, @end_time))
266 elsif (str == :timeout)
267 return false # time isn't expired. players aren't swapped. continue game
269 t = @time_clock.process_time(@current_player, @start_time, @end_time)
270 move_status = @board.handle_one_move(str, @sente == @current_player)
271 # log_debug("move_status: %s for %s's %s" % [move_status, @sente == @current_player ? "BLACK" : "WHITE", str])
273 if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
274 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
276 if :toryo != move_status
277 # Thinking time includes network traffic
278 @sente.write_safe(sprintf("%s,T%d\n", str, t))
279 @gote.write_safe(sprintf("%s,T%d\n", str, t))
280 @fh.printf("%s\nT%d\n", str, t)
281 @last_move = sprintf("%s,T%d", str, t)
284 @monitors.each do |monitor_handler|
285 monitor_handler.write_one_move(@game_id, self)
288 # if move_status is :toryo then a GameResult message will be sent to monitors
293 if (@next_player.status != "game") # rival is logout or disconnected
294 @result = GameResultAbnormalWin.new(self, @current_player, @next_player)
295 elsif (status == :timeout)
296 # current_player losed
297 @result = GameResultTimeoutWin.new(self, @next_player, @current_player)
298 elsif (move_status == :illegal)
299 @result = GameResultIllegalMoveWin.new(self, @next_player, @current_player)
300 elsif (move_status == :kachi_win)
301 @result = GameResultKachiWin.new(self, @current_player, @next_player)
302 elsif (move_status == :kachi_lose)
303 @result = GameResultIllegalKachiWin.new(self, @next_player, @current_player)
304 elsif (move_status == :toryo)
305 @result = GameResultToryoWin.new(self, @next_player, @current_player)
306 elsif (move_status == :outori)
307 # The current player captures the next player's king
308 @result = GameResultOutoriWin.new(self, @current_player, @next_player)
309 elsif (move_status == :oute_sennichite_sente_lose)
310 @result = GameResultOuteSennichiteWin.new(self, @gote, @sente) # Sente is checking
311 elsif (move_status == :oute_sennichite_gote_lose)
312 @result = GameResultOuteSennichiteWin.new(self, @sente, @gote) # Gote is checking
313 elsif (move_status == :sennichite)
314 @result = GameResultSennichiteDraw.new(self, @current_player, @next_player)
315 elsif (move_status == :uchifuzume)
316 # the current player losed
317 @result = GameResultUchifuzumeWin.new(self, @next_player, @current_player)
318 elsif (move_status == :oute_kaihimore)
319 # the current player losed
320 @result = GameResultOuteKaihiMoreWin.new(self, @next_player, @current_player)
321 elsif (move_status == :max_moves)
322 @result = GameResultMaxMovesDraw.new(self, @current_player, @next_player)
326 @result.process if @result
327 finish() if finish_flag
328 @current_player, @next_player = @next_player, @current_player
329 @start_time = Time.now
333 def is_startable_status?
334 return (@sente && @gote &&
335 (@sente.status == "start_waiting") &&
336 (@gote.status == "start_waiting"))
340 log_message(sprintf("game started %s", @game_id))
341 @sente.status = "game"
342 @gote.status = "game"
343 @sente.write_safe(sprintf("START:%s\n", @game_id))
344 @gote.write_safe(sprintf("START:%s\n", @game_id))
345 @sente.mytime = @total_time
346 @gote.mytime = @total_time
347 @start_time = Time.now
352 @fh.puts("N+#{@sente.name}")
353 @fh.puts("N-#{@gote.name}")
354 @fh.puts("'Max_Moves:#{@board.max_moves}")
355 @fh.puts("'Least_Time_Per_Move:#{@board.least_time_per_move}")
357 @fh.puts("'Increment:#{@fischer}")
359 @fh.puts("$EVENT:#{@game_id}")
361 @sente.write_safe(propose_message("+"))
362 @gote.write_safe(propose_message("-"))
364 now = Time.now.strftime("%Y/%m/%d %H:%M:%S")
365 @fh.puts("$START_TIME:#{now}")
366 @fh.print(@board.initial_string)
368 black_name = @sente.rated? ? @sente.player_id : @sente.name
369 white_name = @gote.rated? ? @gote.player_id : @gote.name
370 @fh.puts("'rating:%s:%s" % [black_name, white_name])
371 if @sente.rated? && @sente.rate != 0
372 @fh.puts("'black_rate:%s:%s" % [@sente.player_id, @sente.rate])
374 if @gote.rated? && @gote.rate != 0
375 @fh.puts("'white_rate:%s:%s" % [@gote.player_id, @gote.rate])
378 unless @board.initial_moves.empty?
379 @fh.puts "'buoy game starting with %d moves" % [@board.initial_moves.size]
380 @board.initial_moves.each do |move|
399 Declaration:Jishogi 1.1
405 Max_Moves:#{@board.max_moves}
407 Time_Unit:#{@time_clock.time_unit}
408 Total_Time:#{@total_time}
410 Increment:#{@fischer}
411 Least_Time_Per_Move:#{@board.least_time_per_move}
412 Remaining_Time+:#{@sente.mytime}
413 Remaining_Time-:#{@gote.mytime}
414 Last_Move:#{@last_move}
415 Current_Turn:#{@current_turn}
425 return str0 + @board.to_s + str1
428 def propose_message(sg_flag)
434 Declaration:Jishogi 1.1
440 To_Move:#{@board.teban ? "+" : "-"}
441 Max_Moves:#{@board.max_moves}
443 Time_Unit:#{@time_clock.time_unit}
444 Total_Time:#{@total_time}
446 Increment:#{@fischer}
447 Least_Time_Per_Move:#{@board.least_time_per_move}
450 #{@board.initial_string.chomp}
451 #{@board.initial_moves.collect do |m|
462 # An empty @board.initial_moves causes an empty line, which should be
464 return str.gsub("\n\n", "\n")
468 if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
475 # Read the .csa file and returns an array of moves and times.
476 # ex. [["+7776FU","T2"], ["-3334FU","T5"]]
480 IO.foreach(@logfile) do |line|
481 if /^[\+\-]\d{4}[A-Z]{2}/ =~ line
483 elsif /^T\d*/ =~ line
484 ret[-1] << line.chomp
492 def issue_current_time
493 time = Time.now.strftime("%Y%m%d%H%M%S").to_i
494 @@mutex.synchronize do
495 while time <= @@time do