-
Notifications
You must be signed in to change notification settings - Fork 0
/
board.rb
97 lines (73 loc) · 1.94 KB
/
board.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
require_relative 'pieces.rb'
require_relative 'checkers_errors.rb'
class Board
COLORS = { w: 1, b: -1 }
attr_accessor :board
attr_reader :size
def initialize(size = 8, clean_board = false)
# size should be even! There are no rulesets for odd-sized checkers boards.
# Behavior with an odd-sized board is undefined.
@size = size
@board = Array.new(@size) { Array.new(@size) }
# Note: player's rightmost square is light
# => only dark squares are occupied
# => Thus: x_x_x_x_ would be a back row
COLORS.each_key { |color| populate(color) } unless clean_board == true
end
def dup
board_dup = Board.new(@size, true)
@board.each_with_index do |row, x|
row.each_with_index do |el, y|
board_dup[[y,x]] = el.dup(board_dup) unless el.nil?
end
end
board_dup
end
def [](pos)
x, y = pos
@board[y][x]
end
def []=(pos, piece)
x, y = pos
@board[y][x] = piece
end
def render
rendering = ""
(@board.count - 1).downto(0) do |x|
rendering << (x + 1).to_s
@size.times do |y|
el = @board[x][y]
rendering << (el.nil? ? " " : el.to_s.concat(" "))
end
rendering << "\n"
end
rendering += " 1 2 3 4 5 6 7 8 \n"
end
def game_over? # debug method
piece_count = [0, 0]
pieces = @board.flatten.compact
pieces.each do |piece|
idx = piece.color == :w ? 0 : 1
piece_count[idx] += 1
end
piece_count.any? { |x| x == 0 }
end
private
def populate(color)
start = (color == :w ? 0 : @size - 1)
sense = COLORS[color]
# Populate all but the center two rows.
# Typical of most checkers variants.
(size / 2 - 1).times do |dy|
(@size / 2).times do |dx|
y = start + (dy * sense)
x = y % 2 + dx * 2
Piece.new(self, [x,y], color)
end
end
end
end # end of class Board
if $PROGRAM_NAME == __FILE__
board = Board.new
puts board.render
end