OSDN Git Service

afb5d08f04ca5815605c16e32feb0514a419e252
[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-2008 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/util'
23
24 module ShogiServer # for a namespace
25
26 class Game
27   # When this duration passes after this object instanciated (i.e.
28   # the agree_waiting or start_waiting state lasts too long),
29   # the game will be rejected by the Server.
30   WAITING_EXPIRATION = 120 # seconds
31
32   @@mutex = Mutex.new
33   @@time  = 0
34
35   # Decide an actual turn of each player according to their turn preferences.
36   # p2 is a rival player of the p1 player.
37   # p1_sente_string must be "*", "+" or "-".
38   # After this call, the sente value of each player is always true or false, not
39   # nil.
40   #
41   def Game.decide_turns(p1, p1_sente_string, p2)
42     if ((p1_sente_string == "*") && (p2.sente == nil))
43       if (rand(2) == 0)
44         p1.sente = true
45         p2.sente = false
46       else
47         p1.sente = false
48         p2.sente = true
49       end
50     elsif (p2.sente == true) # rival has higher priority
51       p1.sente = false
52     elsif (p2.sente == false)
53       p1.sente = true
54     elsif (p1_sente_string == "+")
55       p1.sente = true
56       p2.sente = false
57     elsif (p1_sente_string == "-")
58       p1.sente = false
59       p2.sente = true
60     else
61       ## never reached
62     end
63   end
64
65
66   def initialize(game_name, player0, player1, board)
67     @monitors = Array::new # array of MonitorHandler*
68     @game_name = game_name
69     if (@game_name =~ /-(\d+)-(\d+)$/)
70       @total_time = $1.to_i
71       @byoyomi = $2.to_i
72     end
73
74     if (player0.sente)
75       @sente, @gote = player0, player1
76     else
77       @sente, @gote = player1, player0
78     end
79     @sente.socket_buffer.clear
80     @gote.socket_buffer.clear
81     @board = board
82     if @board.teban
83       @current_player, @next_player = @sente, @gote
84     else
85       @current_player, @next_player = @gote, @sente
86     end
87     @sente.game = self
88     @gote.game  = self
89
90     @last_move = ""
91     unless @board.initial_moves.empty?
92       last_move = @board.initial_moves.last
93       case last_move
94       when Array
95         @last_move = last_move.join(",")
96       when String
97         @last_move = "%s,T1" % [last_move]
98       end
99     end
100     @current_turn = @board.initial_moves.size
101
102     @sente.status = "agree_waiting"
103     @gote.status  = "agree_waiting"
104
105     @game_id = sprintf("%s+%s+%s+%s+%s", 
106                   $league.event, @game_name, 
107                   @sente.name, @gote.name, issue_current_time)
108     
109     # The time when this Game instance was created.
110     # Don't be confused with @start_time when the game was started to play.
111     @prepared_time = Time.now 
112     log_dir_name = File.join($league.dir, 
113                              @prepared_time.strftime("%Y"),
114                              @prepared_time.strftime("%m"),
115                              @prepared_time.strftime("%d"))
116     @logfile = File.join(log_dir_name, @game_id + ".csa")
117     Mkdir.mkdir_for(@logfile)
118
119     $league.games[@game_id] = self
120
121     log_message(sprintf("game created %s", @game_id))
122
123     @start_time = nil
124     @fh = open(@logfile, "w")
125     @fh.sync = true
126     @result = nil
127
128     propose
129   end
130   attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors
131   attr_accessor :last_move, :current_turn
132   attr_reader   :result, :prepared_time
133
134   # Path of a log file for this game.
135   attr_reader   :logfile
136
137   def rated?
138     @sente.rated? && @gote.rated?
139   end
140
141   def turn?(player)
142     return player.status == "game" && @current_player == player
143   end
144
145   def monitoron(monitor_handler)
146     monitoroff(monitor_handler)
147     @monitors.push(monitor_handler)
148   end
149
150   def monitoroff(monitor_handler)
151     @monitors.delete_if {|mon| mon == monitor_handler}
152   end
153
154   def each_monitor
155     @monitors.each do |monitor_handler|
156       yield monitor_handler
157     end
158   end
159
160   def log_game(str)
161     if @fh.closed?
162       log_error("Failed to write to Game[%s]'s log file: %s" %
163                 [@game_id, str])
164     end
165     @fh.printf("%s\n", str)
166   end
167
168   def reject(rejector)
169     @sente.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
170     @gote.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
171     finish
172   end
173
174   def kill(killer)
175     [@sente, @gote].each do |player|
176       if ["agree_waiting", "start_waiting"].include?(player.status)
177         reject(killer.name)
178         return # return from this method
179       end
180     end
181     
182     if (@current_player == killer)
183       @result = GameResultAbnormalWin.new(self, @next_player, @current_player)
184       @result.process
185       finish
186     end
187   end
188
189   def finish
190     log_message(sprintf("game finished %s", @game_id))
191
192     # In a case where a player in agree_waiting or start_waiting status is
193     # rejected, a GameResult object is not yet instanciated.
194     # See test/TC_before_agree.rb.
195     end_time = @result ? @result.end_time : Time.now
196     @fh.printf("'$END_TIME:%s\n", end_time.strftime("%Y/%m/%d %H:%M:%S"))    
197     @fh.close
198
199     @sente.game = nil
200     @gote.game = nil
201     @sente.status = "connected"
202     @gote.status = "connected"
203
204     if (@current_player.protocol == LoginCSA::PROTOCOL)
205       @current_player.finish
206     end
207     if (@next_player.protocol == LoginCSA::PROTOCOL)
208       @next_player.finish
209     end
210     @monitors = Array::new
211     @sente = nil
212     @gote = nil
213     @current_player = nil
214     @next_player = nil
215     $league.games.delete(@game_id)
216   end
217
218   # class Game
219   def handle_one_move(str, player, end_time)
220     unless turn?(player)
221       return false if str == :timeout
222
223       @fh.puts("'Deferred %s" % [str])
224       log_warning("Deferred a move [%s] scince it is not %s 's turn." %
225                   [str, player.name])
226       player.socket_buffer << str # always in the player's thread
227       return nil
228     end
229
230     finish_flag = true
231     @end_time = end_time
232     t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
233     
234     move_status = nil
235     if ((@current_player.mytime - t <= -@byoyomi) && 
236         ((@total_time > 0) || (@byoyomi > 0)))
237       status = :timeout
238     elsif (str == :timeout)
239       return false            # time isn't expired. players aren't swapped. continue game
240     else
241       @current_player.mytime -= t
242       if (@current_player.mytime < 0)
243         @current_player.mytime = 0
244       end
245
246       move_status = @board.handle_one_move(str, @sente == @current_player)
247       # log_debug("move_status: %s for %s's %s" % [move_status, @sente == @current_player ? "BLACK" : "WHITE", str])
248
249       if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
250         @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
251       else
252         if :toryo != move_status
253           # Thinking time includes network traffic
254           @sente.write_safe(sprintf("%s,T%d\n", str, t))
255           @gote.write_safe(sprintf("%s,T%d\n", str, t))
256           @fh.printf("%s\nT%d\n", str, t)
257           @last_move = sprintf("%s,T%d", str, t)
258           @current_turn += 1
259
260           @monitors.each do |monitor_handler|
261             monitor_handler.write_one_move(@game_id, self)
262           end
263         end # if
264         # if move_status is :toryo then a GameResult message will be sent to monitors   
265       end # if
266     end
267
268     @result = nil
269     if (@next_player.status != "game") # rival is logout or disconnected
270       @result = GameResultAbnormalWin.new(self, @current_player, @next_player)
271     elsif (status == :timeout)
272       # current_player losed
273       @result = GameResultTimeoutWin.new(self, @next_player, @current_player)
274     elsif (move_status == :illegal)
275       @result = GameResultIllegalMoveWin.new(self, @next_player, @current_player)
276     elsif (move_status == :kachi_win)
277       @result = GameResultKachiWin.new(self, @current_player, @next_player)
278     elsif (move_status == :kachi_lose)
279       @result = GameResultIllegalKachiWin.new(self, @next_player, @current_player)
280     elsif (move_status == :toryo)
281       @result = GameResultToryoWin.new(self, @next_player, @current_player)
282     elsif (move_status == :outori)
283       # The current player captures the next player's king
284       @result = GameResultOutoriWin.new(self, @current_player, @next_player)
285     elsif (move_status == :oute_sennichite_sente_lose)
286       @result = GameResultOuteSennichiteWin.new(self, @gote, @sente) # Sente is checking
287     elsif (move_status == :oute_sennichite_gote_lose)
288       @result = GameResultOuteSennichiteWin.new(self, @sente, @gote) # Gote is checking
289     elsif (move_status == :sennichite)
290       @result = GameResultSennichiteDraw.new(self, @current_player, @next_player)
291     elsif (move_status == :uchifuzume)
292       # the current player losed
293       @result = GameResultUchifuzumeWin.new(self, @next_player, @current_player)
294     elsif (move_status == :oute_kaihimore)
295       # the current player losed
296       @result = GameResultOuteKaihiMoreWin.new(self, @next_player, @current_player)
297     else
298       finish_flag = false
299     end
300     @result.process if @result
301     finish() if finish_flag
302     @current_player, @next_player = @next_player, @current_player
303     @start_time = Time.now
304     return finish_flag
305   end
306
307   def is_startable_status?
308     return (@sente && @gote &&
309             (@sente.status == "start_waiting") &&
310             (@gote.status  == "start_waiting"))
311   end
312
313   def start
314     log_message(sprintf("game started %s", @game_id))
315     @sente.status = "game"
316     @gote.status  = "game"
317     @sente.write_safe(sprintf("START:%s\n", @game_id))
318     @gote.write_safe(sprintf("START:%s\n", @game_id))
319     @sente.mytime = @total_time
320     @gote.mytime = @total_time
321     @start_time = Time.now
322   end
323
324   def propose
325     @fh.puts("V2")
326     @fh.puts("N+#{@sente.name}")
327     @fh.puts("N-#{@gote.name}")
328     @fh.puts("$EVENT:#{@game_id}")
329
330     @sente.write_safe(propose_message("+"))
331     @gote.write_safe(propose_message("-"))
332
333     now = Time.now.strftime("%Y/%m/%d %H:%M:%S")
334     @fh.puts("$START_TIME:#{now}")
335     @fh.print(@board.initial_string)
336     if rated?
337       black_name = @sente.rated? ? @sente.player_id : @sente.name
338       white_name = @gote.rated?  ? @gote.player_id  : @gote.name
339       @fh.puts("'rating:%s:%s" % [black_name, white_name])
340     end
341     unless @board.initial_moves.empty?
342       @fh.puts "'buoy game starting with %d moves" % [@board.initial_moves.size]
343       @board.initial_moves.each do |move|
344         case move
345         when Array
346           @fh.puts move[0]
347           @fh.puts move[1]
348         when String
349           @fh.puts move
350           @fh.puts "T1"
351         end
352       end
353     end
354   end
355
356   def show()
357     str0 = <<EOM
358 BEGIN Game_Summary
359 Protocol_Version:1.1
360 Protocol_Mode:Server
361 Format:Shogi 1.0
362 Declaration:Jishogi 1.1
363 Game_ID:#{@game_id}
364 Name+:#{@sente.name}
365 Name-:#{@gote.name}
366 Rematch_On_Draw:NO
367 To_Move:+
368 BEGIN Time
369 Time_Unit:1sec
370 Total_Time:#{@total_time}
371 Byoyomi:#{@byoyomi}
372 Least_Time_Per_Move:#{Least_Time_Per_Move}
373 Remaining_Time+:#{@sente.mytime}
374 Remaining_Time-:#{@gote.mytime}
375 Last_Move:#{@last_move}
376 Current_Turn:#{@current_turn}
377 END Time
378 BEGIN Position
379 EOM
380
381     str1 = <<EOM
382 END Position
383 END Game_Summary
384 EOM
385
386     return str0 + @board.to_s + str1
387   end
388
389   def propose_message(sg_flag)
390     str = <<EOM
391 BEGIN Game_Summary
392 Protocol_Version:1.1
393 Protocol_Mode:Server
394 Format:Shogi 1.0
395 Declaration:Jishogi 1.1
396 Game_ID:#{@game_id}
397 Name+:#{@sente.name}
398 Name-:#{@gote.name}
399 Your_Turn:#{sg_flag}
400 Rematch_On_Draw:NO
401 To_Move:#{@board.teban ? "+" : "-"}
402 BEGIN Time
403 Time_Unit:1sec
404 Total_Time:#{@total_time}
405 Byoyomi:#{@byoyomi}
406 Least_Time_Per_Move:#{Least_Time_Per_Move}
407 END Time
408 BEGIN Position
409 #{@board.initial_string.chomp}
410 #{@board.initial_moves.collect do |m|
411   case m
412   when Array
413     m.join(",")
414   when String
415     m + ",T1"
416   end
417 end.join("\n")}
418 END Position
419 END Game_Summary
420 EOM
421     # An empty @board.initial_moves causes an empty line, which should be
422     # eliminated.
423     return str.gsub("\n\n", "\n")
424   end
425
426   def prepared_expire?
427     if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
428       return true
429     end
430
431     return false
432   end
433
434   # Read the .csa file and returns an array of moves and times.
435   # ex. [["+7776FU","T2"], ["-3334FU","T5"]]
436   #
437   def read_moves
438     ret = []
439     IO.foreach(@logfile) do |line|
440       if /^[\+\-]\d{4}[A-Z]{2}/ =~ line
441         ret << [line.chomp]
442       elsif /^T\d*/ =~ line
443         ret[-1] << line.chomp
444       end
445     end
446     return ret
447   end
448   
449   private
450   
451   def issue_current_time
452     time = Time.now.strftime("%Y%m%d%H%M%S").to_i
453     @@mutex.synchronize do
454       while time <= @@time do
455         time += 1
456       end
457       @@time = time
458     end
459   end
460 end
461
462 end # ShogiServer