OSDN Git Service

Fix some lint warnings
[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       log_info(sprintf("+++ DEBUG %s consumed %d sec. remain %d sec",
271                 @current_player.name, t, @current_player.mytime))
272       move_status = @board.handle_one_move(str, @sente == @current_player)
273       # log_debug("move_status: %s for %s's %s" % [move_status, @sente == @current_player ? "BLACK" : "WHITE", str])
274
275       if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
276         @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
277       else
278         if :toryo != move_status
279           # Thinking time includes network traffic
280           @sente.write_safe(sprintf("%s,T%d\n", str, t))
281           @gote.write_safe(sprintf("%s,T%d\n", str, t))
282           @fh.printf("%s\nT%d\n", str, t)
283           @last_move = sprintf("%s,T%d", str, t)
284           @current_turn += 1
285
286           @monitors.each do |monitor_handler|
287             monitor_handler.write_one_move(@game_id, self)
288           end
289         end # if
290         # if move_status is :toryo then a GameResult message will be sent to monitors   
291       end # if
292     end
293
294     @result = nil
295     if (@next_player.status != "game") # rival is logout or disconnected
296       @result = GameResultAbnormalWin.new(self, @current_player, @next_player)
297     elsif (status == :timeout)
298       # current_player losed
299       @result = GameResultTimeoutWin.new(self, @next_player, @current_player)
300     elsif (move_status == :illegal)
301       @result = GameResultIllegalMoveWin.new(self, @next_player, @current_player)
302     elsif (move_status == :kachi_win)
303       @result = GameResultKachiWin.new(self, @current_player, @next_player)
304     elsif (move_status == :kachi_lose)
305       @result = GameResultIllegalKachiWin.new(self, @next_player, @current_player)
306     elsif (move_status == :toryo)
307       @result = GameResultToryoWin.new(self, @next_player, @current_player)
308     elsif (move_status == :outori)
309       # The current player captures the next player's king
310       @result = GameResultOutoriWin.new(self, @current_player, @next_player)
311     elsif (move_status == :oute_sennichite_sente_lose)
312       @result = GameResultOuteSennichiteWin.new(self, @gote, @sente) # Sente is checking
313     elsif (move_status == :oute_sennichite_gote_lose)
314       @result = GameResultOuteSennichiteWin.new(self, @sente, @gote) # Gote is checking
315     elsif (move_status == :sennichite)
316       @result = GameResultSennichiteDraw.new(self, @current_player, @next_player)
317     elsif (move_status == :uchifuzume)
318       # the current player losed
319       @result = GameResultUchifuzumeWin.new(self, @next_player, @current_player)
320     elsif (move_status == :oute_kaihimore)
321       # the current player losed
322       @result = GameResultOuteKaihiMoreWin.new(self, @next_player, @current_player)
323     elsif (move_status == :max_moves)
324       @result = GameResultMaxMovesDraw.new(self, @current_player, @next_player)
325     else
326       finish_flag = false
327     end
328     @result.process if @result
329     finish() if finish_flag
330     @current_player, @next_player = @next_player, @current_player
331     @start_time = Time.now
332     return finish_flag
333   end
334
335   def is_startable_status?
336     return (@sente && @gote &&
337             (@sente.status == "start_waiting") &&
338             (@gote.status  == "start_waiting"))
339   end
340
341   def start
342     log_message(sprintf("game started %s", @game_id))
343     @sente.status = "game"
344     @gote.status  = "game"
345     @sente.write_safe(sprintf("START:%s\n", @game_id))
346     @gote.write_safe(sprintf("START:%s\n", @game_id))
347     @sente.mytime = @total_time
348     @gote.mytime = @total_time
349     @start_time = Time.now
350   end
351
352   def propose
353     @fh.puts("V2")
354     @fh.puts("N+#{@sente.name}")
355     @fh.puts("N-#{@gote.name}")
356     @fh.puts("'Max_Moves:#{@board.max_moves}")
357     @fh.puts("'Least_Time_Per_Move:#{@board.least_time_per_move}")
358     if @fischer > 0
359       @fh.puts("'Increment:#{@fischer}")
360     end
361     @fh.puts("$EVENT:#{@game_id}")
362
363     @sente.write_safe(propose_message("+"))
364     @gote.write_safe(propose_message("-"))
365
366     now = Time.now.strftime("%Y/%m/%d %H:%M:%S")
367     @fh.puts("$START_TIME:#{now}")
368     @fh.print(@board.initial_string)
369     if rated?
370       black_name = @sente.rated? ? @sente.player_id : @sente.name
371       white_name = @gote.rated?  ? @gote.player_id  : @gote.name
372       @fh.puts("'rating:%s:%s" % [black_name, white_name])
373       if @sente.rated? && @sente.rate != 0
374         @fh.puts("'black_rate:%s:%s" % [@sente.player_id, @sente.rate])
375       end
376       if @gote.rated? && @gote.rate != 0
377         @fh.puts("'white_rate:%s:%s" % [@gote.player_id, @gote.rate])
378       end
379     end
380     unless @board.initial_moves.empty?
381       @fh.puts "'buoy game starting with %d moves" % [@board.initial_moves.size]
382       @board.initial_moves.each do |move|
383         case move
384         when Array
385           @fh.puts move[0]
386           @fh.puts move[1]
387         when String
388           @fh.puts move
389           @fh.puts "T1"
390         end
391       end
392     end
393   end
394
395   def show()
396     str0 = <<EOM
397 BEGIN Game_Summary
398 Protocol_Version:1.2
399 Protocol_Mode:Server
400 Format:Shogi 1.0
401 Declaration:Jishogi 1.1
402 Game_ID:#{@game_id}
403 Name+:#{@sente.name}
404 Name-:#{@gote.name}
405 Rematch_On_Draw:NO
406 To_Move:+
407 Max_Moves:#{@board.max_moves}
408 BEGIN Time
409 Time_Unit:#{@time_clock.time_unit}
410 Total_Time:#{@total_time}
411 Byoyomi:#{@byoyomi}
412 Increment:#{@fischer}
413 Least_Time_Per_Move:#{@board.least_time_per_move}
414 Remaining_Time+:#{@sente.mytime}
415 Remaining_Time-:#{@gote.mytime}
416 Last_Move:#{@last_move}
417 Current_Turn:#{@current_turn}
418 END Time
419 BEGIN Position
420 EOM
421
422     str1 = <<EOM
423 END Position
424 END Game_Summary
425 EOM
426
427     return str0 + @board.to_s + str1
428   end
429
430   def propose_message(sg_flag)
431     str = <<EOM
432 BEGIN Game_Summary
433 Protocol_Version:1.2
434 Protocol_Mode:Server
435 Format:Shogi 1.0
436 Declaration:Jishogi 1.1
437 Game_ID:#{@game_id}
438 Name+:#{@sente.name}
439 Name-:#{@gote.name}
440 Your_Turn:#{sg_flag}
441 Rematch_On_Draw:NO
442 To_Move:#{@board.teban ? "+" : "-"}
443 Max_Moves:#{@board.max_moves}
444 BEGIN Time
445 Time_Unit:#{@time_clock.time_unit}
446 Total_Time:#{@total_time}
447 Byoyomi:#{@byoyomi}
448 Increment:#{@fischer}
449 Least_Time_Per_Move:#{@board.least_time_per_move}
450 END Time
451 BEGIN Position
452 #{@board.initial_string.chomp}
453 #{@board.initial_moves.collect do |m|
454   case m
455   when Array
456     m.join(",")
457   when String
458     m + ",T1"
459   end
460 end.join("\n")}
461 END Position
462 END Game_Summary
463 EOM
464     # An empty @board.initial_moves causes an empty line, which should be
465     # eliminated.
466     return str.gsub("\n\n", "\n")
467   end
468
469   def prepared_expire?
470     if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
471       return true
472     end
473
474     return false
475   end
476
477   # Read the .csa file and returns an array of moves and times.
478   # ex. [["+7776FU","T2"], ["-3334FU","T5"]]
479   #
480   def read_moves
481     ret = []
482     IO.foreach(@logfile) do |line|
483       if /^[\+\-]\d{4}[A-Z]{2}/ =~ line
484         ret << [line.chomp]
485       elsif /^T\d*/ =~ line
486         ret[-1] << line.chomp
487       end
488     end
489     return ret
490   end
491   
492   private
493   
494   def issue_current_time
495     time = Time.now.strftime("%Y%m%d%H%M%S").to_i
496     @@mutex.synchronize do
497       while time <= @@time do
498         time += 1
499       end
500       @@time = time
501     end
502   end
503 end
504
505 end # ShogiServer