OSDN Git Service

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