-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathgrid.py
81 lines (65 loc) · 1.66 KB
/
grid.py
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
class Grid:
def __init__(self):
self.grid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
def pretty_print(self):
h_line = '+---+---+---+'
for row in self.grid:
print(h_line)
print('|', end='')
for cell in row:
print(f' {cell} |', end='')
print() # Newline at the end of the row
print(h_line)
@staticmethod
def cartesian_to_array(x, y):
row = 2 - y
col = x
return row, col
def is_complete(self):
return self.number_filled_cells() == 9
def score_complete_grid(self):
if not self.is_complete():
raise Exception("Grid is incomplete!")
total = 0
for row in self.grid:
row_total = row[0] * 100 + row[1] * 10 + row[2]
total += row_total
return abs(total - 1000)
def is_grid_empty(self):
return self.number_filled_cells() == 0
def number_filled_cells(self):
filled = 0
for row in self.grid:
for cell in row:
if cell > 0:
filled += 1
return filled
def set_value(self, x, y, val):
if self.has_value_been_set(x, y):
raise Exception("Cannot overwrite value")
row, col = self.cartesian_to_array(x, y)
self.grid[row][col] = val
def get_value(self, x, y):
row, col = self.cartesian_to_array(x, y)
return self.grid[row][col]
def has_value_been_set(self, x, y):
row, col = self.cartesian_to_array(x, y)
return self.grid[row][col] != 0
def fill_next_empty_space(self, val):
col = 2
while col > -1:
row = 0
while row < 3:
if (self.grid[row][col] == 0):
self.grid[row][col] = val
return
row += 1
col -= 1
def eval_column(self, x):
return sum([val[x] for val in self.grid])
def main():
grid = Grid()
grid.set_value(2, 2, 6)
grid.pretty_print()
if __name__ == "__main__":
main()