-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudokugui.py
264 lines (203 loc) · 7.75 KB
/
sudokugui.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import argparse
from sudoku import solve
from tkinter import Tk, Canvas, Frame, Button, BOTH, BOTTOM, TOP
boards = ['n00b', 'pr0', 'debug', 'error']
margin = 20
cellSide = 50
WIDTH = HEIGHT = margin*2 + cellSide*9
class SudokuError(Exception):
"""
An Exception Occured!
"""
pass
class SudokuBoard(object):
"""Board Representation"""
def __init__(self, sudFile):
self.board = self.__createBoard(sudFile)
def __createBoard(self, sudFile):
board = []
for line in sudFile:
line = line.strip()
if len(line) != 9:
raise SudokuError(f"{line} contains more or less than 9 characters!")
board.append([])
for char in line:
if char.isdigit():
board[-1].append(int(char))
else:
raise SudokuError(f"{char} in {line} is not a Number")
if len(board)!=9:
raise SudokuError("Board does not contain 9 lines")
return board
class SudokuGame(object):
"""Stores state of game and checks if it has won!"""
def __init__(self, boardFile):
self.boardFile = boardFile
self.startPuzzle = SudokuBoard(boardFile).board
def start(self):
self.gameOver = False
self.puzzle = []
for i in range(9):
self.puzzle.append([])
for j in range(9):
self.puzzle[i].append(self.startPuzzle[i][j])
def is_valid(self, i, j, n, bo):
if n==0:
return False
x = 3
if(bo[i].count(n)==0 and [rows[j] for rows in bo].count(n)==0):
for p in range(i-(i%x),i+x-(i%x)):
for q in range(j-(j%x),j+x-(j%x)):
if bo[p][q]==n:
return False
return True
return False
def check_win(self):
for row in range(9):
if not self.__check_row(row):
return False
for column in range(9):
if not self.__check_column(column):
return False
for row in range(3):
for column in range(3):
if not self.__check_square(row, column):
return False
self.gameOver = True
return True
def __check_block(self, block):
return set(block) == set(range(1, 10))
def __check_row(self, row):
return self.__check_block(self.puzzle[row])
def __check_column(self, column):
return self.__check_block(
[self.puzzle[row][column] for row in range(9)]
)
def __check_square(self, row, column):
return self.__check_block(
[
self.puzzle[r][c]
for r in range(row * 3, (row + 1) * 3)
for c in range(column * 3, (column + 1) * 3)
]
)
class SudokuUI(Frame):
"""This will draw UI and accept user input"""
def __init__(self, parent, game):
self.game = game
self.parent = parent
Frame.__init__(self, parent)
self.row = 0
self.col = 0
self.__initUI()
def __initUI(self):
self.parent.title("Sudoku")
self.pack(fill=BOTH, expand=1)
self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
self.canvas.pack(fill=BOTH, side=TOP)
clearButton = Button(self, text="Clear ALL", command=self.__clearAnswers)
clearButton.pack(side=BOTTOM, fill=BOTH)
solveButton = Button(self, text="Solve?", command=self.__solve)
solveButton.pack(side=BOTTOM, fill=BOTH)
self.__drawGrid()
self.__drawPuzzle()
self.canvas.bind("<Button-1>", self.__cellClicked)
self.canvas.bind("<Key>", self.__keyPressed)
def __solve(self):
self.__clearAnswers()
solve(self.game.puzzle)
self.__drawPuzzle()
self.__drawSolved()
def __drawGrid(self):
for x in range(10):
color = 'red' if x%3==0 else 'black'
x0 = margin + x * cellSide
y0 = margin
x1 = margin + x * cellSide
y1 = HEIGHT - margin
p0 = margin
q0 = margin + x * cellSide
p1 = WIDTH - margin
q1 = margin + x * cellSide
self.canvas.create_line(x0, y0, x1, y1, fill=color)
self.canvas.create_line(p0, q0, p1, q1, fill=color)
def __drawPuzzle(self):
self.canvas.delete("numbers")
for i in range(9):
for j in range(9):
answer = self.game.puzzle[i][j]
if answer!=0:
x = margin + j * cellSide + cellSide/2
y = margin + i * cellSide + cellSide/2
original = self.game.startPuzzle[i][j]
color = "black" if answer==original else "sea green"
self.canvas.create_text(x, y, text=answer, tags="numbers", fill=color)
def __clearAnswers(self):
self.game.start()
self.canvas.delete("victory")
self.canvas.delete("solved")
self.__drawPuzzle()
def __cellClicked(self, event):
if self.game.gameOver:
return
x, y = event.x, event.y
if (margin < x < WIDTH - margin and margin < y < HEIGHT - margin):
self.canvas.focus_set()
row, col = int((y - margin) / cellSide), int((x - margin) / cellSide)
if (row, col) == (self.row, self.col):
self.row, self.col = -1, -1
elif self.game.startPuzzle[row][col] == 0:
self.row, self.col = row, col
else:
self.row, self.col = -1, -1
self.__drawCursor()
def __drawCursor(self):
self.canvas.delete("cursors")
if(self.row>=0 and self.col>=0):
x0 = margin + self.col * cellSide
y0 = margin + self.row * cellSide
self.canvas.create_rectangle(x0, y0, x0 + cellSide, y0 + cellSide, outline = "red", tags = "cursors")
def __keyPressed(self, event):
if self.game.gameOver:
print(1)
return
if self.row>=0 and self.col>=0 and event.char in "1234567890":
self.game.puzzle[self.row][self.col] = int(event.char)
self.row, self.col = -1, -1
self.__drawPuzzle()
self.__drawCursor()
if self.game.check_win():
self.__drawVictory()
def __drawVictory(self):
x0 = y0 = margin + cellSide
x1 = y1 = margin + cellSide * 8
self.canvas.create_oval(x0, y0, x1, y1, tags = "victory", fill="black", outline="red")
x = y = margin + cellSide * 4 + cellSide/2
self.canvas.create_text(x, y, text="YOU WON!", tags="victory", fill="red", font=("Arial", 32))
def __drawSolved(self):
y0 = margin + HEIGHT - cellSide
y1 = margin + HEIGHT - cellSide/2
x0 = margin + cellSide
x1 = WIDTH - cellSide
self.canvas.create_rectangle(x0, y0, x1, y1, tags = "solved", fill="black", outline="red")
x = (x0+x1)/2
y = (y0+y1)/2
self.canvas.create_text(x, y, text="I solved IT!! Not YOU!!", tags="solved", fill="red", font=("Arial", 14))
def parse_arguments():
"""
Parses arguments of the form:
sudoku_gui.py <board name>
"""
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--board", help="desired board name", type=str, choices=boards, required=True)
args = arg_parser.parse_args()
return args.board
if __name__ == "__main__":
boardSelected = parse_arguments()
with open("%s.sudoku" % boardSelected, 'r') as boardFile:
game = SudokuGame(boardFile)
game.start()
root = Tk()
SudokuUI(root, game)
root.geometry("%dx%d" % (WIDTH, HEIGHT+100))
root.mainloop()