-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpiece.rb
More file actions
148 lines (112 loc) · 2.56 KB
/
Copy pathpiece.rb
File metadata and controls
148 lines (112 loc) · 2.56 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
require_relative 'board'
class Piece
RED_DELTAS = [[-1, -1], [-1, 1]]
BLACK_DELTAS = [[1, -1], [1, 1]]
attr_accessor :pos, :color, :grid, :kinged
def initialize(pos, color, grid)
@color, @pos, @grid = color, pos, grid
self.grid
@kinged = false
end
def to_s
"#{self.color}"
end
def move(to_pos)
if slide_moves.include?(to_pos)
move_slide(to_pos)
elsif jump_moves.include?(to_pos)
move_jump(to_pos)
else
raise "ERROR! can't move there."
end
king_check(to_pos)
nil
end
def valid_move_seq?(moves)
start_pos = pos
test_grid = self.grid.dup
begin
test_grid[start_pos].perform_moves!(moves)
rescue
return false
end
true
end
def perform_moves!(moves)
if moves.size == 1
move(moves.first)
else
queue = moves
until queue.empty?
if jump_moves.include?(queue.first)
move_jump(queue.shift)
else
raise ArgumentError "ERROR! invalid jump"
end
end
end
nil
end
# private
def deltas
return RED_DELTAS + BLACK_DELTAS if self.kinged
(self.color == :r) ? RED_DELTAS : BLACK_DELTAS
end
def move_slide(to_pos)
if grid[to_pos].nil?
grid.move!(self.pos,to_pos)
else
raise "ERROR! in slide move"
end
nil
end
def slide_moves
possible_moves = []
row, col = self.pos
deltas.each do |delta|
row_delta, col_delta = delta
move = [row + row_delta, col + col_delta]
possible_moves << move if self.grid[move].nil?
end
possible_moves
end
def move_jump(to_pos)
from, to = self.pos, to_pos
if grid.on_board?(to)
grid.move!(from, to)
clear_jumped_space(from, to)
else
raise "ERROR! Can't jump there."
end
end
def jump_moves
possible_jumps = []
row, col = self.pos
deltas.each do |delta|
row_delta, col_delta = delta
possible_jumps << [row + (2 * row_delta), col + (2 * col_delta)]
end
possible_jumps
end
def clear_jumped_space(from_pos, to_pos)
start_x, start_y = from_pos
end_x, end_y = to_pos
jumped_x = ((start_x + end_x) / 2)
jumped_y = ((start_y + end_y) / 2)
grid.clear_space([jumped_x, jumped_y])
end
def king_check(pos)
row, col = pos
self.kinged = true if row == 0 || row == 7
end
end
if __FILE__ == $PROGRAM_NAME
board = Board.new
board.add_piece([2,2], :r)
board.add_piece([1,3], :b)
board.render
board[[2,2]].move([0,4])
board.render
board[[0,4]].move([1,3])
board.render
end