-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboard.rb
65 lines (57 loc) · 1.55 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
class Board
attr_accessor :size
def initialize(size)
@grid = []
@size = size
number = 1
@size.times do
row = []
@size.times do
row << number
number += 1
end
@grid << row
end
end
def record_mark(number, mark)
x = (number-1) / @size
y = (number-1) % (@size)
if @grid[x][y] == number
@grid[x][y] = mark
else
return false
end
end
def check_rows(mark)
@grid.each do |square|
return true if square.count(mark) == @size
end
false
end
def check_columns(mark)
@grid.transpose.each do |square|
return true if square.count(mark) == @size
end
false
end
def check_diagonals(mark)
((0...@size).collect { |i| @grid[i][i] }.count(mark) == @size) || ((0...@size).collect { |i| @grid[i][@size-1-i] }.count(mark) == @size)
end
def win?(mark)
(check_rows(mark)) || (check_columns(mark)) || (check_diagonals(mark))
end
def display
dash = "-----"*@size
display = ""
@grid.each do |row|
display_row = ""
row.each do |square|
display_row << " #{square} |" if square.to_i > 9
display_row << " #{square} |" if square.to_i <= 9
end
display << "#{display_row[0..-3]}\n#{dash}\n"
end
subtract = -(dash.length + 2)
puts display[0..subtract]
end
end