OSDN Git Service

[shogi-server] New pairing algorithm: ShogiServer::Pairing::LeastDiff
[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(@board.initial_string)
327     if rated?
328       black_name = @sente.rated? ? @sente.player_id : @sente.name
329       white_name = @gote.rated?  ? @gote.player_id  : @gote.name
330       @fh.puts("'rating:%s:%s" % [black_name, white_name])
331     end
332     unless @board.initial_moves.empty?
333       @fh.puts "'buoy game starting with %d moves" % [@board.initial_moves.size]
334       @board.initial_moves.each do |move|
335         @fh.puts move
336         @fh.puts "T1"
337       end
338     end
339   end
340
341   def show()
342     str0 = <<EOM
343 BEGIN Game_Summary
344 Protocol_Version:1.1
345 Protocol_Mode:Server
346 Format:Shogi 1.0
347 Declaration:Jishogi 1.1
348 Game_ID:#{@game_id}
349 Name+:#{@sente.name}
350 Name-:#{@gote.name}
351 Rematch_On_Draw:NO
352 To_Move:+
353 BEGIN Time
354 Time_Unit:1sec
355 Total_Time:#{@total_time}
356 Byoyomi:#{@byoyomi}
357 Least_Time_Per_Move:#{Least_Time_Per_Move}
358 Remaining_Time+:#{@sente.mytime}
359 Remaining_Time-:#{@gote.mytime}
360 Last_Move:#{@last_move}
361 Current_Turn:#{@current_turn}
362 END Time
363 BEGIN Position
364 EOM
365
366     str1 = <<EOM
367 END Position
368 END Game_Summary
369 EOM
370
371     return str0 + @board.to_s + str1
372   end
373
374   def propose_message(sg_flag)
375     str = <<EOM
376 BEGIN Game_Summary
377 Protocol_Version:1.1
378 Protocol_Mode:Server
379 Format:Shogi 1.0
380 Declaration:Jishogi 1.1
381 Game_ID:#{@game_id}
382 Name+:#{@sente.name}
383 Name-:#{@gote.name}
384 Your_Turn:#{sg_flag}
385 Rematch_On_Draw:NO
386 To_Move:#{@board.teban ? "+" : "-"}
387 BEGIN Time
388 Time_Unit:1sec
389 Total_Time:#{@total_time}
390 Byoyomi:#{@byoyomi}
391 Least_Time_Per_Move:#{Least_Time_Per_Move}
392 END Time
393 BEGIN Position
394 #{@board.initial_string.chomp}
395 #{@board.initial_moves.collect {|m| m + ",T1"}.join("\n")}
396 END Position
397 END Game_Summary
398 EOM
399     # An empty @board.initial_moves causes an empty line, which should be
400     # eliminated.
401     return str.gsub("\n\n", "\n")
402   end
403
404   def prepared_expire?
405     if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
406       return true
407     end
408
409     return false
410   end
411   
412   private
413   
414   def issue_current_time
415     time = Time.now.strftime("%Y%m%d%H%M%S").to_i
416     @@mutex.synchronize do
417       while time <= @@time do
418         time += 1
419       end
420       @@time = time
421     end
422   end
423 end
424
425 end # ShogiServer