Class: ConsoleShogi::PieceMovementChecker
- Inherits:
-
Object
- Object
- ConsoleShogi::PieceMovementChecker
- Defined in:
- lib/console_shogi/piece_movement_checker.rb
Instance Method Summary collapse
- #can_move? ⇒ Boolean
-
#initialize(board:, from:, to:) ⇒ PieceMovementChecker
constructor
A new instance of PieceMovementChecker.
Constructor Details
#initialize(board:, from:, to:) ⇒ PieceMovementChecker
Returns a new instance of PieceMovementChecker.
5 6 7 8 9 |
# File 'lib/console_shogi/piece_movement_checker.rb', line 5 def initialize(board:, from:, to:) @board = board @from = from @to = to end |
Instance Method Details
#can_move? ⇒ Boolean
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/console_shogi/piece_movement_checker.rb', line 11 def can_move? return false unless board.within_range?(x: to[:x], y: to[:y]) diff = {x: to[:x] - from[:x], y: to[:y] - from[:y]} return false if from_piece.moves.none? {|m| m[:x] == diff[:x] && m[:y] == diff[:y] } return false if from_piece.teban == to_piece.teban return true unless from_piece.can_move_long_distance? distance = (diff[:x].nonzero? || diff[:y]).abs element = [diff[:x] / distance, diff[:y] / distance] 1.upto(distance - 1) do |d| piece = board.fetch_piece(x: from[:x] + element[0] * d, y: from[:y] + element[1] * d) return false unless piece.none? end true end |