Debian Codegraph @

fltk/test/sudoku.py

raw symbols SCIP
1 #
2 # "$Id: sudoku.py 536 2020-10-30 15:20:32Z andreasheld $"
3 #
4 # Sudoku game using pyFLTK, the Python bindings
5 # for the Fast Light Tool Kit (FLTK).
6 # Port of the game by Michael Sweet
7 # Copyright 2005-2006 by Michael Sweet.
8 #
9 # FLTK copyright 1998-1999 by Bill Spitzak and others.
10 # pyFLTK copyright 2003 by Andreas Held and others.
11 #
12 # This library is free software you can redistribute it and/or
13 # modify it under the terms of the GNU Library General Public
14 # License, version 2.0 as published by the Free Software Foundation.
15 #
16 # This library is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 # Library General Public License for more details.
20 #
21 # You should have received a copy of the GNU Library General Public
22 # License along with this library if not, write to the Free Software
23 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
24 # USA.
25 #
26 # Please report all bugs and problems to "[email protected]".
27 #
28
29 from fltk import *
30 import sys, time, random
31 import pdb
32
33 # default sizes
34 GROUP_SIZE = 160
35 CELL_SIZE = 50
36 CELL_OFFSET = 5
37 MENU_OFFSET = 25
38
39
40 # Sudoku cell class
41 class SudokuCell(Fl_Widget):
42 readonly_ = 0
43 #test_value_ = [0]*8
44 test_value_ = []
45 value_ = 0
46 parent_ = None
47
48 def __init__(self, X, Y, W, H):
49 Fl_Widget.__init__(self, X, Y, W, H)
50 self.test_value_ = [0]*8
51
52 def readonly(self, arg = None):
53 if arg == None:
54 return self.readonly_
55 else:
56 self.readonly_ = arg
57
58 def value(self, arg = None):
59 if arg == None:
60 return self.value_
61 else:
62 self.value_ = arg
63
64 def test_value(self, pos, value = -1):
65 if value == -1:
66 return self.test_value_[pos]
67 else:
68 self.test_value_[pos] = value
69 self.redraw()
70
71 def draw(self):
72 align = [FL_ALIGN_TOP_LEFT,
73 FL_ALIGN_TOP,
74 FL_ALIGN_TOP_RIGHT,
75 FL_ALIGN_RIGHT,
76 FL_ALIGN_BOTTOM_RIGHT,
77 FL_ALIGN_BOTTOM,
78 FL_ALIGN_BOTTOM_LEFT,
79 FL_ALIGN_LEFT]
80
81 # draw the cell ...
82 if self.readonly():
83 fl_draw_box(FL_UP_BOX, self.x(), self.y(), self.w(), self.h(), self.color())
84 else:
85 fl_draw_box(FL_DOWN_BOX, self.x(), self.y(), self.w(), self.h(), self.color())
86 # draw the cell background ...
87 if Fl.focus() == self:
88 c = fl_color_average(FL_SELECTION_COLOR, self.color(), 0.5)
89 fl_color(c)
90 fl_rectf(self.x()+4, self.y()+4, self.w()-8, self.h()-8)
91 fl_color(fl_contrast(self.labelcolor(), c))
92 else:
93 fl_color(self.labelcolor())
94
95 # draw the cell value ...
96 s = str(self.value())
97 if self.value() > 0:
98 fl_font(FL_HELVETICA_BOLD, self.h()-10)
99 fl_draw(s, self.x(), self.y(), self.w(), self.h(), FL_ALIGN_CENTER)
100
101 fl_font(FL_HELVETICA_BOLD, int(self.h()/5))
102
103 for i in range(8):
104 if self.test_value_[i] != 0:
105 s = str(self.test_value_[i])
106 fl_draw(s, self.x()+5, self.y()+5, self.w()-10, self.h()-10, align[i])
107
108 # handle events
109 def handle(self, event):
110 if event == FL_FOCUS:
111 Fl.focus(self)
112 self.redraw()
113 return 1
114 elif event == FL_UNFOCUS:
115 self.redraw()
116 return 1
117 elif event == FL_PUSH:
118 if Fl.event_inside(self):
119 if Fl.event_clicks():
120 if self.value():
121 if self.value() < 9:
122 self.value(self.value()+1)
123 else:
124 self.value(1)
125 else:
126 self.value(self.parent_.next_value(self))
127 Fl.focus(self)
128 self.redraw()
129 return 1
130 elif event == FL_KEYDOWN:
131 if Fl.event_state() & FL_CTRL:
132 pass
133 else:
134 key = Fl.event_key()-ord('0')
135 if key < 0 or key > 9:
136 key = Fl.event_key()-FL_KP-ord('0')
137 if key >= 0 and key <= 9:
138 if self.readonly():
139 fl_beep(FL_BEEP_ERROR)
140 return 1
141 if Fl.event_state() & (FL_SHIFT | FL_CAPS_LOCK):
142 status = 0
143 for i in range(8):
144 if self.test_value_[i] == key:
145 self.test_value_[i] = 0
146 break
147 else:
148 for i in range(8):
149 if self.test_value_[i] == 0:
150 self.test_value_[i] = key
151 break
152 else:
153 for i in range(7):
154 self.test_value_[i] = self.test_value_[i+1]
155 self.test_value_[7] = key
156 self.redraw()
157 else:
158 self.value(key)
159 self.do_callback()
160 return 1
161 return Fl_Widget.handle(self, event)
162
163
164
165 # Sudoku window class
166 class Sudoku(Fl_Window):
167 grid_groups = [[]]*3
168 grid_cells = [[]]*9
169 grid_values = [[]]*9
170 seed = 0.0
171 help_dialog_ = None
172
173 def __init__(self):
174 Fl_Window.__init__(self, GROUP_SIZE*3, GROUP_SIZE*3+MENU_OFFSET, "pySudoku")
175
176 items = [[ "&Game", 0, 0, 0, FL_SUBMENU ],
177 [ "&New Game", FL_COMMAND | ord('n'), self.new_cb, self, FL_MENU_DIVIDER ],
178 [ "&Check Game", FL_COMMAND | ord('c'), self.check_cb, 0, 0 ],
179 [ "&Restart Game", FL_COMMAND | ord('r'), self.restart_cb, 0, 0 ],
180 [ "&Solve Game", FL_COMMAND | ord('s'), self.solve_cb, 0, FL_MENU_DIVIDER ],
181 [ "&Quit", FL_COMMAND | ord('q'), self.close_cb, 0, 0 ],
182 [ None, 0 ],
183 [ "&Difficulty", 0, 0, 0, FL_SUBMENU ],
184 [ "&Easy", 0, self.diff_cb, "0", FL_MENU_RADIO ],
185 [ "&Medium", 0, self.diff_cb, "1", FL_MENU_RADIO ],
186 [ "&Hard", 0, self.diff_cb, "2", FL_MENU_RADIO ],
187 [ "&Impossible", 0, self.diff_cb, "3", FL_MENU_RADIO ],
188 [ None, 0 ],
189 [ "&Help", 0, 0, 0, FL_SUBMENU ],
190 [ "&About Sudoku", FL_F + 1, self.help_cb, 0, 0 ],
191 [ None, 0 ],
192 [ None, 0 ]
193 ]
194
195 #pdb.set_trace()
196 self.prefs = Fl_Preferences(Fl_Preferences.USER, "fltk.org", "pysudoku")
197 (status, self.difficulty) = self.prefs.get("difficulty", 0)
198 if self.difficulty < 0 or self.difficulty > 3:
199 self.difficulty = 0
200
201 items[8+self.difficulty][4] = items[8+self.difficulty][4] | FL_MENU_VALUE
202 new_items = []
203 for item in items:
204 new_items.append(tuple(item))
205
206 self.menubar = Fl_Menu_Bar(0, 0, 3*GROUP_SIZE, 25)
207 self.menubar.menu(tuple(new_items))
208
209 # create the grids ...
210 self.grid = Fl_Group(0, MENU_OFFSET, 3*GROUP_SIZE, 3*GROUP_SIZE)
211
212 for i in range(3):
213 for j in range(3):
214 g = Fl_Group(j*GROUP_SIZE, i*GROUP_SIZE+MENU_OFFSET, GROUP_SIZE, GROUP_SIZE)
215 g.box(FL_BORDER_BOX)
216 if i==1 ^ j==1:
217 g.color(FL_DARK3)
218 else:
219 g.color(FL_DARK2)
220 g.end()
221
222 self.grid_groups[i].append(g)
223
224
225 for i in range(9):
226 self.grid_cells[i] = []
227 for j in range(9):
228 cell = SudokuCell(int(j * CELL_SIZE + CELL_OFFSET +
229 (j / 3) * (GROUP_SIZE - 3 * CELL_SIZE)),
230 int(i * CELL_SIZE+CELL_OFFSET+MENU_OFFSET +
231 (i / 3) * (GROUP_SIZE - 3 * CELL_SIZE)),
232 CELL_SIZE, CELL_SIZE)
233 cell.parent_ = self
234 cell.callback(self.reset_cb)
235 cell.readonly(0)
236 self.grid_cells[i].append(cell)
237
238 # catch window close events...
239 self.callback(self.close_cb, 0)
240
241 # make the window resizable ...
242 self.resizable(self.grid)
243 self.size_range(3*GROUP_SIZE, 3 * GROUP_SIZE + MENU_OFFSET, 0, 0, 5, 5, 1)
244
245 # restore the previous window dimensions ...
246 X = -1
247 Y = -1
248 W = 3*GROUP_SIZE
249 H = 3*GROUP_SIZE+MENU_OFFSET
250 (status, X) = self.prefs.get("x", -1)
251 if status:
252 (status, Y) = self.prefs.get("y", -1)
253 (status, W) = self.prefs.get("w", 3 * GROUP_SIZE)
254 (status, H) = self.prefs.get("h", 3 * GROUP_SIZE+MENU_OFFSET)
255
256 self.resize(X, Y, W, H)
257
258 self.set_title()
259
260 # check for a solution to the game
261 def check_cb(self, widget, data):
262 self.check_game()
263
264 # check if the user has correctly solved the game
265 def check_game(self, highlight = 1):
266 empty = False
267 correct = True
268
269 # check the game for right/wrong answers
270 for i in range(9):
271 for j in range(9):
272 cell = self.grid_cells[i][j]
273 if cell.readonly() == 1:
274 continue
275 val = cell.value()
276 if val == 0:
277 empty = True
278 else:
279 loop_done = 0
280 for k in range(9):
281 if (i != k and self.grid_cells[k][j].value() == val) or (j != k and self.grid_cells[i][k].value() == val):
282 break
283 else:
284 loop_done = 1
285 if loop_done == 0:
286 if highlight == 1:
287 cell.color(FL_YELLOW)
288 cell.redraw()
289
290 correct = False
291 elif highlight == 1:
292 cell.color(FL_LIGHT3)
293 cell.redraw()
294
295 # check subgrids for duplicate numbers
296 for i in range(0,9,3):
297 for j in range(0,9,3):
298 for ii in range(3):
299 for jj in range(3):
300 cell = self.grid_cells[i+ii][j+jj]
301 val = cell.value()
302
303 if cell.readonly() == 1 or val == 0:
304 continue
305
306 break_loop = 0
307 for iii in range(3):
308 for jjj in range(3):
309 if not ii == iii and not jj == jjj and self.grid_cells[i+iii][j+jjj].value() == val:
310 break_loop = 1
311 break
312 if break_loop == 1:
313 break
314 if break_loop == 1:
315 if highlight == 1:
316 cell.color(FL_YELLOW)
317 cell.redraw()
318 correct = False
319 if not empty and correct:
320 # success
321 for i in range(9):
322 for j in range(9):
323 cell = self.grid_cells[i][j]
324 cell.color(FL_GREEN)
325 cell.redraw()
326 cell.readonly(1)
327
328
329 # close the window, saving the game first...
330 def close_cb(self, widget, data):
331 self.prefs = None
332 self.hide()
333
334 # set the level of difficulty
335 def diff_cb(self, widget, d):
336 diff = ord(d)-ord('0')
337 #pdb.set_trace()
338 if diff != self.difficulty:
339 self.difficulty = diff
340 self.new_game(self.seed)
341 self.set_title()
342 self.redraw()
343
344 self.prefs.set("difficulty", diff)
345
346 # show the online help
347 def help_cb(self, widget, data):
348 if (self.help_dialog_ == None) :
349 self.help_dialog_ = Fl_Help_Dialog()
350
351 self.help_dialog_.value(
352 "<HTML>\n"
353 "<HEAD>\n"
354 "<TITLE>Sudoku Help</TITLE>\n"
355 "</HEAD>\n"
356 "<BODY BGCOLOR='#ffffff'>\n"
357
358 "<H2>About the Game</H2>\n"
359
360 "<P>Sudoku (pronounced soo-dough-coo with the emphasis on the\n"
361 "first syllable) is a simple number-based puzzle/game played on a\n"
362 "9x9 grid that is divided into 3x3 subgrids. The goal is to enter\n"
363 "a number from 1 to 9 in each cell so that each number appears\n"
364 "only once in each column and row. In addition, each 3x3 subgrid\n"
365 "may only contain one of each number.</P>\n"
366
367 "<P>This version of the puzzle is Copyright 2005 by Michael R Sweet</P>\n"
368
369 "<H2>How to Play the Game</H2>\n"
370
371 "<P>At the start of a new game, Sudoku fills in a random selection\n"
372 "of cells for you - the number of cells depends on the difficulty\n"
373 "level you use. Click in any of the empty cells or use the arrow\n"
374 "keys to highlight individual cells and press a number from 1 to 9\n"
375 "to fill in the cell. To clear a cell, press 0, Delete, or\n"
376 "Backspace. When you have successfully completed all subgrids, the\n"
377 "entire puzzle is highlighted in green until you start a new\n"
378 "game.</P>\n"
379
380 "<P>As you work to complete the puzzle, you can display possible\n"
381 "solutions inside each cell by holding the Shift key and pressing\n"
382 "each number in turn. Repeat the process to remove individual\n"
383 "numbers, or press a number without the Shift key to replace them\n"
384 "with the actual number to use.</P>\n"
385 "</BODY>\n"
386 )
387
388
389 self.help_dialog_.show()
390
391 # load the game from saved preferences
392 def load_game(self):
393 # Load the current values and state of each grid...
394 for i in range(9):
395 if len(self.grid_values[i]) != 9:
396 self.grid_values[i] = [0]*9
397 else:
398 for j in range(9):
399 self.grid_values[i][j] = 0
400
401 solved = True
402
403 for i in range(9):
404 for j in range(9):
405 cell = self.grid_cells[i][j]
406 name = f"value{i}.{j}"
407 val = 0
408 (status, val) = self.prefs.get(name, 0)
409 if status == 0:
410 self.grid_values[0][0] = 0
411 break
412 self.grid_values[i][j] = val
413
414 name = f"state{i}.{j}"
415 (status, val) = self.prefs.get(name, 0)
416 cell.readonly(val)
417 if val != 0:
418 cell.color(FL_GRAY)
419 else:
420 cell.color(FL_LIGHT3)
421 solved = False
422
423 for k in range(8):
424 name = f"test{k}{i}.{j}"
425 (status, val) = self.prefs.get(name, 0)
426 cell.test_value(k, val)
427
428 # If we didn't load any values or the last game was solved, then
429 # create a new game automatically...
430 if solved or self.grid_values[0][0] == 0:
431 self.new_game(0)
432 else:
433 self.check_game(False);
434
435 # create a new game ...
436 def new_cb(self, widget, data):
437 s = data
438
439 if s.grid_cells[0][0].color() != FL_GREEN:
440 if not fl_choice("Are you sure you want to change the difficulty level and "
441 "discard the current game?", "Keep Current Game", "Start New Game", None):
442 return
443 s.new_game(time.time())
444 s.redraw()
445
446 # create a new game ...
447 def new_game(self, seed):
448 # Generate a new (valid) Sudoku grid...
449 self.seed = seed
450 random.seed(seed)
451
452 ValidPuzzle = 0
453 while ValidPuzzle == 0:
454 ValidPuzzle = 1
455 for i in range(9):
456 self.grid_values[i] = []
457 for j in range(9):
458 self.grid_values[i].append(0)
459
460
461 # loop over all cells
462 for i in range(0,9,3):
463 for j in range(0,9,3):
464 # get all possible positions
465 pos = []
466 for ii in range(3):
467 for jj in range(3):
468 pos.append([ii,jj])
469
470 # for all possible numbers
471 for t in range(1,10):
472 for count in range(30):
473 p1 = random.randint(0, len(pos)-1)
474 k = i+pos[p1][0]
475 m = j+pos[p1][1]
476 if self.grid_values[k][m] == 0:
477 t1 = []
478 t2 = []
479 if m > 0:
480 t1 = self.grid_values[k][:m]
481 if k > 0:
482 t2 = [r[m] for r in self.grid_values][:k]
483 if t not in t1 and t not in t2:
484 self.grid_values[k][m] = t
485 done = 1
486 del pos[p1]
487 break
488 else:
489 ValidPuzzle = 0
490 break
491 if ValidPuzzle == 0:
492 break
493 if ValidPuzzle == 0:
494 break
495
496 # Start by making all cells editable
497 cell = None
498 for i in range(9):
499 for j in range(9):
500 cell = self.grid_cells[i][j]
501
502 cell.value(0)
503 cell.readonly(0)
504 cell.color(FL_LIGHT3)
505
506 # Show N cells...
507 count = 10 * (5 - self.difficulty)
508
509 numbers = list(range(10)[1:])
510
511 while count > 0:
512 for i in range(20):
513 k = random.randint(0,8)
514 m = random.randint(0,8)
515 t =numbers[k]
516 numbers[k] = numbers[m]
517 numbers[m] = t
518
519 i = -1
520 while count > 0 and i < 8:
521 i += 1
522 t = numbers[i]
523 j = -1
524 while count > 0 and j < 8:
525 j += 1
526
527 cell = self.grid_cells[i][j]
528 if self.grid_values[i][j] == t and cell.readonly() == 0:
529 cell.value(self.grid_values[i][j])
530 cell.readonly(1)
531 cell.color(FL_GRAY)
532
533 count -= 1
534
535 break
536
537
538
539 def next_value(self, c):
540 # find the cell
541 xpos = -1
542 ypos = -1
543 for i in range(9):
544 for j in range(9):
545 if self.grid_cells[i][j] == c:
546 xpos = i
547 ypos = j
548 break
549 if xpos > -1:
550 break
551
552 if xpos < 0:
553 return 1
554
555 i -= i % 3
556 j -= j % 3
557
558 #numbers = map(0, range(9))
559 numbers = [0]*9
560
561 for k in range(3):
562 for m in range(3):
563 c = self.grid_cells[i+k][j+m]
564 if c.value():
565 numbers[c.value()-1] = 1
566
567 for i in range(9):
568 if not numbers[i]:
569 return i+1
570
571 return 1
572
573 # reset widget color to gray
574 def reset_cb(self, widget):
575 widget.color(FL_LIGHT3)
576 widget.redraw()
577
578 self.check_game(0)
579
580 # resize the window
581 def resize(self, X, Y, W, H):
582 # resize the window
583 Fl_Window.resize(self, X, Y, W, H)
584
585 # save the new window geometry
586 self.prefs.set("x", X);
587 self.prefs.set("y", Y);
588 self.prefs.set("width", W);
589 self.prefs.set("height", H);
590
591
592 def restart_cb(self, widget, data):
593 Solved = True;
594
595 for i in range(9):
596 for j in range(9):
597 cell = self.grid_cells[i][j]
598
599 if cell.readonly() == 0:
600 Solved = False
601 v = cell.value()
602 cell.value(0)
603 cell.color(FL_LIGHT3)
604
605 if Solved:
606 self.new_game(self.seed)
607
608 def save_game(self):
609 # Save the current values and state of each grid...
610 for i in range(9):
611 for j in range(9):
612 cell = self.grid_cells[i][j]
613 name = f"value{i}.{j}"
614 self.prefs.set(name, self.grid_values[i][j])
615
616 name = f"state{i}.{j}"
617 self.prefs.set(name, cell.value())
618
619 name = f"readonly{i}.{j}"
620 self.prefs.set(name, cell.readonly())
621
622 for k in range(8):
623 name = f"test{k}{i}.{j}"
624 self.prefs.set(name, cell.test_value(k))
625
626 def set_title(self):
627 titles = ["pySudoku - Easy",
628 "pySudoku - Medium",
629 "pySudoku - Hard",
630 "pySudoku - Impossible"]
631 self.label(titles[self.difficulty])
632
633 # solve the puzzle
634 def solve_cb(self, widget, data):
635 self.solve_game()
636
637 def solve_game(self):
638 try:
639 for i in range(9):
640 for j in range(9):
641 cell = self.grid_cells[i][j]
642
643 cell.value(self.grid_values[i][j])
644 cell.readonly(1)
645 cell.color(FL_GRAY)
646 cell.redraw()
647 self.redraw()
648 except IndexError:
649 print("IndexError")
650 # we reach here if the puzzle has not been initialized yet
651 pass
652
653 # main entry
654 if __name__=='__main__':
655
656 s = Sudoku()
657
658 # show the game
659 s.show(sys.argv)
660
661 # load the previous game
662 s.load_game()
663
664 # run
665 Fl.run()
666
667