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 'observer'
22
23 module ShogiServer # for a namespace
24
25 # MonitorObserver obserers GameResult to send messages to the monotors
26 # watching the game
27 #
28 class MonitorObserver
29   def update(game_result)
30     game_result.game.each_monitor do |monitor|
31       monitor.write_safe("##[MONITOR][%s] %s\n" % [game_result.game.game_id, game_result.result_type])
32     end
33   end
34 end
35
36 # Base class for a game result
37 #
38 class GameResult
39   include Observable
40
41   # Game object
42   attr_reader :game
43   # Array of players
44   attr_reader :players
45   # Black player object
46   attr_reader :black
47   # White plyer object
48   attr_reader :white
49   # Command to send monitors such as '%TORYO' etc...
50   attr_reader :result_type
51
52   def initialize(game, p1, p2)
53     @game = game
54     @players = [p1, p2]
55     if p1.sente && !p2.sente
56       @black, @white = p1, p2
57     elsif !p1.sente && p2.sente
58       @black, @white = p2, p1
59     else
60       raise "Never reached!"
61     end
62     @players.each do |player|
63       player.status = "connected"
64     end
65     @result_type = ""
66
67     regist_observers
68   end
69
70   def regist_observers
71     add_observer MonitorObserver.new
72
73     if League::Floodgate.game_name?(@game.game_name) &&
74        @game.sente.player_id &&
75        @game.gote.player_id &&
76        $options["floodgate-history"]
77       add_observer League::Floodgate::History.factory
78     end
79   end
80
81   def process
82     raise "Implement me!"
83   end
84
85   def notify
86     changed
87     notify_observers(self)
88   end
89
90   def log(str)
91     @game.log_game(str)
92   end
93
94   def log_board
95     log(@game.board.to_s.gsub(/^/, "\'").chomp)
96   end
97
98 end
99
100 class GameResultWin < GameResult
101   attr_reader :winner, :loser
102
103   def initialize(game, winner, loser)
104     super
105     @winner, @loser = winner, loser
106     @winner.last_game_win = true
107     @loser.last_game_win  = false
108   end
109
110   def log_summary(type)
111     log_board
112
113     black_result = white_result = ""
114     if @black == @winner
115       black_result = "win"
116       white_result = "lose"
117     else
118       black_result = "lose"
119       white_result = "win"
120     end
121     log("'summary:%s:%s %s:%s %s" % [type, 
122                                      @black.name, black_result,
123                                      @white.name, white_result])
124
125   end
126 end
127
128 class GameResultAbnormalWin < GameResultWin
129   def process
130     @winner.write_safe("%TORYO\n#RESIGN\n#WIN\n")
131     @loser.write_safe( "%TORYO\n#RESIGN\n#LOSE\n")
132     log("%TORYO")
133     log_summary("abnormal")
134     @result_type = "%TORYO"
135     notify
136   end
137 end
138
139 class GameResultTimeoutWin < GameResultWin
140   def process
141     @winner.write_safe("#TIME_UP\n#WIN\n")
142     @loser.write_safe( "#TIME_UP\n#LOSE\n")
143     log_summary("time up")
144     @result_type = "#TIME_UP"
145     notify
146   end
147 end
148
149 # A player declares (successful) Kachi
150 class GameResultKachiWin < GameResultWin
151   def process
152     @winner.write_safe("%KACHI\n#JISHOGI\n#WIN\n")
153     @loser.write_safe( "%KACHI\n#JISHOGI\n#LOSE\n")
154     log("%KACHI")
155     log_summary("kachi")
156     @result_type = "%KACHI"
157     notify
158   end
159 end
160
161 # A player declares wrong Kachi
162 class GameResultIllegalKachiWin < GameResultWin
163   def process
164     @winner.write_safe("%KACHI\n#ILLEGAL_MOVE\n#WIN\n")
165     @loser.write_safe( "%KACHI\n#ILLEGAL_MOVE\n#LOSE\n")
166     log("%KACHI")
167     log_summary("illegal kachi")
168     @result_type = "%KACHI"
169     notify
170   end
171 end
172
173 class GameResultIllegalWin < GameResultWin
174   def initialize(game, winner, loser, cause)
175     super(game, winner, loser)
176     @cause = cause
177   end
178
179   def process
180     @winner.write_safe("#ILLEGAL_MOVE\n#WIN\n")
181     @loser.write_safe( "#ILLEGAL_MOVE\n#LOSE\n")
182     log_summary(@cause)
183     @result_type = "#ILLEGAL_MOVE"
184     notify
185   end
186 end
187
188 class GameResultIllegalMoveWin < GameResultIllegalWin
189   def initialize(game, winner, loser)
190     super(game, winner, loser, "illegal move")
191   end
192 end
193
194 class GameResultUchifuzumeWin < GameResultIllegalWin
195   def initialize(game, winner, loser)
196     super(game, winner, loser, "uchifuzume")
197   end
198 end
199
200 class GameResultOuteKaihiMoreWin < GameResultIllegalWin
201   def initialize(game, winner, loser)
202     super(game, winner, loser, "oute_kaihimore")
203   end
204 end
205
206 class GameResultOutoriWin < GameResultWin
207   def initialize(game, winner, loser)
208     super(game, winner, loser)
209   end
210 end
211
212 class GameResultToryoWin < GameResultWin
213   def process
214     @winner.write_safe("%TORYO\n#RESIGN\n#WIN\n")
215     @loser.write_safe( "%TORYO\n#RESIGN\n#LOSE\n")
216     log("%TORYO")
217     log_summary("toryo")
218     @result_type = "%TORYO"
219     notify
220   end
221 end
222
223 class GameResultOuteSennichiteWin < GameResultWin
224   def process
225     @winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
226     @loser.write_safe( "#OUTE_SENNICHITE\n#LOSE\n")
227     log_summary("oute_sennichite")
228     @result_type = "#OUTE_SENNICHITE"
229     notify
230   end
231 end
232
233 class GameResultDraw < GameResult
234   def initialize(game, p1, p2)
235     super
236     p1.last_game_win = false
237     p2.last_game_win = false
238   end
239   
240   def log_summary(type)
241     log_board
242     log("'summary:%s:%s draw:%s draw" % [type, @black.name, @white.name])
243   end
244 end
245
246 class GameResultSennichiteDraw < GameResultDraw
247   def process
248     @players.each do |player|
249       player.write_safe("#SENNICHITE\n#DRAW\n")
250     end
251     log_summary("sennichite")
252     @result_type = "#SENNICHITE"
253     notify
254   end
255 end
256
257 class Game
258   # When this duration passes after this object instanciated (i.e.
259   # the agree_waiting or start_waiting state lasts too long),
260   # the game will be rejected by the Server.
261   WAITING_EXPIRATION = 120 # seconds
262
263   @@mutex = Mutex.new
264   @@time  = 0
265   def initialize(game_name, player0, player1)
266     @monitors = Array::new
267     @game_name = game_name
268     if (@game_name =~ /-(\d+)-(\d+)$/)
269       @total_time = $1.to_i
270       @byoyomi = $2.to_i
271     end
272
273     if (player0.sente)
274       @sente, @gote = player0, player1
275     else
276       @sente, @gote = player1, player0
277     end
278     @sente.socket_buffer.clear
279     @gote.socket_buffer.clear
280     @current_player, @next_player = @sente, @gote
281     @sente.game = self
282     @gote.game  = self
283
284     @last_move = ""
285     @current_turn = 0
286
287     @sente.status = "agree_waiting"
288     @gote.status  = "agree_waiting"
289
290     @game_id = sprintf("%s+%s+%s+%s+%s", 
291                   $league.event, @game_name, 
292                   @sente.name, @gote.name, issue_current_time)
293     
294     # The time when this Game instance was created.
295     # Don't be confused with @start_time when the game was started to play.
296     @prepared_time = Time.now 
297     log_dir_name = File.join($league.dir, 
298                              @prepared_time.strftime("%Y"),
299                              @prepared_time.strftime("%m"),
300                              @prepared_time.strftime("%d"))
301     FileUtils.mkdir_p(log_dir_name) unless File.exist?(log_dir_name)
302     @logfile = File.join(log_dir_name, @game_id + ".csa")
303
304     $league.games[@game_id] = self
305
306     log_message(sprintf("game created %s", @game_id))
307
308     @board = Board::new
309     @board.initial
310     @start_time = nil
311     @fh = open(@logfile, "w")
312     @fh.sync = true
313     @result = nil
314
315     propose
316   end
317   attr_accessor :game_name, :total_time, :byoyomi, :sente, :gote, :game_id, :board, :current_player, :next_player, :fh, :monitors
318   attr_accessor :last_move, :current_turn
319   attr_reader   :result, :prepared_time
320
321   def rated?
322     @sente.rated? && @gote.rated?
323   end
324
325   def turn?(player)
326     return player.status == "game" && @current_player == player
327   end
328
329   def monitoron(monitor)
330     @monitors.delete(monitor)
331     @monitors.push(monitor)
332   end
333
334   def monitoroff(monitor)
335     @monitors.delete(monitor)
336   end
337
338   def each_monitor
339     @monitors.each do |monitor|
340       yield monitor
341     end
342   end
343
344   def log_game(str)
345     if @fh.closed?
346       log_error("Failed to write to Game[%s]'s log file: %s" %
347                 [@game_id, str])
348     end
349     @fh.printf("%s\n", str)
350   end
351
352   def reject(rejector)
353     @sente.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
354     @gote.write_safe(sprintf("REJECT:%s by %s\n", @game_id, rejector))
355     finish
356   end
357
358   def kill(killer)
359     [@sente, @gote].each do |player|
360       if ["agree_waiting", "start_waiting"].include?(player.status)
361         reject(killer.name)
362         return # return from this method
363       end
364     end
365     
366     if (@current_player == killer)
367       result = GameResultAbnormalWin.new(self, @next_player, @current_player)
368       result.process
369       finish
370     end
371   end
372
373   def finish
374     log_message(sprintf("game finished %s", @game_id))
375     @fh.printf("'$END_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))    
376     @fh.close
377
378     @sente.game = nil
379     @gote.game = nil
380     @sente.status = "connected"
381     @gote.status = "connected"
382
383     if (@current_player.protocol == LoginCSA::PROTOCOL)
384       @current_player.finish
385     end
386     if (@next_player.protocol == LoginCSA::PROTOCOL)
387       @next_player.finish
388     end
389     @monitors = Array::new
390     @sente = nil
391     @gote = nil
392     @current_player = nil
393     @next_player = nil
394     $league.games.delete(@game_id)
395   end
396
397   # class Game
398   def handle_one_move(str, player)
399     unless turn?(player)
400       return false if str == :timeout
401
402       @fh.puts("'Deferred %s" % [str])
403       log_warning("Deferred a move [%s] scince it is not %s 's turn." %
404                   [str, player.name])
405       player.socket_buffer << str # always in the player's thread
406       return nil
407     end
408
409     finish_flag = true
410     @end_time = Time::new
411     t = [(@end_time - @start_time).floor, Least_Time_Per_Move].max
412     
413     move_status = nil
414     if ((@current_player.mytime - t <= -@byoyomi) && 
415         ((@total_time > 0) || (@byoyomi > 0)))
416       status = :timeout
417     elsif (str == :timeout)
418       return false            # time isn't expired. players aren't swapped. continue game
419     else
420       @current_player.mytime -= t
421       if (@current_player.mytime < 0)
422         @current_player.mytime = 0
423       end
424
425       move_status = @board.handle_one_move(str, @sente == @current_player)
426       # log_debug("move_status: %s for %s's %s" % [move_status, @sente == @current_player ? "BLACK" : "WHITE", str])
427
428       if [:illegal, :uchifuzume, :oute_kaihimore].include?(move_status)
429         @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
430       else
431         if [:normal, :outori, :sennichite, :oute_sennichite_sente_lose, :oute_sennichite_gote_lose].include?(move_status)
432           # Thinking time includes network traffic
433           @sente.write_safe(sprintf("%s,T%d\n", str, t))
434           @gote.write_safe(sprintf("%s,T%d\n", str, t))
435           @fh.printf("%s\nT%d\n", str, t)
436           @last_move = sprintf("%s,T%d", str, t)
437           @current_turn += 1
438         end
439
440         @monitors.each do |monitor|
441           monitor.write_safe(show.gsub(/^/, "##[MONITOR][#{@game_id}] "))
442           monitor.write_safe(sprintf("##[MONITOR][%s] +OK\n", @game_id))
443         end
444       end
445     end
446
447     result = nil
448     if (@next_player.status != "game") # rival is logout or disconnected
449       result = GameResultAbnormalWin.new(self, @current_player, @next_player)
450     elsif (status == :timeout)
451       # current_player losed
452       result = GameResultTimeoutWin.new(self, @next_player, @current_player)
453     elsif (move_status == :illegal)
454       result = GameResultIllegalMoveWin.new(self, @next_player, @current_player)
455     elsif (move_status == :kachi_win)
456       result = GameResultKachiWin.new(self, @current_player, @next_player)
457     elsif (move_status == :kachi_lose)
458       result = GameResultIllegalKachiWin.new(self, @next_player, @current_player)
459     elsif (move_status == :toryo)
460       result = GameResultToryoWin.new(self, @next_player, @current_player)
461     elsif (move_status == :outori)
462       # The current player captures the next player's king
463       result = GameResultOutoriWin.new(self, @current_player, @next_player)
464     elsif (move_status == :oute_sennichite_sente_lose)
465       result = GameResultOuteSennichiteWin.new(self, @gote, @sente) # Sente is checking
466     elsif (move_status == :oute_sennichite_gote_lose)
467       result = GameResultOuteSennichiteWin.new(self, @sente, @gote) # Gote is checking
468     elsif (move_status == :sennichite)
469       result = GameResultSennichiteDraw.new(self, @current_player, @next_player)
470     elsif (move_status == :uchifuzume)
471       # the current player losed
472       result = GameResultUchifuzumeWin.new(self, @next_player, @current_player)
473     elsif (move_status == :oute_kaihimore)
474       # the current player losed
475       result = GameResultOuteKaihiMoreWin.new(self, @next_player, @current_player)
476     else
477       finish_flag = false
478     end
479     result.process if result
480     finish() if finish_flag
481     @current_player, @next_player = @next_player, @current_player
482     @start_time = Time::new
483     return finish_flag
484   end
485
486   def start
487     log_message(sprintf("game started %s", @game_id))
488     @sente.write_safe(sprintf("START:%s\n", @game_id))
489     @gote.write_safe(sprintf("START:%s\n", @game_id))
490     @sente.mytime = @total_time
491     @gote.mytime = @total_time
492     @start_time = Time::new
493   end
494
495   def propose
496     @fh.puts("V2")
497     @fh.puts("N+#{@sente.name}")
498     @fh.puts("N-#{@gote.name}")
499     @fh.puts("$EVENT:#{@game_id}")
500
501     @sente.write_safe(propose_message("+"))
502     @gote.write_safe(propose_message("-"))
503
504     now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
505     @fh.puts("$START_TIME:#{now}")
506     @fh.print <<EOM
507 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
508 P2 * -HI *  *  *  *  * -KA * 
509 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
510 P4 *  *  *  *  *  *  *  *  * 
511 P5 *  *  *  *  *  *  *  *  * 
512 P6 *  *  *  *  *  *  *  *  * 
513 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
514 P8 * +KA *  *  *  *  * +HI * 
515 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
516 +
517 EOM
518     if rated?
519       black_name = @sente.rated? ? @sente.player_id : @sente.name
520       white_name = @gote.rated?  ? @gote.player_id  : @gote.name
521       @fh.puts("'rating:%s:%s" % [black_name, white_name])
522     end
523   end
524
525   def show()
526     str0 = <<EOM
527 BEGIN Game_Summary
528 Protocol_Version:1.1
529 Protocol_Mode:Server
530 Format:Shogi 1.0
531 Declaration:Jishogi 1.1
532 Game_ID:#{@game_id}
533 Name+:#{@sente.name}
534 Name-:#{@gote.name}
535 Rematch_On_Draw:NO
536 To_Move:+
537 BEGIN Time
538 Time_Unit:1sec
539 Total_Time:#{@total_time}
540 Byoyomi:#{@byoyomi}
541 Least_Time_Per_Move:#{Least_Time_Per_Move}
542 Remaining_Time+:#{@sente.mytime}
543 Remaining_Time-:#{@gote.mytime}
544 Last_Move:#{@last_move}
545 Current_Turn:#{@current_turn}
546 END Time
547 BEGIN Position
548 EOM
549
550     str1 = <<EOM
551 END Position
552 END Game_Summary
553 EOM
554
555     return str0 + @board.to_s + str1
556   end
557
558   def propose_message(sg_flag)
559     str = <<EOM
560 BEGIN Game_Summary
561 Protocol_Version:1.1
562 Protocol_Mode:Server
563 Format:Shogi 1.0
564 Declaration:Jishogi 1.1
565 Game_ID:#{@game_id}
566 Name+:#{@sente.name}
567 Name-:#{@gote.name}
568 Your_Turn:#{sg_flag}
569 Rematch_On_Draw:NO
570 To_Move:+
571 BEGIN Time
572 Time_Unit:1sec
573 Total_Time:#{@total_time}
574 Byoyomi:#{@byoyomi}
575 Least_Time_Per_Move:#{Least_Time_Per_Move}
576 END Time
577 BEGIN Position
578 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
579 P2 * -HI *  *  *  *  * -KA * 
580 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
581 P4 *  *  *  *  *  *  *  *  * 
582 P5 *  *  *  *  *  *  *  *  * 
583 P6 *  *  *  *  *  *  *  *  * 
584 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
585 P8 * +KA *  *  *  *  * +HI * 
586 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
587 P+
588 P-
589 +
590 END Position
591 END Game_Summary
592 EOM
593     return str
594   end
595
596   def prepared_expire?
597     if @prepared_time && (@prepared_time + WAITING_EXPIRATION < Time.now)
598       return true
599     end
600
601     return false
602   end
603   
604   private
605   
606   def issue_current_time
607     time = Time::new.strftime("%Y%m%d%H%M%S").to_i
608     @@mutex.synchronize do
609       while time <= @@time do
610         time += 1
611       end
612       @@time = time
613     end
614   end
615 end
616
617 end # ShogiServer