-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudokuban.py
executable file
·1355 lines (1058 loc) · 45.7 KB
/
sudokuban.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# sudokuban.py - GUI for SudokuBan.
#
import os, sys, time
import pygtk, gtk, pango
from sudoku import *
# Current version.
sudokuBanVersion = '1.1pre'
# Key press event values for arrow keys. This is probably
# defined somewhere (or at least it should be) but I couldn't
# find it.
KEY_LEFT = 65361
KEY_UP = 65362
KEY_RIGHT = 65363
KEY_DOWN = 65364
KEY_ARROWS = (KEY_LEFT, KEY_UP, KEY_RIGHT, KEY_DOWN)
KEY_BACKSPACE = 65288
KEY_DELETE = 65535
# Tooltips. TODO: i18n.
tipNew = 'Create a new empty or random puzzle.'
tipOpen = 'Load a puzzle from a file.'
tipDuplicate = 'Create a copy of this puzzle in a new window.'
tipSave = 'Save a puzzle to a file.'
tipSaveAs = 'Save a puzzle to a new location.'
tipClose = 'Close the current puzzle window.'
tipQuit = 'Exit SudokuBan.'
tipUndo = 'Undo the last action.'
tipRedo = 'Redo the last undone action.'
tipFonts = 'Edit fonts used in the main window.'
tipColours = 'Edit colours used in the main window.'
tipSolve = 'Find a solution for the current puzzle. If there are multiple solutions, it will only find one.'
tipHighlight = 'Colour squares that are in the same row, column or region as the selected number anywhere in the puzzle. Squares that are not coloured could be that number.'
tipExclude = 'Restricts input to numbers that are available for each square. Right-click on a square to see which numbers are available for it.'
tipPresets = 'Edit the pre-given numbers in the puzzle. You should only need to do this when creating or entering a new puzzle.'
tipCheckValid = 'Check whether all numbers entered so far are unique in their row, column and region.'
tipCheckSolvable = 'Check whether the puzzle can be solved from this point. This will tell you whether the puzzle is solvable, unsolvable or has multiple solutions.'
tipDifficulty = 'Estimate the difficulty of this puzzle. The difficulty ratings are, in order: Easy, Moderate, Challenging, Tough, Outrageous.'
tipNewWidth = 'The width of each region, and the number of regions vertically.'
tipNewHeight = 'The height of each region, and the number of regions horizontally.'
tipNewEmpty = 'Create a blank puzzle.'
tipNewRandom = 'Generate a random puzzle.'
tipNewSymmetrical = 'Makes the new puzzle symmetrical.'
tipNewCrossHatchOnly = 'Make the puzzle solvable using only "cross-hatching" - looking for intersections in each region between rows and columns that have the same number. This tends to make the puzzle easier.'
tipNewLookAhead = 'The maximum number of steps in solving the puzzle that require you to "look ahead" to determine some numbers. Values above zero tend to make the puzzle much more difficult.'
class Settings:
def __init__(self, filename = None):
self.filename = filename
# Defaults
self.colourBackground = gtk.gdk.Color(0xffff, 0xffff, 0xffff)
self.colourBorder = gtk.gdk.Color(0x3fff, 0x3fff, 0x3fff)
self.colourPreset = gtk.gdk.Color(0x0000, 0x0000, 0x0000)
self.colourUnset = gtk.gdk.Color(0x0000, 0x3fff, 0x7fff)
self.colourRow = gtk.gdk.Color(0xcfff, 0xcfff, 0xf7ff)
self.colourColumn = gtk.gdk.Color(0xbfff, 0xf7ff, 0xbfff)
self.colourRegion = gtk.gdk.Color(0xffff, 0xc7ff, 0xc7ff)
self.fontPreset = pango.FontDescription('sans bold 24')
self.fontUnset = pango.FontDescription('sans 24')
# Load from file
self.load()
self.update()
def update(self):
# Calculate highlighting shades
self.highlightShade = {}
for col in (True, False):
for row in (True, False):
for reg in (True, False):
shade = gtk.gdk.Color(self.colourBackground.red,
self.colourBackground.green,
self.colourBackground.blue)
if not row:
shade.red = max(shade.red - 0xffff + self.colourRow.red, 0)
shade.green = max(shade.green - 0xffff + self.colourRow.green, 0)
shade.blue = max(shade.blue - 0xffff + self.colourRow.blue, 0)
if not col:
shade.red = max(shade.red - 0xffff + self.colourColumn.red, 0)
shade.green = max(shade.green - 0xffff + self.colourColumn.green, 0)
shade.blue = max(shade.blue - 0xffff + self.colourColumn.blue, 0)
if not reg:
shade.red = max(shade.red - 0xffff + self.colourRegion.red, 0)
shade.green = max(shade.green - 0xffff + self.colourRegion.green, 0)
shade.blue = max(shade.blue - 0xffff + self.colourRegion.blue, 0)
self.highlightShade[(row, col, reg)] = shade
def colourToStr(self, colour):
return '#%04X%04X%04X' % (colour.red, colour.green, colour.blue)
def colourFromStr(self, string):
try:
return gtk.gdk.color_parse(string)
except:
return None
def load(self):
if not self.filename:
return False
try:
inFile = file(self.filename)
for line in inFile.readlines():
try:
if line.startswith('#'):
continue
tokens = line.split('=', 1)
if len(tokens) != 2:
continue
attrib = tokens[0].strip().lower()
value = tokens[1].strip()
if attrib.startswith('colour.'):
value = self.colourFromStr(value)
if not value:
continue
if attrib == 'colour.background':
self.colourBackground = value
elif attrib == 'colour.border':
self.colourBorder = value
elif attrib == 'colour.preset':
self.colourPreset = value
elif attrib == 'colour.unset':
self.colourUnset = value
elif attrib == 'colour.row':
self.colourRow = value
elif attrib == 'colour.column':
self.colourColumn = value
elif attrib == 'colour.region':
self.colourRegion = value
elif attrib.startswith('font.'):
value = pango.FontDescription(value)
if attrib == 'font.preset':
self.fontPreset = value
elif attrib == 'font.unset':
self.fontUnset = value
except:
continue
except:
return False
def save(self):
if not self.filename:
return False
try:
out = file(self.filename, 'w')
print >> out, 'colour.background =', self.colourToStr(self.colourBackground)
print >> out, 'colour.border =', self.colourToStr(self.colourBorder)
print >> out, 'colour.preset =', self.colourToStr(self.colourPreset)
print >> out, 'colour.unset =', self.colourToStr(self.colourUnset)
print >> out, 'colour.row =', self.colourToStr(self.colourRow)
print >> out, 'colour.column =', self.colourToStr(self.colourColumn)
print >> out, 'colour.region =', self.colourToStr(self.colourRegion)
print >> out, 'font.preset =', self.fontPreset.to_string()
print >> out, 'font.unset =', self.fontUnset.to_string()
out.close()
return True
except:
return False
class SudokuAction:
def __init__(self, gui):
self.gui = gui
def execute(self):
pass
def inverse(self):
return None
def __repr__(self):
return 'Action'
class SetEntryAction(SudokuAction):
def __init__(self, gui, entry, value, select = True,
preset = None, update = True, title = None):
SudokuAction.__init__(self, gui)
self.entry = entry
self.value = value
self.select = select
self.update = update
if preset == None:
self.preset = gui.preset
else:
self.preset = preset
if title:
self.title = title
else:
if self.value:
if self.preset:
self.title = 'Preset %d' % self.value
else:
self.title = 'Value %d' % self.value
else:
self.title = 'Clear Cell'
def inverse(self):
return SetEntryAction(self.gui, self.entry, self.entry.getValue(),
self.select, self.entry.isPreset(),
self.update, self.title)
def execute(self):
self.entry.setValue(self.value, self.preset)
if self.select:
self.gui.setSelection(self.entry)
if self.update:
self.gui.update(self.entry)
def __repr__(self):
return self.title
class CompoundAction(SudokuAction):
def __init__(self, gui, actions, title, update = True):
SudokuAction.__init__(self, gui)
self.actions = actions
self.title = title
self.update = update
def inverse(self):
inverse_actions = []
for i in range(len(self.actions)-1, -1, -1):
inverse_actions.append(self.actions[i].inverse())
return CompoundAction(self.gui, inverse_actions, self.title)
def execute(self):
for action in self.actions:
action.execute()
if self.update:
self.gui.updateAll()
def __repr__(self):
return self.title
class BoardEntry(gtk.EventBox):
def __init__(self, cell, gui):
gtk.EventBox.__init__(self)
self.cell = cell
self.gui = gui
self.label = gtk.Label()
self.label.set_alignment(0.5, 0.5)
self.label.show()
self.add(self.label)
self.connect('button_press_event', gui.clickInCell, self.cell)
self.connect('popup_menu', gui.numberMenu, self.cell)
self.connect('size-request', self.setSizeRequest)
self.update()
def update(self):
if self.cell.value:
self.label.set_text(str(self.cell.value))
else:
self.label.set_text(' ')
if self.gui.scanHighlight and self.gui.selectedValue:
shadeKey = (
self.cell.sets[0].isAvailable(self.gui.selectedValue),
self.cell.sets[1].isAvailable(self.gui.selectedValue),
self.cell.sets[2].isAvailable(self.gui.selectedValue)
)
self.modify_bg(gtk.STATE_NORMAL, settings.highlightShade[shadeKey])
else:
self.modify_bg(gtk.STATE_NORMAL, settings.colourBackground)
if self.cell.state == CELL_PRESET:
self.label.modify_font(settings.fontPreset)
self.label.modify_fg(gtk.STATE_NORMAL, settings.colourPreset)
else:
self.label.modify_font(settings.fontUnset)
self.label.modify_fg(gtk.STATE_NORMAL, settings.colourUnset)
if self is self.gui.selection:
self.set_state(gtk.STATE_SELECTED)
else:
self.set_state(gtk.STATE_NORMAL)
def setSizeRequest(self, widget, requisition):
if requisition.width < requisition.height:
self.set_size_request(requisition.height, requisition.height)
elif requisition.height < requisition.width:
self.set_size_request(requisition.width, requisition.width)
def setValue(self, value, preset):
if value == 0:
value = None
preset = False
if value != self.cell.value or \
preset != (self.cell.state == CELL_PRESET):
self.gui.dirty = True
if self.cell.value != value:
self.cell.setValue(value)
if preset:
self.cell.state = CELL_PRESET
else:
self.cell.state = CELL_UNSET
if value and self == self.gui.selection:
self.gui.selectedValue = value
def getValue(self):
return self.cell.value
def isPreset(self):
return self.cell.state == CELL_PRESET
class SudokuGUI:
def __init__(self, board = SudokuBoard(), filename = None, dirty = False):
openWindows.append(self)
self.scanHighlight = False
self.selection = None
self.selectedValue = 0
self.exclude = False
self.digitKeys = ''
self.preset = False
self.dirty = dirty
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect('delete-event', self.destroy)
self.window.connect('key-press-event', self.keyPress)
self.vbox = gtk.VBox(False, 0)
self.window.add(self.vbox)
self.vbox.show()
self.undoList = []
self.redoList = []
self.createActions()
self.setFilename(filename)
self.board = board
regions = self.board.regionCount
regionSize = self.board.regionSize
self.table = gtk.Table(regions[1], regions[0], True)
self.table.set_row_spacings(5)
self.table.set_col_spacings(5)
self.window.modify_bg(gtk.STATE_NORMAL, settings.colourBorder)
self.entries = []
self.cells = {}
for regionY in range(regions[1]):
for regionX in range(regions[0]):
regionTable = gtk.Table(regionSize[1], regionSize[0], True)
regionTable.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0xffff, 0, 0))
regionTable.set_row_spacings(1)
regionTable.set_col_spacings(1)
xStart = regionX * regionSize[0]
yStart = regionY * regionSize[1]
for y in range(regionSize[1]):
for x in range(regionSize[0]):
cellX = xStart + x
cellY = yStart + y
cell = self.board[cellX, cellY]
entry = BoardEntry(cell, self)
self.entries.append(entry)
self.cells[cell.coord] = entry
regionTable.attach(entry, x, x + 1, y, y + 1)
entry.show()
self.table.attach(regionTable,
regionX, regionX + 1,
regionY, regionY + 1)
regionTable.show()
# Empty board starts off editing presets
if self.board.filled == 0:
self.actionGroup.get_action('Presets').set_active(True)
self.vbox.add(self.table)
self.table.show()
self.window.show()
def keyPress(self, widget, event):
key = event.keyval
if key >= 0 and key < 256:
keyStr = chr(key)
if keyStr.isdigit() and self.selection:
self.digitKeys += keyStr
while self.digitKeys:
value = int(self.digitKeys)
if 0 <= value and value <= self.board.values and \
(not self.exclude or value in self.selection.cell.possibleValues()):
self.setEntry(self.selection, value)
return True
self.digitKeys = self.digitKeys[1:]
elif key == KEY_BACKSPACE or key == KEY_DELETE:
if self.selection:
self.digitKeys = ''
self.setEntry(self.selection, 0)
elif key in KEY_ARROWS:
if self.selection:
(x, y) = self.selection.cell.coord
else:
(x, y) = (0, 0)
if key == KEY_LEFT:
x -= 1
elif key == KEY_UP:
y -= 1
elif key == KEY_RIGHT:
x += 1
elif key == KEY_DOWN:
y += 1
(width, height) = self.board.size
if x < 0:
x += width
y -= 1
if y < 0:
y += height
elif x >= width:
x -= width
y += 1
if y >= height:
y -= height
elif y < 0:
y += height
x -= 1
if x < 0:
x += width
elif y >= height:
y -= height
x += 1
if x >= width:
x -= width
self.setSelection(self.cells[(x, y)])
return True
def setFilename(self, filename):
self.filename = filename
self.setTitle()
self.actionGroup.get_action('Save').set_sensitive(filename != None)
def setTitle(self):
title = 'SudokuBan'
if self.filename:
title = os.path.basename(self.filename) + ' - ' + title
self.window.set_title(title)
def setSelection(self, widget, data = None):
oldSelection = self.selection
self.selection = widget
if oldSelection:
oldSelection.update()
if self.selection:
self.selection.update()
if self.selection.cell.value and self.selection.cell.value != self.selectedValue:
self.selectedValue = self.selection.cell.value
if self.scanHighlight:
self.updateAll()
else:
if self.selectedValue:
self.selectedValue = 0
if self.scanHighlight:
self.updateAll()
if not oldSelection is widget:
self.digitKeys = ''
def createActions(self):
uimanager = gtk.UIManager()
self.window.add_accel_group(uimanager.get_accel_group())
# Custom icons
self.iconFactory = gtk.IconFactory()
self.registerIcon('sudoku-solve', os.path.join(programDir, 'images/solve.png'))
self.registerIcon('sudoku-highlight', os.path.join(programDir, 'images/highlight.png'))
self.registerIcon('sudoku-exclude', os.path.join(programDir, 'images/exclude.png'))
self.registerIcon('sudoku-presets', os.path.join(programDir, 'images/presets.png'))
self.iconFactory.add_default()
self.actionGroup = gtk.ActionGroup('SudokuBan')
self.actionGroup.add_actions([
('File', None, '_File'),
('New', gtk.STOCK_NEW, '_New', '<Control>N', tipNew, self.newPuzzleDialog),
('Open', gtk.STOCK_OPEN, '_Open', '<Control>O', tipOpen, openDialog),
('Duplicate', None, '_Duplicate', None, tipDuplicate, self.duplicate),
('Save', gtk.STOCK_SAVE, '_Save', '<Control>S', tipSave, self.saveFile),
('SaveAs', gtk.STOCK_SAVE_AS, 'Save _As...', '<Control><Shift>S', tipSaveAs, self.saveAsDialog),
('Close', gtk.STOCK_CLOSE, '_Close', '<Control>W', tipClose, self.destroy),
('Quit', gtk.STOCK_QUIT, '_Quit', '<Control>Q', tipQuit, closeAll),
('Edit', None, '_Edit'),
('Undo', gtk.STOCK_UNDO, '_Undo', '<Control>Z', tipUndo, self.undo),
('Redo', gtk.STOCK_REDO, '_Redo', '<Control>Y', tipRedo, self.redo),
('Settings', None, '_Settings'),
('Fonts', gtk.STOCK_SELECT_FONT, '_Fonts', None, tipFonts, fontsDialog),
('Colours', gtk.STOCK_SELECT_COLOR, '_Colours', None, tipColours, coloursDialog),
('Puzzle', None, '_Puzzle'),
('CheckValid', None, 'Check _Valid', None, tipCheckValid, self.checkValid),
('CheckSolvable', None, 'Check _Solvable', None, tipCheckSolvable, self.checkSolvable),
('Difficulty', None, '_Difficulty', None, tipDifficulty, self.difficulty),
('Hints', None, '_Hints'),
('Solve', 'sudoku-solve', '_Solve', None, tipSolve, self.solve)
])
self.actionGroup.add_toggle_actions([
('Presets', 'sudoku-presets', '_Presets', None, tipPresets, self.togglePreset),
('Highlight', 'sudoku-highlight', '_Highlight', None, tipHighlight, self.toggleScanHighlight),
('Exclude', 'sudoku-exclude', '_Restrict', None, tipExclude, self.toggleExclude)
])
self.undoAction = self.actionGroup.get_action('Undo')
self.redoAction = self.actionGroup.get_action('Redo')
self.updateUndoActions()
# Catch error under PyGTK <2.6, i.e. before AboutDialog and STOCK_ABOUT.
# Not sure exactly what this will achieve, but at least it won't crash.
try:
self.actionGroup.add_actions([
('Help', None, '_Help'),
('About', gtk.STOCK_ABOUT, '_About SudokuBan', None, None, aboutDialog)
])
except:
pass
uimanager.insert_action_group(self.actionGroup, 0)
uimanager.add_ui_from_file(os.path.join(programDir, 'sudoku-ui.xml'))
menubar = uimanager.get_widget('/MenuBar')
toolbar = uimanager.get_widget('/Toolbar')
self.vbox.pack_start(menubar, False, True, 0)
self.vbox.pack_start(toolbar, False, True, 0)
toolbar.connect('button-press-event', self.clearSelection)
def registerIcon(self, id, filename):
try:
pixbuf = gtk.gdk.pixbuf_new_from_file(filename)
iconset = gtk.IconSet(pixbuf)
self.iconFactory.add(id, iconset)
except:
pass
def clearSelection(self, widget, data = None):
self.setSelection(None)
def toggleScanHighlight(self, action):
self.scanHighlight = action.get_active()
if self.selection:
self.selectedValue = self.selection.cell.value
else:
self.selectedValue = 0
self.updateAll()
def toggleExclude(self, action):
self.exclude = action.get_active()
def togglePreset(self, action):
self.preset = action.get_active()
def clickInCell(self, widget, event, cell):
if event.button == 1:
self.setSelection(widget)
elif event.button == 3:
return self.numberMenu(widget, cell, event.button, event.time)
def numberMenu(self, widget, cell, button = 0, eventTime = 0):
if (not self.preset) and (cell.value) and (cell.state == CELL_PRESET):
return False
if self.exclude:
values = [0] + cell.possibleValues(True)
else:
values = range(self.board.values + 1)
menu = gtk.Menu()
for value in values:
if value:
text = str(value)
else:
text = ' '
item = gtk.MenuItem(text)
item.connect_object('activate', self.setEntry, widget, value)
item.show()
menu.append(item)
menu.popup(None, None, None, button, eventTime)
return True
def update(self, entry):
if self.scanHighlight:
self.updateAll()
else:
entry.update()
def updateAll(self):
self.window.modify_bg(gtk.STATE_NORMAL, settings.colourBorder)
for entry in self.entries:
entry.update()
def setEntry(self, entry, value):
if (not self.preset) and entry.isPreset():
return
action = SetEntryAction(self, entry, value)
self.runAction(action)
def runAction(self, action):
self.redoList = []
self.undoList.append(action.inverse())
action.execute()
self.updateUndoActions()
def undo(self, widget = None):
if self.undoList:
action = self.undoList.pop()
self.redoList.append(action.inverse())
action.execute()
self.updateUndoActions()
def redo(self, widget = None):
if self.redoList:
action = self.redoList.pop()
self.undoList.append(action.inverse())
action.execute()
self.updateUndoActions()
def updateUndoActions(self):
self.undoAction.set_sensitive(self.undoList != [])
self.redoAction.set_sensitive(self.redoList != [])
if self.undoList:
self.undoAction.set_property('label', '_Undo %s' % repr(self.undoList[-1]))
else:
self.undoAction.set_property('label', '_Undo')
if self.redoList:
self.redoAction.set_property('label', '_Redo %s' % repr(self.redoList[-1]))
else:
self.redoAction.set_property('label', '_Redo')
def checkValid(self, widget = None):
if self.board.isValid():
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL,
gtk.MESSAGE_INFO, gtk.BUTTONS_OK)
dialog.set_markup('Puzzle is valid.')
else:
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL,
gtk.MESSAGE_WARNING, gtk.BUTTONS_OK)
dialog.set_markup('Puzzle is not valid.')
dialog.connect('response', destroyDialog)
dialog.show()
def checkSolvable(self, widget = None):
progress = ProgressDialog('Check Solvable')
progress.setLabel('Checking for solutions...')
progress.show()
progress.update()
solutions = self.board.solve(True, 2, progress = progress.pulse,
cancel = progress.cancelled)
cancelled = progress.isCancelled
progress.destroy()
if cancelled:
return
if solutions == 1:
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL,
gtk.MESSAGE_INFO, gtk.BUTTONS_OK)
dialog.set_markup('Puzzle is solvable.')
elif solutions == 0:
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL,
gtk.MESSAGE_WARNING, gtk.BUTTONS_OK)
dialog.set_markup('Puzzle has no solution.')
else:
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL,
gtk.MESSAGE_WARNING, gtk.BUTTONS_OK)
dialog.set_markup('Puzzle has multiple solutions.')
dialog.connect('response', destroyDialog)
dialog.show()
def difficulty(self, widget = None):
basePuzzle = self.board.copy(True)
progress = ProgressDialog('Difficulty')
progress.setLabel('Estimating difficulty...')
progress.show()
progress.update()
difficulty = basePuzzle.difficultyString(3, progress = progress.pulse,
cancel = progress.cancelled)
cancelled = progress.isCancelled
progress.destroy()
if cancelled:
return
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL,
gtk.MESSAGE_INFO, gtk.BUTTONS_OK)
dialog.set_markup('Puzzle difficulty: ' + difficulty)
dialog.connect('response', destroyDialog)
dialog.show()
def solve(self, action):
progress = ProgressDialog('Solve Puzzle')
progress.setLabel('Solving puzzle...')
progress.show()
progress.update()
solutions = self.board.solve(maxCount = 1, progress = progress.pulse,
cancel = progress.cancelled)
cancelled = progress.isCancelled
progress.destroy()
if cancelled:
return
if solutions:
actions = []
for y in range(self.board.regionCount[1] * self.board.regionSize[1]):
for x in range(self.board.regionCount[0] * self.board.regionSize[0]):
entry = self.cells[(x, y)]
actions.append(SetEntryAction(self, entry,
solutions[0][x, y].value,
False, entry.isPreset(),
False))
compound = CompoundAction(self, actions, 'Solve')
self.runAction(compound)
def duplicate(self, widget):
gui = SudokuGUI(self.board.copy(), dirty = True)
def newPuzzleDialog(self, widget):
newPuzzleDialog(widget, self)
def saveAsDialog(self, widget = None, destroyAfter = False):
filedialog = gtk.FileSelection('Save As')
filedialog.set_modal(True)
if destroyAfter:
filedialog.ok_button.connect_object('clicked', self.saveThenDestroy, filedialog)
else:
filedialog.ok_button.connect_object('clicked', self.saveFromDialog, filedialog)
filedialog.cancel_button.connect_object('clicked', destroyDialog, filedialog)
filedialog.show()
def saveThenDestroy(self, filedialog, overwrite = False):
self.saveFromDialog(filedialog, overwrite, True)
def saveFromDialog(self, filedialog, overwrite = False, destroyAfter = False):
filename = filedialog.get_filename()
if filename:
if not overwrite and os.path.exists(filename):
confirm = gtk.MessageDialog(filedialog, type=gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO)
confirm.set_markup('Overwrite %s?' % filename)
confirm.set_title('Confirm overwrite')
confirm.set_modal(True)
confirm.connect('response', self.confirmOverwrite, filedialog, destroyAfter)
confirm.show()
else:
self.setFilename(filename)
if self.saveFile():
filedialog.destroy()
if destroyAfter:
self.destroy()
def confirmOverwrite(self, dialog, response, filedialog, destroyAfter):
dialog.destroy()
if response == gtk.RESPONSE_YES:
self.saveFromDialog(filedialog, True, destroyAfter)
def saveFile(self, widget = None):
errorMessage = None
try:
writeSudoku(self.board, self.filename)
self.dirty = False
except IOError, error:
errorMessage = error.strerror + ': ' + error.filename
except:
errorMessage = 'An unknown error occurred.'
if errorMessage:
errorDialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL,
gtk.MESSAGE_ERROR, gtk.BUTTONS_OK)
errorDialog.set_markup(errorMessage)
errorDialog.connect('response', destroyDialog)
errorDialog.show()
return False
return True
def destroy(self, widget = None, data = None):
if data == gtk.RESPONSE_YES:
widget.destroy()
if self.filename:
if not self.saveFile():
return True
else:
self.saveAsDialog(destroyAfter = True)
return True
elif data == gtk.RESPONSE_CANCEL:
widget.destroy()
return True
elif data == gtk.RESPONSE_NO:
widget.destroy()
elif self.dirty:
self.window.grab_focus()
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL,
type = gtk.MESSAGE_QUESTION)
dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES,
gtk.STOCK_NO, gtk.RESPONSE_NO,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
message = 'Save changes to '
if self.filename:
message += os.path.basename(self.filename)
else:
message += 'untitled puzzle'
message += '?'
dialog.set_markup(message)
dialog.connect('response', self.destroy)
dialog.show()
return True
if self in openWindows:
openWindows.remove(self)
if openWindows:
self.window.destroy()
else:
quit()
class ProgressDialog(gtk.Dialog):
def __init__(self, title = 'Progress'):
gtk.Dialog.__init__(self, title,
buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
self.isCancelled = False
self.bar = gtk.ProgressBar()
self.bar.show()
self.label = gtk.Label()
self.vbox.pack_start(self.label, padding = 5)
self.vbox.pack_start(self.bar, padding = 5)
self.connect('response', self.cancel)
self.connect('destroy', self.cancel)
def setLabel(self, text):
if not self.isCancelled:
self.label.show()
self.label.set_text(text)
self.update()
def setText(self, text):
if not self.isCancelled:
self.bar.set_text(text)
self.update()
def setFraction(self, fraction):
if not self.isCancelled:
self.bar.set_fraction(fraction)
self.update()
def pulse(self):
if not self.isCancelled:
self.bar.pulse()
self.update()
def cancelled(self):
return self.isCancelled
def cancel(self, widget = None, data = None):
self.isCancelled = True
def update(self):
while gtk.events_pending():
gtk.main_iteration()
class ColourDialog(gtk.Dialog):
def __init__(self):
gtk.Dialog.__init__(self, 'Colours',
buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_OK, gtk.RESPONSE_OK))
self.table = gtk.Table(7, 2)
self.table.set_row_spacings(5)
self.table.set_col_spacings(5)
self.table.set_border_width(10)
self.table.show()
self.row = 0
self.oldBackground = settings.colourBackground
self.oldBorder = settings.colourBorder
self.oldPreset = settings.colourPreset
self.oldUnset = settings.colourUnset
self.oldRow = settings.colourRow
self.oldColumn = settings.colourColumn
self.oldRegion = settings.colourRegion
self.backgroundButton = self.createButton('Background', self.oldBackground)
self.borderButton = self.createButton('Border', self.oldBorder)
self.presetButton = self.createButton('Preset numbers', self.oldPreset)
self.unsetButton = self.createButton('Filled-in numbers', self.oldUnset)
self.rowButton = self.createButton('Hatch row', self.oldRow)
self.columnButton = self.createButton('Hatch column', self.oldColumn)
self.regionButton = self.createButton('Hatch region', self.oldRegion)
self.vbox.add(self.table)
self.connect('response', self.response)
self.show()
def createButton(self, text, colour):
label = gtk.Label(text)
label.show()
self.table.attach(label, 0, 1, self.row, self.row+1)
button = gtk.ColorButton(colour)
button.show()
button.set_title(text)
button.connect('color-set', self.setColour)
self.table.attach(button, 1, 2, self.row, self.row+1)
self.row += 1