Class: Piece

Inherits:
Object
  • Object
show all
Defined in:
lib/pieces/piece.rb

Direct Known Subclasses

Pawn, SlidingPiece, SteppingPiece

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(board, color, pos) ⇒ Piece

Returns a new instance of Piece.



6
7
8
9
10
11
# File 'lib/pieces/piece.rb', line 6

def initialize(board, color, pos)
  @board = board
  @color = color
  @pos = pos
  @moved = false
end

Instance Attribute Details

#colorObject (readonly)

Returns the value of attribute color.



3
4
5
# File 'lib/pieces/piece.rb', line 3

def color
  @color
end

#movedObject

Returns the value of attribute moved.



4
5
6
# File 'lib/pieces/piece.rb', line 4

def moved
  @moved
end

#posObject

Returns the value of attribute pos.



4
5
6
# File 'lib/pieces/piece.rb', line 4

def pos
  @pos
end

Instance Method Details

#dup(dup_board) ⇒ Object



25
26
27
# File 'lib/pieces/piece.rb', line 25

def dup(dup_board)
  self.class.new(dup_board, @color, @pos.dup)
end

#in_range_of_enemy?Boolean

Returns:

  • (Boolean)


13
14
15
16
17
18
19
# File 'lib/pieces/piece.rb', line 13

def in_range_of_enemy?
  @color == :white ? enemy_color = :black : enemy_color = :white
  @board.pieces(enemy_color).each do |piece|
    return true if piece.valid_moves.include?(@pos)
  end
  false
end

#move_into_check?(move) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
36
37
# File 'lib/pieces/piece.rb', line 33

def move_into_check?(move)
  duped_board = @board.deep_dup
  duped_board.move!(self.pos, move)
  duped_board.in_check?(@color)
end

#sum_positions(pos1, pos2) ⇒ Object



39
40
41
# File 'lib/pieces/piece.rb', line 39

def sum_positions(pos1, pos2)
  [pos1.first + pos2.first, pos1.last + pos2.last]
end

#symbolObject



21
22
23
# File 'lib/pieces/piece.rb', line 21

def symbol
  raise NotImplementedError.new ("No symbol!")
end

#valid_movesObject



29
30
31
# File 'lib/pieces/piece.rb', line 29

def valid_moves
  moves.reject { |move| move_into_check?(move) }
end