-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboard.rb
executable file
·42 lines (35 loc) · 1.2 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
class Board
def initialize
clear_grid # initialise multidimensional array to store the marks.
end
# clear the grid from all the marks.
def clear_grid
@grid = Array.new(3).map! { Array.new(3) }
end
# marks a given square on the grid.
def mark symbol, row, column
raise "Square #{row}, #{column} is already taken." if marked? row, column
@grid[row][column] = symbol
end
# check whether a square has been marked.
def marked? row, column
@grid[row][column].nil? ? false : true
end
# return the symbol in a given square.
def get_symbol row, column
marked?(row,column) ? @grid[row][column] : false
end
# check whether the grid is full or not.
def grid_full?
@grid.flatten.map {|symbol| !symbol.nil?}.all?
end
def victory? symbol
winning_row? @grid, symbol or # check row
winning_row? @grid.transpose, symbol or # check column
winning_row? [(0..2).map {|index| @grid[index][index]}, (0..2).map {|index| @grid[index][2-index]}], symbol # check diagonals
end
protected
def winning_row? test_grid, symbol
test_grid.map { |row| row.all? {|mark| mark == symbol } }.any?
end
end