-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudoku.py
executable file
·278 lines (227 loc) · 9.63 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
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
#!/usr/bin/env python3
"""
Author : schackartk
Date : 2019-04-17
Purpose: Generate a game of sudoku
"""
import argparse
import sys
import random
import re
# --------------------------------------------------
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Commandline Sudoku game',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'-d',
'--difficulty',
help='Game difficulty (E)asy, (M)edium, or (H)ard)',
metavar='str',
type=str,
required=True)
parser.add_argument(
'-s', '--seed', help='A seed to allow for testing', action='store_true')
parser.add_argument(
'-t', '--tip', help='Color bad placements', action='store_true')
parser.add_argument(
'-c', '--coloroff', help='Turn off coloring for testing', action='store_true')
return parser.parse_args()
# --------------------------------------------------
class color:
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
END = '\033[0m'
# --------------------------------------------------
def warn(msg):
"""Print a message to STDERR"""
print(msg, file=sys.stderr)
# --------------------------------------------------
def die(msg='Something bad happened'):
"""warn() and exit with error"""
warn(msg)
sys.exit(1)
# --------------------------------------------------
def make_board(diff):
cells = [[], [], [], [], [], [], [], [], []]
if diff == 'E':
cells[0] = [' ', ' ', ' ', 'b', 'f', ' ', 'g', ' ', 'a']
cells[1] = ['f', 'h', ' ', ' ', 'g', ' ', ' ', 'i', ' ']
cells[2] = ['a', 'i', ' ', ' ', ' ', 'd', 'e', ' ', ' ']
cells[3] = ['h', 'b', ' ', 'a', ' ', ' ', ' ', 'd', ' ']
cells[4] = [' ', ' ', 'd', 'f', ' ', 'b', 'i', ' ', ' ']
cells[5] = [' ', 'e', ' ', ' ', ' ', 'c', ' ', 'b', 'h']
cells[6] = [' ', ' ', 'i', 'c', ' ', ' ', ' ', 'g', 'd']
cells[7] = [' ', 'd', ' ', ' ', ' ', 'e', ' ', 'c', 'f']
cells[8] = ['g', ' ', 'c', ' ', 'a', 'h', ' ', ' ', ' ']
if diff == 'M':
cells[0] = [' ', 'b', ' ', 'f', ' ', 'h', ' ', ' ', ' ']
cells[1] = ['e', 'h', ' ', ' ', ' ', 'i', 'g', ' ', ' ']
cells[2] = [' ', ' ', ' ', ' ', 'd', ' ', ' ', ' ', ' ']
cells[3] = ['c', 'g', ' ', ' ', ' ', ' ', 'e', ' ', ' ']
cells[4] = ['f', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'd']
cells[5] = [' ', ' ', 'h', ' ', ' ', ' ', ' ', 'a', 'c']
cells[6] = [' ', ' ', ' ', ' ', 'b', ' ', ' ', ' ', ' ']
cells[7] = [' ', ' ', 'i', 'h', ' ', ' ', ' ', 'c', 'f']
cells[8] = [' ', ' ', ' ', 'c', ' ', 'f', ' ', 'i', ' ']
if diff == 'H':
cells[0] = [' ', ' ', ' ', 'f', ' ', ' ', 'd', ' ', ' ']
cells[1] = ['g', ' ', ' ', ' ', ' ', 'c', 'f', ' ', ' ']
cells[2] = [' ', ' ', ' ', ' ', 'i', 'a', ' ', 'h', ' ']
cells[3] = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
cells[4] = [' ', 'e', ' ', 'a', 'h', ' ', ' ', ' ', 'c']
cells[5] = [' ', ' ', ' ', 'c', ' ', 'f', ' ', 'd', 'e']
cells[6] = [' ', 'd', ' ', 'b', ' ', ' ', ' ', 'f', ' ']
cells[7] = ['i', ' ', 'c', ' ', ' ', ' ', ' ', ' ', ' ']
cells[8] = [' ', 'b', ' ', ' ', ' ', ' ', 'a', ' ', ' ']
return (cells)
# --------------------------------------------------
def modify_board(cells, seed):
diction = {}
new_cells = [[], [], [], [], [], [], [], [], []]
hor_cells = [[], [], [], [], [], [], [], [], []]
vert_cells = [[], [], [], [], [], [], [], [], []]
diag_cells = [[], [], [], [], [], [], [], [], []]
this_row = ['', '', '', '', '', '', '', '', '']
immut = []
if seed:
random.seed(seed)
for l in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']:
num = str(random.choice(range(1, 10)))
while num in diction.values():
num = str(random.choice(range(1, 10)))
diction[l] = num
diction[' '] = ' '
for row in range(0, 9):
for col in range(0, 9):
this_row[col] = diction[cells[row][col]]
new_cells[row] = this_row.copy()
flip_hor = random.choice([0, 1])
flip_vert = random.choice([0, 1])
flip_diag = random.choice([0, 1])
if flip_hor:
for row in range(0, 9):
for col in range(0, 9):
this_row[col] = new_cells[row][8 - col]
hor_cells[row] = this_row.copy()
else:
hor_cells = new_cells
if flip_vert:
for row in range(0, 9):
for col in range(0, 9):
this_row[col] = hor_cells[8 - row][col]
vert_cells[row] = this_row.copy()
else:
vert_cells = hor_cells
if flip_diag:
for row in range(0, 9):
for col in range(0, 9):
this_row[col] = vert_cells[col][row]
diag_cells[row] = this_row.copy()
else:
diag_cells = vert_cells
for row in range(0, 9):
for col in range(0, 9):
if diag_cells[row][col].isdigit():
immut.append((row, col))
return diag_cells, immut
# --------------------------------------------------
def print_board(cells, immut, bad, cannot, tip, color_off):
minor_border = '·' * 37
major_border = '-' * 37
print(major_border)
for i in range(0, 9):
for j in range(0, 9):
print('|' if not j % 3 else '⁝', end='')
if tuple([i, j]) in immut and not color_off:
print(color.GREEN + '{:^3}'.format(str(cells[i][j])) + color.END, end='')
elif tuple([i, j]) in cannot and tip and not color_off:
print(color.RED + '{:^3}'.format(str(cells[i][j])) + color.END, end='')
elif tuple([i, j]) in bad and tip and not color_off:
print(color.YELLOW + '{:^3}'.format(str(cells[i][j])) + color.END, end='')
else:
print('{:^3}'.format(str(cells[i][j])), end='')
print('|')
print(minor_border if (i + 1) % 3 else major_border)
# --------------------------------------------------
def check_board(cells, immut):
bad = []
cannot = []
for row in range(0, 9):
for col in range(0, 9):
now_cell = cells[row][col]
if not now_cell == ' ' and tuple([row, col]) not in immut:
for check_row in range(0, 9):
if now_cell == cells[check_row][col] and not check_row == row:
cannot.extend([(row, col)]) if tuple([check_row, col]) in immut else bad.extend([(row, col)])
for check_col in range(0, 9):
if now_cell == cells[row][check_col] and not check_col == col:
cannot.extend([(row, col)]) if tuple([row, check_col]) in immut else bad.extend([(row, col)])
for check_row in range((row // 3) * 3, (row // 3) * 3 + 3):
for check_col in range((col // 3) * 3, (col // 3) * 3 + 3):
if now_cell == cells[check_row][check_col] and not check_col == col and not check_row == row:
cannot.extend([(row, col)]) if tuple([check_row, check_col]) in immut else bad.extend(
[(row, col)])
if (0 == sum(' ' in row for row in cells)) and len(bad) == 0 and len(cannot) == 0:
won = True
else:
won = False
return set(bad), set(cannot), won
# --------------------------------------------------
def main():
args = get_args()
difficulty = args.difficulty
seed = args.seed
color_off = args.coloroff
if args.seed:
random.seed(args.seed)
tip = True if args.tip else False
if re.compile('^[Ee]').match(difficulty):
diff = 'E'
elif re.compile('^[Mm]').match(difficulty):
diff = 'M'
elif re.compile('^[Hh]').match(difficulty):
diff = 'H'
else:
die('--difficulty "{}" must be (E)asy, (M)edium, or (H)ard'.format(difficulty))
cells = make_board(diff) # Make a seed board based on the difficulty level
cells, immut = modify_board(cells, seed) # Fill in the board with numbers and mutate
over = False
bad = set()
cannot = set()
while not over:
print('\n\n')
print_board(cells, immut, bad, cannot, tip, color_off)
print('\n\n')
resp = input('What is your next move? (format as row,column:number): ')
move_match = re.compile('(?P<row>\d)' + '[\D]' + '(?P<col>\d)' + '[\D]''(?P<move>[d\d])').match(resp)
row, col, move = ['', '', '']
if move_match:
row = int(move_match.group('row'))
col = int(move_match.group('col'))
move = move_match.group('move')
for num in [row, col]:
if not 0 < num < 10:
warn('Invalid location entry "{}" must be integers 1-9'.format(resp))
move = ' '
if tuple([row - 1, col - 1]) in immut:
print('Location ({},{}) is immutable, please select another location.'.format(row, col))
continue
elif move.isdigit():
if 0 < int(move) < 10:
cells[row - 1][col - 1] = move
else:
print('Move "{}" must be 1-9'.format(move))
elif move == 'd':
cells[row - 1][col - 1] = ' '
else:
print('Invlaid move "{}", must be 1-9 or "d"'.format(move))
bad, cannot, over = check_board(cells, immut)
else:
print('Invalid move entry "{}", must be 1-9 formatted as row,column:number'.format(resp))
print('Congratulations, you won!')
# --------------------------------------------------
if __name__ == '__main__':
main()