-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
94 lines (77 loc) · 2.94 KB
/
main.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
import time
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock
from sudoku import Sudoku
class SudokuGame(FloatLayout):
# Initialize the grid of text inputs
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.text_inputs = []
self.error_messages = []
grid = self.ids["grid"]
for i in range(81):
text_input = SudokuCell()
grid.add_widget(text_input)
self.text_inputs.append(text_input)
# Test grid: supposedly the most complicated Sudoku in the world
# self.text_inputs[ 0].text = "8";
# self.text_inputs[11].text = "3";
# self.text_inputs[12].text = "6";
# self.text_inputs[19].text = "7";
# self.text_inputs[22].text = "9";
# self.text_inputs[24].text = "2";
# self.text_inputs[28].text = "5";
# self.text_inputs[32].text = "7";
# self.text_inputs[40].text = "4";
# self.text_inputs[41].text = "5";
# self.text_inputs[42].text = "7";
# self.text_inputs[48].text = "1";
# self.text_inputs[52].text = "3";
# self.text_inputs[56].text = "1";
# self.text_inputs[61].text = "6";
# self.text_inputs[62].text = "8";
# self.text_inputs[65].text = "8";
# self.text_inputs[66].text = "5";
# self.text_inputs[70].text = "1";
# self.text_inputs[73].text = "9";
# self.text_inputs[78].text = "4";
# Get the value in a given cell
# Return 0 if no value is specified
def get_value(self, row, col):
text = self.text_inputs[9 * row + col].text
return int(text) if len(text) > 0 else 0
# Solve the current board
def solve(self):
# Read values from the grid
values = [[self.get_value(row, col) for col in range(9)] for row in range(9)]
# Try to solve the Sudoku
solver = Sudoku(values)
if solver.solve():
for row in range(9):
for col in range(9):
self.text_inputs[9 * row + col].text = str(solver.get_value(row, col))
else:
error_message = ErrorMessage()
self.error_messages.append(error_message)
self.add_widget(error_message)
Clock.schedule_once(self.remove_error_message, 2)
# Remove the last error message on screen
def remove_error_message(self, dt):
error_message = self.error_messages.pop()
self.remove_widget(error_message)
# Remove all values on the board
def clear(self):
for text_input in self.ids["grid"].children:
text_input.text = ""
class SudokuCell(TextInput):
pass
class ErrorMessage(Label):
pass
class SudokuApp(App):
def build(self):
return SudokuGame()
if __name__ == '__main__':
SudokuApp().run()