forked from akulakov/simple-games
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudoku.py
executable file
·206 lines (164 loc) · 4.95 KB
/
sudoku.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
#!/usr/bin/env python3
# Imports {{{
import sys
from random import choice as rndchoice
from utils import enumerate1, sjoin, TextInput, space, nl
from board import Board, Loc, BaseTile, Dir
from avkutil import Term
size = 9
blank = '.'
tiletpl = '%2s'
rng3 = range(3)
rng9 = range(9)
offsets = (0, 3, 6)
# in the format produced by QQwing program; just one puzzle for testing
puzzles = [".13.....22.....48....7...19...9..8..7......2....3.......263.9..4.9.7.6....149...8"]
commands = {
'a' : "left",
'd' : "right",
'w' : "up",
's' : "down",
't' : "toggle",
'\n': "move",
' ' : "move",
'q' : "quit",
}
# }}}
class Tile(BaseTile):
initial = blank = False
num = None
def __repr__(self):
return str(self.num) if self.num else blank
def __eq__(self, other):
return bool(self.num == other)
class Number(Tile):
def __init__(self, num):
super(Number, self).__init__()
self.num = int(num)
class Blank(Tile):
pass
class Initial(Number):
pass
class SudokuBoard(Board):
def __init__(self, size, def_tile, puzzle):
super(SudokuBoard, self).__init__(size, def_tile)
self.hl_visible = False
self.current = Loc(0,0)
for tile, val in zip(self, puzzle):
if val != blank:
self[tile] = Initial(val)
self.regions = [self.make_region(xo, yo) for xo in offsets for yo in offsets]
lines = []
for n in rng9:
lines.extend(( [Loc(x, n) for x in rng9], [Loc(n, y) for y in rng9] ))
self.lines = lines
def make_region(self, xo, yo):
"""Make one region at x offset `xo` and y offset `yo`."""
return [ Loc(xo + x, yo + y) for x in rng3 for y in rng3 ]
def draw(self):
print(nl*5)
def ljoin(L):
return sjoin(L, space, tiletpl)
for n, row in enumerate1(self.board):
print(space,
ljoin(row[:3]),
space,
ljoin(row[3:6]),
space,
ljoin(row[6:9]),
nl)
if n in (3,6):
print()
class Sudoku(object):
winmsg = "Solved!"
def valid_move(self, loc, val):
if board[loc].initial:
return False
for reg_line in board.lines + board.regions:
if loc in reg_line and val in (board[loc] for loc in reg_line):
return False
return True
def check_end(self):
if not any(t.blank for t in board):
print(nl, self.winmsg)
sys.exit()
class Commands:
player = None
commands = commands
def __getitem__(self, cmd):
return getattr(self, self.commands[cmd])
def move_dir(self, dir):
loc = board.nextloc(board.current, dir)
self.highlight(loc)
def down(self):
self.move_dir(Dir(0,1))
def up(self):
self.move_dir(Dir(0,-1))
def right(self):
self.move_dir(Dir(1,0))
def left(self):
self.move_dir(Dir(-1,0))
def toggle(self):
if board.hl_visible:
board.hl_visible = False
board.draw()
else:
i = board[board.current]
board[board.current] = '*'
board.draw()
board[board.current] = i
board.hl_visible = True
def move(self, val):
loc = board.current
if sudoku.valid_move(loc, val):
board[loc] = val
board.hl_visible = False
return loc, val
else:
print("Invalid move")
def highlight(self, loc):
if not loc: return
i = board[loc]
board[loc] = '*'
board.draw()
board[loc] = i
board.current = loc
board.hl_visible = True
def quit(self):
sys.exit()
class BasicInterface(object):
def run(self):
self.term = Term()
while True:
board.draw()
loc, val = self.get_move()
board[loc] = Number(val)
sudoku.check_end()
def get_move(self):
"UNUSED."
while True:
cmd = self.textinput.getinput()
if sudoku.valid_move(*cmd):
return cmd
else:
print(self.textinput.invalid_move)
def get_move(self):
while True:
cmd = self.term.getch()
try:
if cmd.isdigit():
val = commands.move(int(cmd))
else:
val = commands[cmd]()
if val:
return val
except KeyError:
print("invalid command:", cmd)
if __name__ == "__main__":
board = SudokuBoard(size, Blank, rndchoice(puzzles))
sudoku = Sudoku()
commands = Commands()
try:
BasicInterface().run()
except KeyboardInterrupt:
sys.exit()