OSDN Git Service

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