/
board.rb
54 lines (45 loc) · 1.14 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
# Encoding: utf-8
require 'forwardable'
module Tictactoe
class Board
include Enumerable
BLANK = nil
attr_reader :width, :number_of_spaces, :number_of_blanks, :number_of_occupied, :blank_spaces
def initialize(width)
@width = width
@number_of_spaces = @number_of_blanks = width**2
@number_of_occupied = 0
@blank_spaces = square_array(width.times.to_a)
@board = Array.new(width) { Array.new(width) { BLANK } }
end
def blank?
@number_of_blanks == @number_of_spaces
end
def place_piece(piece, space)
unless piece == BLANK
@board[space.first][space.last] = piece
@number_of_blanks -= 1
@number_of_occupied += 1
@blank_spaces.delete(space)
end
self
end
def contents_of(space)
@board[space.first][space.last]
end
def to_a
@board.flatten
end
private
def initialize_copy(source)
blank_spaces = @blank_spaces.map(&:dup)
board = @board.map(&:dup)
super
@blank_spaces = blank_spaces
@board = board
end
def square_array(array)
array.product(array)
end
end
end