def keyPressEvent(self, event): """ Handles key presses. If is a number key, update the value in selected cell """ key = event.key() keyStr = event.text() if self.selectedCell and self.selectedCell.CanEdit(): # If number key pressed if QtCore.Qt.Key_1 <= key <= QtCore.Qt.Key_9: self.selectedCell.UpdateValue(keyStr) self.currBoard[self.selectedCell.i][self.selectedCell.j] = int( keyStr) # self.UpdatePossibleCandidates() if key == QtCore.Qt.Key_Backspace: self.selectedCell.UpdateValue(' ') self.currBoard[self.selectedCell.i][self.selectedCell.j] = 0 # self.candBoard = sd.SolveCandidates(self.currBoard) dups = sd.FindDuplicates(self.currBoard) if not sd.CheckValid(dups): print('Invalid', dups) self.ShowInvalidCells(dups)
def FillinSingleCandidatesStep(self): """ Look for cells with only 1 candidate and fill them in. Updates the candidates after finished """ self.ClearHighlights() dups = sd.FindDuplicates(self.currBoard) if sd.CheckValid(dups): prevBoard = deepcopy(self.currBoard) changed, self.currBoard, self.candBoard = sd.FillSingleCandidates( self.currBoard, self.candBoard) if changed: self.UpdateChangedCells(prevBoard) dups = sd.FindDuplicates(self.currBoard) if not sd.CheckValid(dups): print('Invalid') self.ShowInvalidCells(dups)
def Solve(self): """ Solves the board using the backtracking alogorithm """ if sd.BoardSolved(self.currBoard): return self.ClearHighlights() dups = sd.FindDuplicates(self.currBoard) NumSolns = 0 if sd.CheckValid(dups): self.FillinSingleCandidates() prevBoard = deepcopy(self.currBoard) print('Start Solver') NumSolns, solnBoard = sd.SolvewBacktrack(self.currBoard) print('End Solver') if NumSolns == 0: print('No solution') self.msgText.setText('Num Solutions: 0') elif NumSolns == 1: self.currBoard = solnBoard self.UpdateChangedCells(prevBoard) dups = sd.FindDuplicates(self.currBoard) if not sd.CheckValid(dups): print('Invalid') NumSolns = 0 else: print('Single Solution') else: print('Multiple Solutions') if NumSolns == 1: self.msgText.setStyleSheet( "border: 1px solid black; color: black;") else: self.msgText.setStyleSheet("border: 1px solid black; color: red;") self.msgText.setText('Num Solutions: ' + str(NumSolns)) self.ShowInvalidCells(dups)
def FillinSingleCandidates(self): """ Look for cells with only 1 candidate and fill them in Then update candidates and iterate until no more changes """ self.ClearHighlights() dups = sd.FindDuplicates(self.currBoard) if sd.CheckValid(dups): notdone = True prevBoard = deepcopy(self.currBoard) while notdone: notdone, self.currBoard, self.candBoard = sd.FillSingleCandidates( self.currBoard, self.candBoard) self.UpdateChangedCells(prevBoard) dups = sd.FindDuplicates(self.currBoard) if not sd.CheckValid(dups): print('Invalid') self.ShowInvalidCells(dups)