-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudoku_gui.py
308 lines (261 loc) · 12 KB
/
sudoku_gui.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 24 20:53:19 2014
@author: jerry.prawiharjo
"""
from Tkinter import *
from tkFileDialog import *
from tkMessageBox import *
import sudoku_solver
import time
class StatusBar(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.label = Label(self, bd=1, relief=RAISED, anchor=W, font = ('Helvetica','14'))
self.label.pack(fill=X)
def set(self, format, *args):
self.label.config(text=format % args)
self.label.update_idletasks()
def clear(self):
self.label.config(text="")
self.label.update_idletasks()
class MainForm(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.Sudoku = sudoku_solver.Sudoku()
self.initUI()
def initUI(self):
self.parent.title("Sudoku Solver")
self.pack(fill=BOTH, expand=1)
self.UserInput = False
self.Editable = False
self.UnoccColor = "#fb0"
self.OccColor = 'green'
self.file_opt = options = {}
options['defaultextension'] = '.txt'
options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
options['initialdir'] = '.'
options['initialfile'] = ''
options['parent'] = self
toolbar = Frame(self,bd = 1, relief = RAISED)
self.Tfont = ('Helvetica','12','bold')
b = Button(toolbar, text = 'Open', width=6, command=self.onOpen, font = self.Tfont)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="Save", width=6, command=self.onSave, font = self.Tfont)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="Solve", width=6, command=self.onSolve, font = self.Tfont)
b.pack(side=LEFT, padx=2, pady=2)
self.btnClear = Button(toolbar, text="User Input", width=8,
command=self.onUser, font = self.Tfont)
self.btnClear.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="About", width=6, command=self.onAbout, font = self.Tfont)
b.pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)
self.Cfont = ('Helvetica','24','bold')
self.Length = 50
self.Space = 10
self.InitX = 30
self.InitY = 30
self.canvas = Canvas(self)
self.canvas.pack()
self.CreateGrid()
self.initFillGrid()
self.canvas.bind("<Double-Button-1>", self.set_focus)
self.canvas.bind("<Button-1>", self.set_focus)
self.canvas.bind("<Key>", self.handle_key)
self.status = StatusBar(self.parent)
self.status.pack(side=BOTTOM, fill=X)
def onOpen(self):
self.clearSudokuGrid()
filename = askopenfile(**self.file_opt)
if filename:
Lines = filename.readlines()
filename.close()
self.SudokuList = []
if len(Lines) < 9:
self.status.set("Error! File contains less than 9 columns")
return False
else:
for ll in Lines[0:9]:
ll = map(int,ll.rstrip('\n').split(','))
if len(ll) < 9:
self.status.set("Line %i ontains less than 9 values",(ll+1))
return False
else:
self.SudokuList.extend(ll)
self.status.set("Input file successfully parsed")
self.Sudoku.SudokuList = self.SudokuList
self.setSudokuProblemGrid()
self.UserInput = False
self.Editable = True
def onSave(self):
if self.Sudoku.Solved:
self.status.set("Saving solution grid...")
filename = asksaveasfilename(title = 'Saving Solution',**self.file_opt)
if filename != "":
if self.Sudoku.write_csv(filename):
self.status.set("Solution successfully saved")
else:
self.status.set("There was an error when attempting to save output file")
else:
self.status.set("Output file not saved. No filename supplied")
elif self.Sudoku.Initialized:
self.status.set("Saving current Sudoku grid")
filename = asksaveasfilename(title = 'Saving Current Grid',**self.file_opt)
if filename != "":
if self.Sudoku.write_csv(filename,Solution = False):
self.status.set("Current grid is successfully saved")
elif self.UserInput:
self.status.set("Saving current Sudoku grid")
self.Sudoku.SudokuList = self.SudokuList
filename = asksaveasfilename(title = 'Saving Current Grid',**self.file_opt)
if filename != "":
if self.Sudoku.write_csv(filename,Solution = False):
self.status.set("Current grid is successfully saved")
else:
self.status.set("!There is nothing to save!")
def onSolve(self):
if self.UserInput or self.Editable:
self.Sudoku.SudokuList = self.SudokuList
if self.Sudoku.Initialized:
Tstart = time.clock()
success = self.Sudoku.Solve()
Telapsed = time.clock() - Tstart
if success:
self.status.set("Solution found in %0.3f s", Telapsed)
self.setSudokuSolutionGrid()
self.Editable = False
self.UserInput = False
else:
if not(self.Sudoku.CheckMinClue):
self.status.set("Sudoku does not have the minimum number of clues [%i]"
%self.Sudoku.MinClue)
elif not(self.Sudoku.ValidateProblem):
self.status.set("Sudoku problem is ill-posed")
else:
self.status.set("Failed find solution")
else:
self.status.set("No problem found")
def onUser(self):
self.UserInput = True
self.Sudoku.Clear()
self.SudokuList = [0] * 81
self.clearSudokuGrid()
self.status.set("User input mode. Directly input values in the grid")
self.focus()
def setSudokuSolutionGrid(self):
SudokuList = self.Sudoku.SudokuSolution
for kk in range(81):
self.canvas.itemconfigure(self.GridText[kk],text = SudokuList[kk])
def setSudokuProblemGrid(self):
SudokuList = self.Sudoku.SudokuList
for kk in range(81):
if SudokuList[kk] != 0:
self.canvas.itemconfigure(self.GridText[kk],text = SudokuList[kk])
self.canvas.itemconfigure(self.Grid[kk],fill = self.OccColor, outline = self.OccColor)
def clearSudokuGrid(self):
for kk in range(81):
self.canvas.itemconfigure(self.Grid[kk],outline=self.UnoccColor, fill=self.UnoccColor)
self.canvas.itemconfigure(self.GridText[kk],text = " ")
self.Sudoku.Initialized = False
self.status.clear()
def CreateGrid(self):
Length = self.Length
Space = self.Space
InitX = self.InitX
InitY = self.InitY
self.Grid = []
for ky in range(9):
for kx in range(9):
self.Grid.append(self.canvas.create_rectangle(InitX + kx * (Length + Space),
InitY + ky * (Length + Space),
InitX + Length + kx * (Length + Space),
InitY + Length + ky * (Length + Space),
outline=self.UnoccColor, fill=self.UnoccColor))
for kx in range(4):
self.canvas.create_line(InitX - 5 + kx * 3 * (Length + Space), InitY - 5,
InitX - 5 + kx * 3 * (Length + Space), InitY - 5 + Length * 9 + Space * 9, width = 3)
for kx in range(4):
self.canvas.create_line(InitX - 5, InitY - 5 + kx * 3 * (Length + Space),
InitX - 5 + Length * 9 + Space * 9, InitY - 5 + kx * 3 * (Length + Space), width = 3 )
self.canvas.pack(side = TOP, fill=BOTH, expand = 1)
def initFillGrid(self):
inGrid = range(81)
if len(inGrid) == 81:
self.GridText = []
for ky in range(9):
for kx in range(9):
self.GridText.append(self.canvas.create_text(self.InitX + self.Length/2 + kx * (self.Length + self.Space),
self.InitY + self.Length/2 + ky * (self.Length + self.Space),
text=' ',font=self.Cfont))
def set_focus(self, event):
if self.canvas.type(CURRENT) != "text":
return
if self.UserInput or self.Editable:
self.canvas.focus_set() # move focus to canvas
self.canvas.focus(CURRENT) # set focus to text item
self.canvas.select_from(CURRENT, 0)
self.canvas.select_to(CURRENT, END)
def handle_key(self, event):
item = self.canvas.focus()
if not item:
return
itemindex = int(item) - self.GridText[0]
insert = self.canvas.index(item, INSERT)
AllowedChars = '123456789'
if event.char in AllowedChars:
if self.canvas.select_item():
self.canvas.dchars(item, SEL_FIRST, SEL_LAST)
self.canvas.select_clear()
if insert == 1:
self.canvas.dchars(item, insert-1, insert)
if insert <= 1:
self.canvas.insert(item, "insert", event.char)
elif event.keysym == "BackSpace":
if self.canvas.select_item():
self.canvas.dchars(item, SEL_FIRST, SEL_LAST)
self.canvas.select_clear()
else:
if insert > 0:
self.canvas.dchars(item, insert-1, insert)
elif event.keysym == "Right":
self.canvas.icursor(item, insert+1)
self.canvas.select_clear()
elif event.keysym == "Left":
self.canvas.icursor(item, insert-1)
self.canvas.select_clear()
else:
pass
CurrentText = self.canvas.itemcget(self.GridText[itemindex],'text')
if len(CurrentText) > 1:
self.canvas.itemconfigure(self.GridText[itemindex], text = CurrentText[0])
if self.canvas.itemcget(self.GridText[itemindex],'text') == '':
self.canvas.itemconfigure(self.GridText[itemindex], text = ' ')
if self.canvas.itemcget(self.GridText[itemindex],'text') in AllowedChars:
self.canvas.itemconfigure(self.Grid[itemindex], fill = self.OccColor, outline = self.OccColor)
self.SudokuList[itemindex] = int(self.canvas.itemcget(self.GridText[itemindex],'text'))
elif self.canvas.itemcget(self.GridText[itemindex],'text') == '':
self.canvas.itemconfigure(self.Grid[itemindex], fill=self.UnoccColor, outline=self.UnoccColor)
self.SudokuList[itemindex] = 0
else:
self.canvas.itemconfigure(self.Grid[itemindex], fill=self.UnoccColor, outline=self.UnoccColor)
self.SudokuList[itemindex] = 0
def onAbout(self):
showinfo("About",
"""Sudoku Solver in Python by Jerry Prawiharjo
Open: Opens txt file containing Sudoku grid in csv format
User can edit the loaded grid.
Save: Saves either sudoku solution grid or current grid
to a txt file in csv format
Solve: Attempts to solve loaded Sudoku grid.
User cannot edit the solved grid
User Input: Clears grid and let user to input own grid""")
def main():
root = Tk()
app = MainForm(root)
root.geometry("590x670+200+100")
root.resizable(0,0)
root.mainloop()
if __name__ == '__main__':
main()