OSDN Git Service

* [shogi-server] - shogi_server/league/floodgate.rb: Improved robustness against...
[shogi-server/shogi-server.git] / shogi_server / game.rb
1 ## $Id$
2
3 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
4 ## Copyright (C) 2007-2012 Daigo Moriwaki (daigo at debian dot org)
5 ##
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.
10 ##
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.
15 ##
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
19
20 require 'shogi_server/league/floodgate'
21 require 'shogi_server/game_result'
22 require 'shogi_server/time_clock'
23 require 'shogi_server/util'
24
25 module ShogiServer # for a namespace
26
27 class Game
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
32
33   @@mutex = Mutex.new
34   @@time  = 0
35
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
40   # nil.
41   #
42   def Game.decide_turns(p1, p1_sente_string, p2)
43     if ((p1_sente_string == "*") && (p2.sente == nil))
44       if (rand(2) == 0)
45         p1.sente = true
46         p2.sente = false
47       else
48         p1.sente = false
49         p2.sente = true
50       end
51     elsif (p2.sente == true) # rival has higher priority
52       p1.sente = false
53     elsif (p2.sente == false)
54       p1.sente = true
55     elsif (p1_sente_string == "+")
56       p1.sente = true
57       p2.sente = false
58     elsif (p1_sente_string == "-")
59       p1.sente = false
60       p2.sente = true
61     else
62       ## never reached
63     end
64   end
65
66
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+)$/)
71       @total_time = $1.to_i
72       @byoyomi = $2.to_i
73
74       @time_clock = TimeClock::factory(Least_Time_Per_Move, @game_name)
75     end
76
77     if (player0.sente)
78       @sente, @gote = player0, player1
79     else
80       @sente, @gote = player1, player0
81     end
82     @sente.socket_buffer.clear
83     @gote.socket_buffer.clear
84     @board = board
85     if @board.teban
86       @current_player, @next_player = @sente, @gote
87     else
88       @current_player, @next_player = @gote, @sente
89     end
90     @sente.game = self
91     @gote.game  = self
92
93     @last_move = ""
94     unless @board.initial_moves.empty?
95       last_move = @board.initial_moves.last
96       case last_move
97       when Array
98         @last_move = last_move.join(",")
99       when String
100         @last_move = "%s,T1" % [last_move]
101       end
102     end
103     @current_turn = @board.initial_moves.size
104
105     @sente.status = "agree_waiting"
106     @gote.status  = "agree_waiting"
107
108     @game_id = sprintf("%s+%s+%s+%s+%s", 
109                   $league.event, @game_name, 
110                   @sente.name, @gote.name, issue_current_time)
111     
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)
121
122     $league.games[@game_id] = self
123
124     log_message(sprintf("game created %s", @game_id))
125     log_message("    " + @time_clock.to_s)
126
127     @start_time = nil
128     @fh = open(@logfile, "w")
129     @fh.sync = true
130     @result = nil
131
132     propose
133   end
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
137
138   # Path of a log file for this game.
139   attr_reader   :logfile
140
141   def rated?
142     @sente.rated? && @gote.rated?
143   end
144
145   def turn?(player)
146     return player.status == "game" && @current_player == player
147   end
148
149   def monitoron(monitor_handler)
150     monitoroff(monitor_handler)
151     @monitors.push(monitor_handler)
152   end
153
154   def monitoroff(monitor_handler)
155     @monitors.delete_if {|mon| mon == monitor_handler}
156   end
157
158   def each_monitor
159     @monitors.each do |monitor_handler|
160       yield monitor_handler
161     end
162   end
163
164   def log_game(str)
165     if @fh.closed?
166       log_error("Failed to write to Game[%s]'s log file: %s" %
167                 [@game_id, str])
168     end
169     @fh.printf("%s\n", str)
170   end
171
172   def reject(rejector)
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))
175     finish
176   end
177
178   def kill(killer)
179     [@sente, @gote].each do |player|
180       if ["agree_waiting", "start_waiting"].include?(player.status)
181         reject(killer.name)
182         return # return from this method
183       end
184     end
185     
186     if (@current_player == killer)
187       @result = GameResultAbnormalWin.new(self, @next_player, @current_player)
188       @result.process
189       finish
190     end
191   end
192
193   def finish
194     log_message(sprintf("game finished %s", @game_id))
195
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"))    
201     @fh.close
202
203     @sente.game = nil
204     @gote.game = nil
205     @sente.status = "connected"
206     @gote.status = "connected"
207
208     if (@current_player.protocol == LoginCSA::PROTOCOL)
209       @current_player.finish
210     end
211     if (@next_player.protocol == LoginCSA::PROTOCOL)
212       @next_player.finish
213     end
214     @monitors = Array::new
215     @sente = nil
216     @gote = nil
217     @current_player = nil
218     @next_player = nil
219     $league.games.delete(@game_id)
220   end
221
222   # class Game
223   def handle_one_move(str, player, end_time)
224     unless turn?(player)
225       return false if str == :timeout
226
227       @fh.puts("'Deferred %s" % [str])
228       log_warning("Deferred a move [%s] scince it is not %s 's turn." %
229                   [str, player.name])
230       player.socket_buffer << str # always in the player's thread
231       return nil
232     end
233
234     @end_time = end_time
235     finish_flag = true
236     move_status = nil
237
238     if (@time_clock.timeout?(@current_player, @start_time, @end_time))
239       status = :timeout
240     elsif (str == :timeout)
241       return false            # time isn't expired. players aren't swapped. continue game
242     else
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])
246
247       if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
248         @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
249       else
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)
256           @current_turn += 1
257
258           @monitors.each do |monitor_handler|
259             monitor_handler.write_one_move(@game_id, self)
260           end
261         end # if
262         # if move_status is :toryo then a GameResult message will be sent to monitors   
263       end # if
264     end
265
266     @result = nil
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)
295     else
296       finish_flag = false
297     end
298     @result.process if @result
299     finish() if finish_flag
300     @current_player, @next_player = @next_player, @current_player
301     @start_time = Time.now
302     return finish_flag
303   end
304
305   def is_startable_status?
306     return (@sente && @gote &&
307             (@sente.status == "start_waiting") &&
308             (@gote.status  == "start_waiting"))
309   end
310
311   def start
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
320   end
321
322   def propose
323     @fh.puts("V2")
324     @fh.puts("N+#{@sente.name}")
325     @fh.puts("N-#{@gote.name}")
326     @fh.puts("$EVENT:#{@game_id}")
327
328     @sente.write_safe(propose_message("+"))
329     @gote.write_safe(propose_message("-"))
330
331     now = Time.now.strftime("%Y/%m/%d %H:%M:%S")
332     @fh.puts("$START_TIME:#{now}")
333     @fh.print(@board.initial_string)
334     if rated?
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])
338     end
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|
342         case move
343         when Array
344           @fh.puts move[0]
345           @fh.puts move[1]
346         when String
347           @fh.puts move
348           @fh.puts "T1"
349         end
350       end
351     end
352   end
353
354   def show()
355     str0 = <<EOM
356 BEGIN Game_Summary
357 Protocol_Version:1.1
358 Protocol_Mode:Server
359 Format:Shogi 1.0
360 Declaration:Jishogi 1.1
361 Game_ID:#{@game_id}
362 Name+:#{@sente.name}
363 Name-:#{@gote.name}
364 Rematch_On_Draw:NO
365 To_Move:+
366 BEGIN Time
367 Time_Unit:#{@time_clock.time_unit}
368 Total_Time:#{@total_time}
369 Byoyomi:#{@byoyomi}
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}
375 END Time
376 BEGIN Position
377 EOM
378
379     str1 = <<EOM
380 END Position
381 END Game_Summary
382 EOM
383
384     return str0 + @board.to_s + str1
385   end
386
387   def propose_message(sg_flag)
388     str = <<EOM
389 BEGIN Game_Summary
390 Protocol_Version:1.1
391 Protocol_Mode:Server
392 Format:Shogi 1.0
393 Declaration:Jishogi 1.1
394 Game_ID:#{@game_id}
395 Name+:#{@sente.name}
396 Name-:#{@gote.name}
397 Your_Turn:#{sg_flag}
398 Rematch_On_Draw:NO
399 To_Move:#{@board.teban ? "+" : "-"}
400 BEGIN Time
401 Time_Unit:#{@time_clock.time_unit}
402 Total_Time:#{@total_time}
403 Byoyomi:#{@byoyomi}
404 Least_Time_Per_Move:#{Least_Time_Per_Move}
405 END Time
406 BEGIN Position
407 #{@board.initial_string.chomp}
408 #{@board.initial_moves.collect do |m|
409   case m
410   when Array
411     m.join(",")
412   when String
413     m + ",T1"
414   end
415 end.join("\n")}
416 END Position
417 END Game_Summary
418 EOM
419     # An empty @board.initial_moves causes an empty line, which should be
420     # eliminated.
421     return str.gsub("\n\n", "\n")
422   end
423
424   def prepared_expire?
425     if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
426       return true
427     end
428
429     return false
430   end
431
432   # Read the .csa file and returns an array of moves and times.
433   # ex. [["+7776FU","T2"], ["-3334FU","T5"]]
434   #
435   def read_moves
436     ret = []
437     IO.foreach(@logfile) do |line|
438       if /^[\+\-]\d{4}[A-Z]{2}/ =~ line
439         ret << [line.chomp]
440       elsif /^T\d*/ =~ line
441         ret[-1] << line.chomp
442       end
443     end
444     return ret
445   end
446   
447   private
448   
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
453         time += 1
454       end
455       @@time = time
456     end
457   end
458 end
459
460 end # ShogiServer