OSDN Git Service

Merge remote-tracking branch 'origin/master' into wdoor-stable
[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   TimeControlParams = Struct.new(:total_time, :byoyomi, :fischer, :stop_watch, :error)
67
68   # Parse time related parts of a game name.
69   #
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)
74
75     if (game_name =~ /-(\d+)-(\d+F?)$/)
76       ret[:total_time] = $1.to_i
77       tmp = $2
78       if tmp =~ /^0\d/
79         ret[:stop_watch] = true
80       end
81       if tmp[-1] == "F"
82         ret[:fischer] = tmp.chop.to_i
83       else
84         ret[:byoyomi] = tmp.to_i
85       end
86       return ret
87     end
88
89     ret[:error] = true
90     return ret
91   end
92
93
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)
102
103     if (player0.sente)
104       @sente, @gote = player0, player1
105     else
106       @sente, @gote = player1, player0
107     end
108     @sente.socket_buffer.clear
109     @gote.socket_buffer.clear
110     @board = board
111     if @board.teban
112       @current_player, @next_player = @sente, @gote
113     else
114       @current_player, @next_player = @gote, @sente
115     end
116     @sente.game = self
117     @gote.game  = self
118
119     @last_move = ""
120     unless @board.initial_moves.empty?
121       last_move = @board.initial_moves.last
122       case last_move
123       when Array
124         @last_move = last_move.join(",")
125       when String
126         @last_move = "%s,T1" % [last_move]
127       end
128     end
129     @current_turn = @board.initial_moves.size
130
131     @sente.status = "agree_waiting"
132     @gote.status  = "agree_waiting"
133
134     @game_id = sprintf("%s+%s+%s+%s+%s", 
135                   $league.event, @game_name, 
136                   @sente.name, @gote.name, issue_current_time)
137     
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)
147
148     $league.games[@game_id] = self
149
150     log_message(sprintf("game created %s", @game_id))
151     log_message("    " + @time_clock.to_s)
152
153     @start_time = nil
154     @fh = open(@logfile, "w")
155     @fh.sync = true
156     @result = nil
157
158     propose
159   end
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
163
164   # Path of a log file for this game.
165   attr_reader   :logfile
166
167   def rated?
168     @sente.rated? && @gote.rated?
169   end
170
171   def turn?(player)
172     return player.status == "game" && @current_player == player
173   end
174
175   def monitoron(monitor_handler)
176     monitoroff(monitor_handler)
177     @monitors.push(monitor_handler)
178   end
179
180   def monitoroff(monitor_handler)
181     @monitors.delete_if {|mon| mon == monitor_handler}
182   end
183
184   def each_monitor
185     @monitors.each do |monitor_handler|
186       yield monitor_handler
187     end
188   end
189
190   def log_game(str)
191     if @fh.closed?
192       log_error("Failed to write to Game[%s]'s log file: %s" %
193                 [@game_id, str])
194     end
195     @fh.printf("%s\n", str)
196   end
197
198   def reject(rejector)
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))
201     finish
202   end
203
204   def kill(killer)
205     [@sente, @gote].each do |player|
206       if ["agree_waiting", "start_waiting"].include?(player.status)
207         reject(killer.name)
208         return # return from this method
209       end
210     end
211     
212     if (@current_player == killer)
213       @result = GameResultAbnormalWin.new(self, @next_player, @current_player)
214       @result.process
215       finish
216     end
217   end
218
219   def finish
220     log_message(sprintf("game finished %s", @game_id))
221
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"))    
227     @fh.close
228
229     @sente.game = nil
230     @gote.game = nil
231     @sente.status = "connected"
232     @gote.status = "connected"
233
234     if (@current_player.protocol == LoginCSA::PROTOCOL)
235       @current_player.finish
236     end
237     if (@next_player.protocol == LoginCSA::PROTOCOL)
238       @next_player.finish
239     end
240     @monitors = Array::new
241     @sente = nil
242     @gote = nil
243     @current_player = nil
244     @next_player = nil
245     $league.games.delete(@game_id)
246   end
247
248   # class Game
249   def handle_one_move(str, player, end_time)
250     unless turn?(player)
251       return false if str == :timeout
252
253       @fh.puts("'Deferred %s" % [str])
254       log_warning("Deferred a move [%s] scince it is not %s 's turn." %
255                   [str, player.name])
256       player.socket_buffer << str # always in the player's thread
257       return nil
258     end
259
260     @end_time = end_time
261     finish_flag = true
262     move_status = nil
263
264     if (@time_clock.timeout?(@current_player, @start_time, @end_time))
265       status = :timeout
266     elsif (str == :timeout)
267       return false            # time isn't expired. players aren't swapped. continue game
268     else
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])
272
273       if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
274         @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
275       else
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)
282           @current_turn += 1
283
284           @monitors.each do |monitor_handler|
285             monitor_handler.write_one_move(@game_id, self)
286           end
287         end # if
288         # if move_status is :toryo then a GameResult message will be sent to monitors   
289       end # if
290     end
291
292     @result = nil
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)
323     else
324       finish_flag = false
325     end
326     @result.process if @result
327     finish() if finish_flag
328     @current_player, @next_player = @next_player, @current_player
329     @start_time = Time.now
330     return finish_flag
331   end
332
333   def is_startable_status?
334     return (@sente && @gote &&
335             (@sente.status == "start_waiting") &&
336             (@gote.status  == "start_waiting"))
337   end
338
339   def start
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
348   end
349
350   def propose
351     @fh.puts("V2")
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}")
356     if @fischer > 0
357       @fh.puts("'Increment:#{@fischer}")
358     end
359     @fh.puts("$EVENT:#{@game_id}")
360
361     @sente.write_safe(propose_message("+"))
362     @gote.write_safe(propose_message("-"))
363
364     now = Time.now.strftime("%Y/%m/%d %H:%M:%S")
365     @fh.puts("$START_TIME:#{now}")
366     @fh.print(@board.initial_string)
367     if rated?
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])
373       end
374       if @gote.rated? && @gote.rate != 0
375         @fh.puts("'white_rate:%s:%s" % [@gote.player_id, @gote.rate])
376       end
377     end
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|
381         case move
382         when Array
383           @fh.puts move[0]
384           @fh.puts move[1]
385         when String
386           @fh.puts move
387           @fh.puts "T1"
388         end
389       end
390     end
391   end
392
393   def show()
394     str0 = <<EOM
395 BEGIN Game_Summary
396 Protocol_Version:1.2
397 Protocol_Mode:Server
398 Format:Shogi 1.0
399 Declaration:Jishogi 1.1
400 Game_ID:#{@game_id}
401 Name+:#{@sente.name}
402 Name-:#{@gote.name}
403 Rematch_On_Draw:NO
404 To_Move:+
405 Max_Moves:#{@board.max_moves}
406 BEGIN Time
407 Time_Unit:#{@time_clock.time_unit}
408 Total_Time:#{@total_time}
409 Byoyomi:#{@byoyomi}
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}
416 END Time
417 BEGIN Position
418 EOM
419
420     str1 = <<EOM
421 END Position
422 END Game_Summary
423 EOM
424
425     return str0 + @board.to_s + str1
426   end
427
428   def propose_message(sg_flag)
429     str = <<EOM
430 BEGIN Game_Summary
431 Protocol_Version:1.2
432 Protocol_Mode:Server
433 Format:Shogi 1.0
434 Declaration:Jishogi 1.1
435 Game_ID:#{@game_id}
436 Name+:#{@sente.name}
437 Name-:#{@gote.name}
438 Your_Turn:#{sg_flag}
439 Rematch_On_Draw:NO
440 To_Move:#{@board.teban ? "+" : "-"}
441 Max_Moves:#{@board.max_moves}
442 BEGIN Time
443 Time_Unit:#{@time_clock.time_unit}
444 Total_Time:#{@total_time}
445 Byoyomi:#{@byoyomi}
446 Increment:#{@fischer}
447 Least_Time_Per_Move:#{@board.least_time_per_move}
448 END Time
449 BEGIN Position
450 #{@board.initial_string.chomp}
451 #{@board.initial_moves.collect do |m|
452   case m
453   when Array
454     m.join(",")
455   when String
456     m + ",T1"
457   end
458 end.join("\n")}
459 END Position
460 END Game_Summary
461 EOM
462     # An empty @board.initial_moves causes an empty line, which should be
463     # eliminated.
464     return str.gsub("\n\n", "\n")
465   end
466
467   def prepared_expire?
468     if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
469       return true
470     end
471
472     return false
473   end
474
475   # Read the .csa file and returns an array of moves and times.
476   # ex. [["+7776FU","T2"], ["-3334FU","T5"]]
477   #
478   def read_moves
479     ret = []
480     IO.foreach(@logfile) do |line|
481       if /^[\+\-]\d{4}[A-Z]{2}/ =~ line
482         ret << [line.chomp]
483       elsif /^T\d*/ =~ line
484         ret[-1] << line.chomp
485       end
486     end
487     return ret
488   end
489   
490   private
491   
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
496         time += 1
497       end
498       @@time = time
499     end
500   end
501 end
502
503 end # ShogiServer