3 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
4 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
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.
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.
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
20 require 'shogi_server/move'
22 module ShogiServer # for a namespace
24 class WrongMoves < ArgumentError; end
28 # Initial board setup.
29 # The string ends with '+', not a line break.
31 INITIAL_HIRATE_POSITION = (<<-EOF).chomp
32 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
33 P2 * -HI * * * * * -KA *
34 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
38 P7+FU+FU+FU+FU+FU+FU+FU+FU+FU
39 P8 * +KA * * * * * +HI *
40 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
44 # Split a moves line into an array of a move string.
45 # If it fails to parse the moves, it raises WrongMoves.
46 # @param moves a moves line. Ex. "+776FU-3334Fu"
47 # @return an array of a move string. Ex. ["+7776FU", "-3334FU"]
49 def Board.split_moves(moves)
52 rs = moves.gsub %r{[\+\-]\d{4}\w{2}} do |s|
56 raise WrongMoves, rs unless rs.empty?
62 def initialize(move_count=0)
63 @sente_hands = Array::new
64 @gote_hands = Array::new
65 @history = Hash::new(0)
66 @sente_history = Hash::new(0)
67 @gote_history = Hash::new(0)
68 @array = [[], [], [], [], [], [], [], [], [], []]
69 @move_count = move_count
70 @teban = nil # black => true, white => false
72 @ous = [nil, nil] # keep OU pieces of Sente and Gote
74 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history, :teban
75 attr_reader :move_count
77 # Initial moves for a Buoy game. If it is an empty array, the game is
78 # normal with the initial setting; otherwise, the game is started after the
80 attr_reader :initial_moves
82 # See if self equals rhs, including a logical board position (i.e.
83 # not see object IDs) and sennichite stuff.
86 return @teban == rhs.teban &&
87 @move_count == rhs.move_count &&
89 @history == rhs.history &&
90 @sente_history == rhs.sente_history &&
91 @gote_history == rhs.gote_history &&
92 @initial_moves == rhs.initial_moves
96 return Marshal.load(Marshal.dump(self))
100 PieceKY::new(self, 1, 1, false)
101 PieceKE::new(self, 2, 1, false)
102 PieceGI::new(self, 3, 1, false)
103 PieceKI::new(self, 4, 1, false)
104 PieceOU::new(self, 5, 1, false)
105 PieceKI::new(self, 6, 1, false)
106 PieceGI::new(self, 7, 1, false)
107 PieceKE::new(self, 8, 1, false)
108 PieceKY::new(self, 9, 1, false)
109 PieceKA::new(self, 2, 2, false)
110 PieceHI::new(self, 8, 2, false)
112 PieceFU::new(self, i, 3, false)
115 PieceKY::new(self, 1, 9, true)
116 PieceKE::new(self, 2, 9, true)
117 PieceGI::new(self, 3, 9, true)
118 PieceKI::new(self, 4, 9, true)
119 PieceOU::new(self, 5, 9, true)
120 PieceKI::new(self, 6, 9, true)
121 PieceGI::new(self, 7, 9, true)
122 PieceKE::new(self, 8, 9, true)
123 PieceKY::new(self, 9, 9, true)
124 PieceKA::new(self, 8, 8, true)
125 PieceHI::new(self, 2, 8, true)
127 PieceFU::new(self, i, 7, true)
133 # Piece#new will call back this method.
143 # Set up a board with the strs.
144 # Failing to parse the moves raises an StandardError.
145 # @param strs a board text
147 def set_from_str(strs)
148 strs.each_line do |str|
151 str.sub!(/^P(.)/, '')
154 while (str.length > 2)
155 str.sub!(/^(...?)/, '')
157 if (one =~ /^([\+\-])(..)/)
165 if ((x < 1) || (9 < x) || (y < 1) || (9 < y))
166 raise "bad position #{x} #{y}"
170 PieceFU::new(self, x, y, sente)
172 PieceKY::new(self, x, y, sente)
174 PieceKE::new(self, x, y, sente)
176 PieceGI::new(self, x, y, sente)
178 PieceKI::new(self, x, y, sente)
180 PieceOU::new(self, x, y, sente)
182 PieceKA::new(self, x, y, sente)
184 PieceHI::new(self, x, y, sente)
186 PieceFU::new(self, x, y, sente, true)
188 PieceKY::new(self, x, y, sente, true)
190 PieceKE::new(self, x, y, sente, true)
192 PieceGI::new(self, x, y, sente, true)
194 PieceKA::new(self, x, y, sente, true)
196 PieceHI::new(self, x, y, sente, true)
198 raise "unkown piece #{name}"
211 while (str.length > 3)
212 str.sub!(/^..(..)/, '')
216 PieceFU::new(self, 0, 0, sente)
218 PieceKY::new(self, 0, 0, sente)
220 PieceKE::new(self, 0, 0, sente)
222 PieceGI::new(self, 0, 0, sente)
224 PieceKI::new(self, 0, 0, sente)
226 PieceKA::new(self, 0, 0, sente)
228 PieceHI::new(self, 0, 0, sente)
230 raise "unkown piece #{name}"
238 raise "bad line: #{str}"
243 # Set up a board starting with a position after the moves.
244 # Failing to parse the moves raises an ArgumentError.
245 # @param moves an array of moves. ex. ["+7776FU", "-3334FU"]
247 def set_from_moves(moves)
249 return :normal if moves.empty?
252 rt = handle_one_move(move, @teban)
253 raise ArgumentError, "bad moves: #{moves}" unless rt == :normal
255 @initial_moves = moves.dup
258 def have_piece?(hands, name)
259 piece = hands.find { |i|
265 # :illegal and :outori do not change this instance (self).
268 x0, x1, y0, y1, name, sente = move.x0, move.x1, move.y0, move.y1, move.name, move.sente
276 piece = have_piece?(hands, name)
277 return :illegal if (piece == nil || ! piece.move_to?(x1, y1, name))
278 piece.move_to(x1, y1)
280 if (@array[x0][y0] == nil || !@array[x0][y0].move_to?(x1, y1, name))
283 if (@array[x1][y1] && @array[x1][y1].name == "OU")
287 # Change the state of this instance (self)
288 if (@array[x0][y0].name != name && !@array[x0][y0].promoted)
289 # the piece is promoting
290 @array[x0][y0].promoted = true
291 move.promotion = true
293 if (@array[x1][y1]) # capture
294 move.set_captured_piece(@array[x1][y1])
295 @array[x1][y1].sente = @array[x0][y0].sente
296 @array[x1][y1].move_to(0, 0)
297 hands.sort! {|a, b| # TODO refactor. Move to Piece class
301 @array[x0][y0].move_to(x1, y1)
304 @teban = @teban ? false : true
308 # Get back the previous move, which moved a name piece from [x0,y0] to
309 # [x1, y1] with or without promotion. If the move captured
310 # a piece, it is captured_piece, which is now in hand. The captured_piece
311 # was promoted or unpromoted.
320 piece = @array[move.x1][move.y1]
324 piece.move_to(move.x0, move.y0)
325 piece.promoted = false if piece.promoted && move.promotion
326 if move.captured_piece
327 move.captured_piece.move_to(move.x1, move.y1)
328 move.captured_piece.sente = move.sente ? false : true
329 move.captured_piece.promoted = true if move.captured_piece_promoted
334 @teban = @teban ? false : true
338 # def each_reserved_square
340 def look_for_ou(sente)
348 # See if sente is checked (i.e. loosing) or not.
349 # Note that the method name "checkmated?" is wrong. Instead, it should be
352 def checkmated?(sente)
353 ou = look_for_ou(sente)
359 (@array[x][y].sente != sente))
360 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
371 # See if sente's FU drop checkmates the opponent or not.
373 def uchifuzume?(sente)
374 rival_ou = look_for_ou(! sente) # rival's ou
375 if (sente) # rival is gote
376 if ((rival_ou.y != 9) &&
377 (@array[rival_ou.x][rival_ou.y + 1]) &&
378 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
379 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
381 fu_y = rival_ou.y + 1
386 if ((rival_ou.y != 1) &&
387 (@array[rival_ou.x][rival_ou.y - 1]) &&
388 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
389 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
391 fu_y = rival_ou.y - 1
397 ## case: rival_ou is moving
398 rival_ou.movable_grids.each do |(cand_x, cand_y)|
399 tmp_board = deep_copy
400 s = tmp_board.move_to(Move.new(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente))
401 raise "internal error" if (s != true)
402 if (! tmp_board.checkmated?(! sente)) # good move
407 ## case: rival is capturing fu
413 (@array[x][y].sente != sente) &&
414 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
417 if (@array[x][y].promoted)
418 names << @array[x][y].promoted_name
420 names << @array[x][y].name
421 if @array[x][y].promoted_name &&
422 @array[x][y].move_to?(fu_x, fu_y, @array[x][y].promoted_name)
423 names << @array[x][y].promoted_name
427 tmp_board = deep_copy
428 s = tmp_board.move_to(Move.new(x, y, fu_x, fu_y, name, ! sente))
432 tmp_board.checkmated?(! sente) # result
435 all_illegal = names.find {|a| a != :illegal}
436 raise "internal error: legal move not found" if all_illegal == nil
437 r = names.find {|a| a == false} # good move
438 return false if r == false # found good move
447 # @[sente|gote]_history has at least one item while the player is checking the other or
449 def update_sennichite(player)
452 if checkmated?(!player)
454 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
456 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
460 @sente_history.clear # no more continuous check
462 @gote_history.clear # no more continuous check
465 if @sente_history.size > 0 # possible for Sente's or Gote's turn
466 @sente_history[str] += 1
468 if @gote_history.size > 0 # possible for Sente's or Gote's turn
469 @gote_history[str] += 1
473 # Deep-copy sennichite stuff, which will later be available to restore.
475 def dup_sennichite_stuff
476 return [@history.dup, @sente_history.dup, @gote_history.dup]
479 # Restore sennihite stuff.
481 def restore_sennichite_stuff(history, sente_history, gote_history)
482 @history, @sente_history, @gote_history = history, sente_history, gote_history
485 def oute_sennichite?(player)
486 return nil unless sennichite?
490 if (@sente_history[to_s] >= 4) # sente is checking gote
491 return :oute_sennichite_sente_lose
492 elsif (@gote_history[to_s] >= 3) # sente is escaping
493 return :oute_sennichite_gote_lose
495 return nil # Not oute_sennichite, but sennichite
499 if (@gote_history[to_s] >= 4) # gote is checking sente
500 return :oute_sennichite_gote_lose
501 elsif (@sente_history[to_s] >= 3) # gote is escaping
502 return :oute_sennichite_sente_lose
504 return nil # Not oute_sennichite, but sennichite
510 if (@history[to_s] >= 4) # already 3 times
516 def good_kachi?(sente)
517 if (checkmated?(sente))
518 puts "'NG: Checkmating." if $DEBUG
522 ou = look_for_ou(sente)
523 if (sente && (ou.y >= 4))
524 puts "'NG: Black's OU does not enter yet." if $DEBUG
527 if (! sente && (ou.y <= 6))
528 puts "'NG: White's OU does not enter yet." if $DEBUG
546 (@array[x][y].sente == sente) &&
547 (@array[x][y].point > 0))
548 point = point + @array[x][y].point
554 hands.each do |piece|
555 point = point + piece.point
559 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
564 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
569 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
574 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
578 # sente is nil only if tests in test_board run
585 # - :oute_sennichite_sente_lose
586 # - :oute_sennichite_gote_lose
590 # - (:outori will not be returned)
592 def handle_one_move(str, sente=nil)
593 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
600 elsif (str =~ /^%KACHI/)
601 raise ArgumentError, "sente is null", caller if sente == nil
602 if (good_kachi?(sente))
607 elsif (str =~ /^%TORYO/)
613 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
614 ((x0 != 0) || (y0 != 0)))
616 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
621 sente = true if sente == nil # deprecated
622 return :illegal unless sente == true # black player's move must be black
625 sente = false if sente == nil # deprecated
626 return :illegal unless sente == false # white player's move must be white
631 if ((x0 == 0) && (y0 == 0))
632 return :illegal if (! have_piece?(hands, name))
633 elsif (! @array[x0][y0])
634 return :illegal # no piece
635 elsif (@array[x0][y0].sente != sente)
636 return :illegal # this is not mine
637 elsif (@array[x0][y0].name != name)
638 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
642 if (@array[x1][y1] &&
643 (@array[x1][y1].sente == sente)) # can't capture mine
645 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
646 return :illegal # can't put on existing piece
649 move = Move.new(x0, y0, x1, y1, name, sente)
650 result = move_to(move)
651 if (result == :illegal)
655 if (checkmated?(sente))
657 return :oute_kaihimore
659 if ((x0 == 0) && (y0 == 0) && (name == "FU") && uchifuzume?(sente))
664 sennichite_stuff = dup_sennichite_stuff
665 update_sennichite(sente)
666 os_result = oute_sennichite?(sente)
667 if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
669 restore_sennichite_stuff(*sennichite_stuff)
674 restore_sennichite_stuff(*sennichite_stuff)
681 # Return a CSA-styled string notation of the current position.
687 a.push(sprintf("P%d", y))
699 a.push(sprintf("\n"))
702 if (! sente_hands.empty?)
704 sente_hands.each do |p|
705 a.push("00" + p.name)
709 if (! gote_hands.empty?)
711 gote_hands.each do |p|
712 a.push("00" + p.name)
716 a.push("%s\n" % [@teban ? "+" : "-"])
720 # Return a CSA-styled string notation of the initial position.
723 tmp_board = self.class.new
725 return tmp_board.to_s