Class: Pawn

Inherits:
Piece show all
Defined in:
lib/ari_chess/pieces/pawn.rb

Constant Summary collapse

CAPTURE_DELTAS =
[
  [1, -1], #capture
  [1,  1], #capture
]
STEP_DELTA =
[
  [1,  0] #anytime
]
DOUBLE_STEP_DELTA =
[
  [2,  0], #first move
]

Instance Attribute Summary collapse

Attributes inherited from Piece

#board, #color, #pos

Instance Method Summary collapse

Methods inherited from Piece

#move_into_check?, #next_pos, #valid_moves, #valid_pos?

Constructor Details

#initialize(pos, board, color) ⇒ Pawn

Returns a new instance of Pawn.



19
20
21
22
# File 'lib/ari_chess/pieces/pawn.rb', line 19

def initialize(pos, board, color)
  super
  @first_move = true
end

Instance Attribute Details

#first_moveObject

Returns the value of attribute first_move.



17
18
19
# File 'lib/ari_chess/pieces/pawn.rb', line 17

def first_move
  @first_move
end

Instance Method Details

#capturable_positionsObject



62
63
64
65
66
# File 'lib/ari_chess/pieces/pawn.rb', line 62

def capturable_positions
  deltas(CAPTURE_DELTAS).map { |delta| new_pos(delta) }.select do |position|
    !board[position].nil? && board[position].color != color
  end
end

#deltas(specific_deltas) ⇒ Object



75
76
77
# File 'lib/ari_chess/pieces/pawn.rb', line 75

def deltas(specific_deltas)
  color == :B ? specific_deltas : specific_deltas.map { |dx, dy| [dx * -1, dy] }
end

#double_step_posObject



55
56
57
58
59
60
# File 'lib/ari_chess/pieces/pawn.rb', line 55

def double_step_pos
  position = new_pos(deltas(DOUBLE_STEP_DELTA).first)
  return position if board[position].nil?

  []
end

#dup(new_board) ⇒ Object



28
29
30
31
32
33
# File 'lib/ari_chess/pieces/pawn.rb', line 28

def dup(new_board)
  copy = super
  copy.first_move = first_move

  copy
end

#first_move?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/ari_chess/pieces/pawn.rb', line 24

def first_move?
  @first_move
end

#movesObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/ari_chess/pieces/pawn.rb', line 35

def moves
  possible_moves = []

  possible_moves.concat(capturable_positions)

  step_pos = new_pos(deltas(STEP_DELTA).first)

  if board[step_pos].nil?
    possible_moves << step_pos
  else
    return possible_moves
  end

  if first_move?
    possible_moves << double_step_pos unless double_step_pos.empty?
  end

  possible_moves
end

#new_pos(delta) ⇒ Object



68
69
70
71
72
73
# File 'lib/ari_chess/pieces/pawn.rb', line 68

def new_pos(delta)
  x, y = pos
  dx, dy = delta

  [x + dx, y + dy]
end

#to_sObject



84
85
86
# File 'lib/ari_chess/pieces/pawn.rb', line 84

def to_s
  color == :W ? "\u2659" : "\u265F"
end

#update_piece(pos) ⇒ Object



79
80
81
82
# File 'lib/ari_chess/pieces/pawn.rb', line 79

def update_piece(pos)
  super
  self.first_move = false
end