-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkers_piece.rb
60 lines (45 loc) · 1.26 KB
/
checkers_piece.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Piece #red on bottom, black moves first
attr_accessor :board, :pos, :king
attr_reader :color
UPDELTAS = [[-1,1],[-1,-1]]
DOWNDELTAS = [[1,1],[1,-1]]
def initialize(color, board, pos, king = false)
@color, @board, @pos, @king = color,board, pos, king
end
def possible_moves
jump_moves.empty? ? slide_moves : jump_moves
end
def jump_moves
my_deltas.map do |delta|
slide = pos.add_delta(delta)
next unless board.in_bounds?(slide) && enemy?(slide)
slide.add_delta(delta)
end.compact.keep_if { |jump| board.valid_pos?(jump) }
end
def slide_moves
my_deltas.map do |delta|
pos.add_delta(delta)
end.keep_if { |pos| board.valid_pos?(pos) }
end
def enemy?(pos)#move to board?
return false if board.empty?(pos)
board[pos].color != color
end
def my_deltas
return (UPDELTAS + DOWNDELTAS) if king
color == :r ? UPDELTAS : DOWNDELTAS
end
def render
player = color == :r ? "red" : "bla"
king ? player.upcase : player
end
end
class Array
def add_delta(delta, &prc)
self.dup.add_delta!(delta, &prc)
end
def add_delta!(delta, &prc)
prc = Proc.new{ |x,y| x + y } unless prc
self.each_with_index { |item,index| self[index] = prc.call(item,delta[index]) }
end
end