OSDN Git Service

232eac49960575c02d73f45dc6d0c76635fbd147
[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 = @board.initial_moves.empty? ? "" : "%s,T1" % [@board.initial_moves.last]
91     @current_turn = @board.initial_moves.size
92
93     @sente.status = "agree_waiting"
94     @gote.status  = "agree_waiting"
95
96     @game_id = sprintf("%s+%s+%s+%s+%s", 
97                   $league.event, @game_name, 
98                   @sente.name, @gote.name, issue_current_time)
99     
100     # The time when this Game instance was created.
101     # Don't be confused with @start_time when the game was started to play.
102     @prepared_time = Time.now 
103     log_dir_name = File.join($league.dir, 
104                              @prepared_time.strftime("%Y"),
105                              @prepared_time.strftime("%m"),
106                              @prepared_time.strftime("%d"))
107     @logfile = File.join(log_dir_name, @game_id + ".csa")
108     Mkdir.mkdir_for(@logfile)
109
110     $league.games[@game_id] = self
111
112     log_message(sprintf("game created %s", @game_id))
113
114     @start_time = nil
115     @fh = open(@logfile, "w")
116     @fh.sync = true
117     @result = nil
118
119     propose
120   end
121   attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors
122   attr_accessor :last_move, :current_turn
123   attr_reader   :result, :prepared_time
124
125   # Path of a log file for this game.
126   attr_reader   :logfile
127
128   def rated?
129     @sente.rated? && @gote.rated?
130   end
131
132   def turn?(player)
133     return player.status == "game" && @current_player == player
134   end
135
136   def monitoron(monitor_handler)
137     monitoroff(monitor_handler)
138     @monitors.push(monitor_handler)
139   end
140
141   def monitoroff(monitor_handler)
142     @monitors.delete_if {|mon| mon == monitor_handler}
143   end
144
145   def each_monitor
146     @monitors.each do |monitor_handler|
147       yield monitor_handler
148     end
149   end
150
151   def log_game(str)
152     if @fh.closed?
153       log_error("Failed to write to Game[%s]'s log file: %s" %
154                 [@game_id, str])
155     end
156     @fh.printf("%s\n", str)
157   end
158
159   def reject(rejector)
160     @sente.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
161     @gote.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
162     finish
163   end
164
165   def kill(killer)
166     [@sente, @gote].each do |player|
167       if ["agree_waiting", "start_waiting"].include?(player.status)
168         reject(killer.name)
169         return # return from this method
170       end
171     end
172     
173     if (@current_player == killer)
174       @result = GameResultAbnormalWin.new(self, @next_player, @current_player)
175       @result.process
176       finish
177     end
178   end
179
180   def finish
181     log_message(sprintf("game finished %s", @game_id))
182
183     # In a case where a player in agree_waiting or start_waiting status is
184     # rejected, a GameResult object is not yet instanciated.
185     # See test/TC_before_agree.rb.
186     end_time = @result ? @result.end_time : Time.now
187     @fh.printf("'$END_TIME:%s\n", end_time.strftime("%Y/%m/%d %H:%M:%S"))    
188     @fh.close
189
190     @sente.game = nil
191     @gote.game = nil
192     @sente.status = "connected"
193     @gote.status = "connected"
194
195     if (@current_player.protocol == LoginCSA::PROTOCOL)
196       @current_player.finish
197     end
198     if (@next_player.protocol == LoginCSA::PROTOCOL)
199       @next_player.finish
200     end
201     @monitors = Array::new
202     @sente = nil
203     @gote = nil
204     @current_player = nil
205     @next_player = nil
206     $league.games.delete(@game_id)
207   end
208
209   # class Game
210   def handle_one_move(str, player, end_time)
211     unless turn?(player)
212       return false if str == :timeout
213
214       @fh.puts("'Deferred %s" % [str])
215       log_warning("Deferred a move [%s] scince it is not %s 's turn." %
216                   [str, player.name])
217       player.socket_buffer << str # always in the player's thread
218       return nil
219     end
220
221     finish_flag = true
222     @end_time = end_time
223     t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
224     
225     move_status = nil
226     if ((@current_player.mytime - t <= -@byoyomi) && 
227         ((@total_time > 0) || (@byoyomi > 0)))
228       status = :timeout
229     elsif (str == :timeout)
230       return false            # time isn't expired. players aren't swapped. continue game
231     else
232       @current_player.mytime -= t
233       if (@current_player.mytime < 0)
234         @current_player.mytime = 0
235       end
236
237       move_status = @board.handle_one_move(str, @sente == @current_player)
238       # log_debug("move_status: %s for %s's %s" % [move_status, @sente == @current_player ? "BLACK" : "WHITE", str])
239
240       if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
241         @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
242       else
243         if :toryo != move_status
244           # Thinking time includes network traffic
245           @sente.write_safe(sprintf("%s,T%d\n", str, t))
246           @gote.write_safe(sprintf("%s,T%d\n", str, t))
247           @fh.printf("%s\nT%d\n", str, t)
248           @last_move = sprintf("%s,T%d", str, t)
249           @current_turn += 1
250
251           @monitors.each do |monitor_handler|
252             monitor_handler.write_one_move(@game_id, self)
253           end
254         end # if
255         # if move_status is :toryo then a GameResult message will be sent to monitors   
256       end # if
257     end
258
259     @result = nil
260     if (@next_player.status != "game") # rival is logout or disconnected
261       @result = GameResultAbnormalWin.new(self, @current_player, @next_player)
262     elsif (status == :timeout)
263       # current_player losed
264       @result = GameResultTimeoutWin.new(self, @next_player, @current_player)
265     elsif (move_status == :illegal)
266       @result = GameResultIllegalMoveWin.new(self, @next_player, @current_player)
267     elsif (move_status == :kachi_win)
268       @result = GameResultKachiWin.new(self, @current_player, @next_player)
269     elsif (move_status == :kachi_lose)
270       @result = GameResultIllegalKachiWin.new(self, @next_player, @current_player)
271     elsif (move_status == :toryo)
272       @result = GameResultToryoWin.new(self, @next_player, @current_player)
273     elsif (move_status == :outori)
274       # The current player captures the next player's king
275       @result = GameResultOutoriWin.new(self, @current_player, @next_player)
276     elsif (move_status == :oute_sennichite_sente_lose)
277       @result = GameResultOuteSennichiteWin.new(self, @gote, @sente) # Sente is checking
278     elsif (move_status == :oute_sennichite_gote_lose)
279       @result = GameResultOuteSennichiteWin.new(self, @sente, @gote) # Gote is checking
280     elsif (move_status == :sennichite)
281       @result = GameResultSennichiteDraw.new(self, @current_player, @next_player)
282     elsif (move_status == :uchifuzume)
283       # the current player losed
284       @result = GameResultUchifuzumeWin.new(self, @next_player, @current_player)
285     elsif (move_status == :oute_kaihimore)
286       # the current player losed
287       @result = GameResultOuteKaihiMoreWin.new(self, @next_player, @current_player)
288     else
289       finish_flag = false
290     end
291     @result.process if @result
292     finish() if finish_flag
293     @current_player, @next_player = @next_player, @current_player
294     @start_time = Time.now
295     return finish_flag
296   end
297
298   def is_startable_status?
299     return (@sente && @gote &&
300             (@sente.status == "start_waiting") &&
301             (@gote.status  == "start_waiting"))
302   end
303
304   def start
305     log_message(sprintf("game started %s", @game_id))
306     @sente.status = "game"
307     @gote.status  = "game"
308     @sente.write_safe(sprintf("START:%s\n", @game_id))
309     @gote.write_safe(sprintf("START:%s\n", @game_id))
310     @sente.mytime = @total_time
311     @gote.mytime = @total_time
312     @start_time = Time.now
313   end
314
315   def propose
316     @fh.puts("V2")
317     @fh.puts("N+#{@sente.name}")
318     @fh.puts("N-#{@gote.name}")
319     @fh.puts("$EVENT:#{@game_id}")
320
321     @sente.write_safe(propose_message("+"))
322     @gote.write_safe(propose_message("-"))
323
324     now = Time.now.strftime("%Y/%m/%d %H:%M:%S")
325     @fh.puts("$START_TIME:#{now}")
326     @fh.print <<EOM
327 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
328 P2 * -HI *  *  *  *  * -KA * 
329 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
330 P4 *  *  *  *  *  *  *  *  * 
331 P5 *  *  *  *  *  *  *  *  * 
332 P6 *  *  *  *  *  *  *  *  * 
333 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
334 P8 * +KA *  *  *  *  * +HI * 
335 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
336 +
337 EOM
338     if rated?
339       black_name = @sente.rated? ? @sente.player_id : @sente.name
340       white_name = @gote.rated?  ? @gote.player_id  : @gote.name
341       @fh.puts("'rating:%s:%s" % [black_name, white_name])
342     end
343     unless @board.initial_moves.empty?
344       @fh.puts "'buoy game starting with %d moves" % [@board.initial_moves.size]
345       @board.initial_moves.each do |move|
346         @fh.puts move
347         @fh.puts "T1"
348       end
349     end
350   end
351
352   def show()
353     str0 = <<EOM
354 BEGIN Game_Summary
355 Protocol_Version:1.1
356 Protocol_Mode:Server
357 Format:Shogi 1.0
358 Declaration:Jishogi 1.1
359 Game_ID:#{@game_id}
360 Name+:#{@sente.name}
361 Name-:#{@gote.name}
362 Rematch_On_Draw:NO
363 To_Move:+
364 BEGIN Time
365 Time_Unit:1sec
366 Total_Time:#{@total_time}
367 Byoyomi:#{@byoyomi}
368 Least_Time_Per_Move:#{Least_Time_Per_Move}
369 Remaining_Time+:#{@sente.mytime}
370 Remaining_Time-:#{@gote.mytime}
371 Last_Move:#{@last_move}
372 Current_Turn:#{@current_turn}
373 END Time
374 BEGIN Position
375 EOM
376
377     str1 = <<EOM
378 END Position
379 END Game_Summary
380 EOM
381
382     return str0 + @board.to_s + str1
383   end
384
385   def propose_message(sg_flag)
386     str = <<EOM
387 BEGIN Game_Summary
388 Protocol_Version:1.1
389 Protocol_Mode:Server
390 Format:Shogi 1.0
391 Declaration:Jishogi 1.1
392 Game_ID:#{@game_id}
393 Name+:#{@sente.name}
394 Name-:#{@gote.name}
395 Your_Turn:#{sg_flag}
396 Rematch_On_Draw:NO
397 To_Move:#{@board.teban ? "+" : "-"}
398 BEGIN Time
399 Time_Unit:1sec
400 Total_Time:#{@total_time}
401 Byoyomi:#{@byoyomi}
402 Least_Time_Per_Move:#{Least_Time_Per_Move}
403 END Time
404 BEGIN Position
405 #{Board::INITIAL_POSITION}
406 #{@board.initial_moves.collect {|m| m + ",T1"}.join("\n")}
407 END Position
408 END Game_Summary
409 EOM
410     # An empty @board.initial_moves causes an empty line, which should be
411     # eliminated.
412     return str.gsub("\n\n", "\n")
413   end
414
415   def prepared_expire?
416     if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
417       return true
418     end
419
420     return false
421   end
422   
423   private
424   
425   def issue_current_time
426     time = Time.now.strftime("%Y%m%d%H%M%S").to_i
427     @@mutex.synchronize do
428       while time <= @@time do
429         time += 1
430       end
431       @@time = time
432     end
433   end
434 end
435
436 end # ShogiServer