def generate_sudoku_grid(difficulty): grid = generate_completed_grid(11) n_givens, lower_bound = specify_grid_properties(difficulty) dig_sequence = generate_dig_sequence(difficulty) holes = 0 while holes < 81 - n_givens: try: i = next(dig_sequence) except StopIteration: print("Reach end of Sequence") break row = int(i / 9) * 9 col = i % 9 if check_for_givens(grid[row:row+9]) > lower_bound and\ check_for_givens(grid[col::9]) > lower_bound: current_number = grid[i] other_numbers = solver.digits.replace(current_number, '') unique = True for digit in other_numbers: grid_check = grid[:i] + digit + grid[i + 1:] if solver.solve(solver.parse_grid(grid_check)): unique = False break if unique: grid = grid[:i] + '0' + grid[i + 1:] holes += 1 return grid
def title_loop(): running = True active_buttons = set() title_screen.draw(active_buttons) pygame.display.flip() while running: active_buttons = set() for button in title_screen.find_buttons(): active_buttons.add(button) title_screen.draw(active_buttons) for event in pygame.event.get(): if event.type == pygame.QUIT: raise SystemExit(0) if event.type == pygame.MOUSEBUTTONDOWN: for button in title_screen.find_buttons(): if button is play_button: display.blit(loading, (0, 0)) pygame.display.flip() global board board = Grid( Sudoku_Solver.generate_board(difficulty).values) board.notes = notes_button.on play_loop() elif button is options_button: options_loop() pygame.display.flip() pygame.time.Clock().tick(30)
def CallSolve(): Sudoku_Solver.Solve(sudoku) for i in range(1, 10): for j in range(1, 10): cube = Entry(window, width=2) cube.insert(END, sudoku[i - 1][j - 1]) cube.grid(row=i, column=j)
def generate_seed(): seed = np.random.choice(range(9), 9, replace=False) + 1 puzzle = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] row = seed[0] // 3 col = seed[0] - 3 * row for i in range(3): for j in range(3): puzzle[row + i][col + j] = int(seed[3 * i + j]) clauses = Sudoku_Solver.get_clauses(puzzle) seed = sat.solve(clauses) return Sudoku_Solver.parse_solution(seed)
def generate_completed_grid(n): # Generate a board by randomly picking n cells and # fill them a random digit from 1-9 values = solver.parse_grid('0' * 81) valid_assignments = 0 while valid_assignments < n: cell_to_assign = solver.squares[random.randint(0, 80)] valid_values = values[cell_to_assign] if len(valid_values): value_to_assign = valid_values[random.randint( 0, len(valid_values) - 1)] solver.assign(values, cell_to_assign, value_to_assign) valid_assignments += 1 complete_values = solver.solve(values) grid = '' for s in solver.squares: grid += complete_values[s] return grid
def main(): try: SOLVED_FLAG = False # Solved flag initialisation LOOP_FLAG = 0 input_suduko = __builtin__.saved_array if np.count_nonzero(input_suduko) < 17: raise Exception( "This Sudoku is unsolvable and must have at least 17 non zero elements" ) input_suduko_2d = [ np.array(input_suduko)[i:i + 9] for i in range(0, len(input_suduko), 9) ] input_suduko_3d = np.zeros((9, 9, 10)) input_suduko_3d[:, :, 0] = input_suduko_2d for i in range(1, 10): input_suduko_3d[:, :, i] = i while not SOLVED_FLAG: if LOOP_FLAG > 150: raise Exception("This Soduku is Unsolvable") for (x, y), value in np.ndenumerate(input_suduko_3d[:, :, 0]): if input_suduko_3d[x, y, 0] != 0: # Clear values that are in the third dimension behind a predefined value in the suduko # puzzle, no advantage except for visual debugging of potential element values for i in range(1, 10): input_suduko_3d[x, y, i] = '100' Sudoku_Solver.in_row(x, x, y, input_suduko_3d) Sudoku_Solver.in_column(y, x, y, input_suduko_3d) Sudoku_Solver.in_block(x, y, input_suduko_3d) for (x, y), value_input_sudoku in np.ndenumerate(input_suduko_3d[:, :, 0]): maybe = [] for i, value in enumerate(input_suduko_3d[x, y, 1:]): if value != 0: maybe.append(value) if len(maybe) == 1: input_suduko_3d[x, y, 0] = maybe[0] if 0 not in input_suduko_3d[:, :, 0]: SOLVED_FLAG = True __builtin__.saved_array = input_suduko_3d[:, :, 0] print __builtin__.saved_array LOOP_FLAG += 1 except Exception, ERROR: ERROR
def __init__(self, values): '''Loads an image of the playable board''' # Generates board values Sudoku_Solver.Board.__init__(self, values) self.solved = Sudoku_Solver.Board(copy.deepcopy(self.values)) self.solved = next(self.solved.solve()) self.full = False self.notes = False self.note_values = {(y, x): set() for y in range(9) for x in range(9)} # Loads in board assets self.board = image_load('Board.png') self.timer = image_load('Timer.png') self.board_rect = pygame.Rect(width // 2 - self.board.get_width() // 2, height // 2 - self.board.get_height() // 2, self.board.get_width(), self.board.get_height()) self.timer_rect = pygame.Rect(width // 2 - self.timer.get_width() // 2, self.board_rect.top - self.timer.get_height() + 17, self.timer.get_width(), self.timer.get_height()) self.digit_pics = {i: image_load(str(i) + '.png') for i in range(10)} self.user_digit_pics = {i: image_load('User_' + str(i) + '.png') for i in range(1, 10)} self.error_digit_pics = {i: image_load('Error_' + str(i) + '.png') for i in range(1, 10)} self.note_digit_pics = {i: image_load('Notes_' + str(i) + '.png') for i in range(1, 10)} self.highlight_digit_pics = {i: image_load( 'Highlight_' + str(i) + '.png') for i in range(1, 10)} self.cursor = image_load('Cursor.png') self.active_cursor = image_load('Active_Cursor.png') # Saves the board's starting values so they can be differentiated from # user input self.starting_values = set() self.past_moves = [] for y in range(9): for x in range(9): if self.values[y][x] != 0: self.starting_values.add((y, x)) self.errors = set() self.active_square = [0, 0]
def main(): try: SOLVED_FLAG = False # Solved flag initialisation LOOP_FLAG = 0 input_suduko = __builtin__.saved_array if np.count_nonzero(input_suduko) < 17: raise Exception("This Sudoku is unsolvable and must have at least 17 non zero elements") input_suduko_2d = [np.array(input_suduko)[i:i + 9] for i in range(0, len(input_suduko), 9)] input_suduko_3d = np.zeros((9, 9, 10)) input_suduko_3d[:, :, 0] = input_suduko_2d for i in range(1, 10): input_suduko_3d[:, :, i] = i while not SOLVED_FLAG: if LOOP_FLAG > 150: raise Exception("This Soduku is Unsolvable") for (x, y), value in np.ndenumerate(input_suduko_3d[:, :, 0]): if input_suduko_3d[x, y, 0] != 0: # Clear values that are in the third dimension behind a predefined value in the suduko # puzzle, no advantage except for visual debugging of potential element values for i in range(1, 10): input_suduko_3d[x, y, i] = '100' Sudoku_Solver.in_row(x, x, y, input_suduko_3d) Sudoku_Solver.in_column(y, x, y, input_suduko_3d) Sudoku_Solver.in_block(x, y, input_suduko_3d) for (x, y), value_input_sudoku in np.ndenumerate(input_suduko_3d[:, :, 0]): maybe = [] for i, value in enumerate(input_suduko_3d[x, y, 1:]): if value != 0: maybe.append(value) if len(maybe) == 1: input_suduko_3d[x, y, 0] = maybe[0] if 0 not in input_suduko_3d[:, :, 0]: SOLVED_FLAG = True __builtin__.saved_array = input_suduko_3d[:, :, 0] print __builtin__.saved_array LOOP_FLAG += 1 except Exception, ERROR: ERROR
def generate_puzzle(seed): unique = True puzzle = np.array(seed) seed = seed.flatten() elements = list(range(81)) while unique: # remove some stuff ind = np.random.choice(elements) elements.remove(ind) seed[ind] = int(0) # check if unique puzzle = list(np.reshape(seed, (9, 9))) clauses = Sudoku_Solver.get_clauses(puzzle) solutions = len(list(sat.itersolve(clauses))) if solutions > 1: unique = False return puzzle
seed[ind] = int(0) # check if unique puzzle = list(np.reshape(seed, (9, 9))) clauses = Sudoku_Solver.get_clauses(puzzle) solutions = len(list(sat.itersolve(clauses))) if solutions > 1: unique = False return puzzle if __name__ == "__main__": seed = generate_seed() print("########### seed ###########") print(Sudoku_Solver.pretty(seed)) # TODO: write to file puzzle = generate_puzzle(seed) print("########### puzzle ###########") print(Sudoku_Solver.pretty(puzzle)) solution = Sudoku_Solver.solve_puzzle(puzzle) print("########### solution ###########") print(Sudoku_Solver.pretty(solution)) Sudoku_Solver.check_solution(solution)
from tkinter import * import Sudoku_Solver sudoku = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] solved = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]] Sudoku_Solver.Solve(solved) def CallSolve(): Sudoku_Solver.Solve(sudoku) for i in range(1, 10): for j in range(1, 10): cube = Entry(window, width=2) cube.insert(END, sudoku[i - 1][j - 1]) cube.grid(row=i, column=j) def PrintGrid(): for i in range(9): for j in range(9):
imgWarpColored = cv2.cvtColor(imgWarpColored, cv2.COLOR_BGR2GRAY) #### 4. SPLIT THE IMAGE AND FIND EACH DIGIT AVAILABLE imgSolvedDigits = imgBlank.copy() boxes = splitBoxes(imgWarpColored) numbers = getPredection(boxes, model) imgDetectedDigits = displayNumbers(imgDetectedDigits, numbers, color=(255, 0, 255)) numbers = np.asarray(numbers) posArray = np.where(numbers > 0, 0, 1) #### 5. FIND SOLUTION OF THE BOARD board = np.array_split(numbers, 9) try: Sudoku_Solver.solve(board) except: pass flatList = [] for sublist in board: for item in sublist: flatList.append(item) solvedNumbers = flatList * posArray imgSolvedDigits = displayNumbers(imgSolvedDigits, solvedNumbers) # #### 6. OVERLAY SOLUTION pts2 = np.float32(biggest) # PREPARE POINTS FOR WARP pts1 = np.float32([[0, 0], [widthImg, 0], [0, heightImg], [widthImg, heightImg]]) # PREPARE POINTS FOR WARP matrix = cv2.getPerspectiveTransform(pts1, pts2) # GER imgInvWarpColored = img.copy()