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'
23 module ShogiServer # for a namespace
25 # MonitorObserver obserers GameResult to send messages to the monotors
29 def update(game_result)
30 game_result.game.each_monitor do |monitor|
31 monitor.write_safe("##[MONITOR][%s] %s\n" % [game_result.game.game_id, game_result.result_type])
36 # Base class for a game result
49 # Command to send monitors such as '%TORYO' etc...
50 attr_reader :result_type
52 def initialize(game, p1, p2)
55 if p1.sente && !p2.sente
56 @black, @white = p1, p2
57 elsif !p1.sente && p2.sente
58 @black, @white = p2, p1
60 raise "Never reached!"
62 @players.each do |player|
63 player.status = "connected"
71 add_observer MonitorObserver.new
73 if League::Floodgate.game_name?(@game.game_name) &&
74 @game.sente.player_id &&
75 @game.gote.player_id &&
76 $options["floodgate-history"]
77 add_observer League::Floodgate::History.factory
88 notify_observers(self)
96 log(@game.board.to_s.gsub(/^/, "\'").chomp)
101 class GameResultWin < GameResult
102 attr_reader :winner, :loser
104 def initialize(game, winner, loser)
106 @winner, @loser = winner, loser
107 @winner.last_game_win = true
108 @loser.last_game_win = false
111 def log_summary(type)
114 black_result = white_result = ""
117 white_result = "lose"
119 black_result = "lose"
122 log("'summary:%s:%s %s:%s %s" % [type,
123 @black.name, black_result,
124 @white.name, white_result])
129 class GameResultAbnormalWin < GameResultWin
131 @winner.write_safe("%TORYO\n#RESIGN\n#WIN\n")
132 @loser.write_safe( "%TORYO\n#RESIGN\n#LOSE\n")
134 log_summary("abnormal")
135 @result_type = "%TORYO"
140 class GameResultTimeoutWin < GameResultWin
142 @winner.write_safe("#TIME_UP\n#WIN\n")
143 @loser.write_safe( "#TIME_UP\n#LOSE\n")
144 log_summary("time up")
145 @result_type = "#TIME_UP"
150 # A player declares (successful) Kachi
151 class GameResultKachiWin < GameResultWin
153 @winner.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
154 @loser.write_safe( "%KACHI\n#JISHOGI\n#LOSE\n")
157 @result_type = "%KACHI"
162 # A player declares wrong Kachi
163 class GameResultIllegalKachiWin < GameResultWin
165 @winner.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
166 @loser.write_safe( "%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
168 log_summary("illegal kachi")
169 @result_type = "%KACHI"
174 class GameResultIllegalWin < GameResultWin
175 def initialize(game, winner, loser, cause)
176 super(game, winner, loser)
181 @winner.write_safe("#ILLEGAL_MOVE\n#WIN\n")
182 @loser.write_safe( "#ILLEGAL_MOVE\n#LOSE\n")
184 @result_type = "#ILLEGAL_MOVE"
189 class GameResultIllegalMoveWin < GameResultIllegalWin
190 def initialize(game, winner, loser)
191 super(game, winner, loser, "illegal move")
195 class GameResultUchifuzumeWin < GameResultIllegalWin
196 def initialize(game, winner, loser)
197 super(game, winner, loser, "uchifuzume")
201 class GameResultOuteKaihiMoreWin < GameResultIllegalWin
202 def initialize(game, winner, loser)
203 super(game, winner, loser, "oute_kaihimore")
207 class GameResultOutoriWin < GameResultWin
208 def initialize(game, winner, loser)
209 super(game, winner, loser)
213 class GameResultToryoWin < GameResultWin
215 @winner.write_safe("%TORYO\n#RESIGN\n#WIN\n")
216 @loser.write_safe( "%TORYO\n#RESIGN\n#LOSE\n")
219 @result_type = "%TORYO"
224 class GameResultOuteSennichiteWin < GameResultWin
226 @winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
227 @loser.write_safe( "#OUTE_SENNICHITE\n#LOSE\n")
228 log_summary("oute_sennichite")
229 @result_type = "#OUTE_SENNICHITE"
234 class GameResultDraw < GameResult
235 def initialize(game, p1, p2)
237 p1.last_game_win = false
238 p2.last_game_win = false
241 def log_summary(type)
243 log("'summary:%s:%s draw:%s draw" % [type, @black.name, @white.name])
247 class GameResultSennichiteDraw < GameResultDraw
249 @players.each do |player|
250 player.write_safe("#SENNICHITE\n#DRAW\n")
252 log_summary("sennichite")
253 @result_type = "#SENNICHITE"
259 # When this duration passes after this object instanciated (i.e.
260 # the agree_waiting or start_waiting state lasts too long),
261 # the game will be rejected by the Server.
262 WAITING_EXPIRATION = 120 # seconds
266 def initialize(game_name, player0, player1, board)
267 @monitors = Array::new
268 @game_name = game_name
269 if (@game_name =~ /-(\d+)-(\d+)$/)
270 @total_time = $1.to_i
275 @sente, @gote = player0, player1
277 @sente, @gote = player1, player0
279 @sente.socket_buffer.clear
280 @gote.socket_buffer.clear
283 @current_player, @next_player = @sente, @gote
285 @current_player, @next_player = @gote, @sente
290 @last_move = @board.initial_moves.empty? ? "" : "%s,T1" % [@board.initial_moves.last]
291 @current_turn = @board.initial_moves.size
293 @sente.status = "agree_waiting"
294 @gote.status = "agree_waiting"
296 @game_id = sprintf("%s+%s+%s+%s+%s",
297 $league.event, @game_name,
298 @sente.name, @gote.name, issue_current_time)
300 # The time when this Game instance was created.
301 # Don't be confused with @start_time when the game was started to play.
302 @prepared_time = Time.now
303 log_dir_name = File.join($league.dir,
304 @prepared_time.strftime("%Y"),
305 @prepared_time.strftime("%m"),
306 @prepared_time.strftime("%d"))
307 FileUtils.mkdir_p(log_dir_name) unless File.exist?(log_dir_name)
308 @logfile = File.join(log_dir_name, @game_id + ".csa")
310 $league.games[@game_id] = self
312 log_message(sprintf("game created %s", @game_id))
315 @fh = open(@logfile, "w")
321 attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors
322 attr_accessor :last_move, :current_turn
323 attr_reader :result, :prepared_time
325 # Path of a log file for this game.
329 @sente.rated? && @gote.rated?
333 return player.status == "game" && @current_player == player
336 def monitoron(monitor)
337 @monitors.delete(monitor)
338 @monitors.push(monitor)
341 def monitoroff(monitor)
342 @monitors.delete(monitor)
346 @monitors.each do |monitor|
353 log_error("Failed to write to Game[%s]'s log file: %s" %
356 @fh.printf("%s\n", str)
360 @sente.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
361 @gote.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
366 [@sente, @gote].each do |player|
367 if ["agree_waiting", "start_waiting"].include?(player.status)
369 return # return from this method
373 if (@current_player == killer)
374 result = GameResultAbnormalWin.new(self, @next_player, @current_player)
381 log_message(sprintf("game finished %s", @game_id))
382 @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
387 @sente.status = "connected"
388 @gote.status = "connected"
390 if (@current_player.protocol == LoginCSA::PROTOCOL)
391 @current_player.finish
393 if (@next_player.protocol == LoginCSA::PROTOCOL)
396 @monitors = Array::new
399 @current_player = nil
401 $league.games.delete(@game_id)
405 def handle_one_move(str, player)
407 return false if str == :timeout
409 @fh.puts("'Deferred %s" % [str])
410 log_warning("Deferred a move [%s] scince it is not %s 's turn." %
412 player.socket_buffer << str # always in the player's thread
417 @end_time = Time::new
418 t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
421 if ((@current_player.mytime - t <= -@byoyomi) &&
422 ((@total_time > 0) || (@byoyomi > 0)))
424 elsif (str == :timeout)
425 return false # time isn't expired. players aren't swapped. continue game
427 @current_player.mytime -= t
428 if (@current_player.mytime < 0)
429 @current_player.mytime = 0
432 move_status = @board.handle_one_move(str, @sente == @current_player)
433 # log_debug("move_status: %s for %s's %s" % [move_status, @sente == @current_player ? "BLACK" : "WHITE", str])
435 if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
436 @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
438 if [:normal, :outori, :sennichite, :oute_sennichite_sente_lose, :oute_sennichite_gote_lose].include?(move_status)
439 # Thinking time includes network traffic
440 @sente.write_safe(sprintf("%s,T%d\n", str, t))
441 @gote.write_safe(sprintf("%s,T%d\n", str, t))
442 @fh.printf("%s\nT%d\n", str, t)
443 @last_move = sprintf("%s,T%d", str, t)
447 @monitors.each do |monitor|
448 monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@game_id}] "))
449 monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @game_id))
455 if (@next_player.status != "game") # rival is logout or disconnected
456 result = GameResultAbnormalWin.new(self, @current_player, @next_player)
457 elsif (status == :timeout)
458 # current_player losed
459 result = GameResultTimeoutWin.new(self, @next_player, @current_player)
460 elsif (move_status == :illegal)
461 result = GameResultIllegalMoveWin.new(self, @next_player, @current_player)
462 elsif (move_status == :kachi_win)
463 result = GameResultKachiWin.new(self, @current_player, @next_player)
464 elsif (move_status == :kachi_lose)
465 result = GameResultIllegalKachiWin.new(self, @next_player, @current_player)
466 elsif (move_status == :toryo)
467 result = GameResultToryoWin.new(self, @next_player, @current_player)
468 elsif (move_status == :outori)
469 # The current player captures the next player's king
470 result = GameResultOutoriWin.new(self, @current_player, @next_player)
471 elsif (move_status == :oute_sennichite_sente_lose)
472 result = GameResultOuteSennichiteWin.new(self, @gote, @sente) # Sente is checking
473 elsif (move_status == :oute_sennichite_gote_lose)
474 result = GameResultOuteSennichiteWin.new(self, @sente, @gote) # Gote is checking
475 elsif (move_status == :sennichite)
476 result = GameResultSennichiteDraw.new(self, @current_player, @next_player)
477 elsif (move_status == :uchifuzume)
478 # the current player losed
479 result = GameResultUchifuzumeWin.new(self, @next_player, @current_player)
480 elsif (move_status == :oute_kaihimore)
481 # the current player losed
482 result = GameResultOuteKaihiMoreWin.new(self, @next_player, @current_player)
486 result.process if result
487 finish() if finish_flag
488 @current_player, @next_player = @next_player, @current_player
489 @start_time = Time::new
493 def is_startable_status?
494 return (@sente && @gote &&
495 (@sente.status == "start_waiting") &&
496 (@gote.status == "start_waiting"))
500 log_message(sprintf("game started %s", @game_id))
501 @sente.status = "game"
502 @gote.status = "game"
503 @sente.write_safe(sprintf("START:%s\n", @game_id))
504 @gote.write_safe(sprintf("START:%s\n", @game_id))
505 @sente.mytime = @total_time
506 @gote.mytime = @total_time
507 @start_time = Time::new
512 @fh.puts("N+#{@sente.name}")
513 @fh.puts("N-#{@gote.name}")
514 @fh.puts("$EVENT:#{@game_id}")
516 @sente.write_safe(propose_message("+"))
517 @gote.write_safe(propose_message("-"))
519 now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
520 @fh.puts("$START_TIME:#{now}")
522 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
523 P2 * -HI * * * * * -KA *
524 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
528 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
529 P8 * +KA * * * * * +HI *
530 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
534 black_name = @sente.rated? ? @sente.player_id : @sente.name
535 white_name = @gote.rated? ? @gote.player_id : @gote.name
536 @fh.puts("'rating:%s:%s" % [black_name, white_name])
538 unless @board.initial_moves.empty?
539 @fh.puts "'buoy game starting with %d moves" % [@board.initial_moves.size]
540 @board.initial_moves.each do |move|
553 Declaration:Jishogi 1.1
561 Total_Time:#{@total_time}
563 Least_Time_Per_Move:#{Least_Time_Per_Move}
564 Remaining_Time+:#{@sente.mytime}
565 Remaining_Time-:#{@gote.mytime}
566 Last_Move:#{@last_move}
567 Current_Turn:#{@current_turn}
577 return str0 + @board.to_s + str1
580 def propose_message(sg_flag)
586 Declaration:Jishogi 1.1
592 To_Move:#{@board.teban ? "+" : "-"}
595 Total_Time:#{@total_time}
597 Least_Time_Per_Move:#{Least_Time_Per_Move}
608 if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
617 def issue_current_time
618 time = Time::new.strftime("%Y%m%d%H%M%S").to_i
619 @@mutex.synchronize do
620 while time <= @@time do