-
Notifications
You must be signed in to change notification settings - Fork 0
/
pawn.rb
39 lines (28 loc) · 902 Bytes
/
pawn.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# encoding: utf-8
class Pawn < Piece
DELTAS = [[1, 0], [2, 0], [1, 1], [1, -1]]
def moves
moves = []
# scalar multiplication flips deltas:
# white => positive, black => negative
if @color == :white
deltas = DELTAS
else
deltas = DELTAS.map {|x,y| [x*-1, y*-1]}
end
poss_moves = deltas.map {|dx,dy| [@pos[0]+dx, @pos[1]+dy]}
moves << poss_moves[0] unless @board.get_spot(poss_moves[0])
moves << poss_moves[1] if move_two?(moves, poss_moves[1])
2.times { |i| moves << poss_moves[i+2] if capture?(poss_moves[i+2]) }
moves
end
def move_two?(moves, poss_move)
(@pos[0] == 1 || @pos[0] == 6) && moves.size == 1 && @board.get_spot(poss_move).nil?
end
def capture?(poss_move)
@board.get_spot(poss_move) && @board.get_spot(poss_move).color != @color
end
def display
@color == :white ? "♙" : "♟"
end
end