OSDN Git Service

* [shogi-server]
[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 # array of MonitorHandler*
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_handler)
104     monitoroff(monitor_handler)
105     @monitors.push(monitor_handler)
106   end
107
108   def monitoroff(monitor_handler)
109     @monitors.delete_if {|mon| mon == monitor_handler}
110   end
111
112   def each_monitor
113     @monitors.each do |monitor_handler|
114       yield monitor_handler
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
150     # In a case where a player in agree_waiting or start_waiting status is
151     # rejected, a GameResult object is not yet instanciated.
152     # See test/TC_before_agree.rb.
153     end_time = @result ? @result.end_time : Time.now
154     @fh.printf("'$END_TIME:%s\n", end_time.strftime("%Y/%m/%d %H:%M:%S"))    
155     @fh.close
156
157     @sente.game = nil
158     @gote.game = nil
159     @sente.status = "connected"
160     @gote.status = "connected"
161
162     if (@current_player.protocol == LoginCSA::PROTOCOL)
163       @current_player.finish
164     end
165     if (@next_player.protocol == LoginCSA::PROTOCOL)
166       @next_player.finish
167     end
168     @monitors = Array::new
169     @sente = nil
170     @gote = nil
171     @current_player = nil
172     @next_player = nil
173     $league.games.delete(@game_id)
174   end
175
176   # class Game
177   def handle_one_move(str, player, end_time)
178     unless turn?(player)
179       return false if str == :timeout
180
181       @fh.puts("'Deferred %s" % [str])
182       log_warning("Deferred a move [%s] scince it is not %s 's turn." %
183                   [str, player.name])
184       player.socket_buffer << str # always in the player's thread
185       return nil
186     end
187
188     finish_flag = true
189     @end_time = end_time
190     t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
191     
192     move_status = nil
193     if ((@current_player.mytime - t <= -@byoyomi) && 
194         ((@total_time > 0) || (@byoyomi > 0)))
195       status = :timeout
196     elsif (str == :timeout)
197       return false            # time isn't expired. players aren't swapped. continue game
198     else
199       @current_player.mytime -= t
200       if (@current_player.mytime < 0)
201         @current_player.mytime = 0
202       end
203
204       move_status = @board.handle_one_move(str, @sente == @current_player)
205       # log_debug("move_status: %s for %s's %s" % [move_status, @sente == @current_player ? "BLACK" : "WHITE", str])
206
207       if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
208         @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
209       else
210         if :toryo != move_status
211           # Thinking time includes network traffic
212           @sente.write_safe(sprintf("%s,T%d\n", str, t))
213           @gote.write_safe(sprintf("%s,T%d\n", str, t))
214           @fh.printf("%s\nT%d\n", str, t)
215           @last_move = sprintf("%s,T%d", str, t)
216           @current_turn += 1
217
218           @monitors.each do |monitor_handler|
219             monitor_handler.write_one_move(@game_id, self)
220           end
221         end # if
222         # if move_status is :toryo then a GameResult message will be sent to monitors   
223       end # if
224     end
225
226     @result = nil
227     if (@next_player.status != "game") # rival is logout or disconnected
228       @result = GameResultAbnormalWin.new(self, @current_player, @next_player)
229     elsif (status == :timeout)
230       # current_player losed
231       @result = GameResultTimeoutWin.new(self, @next_player, @current_player)
232     elsif (move_status == :illegal)
233       @result = GameResultIllegalMoveWin.new(self, @next_player, @current_player)
234     elsif (move_status == :kachi_win)
235       @result = GameResultKachiWin.new(self, @current_player, @next_player)
236     elsif (move_status == :kachi_lose)
237       @result = GameResultIllegalKachiWin.new(self, @next_player, @current_player)
238     elsif (move_status == :toryo)
239       @result = GameResultToryoWin.new(self, @next_player, @current_player)
240     elsif (move_status == :outori)
241       # The current player captures the next player's king
242       @result = GameResultOutoriWin.new(self, @current_player, @next_player)
243     elsif (move_status == :oute_sennichite_sente_lose)
244       @result = GameResultOuteSennichiteWin.new(self, @gote, @sente) # Sente is checking
245     elsif (move_status == :oute_sennichite_gote_lose)
246       @result = GameResultOuteSennichiteWin.new(self, @sente, @gote) # Gote is checking
247     elsif (move_status == :sennichite)
248       @result = GameResultSennichiteDraw.new(self, @current_player, @next_player)
249     elsif (move_status == :uchifuzume)
250       # the current player losed
251       @result = GameResultUchifuzumeWin.new(self, @next_player, @current_player)
252     elsif (move_status == :oute_kaihimore)
253       # the current player losed
254       @result = GameResultOuteKaihiMoreWin.new(self, @next_player, @current_player)
255     else
256       finish_flag = false
257     end
258     @result.process if @result
259     finish() if finish_flag
260     @current_player, @next_player = @next_player, @current_player
261     @start_time = Time::new
262     return finish_flag
263   end
264
265   def is_startable_status?
266     return (@sente && @gote &&
267             (@sente.status == "start_waiting") &&
268             (@gote.status  == "start_waiting"))
269   end
270
271   def start
272     log_message(sprintf("game started %s", @game_id))
273     @sente.status = "game"
274     @gote.status  = "game"
275     @sente.write_safe(sprintf("START:%s\n", @game_id))
276     @gote.write_safe(sprintf("START:%s\n", @game_id))
277     @sente.mytime = @total_time
278     @gote.mytime = @total_time
279     @start_time = Time::new
280   end
281
282   def propose
283     @fh.puts("V2")
284     @fh.puts("N+#{@sente.name}")
285     @fh.puts("N-#{@gote.name}")
286     @fh.puts("$EVENT:#{@game_id}")
287
288     @sente.write_safe(propose_message("+"))
289     @gote.write_safe(propose_message("-"))
290
291     now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
292     @fh.puts("$START_TIME:#{now}")
293     @fh.print <<EOM
294 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
295 P2 * -HI *  *  *  *  * -KA * 
296 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
297 P4 *  *  *  *  *  *  *  *  * 
298 P5 *  *  *  *  *  *  *  *  * 
299 P6 *  *  *  *  *  *  *  *  * 
300 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
301 P8 * +KA *  *  *  *  * +HI * 
302 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
303 +
304 EOM
305     if rated?
306       black_name = @sente.rated? ? @sente.player_id : @sente.name
307       white_name = @gote.rated?  ? @gote.player_id  : @gote.name
308       @fh.puts("'rating:%s:%s" % [black_name, white_name])
309     end
310     unless @board.initial_moves.empty?
311       @fh.puts "'buoy game starting with %d moves" % [@board.initial_moves.size]
312       @board.initial_moves.each do |move|
313         @fh.puts move
314         @fh.puts "T1"
315       end
316     end
317   end
318
319   def show()
320     str0 = <<EOM
321 BEGIN Game_Summary
322 Protocol_Version:1.1
323 Protocol_Mode:Server
324 Format:Shogi 1.0
325 Declaration:Jishogi 1.1
326 Game_ID:#{@game_id}
327 Name+:#{@sente.name}
328 Name-:#{@gote.name}
329 Rematch_On_Draw:NO
330 To_Move:+
331 BEGIN Time
332 Time_Unit:1sec
333 Total_Time:#{@total_time}
334 Byoyomi:#{@byoyomi}
335 Least_Time_Per_Move:#{Least_Time_Per_Move}
336 Remaining_Time+:#{@sente.mytime}
337 Remaining_Time-:#{@gote.mytime}
338 Last_Move:#{@last_move}
339 Current_Turn:#{@current_turn}
340 END Time
341 BEGIN Position
342 EOM
343
344     str1 = <<EOM
345 END Position
346 END Game_Summary
347 EOM
348
349     return str0 + @board.to_s + str1
350   end
351
352   def propose_message(sg_flag)
353     str = <<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 Your_Turn:#{sg_flag}
363 Rematch_On_Draw:NO
364 To_Move:#{@board.teban ? "+" : "-"}
365 BEGIN Time
366 Time_Unit:1sec
367 Total_Time:#{@total_time}
368 Byoyomi:#{@byoyomi}
369 Least_Time_Per_Move:#{Least_Time_Per_Move}
370 END Time
371 BEGIN Position
372 #{@board.to_s.chomp}
373 END Position
374 END Game_Summary
375 EOM
376     return str
377   end
378
379   def prepared_expire?
380     if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
381       return true
382     end
383
384     return false
385   end
386   
387   private
388   
389   def issue_current_time
390     time = Time::new.strftime("%Y%m%d%H%M%S").to_i
391     @@mutex.synchronize do
392       while time <= @@time do
393         time += 1
394       end
395       @@time = time
396     end
397   end
398 end
399
400 end # ShogiServer