-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpiece.rb
More file actions
executable file
·110 lines (83 loc) · 1.89 KB
/
piece.rb
File metadata and controls
executable file
·110 lines (83 loc) · 1.89 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
require_relative 'board'
require_relative 'checkers_errors'
class Piece
COLOR_DIR = { :black => 1, :red => -1 }
include CheckersErrors
attr_reader :board, :color, :pos
def initialize(board = Board.new, color = :red, pos = [0, 0])
@color = color
@pos = pos
@board = board
@board[pos] = self
@first_move = true
@delta = COLOR_DIR[color]
end
attr_reader :delta
def move(new_pos)
board[self.pos] = nil
board[new_pos] = self
self.pos = new_pos
end
def moves
jump_moves + vanilla_moves
end
def jump_moves
moves = []
y = self.pos[0] + 2 * delta
[2, -2].each do |d|
x = self.pos[1] + d
if on_board?([y, x])
skipped = board[ board.middle([y,x], self.pos) ]
unless skipped.nil?
moves << [y,x] if board[[y, x]].nil? && skipped.color != self.color
end
end
end
moves
end
def vanilla_moves
moves = []
y = self.pos[0] + delta
x = self.pos[1] + 1
moves << [y,x] if on_board?([y, x]) && board[[y, x]].nil?
x = self.pos[1] - 1
moves << [y,x] if on_board?([y, x]) && board[[y, x]].nil?
moves
end
def at_end?
self.color == :red ? self.pos[0] == 0 : self.pos[0] == 7
end
def on_board?(pos)
pos[0].between?(0,7) && pos[1].between?(0,7)
end
def legal_jump_moves # I don't think I actually need .legal? anymore.
jump_moves.select { |jump_move| legal?(jump_move) }
end
def valid_moves
return jump_moves unless jump_moves.empty?
return moves if board.pieces(color).all?{ |piece| piece.jump_moves.empty? }
[]
end
def render
'◉'.colorize(color)
end
protected
attr_writer :pos
end
class King < Piece
def moves
@delta = -1
down_moves = super
@delta = 1
up_moves = super
down_moves + up_moves
end
def render
'◎'.colorize(color)
end
end
class NilClass
def render
' '
end
end