-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpiece.rb
135 lines (115 loc) · 2.39 KB
/
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
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
require_relative 'board'
require_relative 'exceptions'
class Piece
SLIDES_W = [
[ 1, 1],
[ 1,-1]
]
SLIDES_B = [
[-1, 1],
[-1,-1]
]
JUMPS_W = [
[ 2, 2],
[ 2,-2]
]
JUMPS_B = [
[-2, 2],
[-2,-2]
]
attr_accessor :promoted, :position, :board
attr_reader :color
def initialize(board, color, position, promoted = false)
@board = board
@color = color
@position = position
@promoted = promoted
end
def perform_slide(pos)
if slide_moves.include?([@position[0] - pos[0],@position[1]-pos[1]])
@board[pos] = @board[@position]
@board[@position] = nil
@position = pos
return true
end
return false
end
def perform_jump(pos)
jumped_piece = jump_direction(pos)
if jump_moves.include?([@position[0]-pos[0],@position[1]-pos[1]]) && @board[jumped_piece].color != self.color
@board[pos] = @board[@position]
@board[@position] = nil
@position = pos
@board[jumped_piece] = nil
return true
end
return false
end
def jump_direction(pos)
x,y = pos
if @position[0] > pos[0]
x+=1
else
x-=1
end
if @position[1] > pos[1]
y+=1
else
y-=1
end
[x,y]
end
def slide_moves
if promoted == true
SLIDES_W + SLIDES_B
elsif @color == :white
SLIDES_W
else
SLIDES_B
end
end
def jump_moves
if promoted == true
JUMPS_W + JUMPS_B
elsif @color == :white
JUMPS_W
else
JUMPS_B
end
end
def perform_moves(move_sequence)
valid_move_seq?(self.position, move_sequence)
perform_moves!(move_sequence)
end
def perform_moves!(move_sequence)
p move_sequence
if move_sequence.count == 1
mover = (perform_slide(move_sequence.flatten) || perform_jump(move_sequence.flatten))
raise InvalidMoveError.new("Invalid Jump") if mover == false
end
if move_sequence.count >= 2
p move_sequence
move_sequence.each do |move|
p move_sequence
raise InvalidMoveError.new("Invalid Jump") if perform_jump(move) == false
perform_jump(move)
end
end
@board.pieces.each { |piece| piece.king? }
end
def valid_move_seq?(piece, move_sequence)
duped_board = @board.dup
duped_board[piece].perform_moves!(move_sequence)
end
def king?
if self.position[0] == 0 && self.color == :white
@promoted = true
elsif self.position[0] == 7 && self.color == :red
@promoted = true
end
end
def to_s
return "X".colorize(:color => @color) if self.promoted == true
return "O".colorize(:color => @color)
end
end