Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Piece < ActiveRecord::Base
- belongs_to :game
- self.inheritance_column = :piece_type
- def self.piece_types
- %w(Pawn Rook Knight Bishop Queen King)
- end
- scope :pawns, -> { where(piece_type: 'Pawn') }
- scope :rooks, -> { where(piece_type: 'Rook') }
- scope :knights, -> { where(piece_type: 'Knight') }
- scope :bishops, -> { where(piece_type: 'Bishop') }
- scope :queens, -> { where(piece_type: 'Queen') }
- scope :kings, -> { where(piece_type: 'King') }
- def valid_move?
- # Implement this method in each subclass.
- # Keep this method here for the parent class, in case things go awry.
- raise 'Abstract method'
- end
- # Note: the find_all_pieces helper relies on the current game existing in the
- # instance variable @game. If it ends up being somewhere else, please change
- # that method's second line accordingly.
- def obstructed?(destination_x, destination_y)
- # Sanity-check the prospective move.
- return true if !linear_move?(destination_x, destination_y)
- # Set delta_x and delta_y to -1, 0, or 1, such that adding them to
- # x_coord and y_coord will move one square toward the destination.
- delta_x = destination_x <=> x_coord
- delta_y = destination_y <=> y_coord
- # Move toward the destination one square at a time, stopping and returning
- # true if an obstructing piece is present. Return false upon successfully
- # reaching the destination.
- piece_locations = find_all_pieces
- iterative_x = x_coord
- iterative_y = y_coord
- loop do
- iterative_x += delta_x
- iterative_y += delta_y
- return false if iterative_x == destination_x && iterative_y == destination_y
- return true if piece_locations.include? [iterative_x, iterative_y]
- end
- end
- def linear_move?(destination_x, destination_y)
- # Determine the magnitude of movement along each axis.
- x_movement = (destination_x - x_coord).abs
- y_movement = (destination_y - y_coord).abs
- return false if x_movement == 0 && y_movement == 0
- # If a move is along a rank or file, x_movement or y_movement will be zero.
- # If a move is along a diagonal, x_movement and y_movement will be equal.
- return false unless x_movement == 0 || y_movement == 0 || x_movement == y_movement
- true
- end
- def square_on_board?(destination_x, destination_y)
- return false unless (1..8).cover?(x_coord) && (1..8).cover?(y_coord)
- return false unless (1..8).cover?(destination_x) && (1..8).cover?(destination_y)
- true
- end
- def find_all_pieces
- locations = []
- game.pieces.each do |piece| #REVIEW
- locations << [piece.x_coord, piece.y_coord]
- end
- locations
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement