forked from jrandow/Sudoku-Solver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudokusolver_GUI.py
176 lines (152 loc) · 6.4 KB
/
sudokusolver_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
import pandas as pd
import numpy as np
from typing import Optional, List
import random
import copy
import sys
import time
class Sudoku():
def __init__(self, puzzle: Optional[List[int]] = None, list_label = None) -> None: # TODO: Optional on list_label
self.puzzle = puzzle
self.list_label = list_label
self.do_save_puzzle = True
self.guessed_numbers = [[[],[],[],[],[],[],[],[],[]],[[],[],[],[],[],[],[],[],[]],[[],[],[],[],[],[],[],[],[]],[[],[],[],[],[],[],[],[],[]],[[],[],[],[],[],[],[],[],[]],[[],[],[],[],[],[],[],[],[]],[[],[],[],[],[],[],[],[],[]],[[],[],[],[],[],[],[],[],[]],[[],[],[],[],[],[],[],[],[]]]
self.guessed = 0
self.blocks = self.set_blocks() # soll permanent abhängig von puzzle sein und sich entsprechend dem puzzle immer gleich mitändern
def get_cols(self):
"""
Return the puzzle columnwise.
return: cols
"""
cols = []
for i in range(len(self.puzzle)):
col = []
for val in self.puzzle:
col.append(val[i])
cols.append(col)
return cols
def set_blocks(self):
block1 = []
block2 = []
block3 = []
block4 = []
block5 = []
block6 = []
block7 = []
block8 = []
block9 = []
for row in range(len(self.puzzle)):
for col in range(len(self.puzzle)):
if row < 3 and col < 3:
block1.append(self.puzzle[row][col])
elif row < 3 and 2 < col < 6:
block2.append(self.puzzle[row][col])
elif row < 3 and col > 5:
block3.append(self.puzzle[row][col])
elif 2 < row < 6 and col < 3:
block4.append(self.puzzle[row][col])
elif 2 < row < 6 and 2 < col < 6:
block5.append(self.puzzle[row][col])
elif 2 < row < 6 and col > 5:
block6.append(self.puzzle[row][col])
elif row > 5 and col < 3:
block7.append(self.puzzle[row][col])
elif row > 5 and 2 < col < 6:
block8.append(self.puzzle[row][col])
elif row > 5 and col > 5:
block9.append(self.puzzle[row][col])
return list([block1,block2,block3,block4,block5,block6,block7,block8,block9])
def draw(self):
"""
Draw the board on GUI (currently not working, because board can't update)
"""
#test
puzzle_list = self.puzzle[0] + self.puzzle[1] + self.puzzle[2] + self.puzzle[3] + self.puzzle[4] + self.puzzle[5] + self.puzzle[6] + self.puzzle[7] + self.puzzle[8]
for i, label in enumerate(self.list_label):
label.setText(str(puzzle_list[i]))
def fillBoard(self):
"""
Iterates through the board and fills it based on the possible numbers for each field.
"""
rows = self.puzzle
cols = self.get_cols()
#blocks = self.get_blocks()
for n in range(1,10):
for row in range(len(self.puzzle)):
for col in range(len(self.puzzle)):
if self.puzzle[row][col] == 0:
numbers = self.possibleNumbers(row,col,rows,cols,self.blocks)
if len(numbers) == 1:
if self.do_save_puzzle:
self.puzzle_save = list(map(list, self.puzzle))
self.do_save_puzzle = False
self.puzzle[row][col] = numbers[0]
# self.puzzle_save.append(self.puzzle)
return #in case n = 1
# the following only happens when there is no unique possible number
if len(numbers) == n: #beginning with n = 2
self.guess = random.choice(numbers)
self.puzzle[row][col] = self.guess
return
self.guessed_numbers[row][col].append(self.guess) # the last guessed (but only the very last for sure) number was wrong
self.guessed += 1
self.puzzle = list(map(list, self.puzzle_save))
def possibleNumbers(self,row,col,rows,cols,blocks):
"""
Returns possible numbers.
"""
numbers = []
matching_row = rows[row]
matching_col = cols[col]
if row < 3 and col < 3:
matching_block = blocks[0]
elif row < 3 and 2 < col < 6:
matching_block = blocks[1]
elif row < 3 and col > 5:
matching_block = blocks[2]
elif 2 < row < 6 and col < 3:
matching_block = blocks[3]
elif 2 < row < 6 and 2 < col < 6:
matching_block = blocks[4]
elif 2 < row < 6 and col > 5:
matching_block = blocks[5]
elif row > 5 and col < 3:
matching_block = blocks[6]
elif row > 5 and 2 < col < 6:
matching_block = blocks[7]
else:
matching_block = blocks[8]
for nr in range(1,10):
if nr not in matching_row and nr not in matching_col and nr not in matching_block and nr not in self.guessed_numbers[row][col]:
numbers.append(nr)
return numbers
def countZeros(self):
"""
Returns the zeros (not filled fileds) on the board.
"""
counter = 0
for i in self.puzzle:
counter += i.count(0)
return counter
def solveSudoku(self):
"""
Main method of the Sudoku Solver.
Breaks if Sudoku is solved (success) or iterations exceed 10000 attempts (fail).
"""
iterations = 0
while True:
self.draw()
#time.sleep(1) # to see what happens
freeSpaces = self.countZeros()
#print("There are", freeSpaces, "free spaces left.")
if freeSpaces == 0:
print("The Sudoku has been solved!")
print("It took", iterations, "iterations.")
print(self.guessed, "time(s) a number has been guessed.")
break
if iterations == 10000:
print("It took", iterations, "iterations.")
print("The Sudoku could not be solved. Try again with another one.")
break
self.fillBoard()
iterations += 1