3 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
4 ## Copyright (C) 2007-2012 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" or
47 # moves with times. Ex "+776FU,T2-3334FU,T5"
48 # @return an array of a move string. Ex. ["+7776FU", "-3334FU"] or
49 # an array of arrays. Ex. [["+7776FU","T2"], ["-3334FU", "T5"]]
51 def Board.split_moves(moves)
57 if moves[i,1] == "+" ||
60 if i == moves.size - 1
66 raise WrongMoves, a[0]
68 if a.size == 1 # "+7776FU"
71 unless /^T\d+/ =~ a[1]
72 raise WrongMoves, a[1]
87 def initialize(move_count=0)
88 @sente_hands = Array::new
89 @gote_hands = Array::new
90 @history = Hash::new(0)
91 @sente_history = Hash::new(0)
92 @gote_history = Hash::new(0)
93 @array = [[], [], [], [], [], [], [], [], [], []]
94 @move_count = move_count
95 @teban = nil # black => true, white => false
98 @ous = [nil, nil] # keep OU pieces of Sente and Gote
100 attr_accessor :array, :sente_hands, :gote_hands, :history, :sente_history, :gote_history, :teban
101 attr_reader :move_count
103 # Initial moves for a Buoy game. If it is an empty array, the game is
104 # normal with the initial setting; otherwise, the game is started after the
106 attr_reader :initial_moves
108 # A move parsed by handle_one_move. If the move is not :normal, the board
109 # position may or may not be rolled back.
113 # See if self equals rhs, including a logical board position (i.e.
114 # not see object IDs) and sennichite stuff.
117 return @teban == rhs.teban &&
118 @move_count == rhs.move_count &&
120 @history == rhs.history &&
121 @sente_history == rhs.sente_history &&
122 @gote_history == rhs.gote_history &&
123 @initial_moves == rhs.initial_moves
127 return Marshal.load(Marshal.dump(self))
131 PieceKY::new(self, 1, 1, false)
132 PieceKE::new(self, 2, 1, false)
133 PieceGI::new(self, 3, 1, false)
134 PieceKI::new(self, 4, 1, false)
135 PieceOU::new(self, 5, 1, false)
136 PieceKI::new(self, 6, 1, false)
137 PieceGI::new(self, 7, 1, false)
138 PieceKE::new(self, 8, 1, false)
139 PieceKY::new(self, 9, 1, false)
140 PieceKA::new(self, 2, 2, false)
141 PieceHI::new(self, 8, 2, false)
143 PieceFU::new(self, i, 3, false)
146 PieceKY::new(self, 1, 9, true)
147 PieceKE::new(self, 2, 9, true)
148 PieceGI::new(self, 3, 9, true)
149 PieceKI::new(self, 4, 9, true)
150 PieceOU::new(self, 5, 9, true)
151 PieceKI::new(self, 6, 9, true)
152 PieceGI::new(self, 7, 9, true)
153 PieceKE::new(self, 8, 9, true)
154 PieceKY::new(self, 9, 9, true)
155 PieceKA::new(self, 8, 8, true)
156 PieceHI::new(self, 2, 8, true)
158 PieceFU::new(self, i, 7, true)
164 # Piece#new will call back this method.
174 # Set up a board with the strs.
175 # Failing to parse the moves raises an StandardError.
176 # @param strs a board text
178 def set_from_str(strs)
179 strs.each_line do |str|
182 str.sub!(/^P(.)/, '')
185 while (str.length > 2)
186 str.sub!(/^(...?)/, '')
188 if (one =~ /^([\+\-])(..)/)
196 if ((x < 1) || (9 < x) || (y < 1) || (9 < y))
197 raise "bad position #{x} #{y}"
201 PieceFU::new(self, x, y, sente)
203 PieceKY::new(self, x, y, sente)
205 PieceKE::new(self, x, y, sente)
207 PieceGI::new(self, x, y, sente)
209 PieceKI::new(self, x, y, sente)
211 PieceOU::new(self, x, y, sente)
213 PieceKA::new(self, x, y, sente)
215 PieceHI::new(self, x, y, sente)
217 PieceFU::new(self, x, y, sente, true)
219 PieceKY::new(self, x, y, sente, true)
221 PieceKE::new(self, x, y, sente, true)
223 PieceGI::new(self, x, y, sente, true)
225 PieceKA::new(self, x, y, sente, true)
227 PieceHI::new(self, x, y, sente, true)
229 raise "unkown piece #{name}"
242 while (str.length > 3)
243 str.sub!(/^..(..)/, '')
247 PieceFU::new(self, 0, 0, sente)
249 PieceKY::new(self, 0, 0, sente)
251 PieceKE::new(self, 0, 0, sente)
253 PieceGI::new(self, 0, 0, sente)
255 PieceKI::new(self, 0, 0, sente)
257 PieceKA::new(self, 0, 0, sente)
259 PieceHI::new(self, 0, 0, sente)
261 raise "unkown piece #{name}"
269 raise "bad line: #{str}"
274 # Set up a board starting with a position after the moves.
275 # Failing to parse the moves raises an ArgumentError.
276 # @param moves an array of moves. ex. ["+7776FU", "-3334FU"] or
277 # an array of arrays. ex. [["+7776FU","T2"], ["-3334FU","T5"]]
279 def set_from_moves(moves)
281 return :normal if moves.empty?
287 rt = handle_one_move(move[0], @teban)
289 rt = handle_one_move(move, @teban)
291 raise ArgumentError, "bad moves: #{moves}" unless rt == :normal
293 @initial_moves = moves.dup
296 def have_piece?(hands, name)
297 piece = hands.find { |i|
303 # :illegal and :outori do not change this instance (self).
306 x0, x1, y0, y1, name, sente = move.x0, move.x1, move.y0, move.y1, move.name, move.sente
314 piece = have_piece?(hands, name)
315 return :illegal if (piece == nil || ! piece.move_to?(x1, y1, name))
316 piece.move_to(x1, y1)
318 if (@array[x0][y0] == nil || !@array[x0][y0].move_to?(x1, y1, name))
321 if (@array[x1][y1] && @array[x1][y1].name == "OU")
325 # Change the state of this instance (self)
326 if (@array[x0][y0].name != name && !@array[x0][y0].promoted)
327 # the piece is promoting
328 @array[x0][y0].promoted = true
329 move.promotion = true
331 if (@array[x1][y1]) # capture
332 move.set_captured_piece(@array[x1][y1])
333 @array[x1][y1].sente = @array[x0][y0].sente
334 @array[x1][y1].move_to(0, 0)
335 hands.sort! {|a, b| # TODO refactor. Move to Piece class
339 @array[x0][y0].move_to(x1, y1)
342 @teban = @teban ? false : true
346 # Get back the previous move, which moved a name piece from [x0,y0] to
347 # [x1, y1] with or without promotion. If the move captured
348 # a piece, it is captured_piece, which is now in hand. The captured_piece
349 # was promoted or unpromoted.
358 piece = @array[move.x1][move.y1]
362 piece.move_to(move.x0, move.y0)
363 piece.promoted = false if piece.promoted && move.promotion
364 if move.captured_piece
365 move.captured_piece.move_to(move.x1, move.y1)
366 move.captured_piece.sente = move.sente ? false : true
367 move.captured_piece.promoted = true if move.captured_piece_promoted
372 @teban = @teban ? false : true
376 # def each_reserved_square
378 def look_for_ou(sente)
386 # See if sente is checked (i.e. loosing) or not.
387 # Note that the method name "checkmated?" is wrong. Instead, it should be
390 def checkmated?(sente)
391 ou = look_for_ou(sente)
397 (@array[x][y].sente != sente))
398 if (@array[x][y].movable_grids.include?([ou.x, ou.y]))
409 # See if sente's FU drop checkmates the opponent or not.
411 def uchifuzume?(sente)
412 rival_ou = look_for_ou(! sente) # rival's ou
413 if (sente) # rival is gote
414 if ((rival_ou.y != 9) &&
415 (@array[rival_ou.x][rival_ou.y + 1]) &&
416 (@array[rival_ou.x][rival_ou.y + 1].name == "FU") &&
417 (@array[rival_ou.x][rival_ou.y + 1].sente == sente)) # uchifu true
419 fu_y = rival_ou.y + 1
424 if ((rival_ou.y != 1) &&
425 (@array[rival_ou.x][rival_ou.y - 1]) &&
426 (@array[rival_ou.x][rival_ou.y - 1].name == "FU") &&
427 (@array[rival_ou.x][rival_ou.y - 1].sente == sente)) # uchifu true
429 fu_y = rival_ou.y - 1
435 ## case: rival_ou is moving
436 rival_ou.movable_grids.each do |(cand_x, cand_y)|
437 tmp_board = deep_copy
438 s = tmp_board.move_to(Move.new(rival_ou.x, rival_ou.y, cand_x, cand_y, "OU", ! sente))
439 raise "internal error" if (s != true)
440 if (! tmp_board.checkmated?(! sente)) # good move
445 ## case: rival is capturing fu
451 (@array[x][y].sente != sente) &&
452 @array[x][y].movable_grids.include?([fu_x, fu_y])) # capturable
455 if (@array[x][y].promoted)
456 names << @array[x][y].promoted_name
458 names << @array[x][y].name
459 if @array[x][y].promoted_name &&
460 @array[x][y].move_to?(fu_x, fu_y, @array[x][y].promoted_name)
461 names << @array[x][y].promoted_name
465 tmp_board = deep_copy
466 s = tmp_board.move_to(Move.new(x, y, fu_x, fu_y, name, ! sente))
470 tmp_board.checkmated?(! sente) # result
473 all_illegal = names.find {|a| a != :illegal}
474 raise "internal error: legal move not found" if all_illegal == nil
475 r = names.find {|a| a == false} # good move
476 return false if r == false # found good move
485 # @[sente|gote]_history has at least one item while the player is checking the other or
487 def update_sennichite(player)
490 if checkmated?(!player)
492 @sente_history["dummy"] = 1 # flag to see Sente player is checking Gote player
494 @gote_history["dummy"] = 1 # flag to see Gote player is checking Sente player
498 @sente_history.clear # no more continuous check
500 @gote_history.clear # no more continuous check
503 if @sente_history.size > 0 # possible for Sente's or Gote's turn
504 @sente_history[str] += 1
506 if @gote_history.size > 0 # possible for Sente's or Gote's turn
507 @gote_history[str] += 1
511 # Deep-copy sennichite stuff, which will later be available to restore.
513 def dup_sennichite_stuff
514 return [@history.dup, @sente_history.dup, @gote_history.dup]
517 # Restore sennihite stuff.
519 def restore_sennichite_stuff(history, sente_history, gote_history)
520 @history, @sente_history, @gote_history = history, sente_history, gote_history
523 def oute_sennichite?(player)
524 return nil unless sennichite?
528 if (@sente_history[to_s] >= 4) # sente is checking gote
529 return :oute_sennichite_sente_lose
530 elsif (@gote_history[to_s] >= 3) # sente is escaping
531 return :oute_sennichite_gote_lose
533 return nil # Not oute_sennichite, but sennichite
537 if (@gote_history[to_s] >= 4) # gote is checking sente
538 return :oute_sennichite_gote_lose
539 elsif (@sente_history[to_s] >= 3) # gote is escaping
540 return :oute_sennichite_sente_lose
542 return nil # Not oute_sennichite, but sennichite
548 if (@history[to_s] >= 4) # already 3 times
554 def good_kachi?(sente)
555 if (checkmated?(sente))
556 puts "'NG: Checkmating." if $DEBUG
560 ou = look_for_ou(sente)
561 if (sente && (ou.y >= 4))
562 puts "'NG: Black's OU does not enter yet." if $DEBUG
565 if (! sente && (ou.y <= 6))
566 puts "'NG: White's OU does not enter yet." if $DEBUG
584 (@array[x][y].sente == sente) &&
585 (@array[x][y].point > 0))
586 point = point + @array[x][y].point
592 hands.each do |piece|
593 point = point + piece.point
597 puts "'NG: Piece#[%d] is too small." % [number] if $DEBUG
602 puts "'NG: Black's point#[%d] is too small." % [point] if $DEBUG
607 puts "'NG: White's point#[%d] is too small." % [point] if $DEBUG
612 puts "'Good: Piece#[%d], Point[%d]." % [number, point] if $DEBUG
616 # sente is nil only if tests in test_board run
623 # - :oute_sennichite_sente_lose
624 # - :oute_sennichite_gote_lose
628 # - (:outori will not be returned)
631 def handle_one_move(str, sente=nil)
632 if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
639 elsif (str =~ /^%KACHI/)
640 raise ArgumentError, "sente is null", caller if sente == nil
641 if (good_kachi?(sente))
646 elsif (str =~ /^%TORYO/)
652 if (((x0 == 0) || (y0 == 0)) && # source is not from hand
653 ((x0 != 0) || (y0 != 0)))
655 elsif ((x1 == 0) || (y1 == 0)) # destination is out of board
660 sente = true if sente == nil # deprecated
661 return :illegal unless sente == true # black player's move must be black
664 sente = false if sente == nil # deprecated
665 return :illegal unless sente == false # white player's move must be white
670 if ((x0 == 0) && (y0 == 0))
671 return :illegal if (! have_piece?(hands, name))
672 elsif (! @array[x0][y0])
673 return :illegal # no piece
674 elsif (@array[x0][y0].sente != sente)
675 return :illegal # this is not mine
676 elsif (@array[x0][y0].name != name)
677 return :illegal if (@array[x0][y0].promoted_name != name) # can't promote
681 if (@array[x1][y1] &&
682 (@array[x1][y1].sente == sente)) # can't capture mine
684 elsif ((x0 == 0) && (y0 == 0) && @array[x1][y1])
685 return :illegal # can't put on existing piece
688 @move = Move.new(x0, y0, x1, y1, name, sente)
689 result = move_to(@move)
690 if (result == :illegal)
694 if (checkmated?(sente))
696 return :oute_kaihimore
698 if ((x0 == 0) && (y0 == 0) && (name == "FU") && uchifuzume?(sente))
703 sennichite_stuff = dup_sennichite_stuff
704 update_sennichite(sente)
705 os_result = oute_sennichite?(sente)
706 if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
708 restore_sennichite_stuff(*sennichite_stuff)
713 restore_sennichite_stuff(*sennichite_stuff)
717 # New rule that CSA introduced in November 2014.
718 # If a game with 256 plies does not end, make the game a draw.
719 # When running test cases $options might be nil.
720 if $options && $options["max-moves"] &&
721 $options["max-moves"] > 0 && @move_count >= $options["max-moves"]
728 # Return a CSA-styled string notation of the current position.
734 a.push(sprintf("P%d", y))
746 a.push(sprintf("\n"))
749 if (! sente_hands.empty?)
751 sente_hands.each do |p|
752 a.push("00" + p.name)
756 if (! gote_hands.empty?)
758 gote_hands.each do |p|
759 a.push("00" + p.name)
763 a.push("%s\n" % [@teban ? "+" : "-"])
767 # Return a CSA-styled string notation of the initial position.
770 tmp_board = self.class.new
772 return tmp_board.to_s