def main(): # Process command line args parser = argparse.ArgumentParser(description="Sudoku Solver args", usage="Usage: {} " "<puzzle file name>".format( os.path.split(sys.argv[0])[1]), prog=os.path.split(sys.argv[0])[1]) parser.add_argument('--debug', dest='debug', default=False, action='store_true') parser.add_argument('file_name') args = parser.parse_args() file_name = args.file_name with open(file_name) as puzzle_file: # Read nine lines data = [puzzle_file.readline().strip() for i in range(9)] puzzle = SudokuBoard(itertools.chain(*data)) print('PUZZLE:') print(puzzle) print() if sudokusolver.solve(puzzle, args.debug): print('SOLUTION:') print(puzzle) else: print('Could not find a solution')
def main(): while keyboard.is_pressed("q") == False: print("Reading", end=" ") start_time = time.time_ns() unsolved_sudoku = web.read_from_webpage() print(f"took {(time.time_ns() - start_time)/1000000000} s") print("Solving", end=" ") start_time = time.time_ns() solved_sudoku = [line[:] for line in unsolved_sudoku] solved_sudoku = solver.solve(solved_sudoku) print(f"took {(time.time_ns() - start_time)/1000000000} s") print("Done\n") time.sleep(2) print("Starting new game") web.new_game()
def place(self, val): ''' Sets actual value if value is valid. ''' row, col = self.selected if self.cubes[row][col].value == 0: if validity(self.board, row, col, val): self.cubes[row][col].set(val) self.update_model() if solve(self.model): return True else: self.cubes[row][col].set(0) self.cubes[row][col].set_temp(0) self.update_model() return False
def print_solution_to_table(normal_table, digit_table): sudoku_string = '' for row in digit_table: sudoku_row = ' '.join(map(str, row)) sudoku_string += '\n' + sudoku_row.replace('-1', '?') # throws exception if unsolvable in case when the given table is broken solved_table = next(solve(sudoku_string)) size = normal_table.shape[0] - 2 * BORDER_SIZE h = size // 10 step = size // 100 for i in range(9): for j in range(9): if digit_table[i][j] == -1: solution = DIGITS[solved_table[i][j]] solution = cv2.resize(solution, (h - 2 * step, h - 2 * step), interpolation=cv2.INTER_AREA) x = step * (i + 1) + h * i + BORDER_SIZE + step // 2 y = step * (j + 1) + h * j + BORDER_SIZE + step // 2 normal_table[x:x + h - 2 * step, y:y + h - 2 * step] = solution return normal_table
def solve(pathImage): heightImg = 450 widthImg = 450 #prep the image # image = cv2.imread(pathImage) image = cv2.imread(pathImage) image = cv2.resize(image, (widthImg, heightImg)) imageBlank = np.zeros((heightImg, widthImg, 3), np.uint8) # blank test for debugging ? imageThreshold = pre_process(image) imageContours = image.copy() imageBigContour = image.copy() contours, hierarchy = cv2.findContours(imageThreshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(imageContours, contours, -1, (0, 255, 0), 3) biggest_square, max_area = biggest_contour(contours) if biggest_square.size != 0: #preparing and sorting image for warping as corners may not # be ordered accordingly biggest_square = reorder_points(biggest_square) # draws contours at square of the sudoku cv2.drawContours(imageBigContour, biggest_square, -1, (0, 0, 255), 25) point1 = np.float32(biggest_square) # prepare the points/coordinates # strctures all the points at each corner accordingly. point2 = np.float32([[0, 0], [widthImg, 0], [0, heightImg], [widthImg, heightImg]]) matrix = cv2.getPerspectiveTransform(point1, point2) imageWarp = cv2.warpPerspective(image, matrix, (widthImg, heightImg)) imageDetectedDigits = imageBlank.copy() imageWarpColored = cv2.cvtColor(imageWarp, cv2.COLOR_BGR2GRAY) image_solved_digits = imageBlank.copy() boxes = split_boxes(imageWarpColored) numbers = get_prediction(boxes, model) # I can probably check if the list of numbers exist in a db # if they do, I can return the solved board # this can optimize redundant computations imageDetectedDigits = display_numbers(imageDetectedDigits, numbers, color=(255, 0, 255)) numbers = np.asarray(numbers) # if the number is greater than 0 it will put 0 # otherwise, it will put in the same position. position_array = np.where(numbers > 0, 0, 1) sudoku_board = np.array_split(numbers, 9) try: sudokusolver.solve(sudoku_board) except: pass # change from np array to regular list regular_list = [] for rows in sudoku_board: for element in rows: regular_list.append(element) # this eliminates overlaying of elements that # are already populated in our sudoku board # when we populate input values from the board with zero # it allows us to overlay only non-populated grids. input_numbers = regular_list * position_array image_solved_digits = display_numbers(image_solved_digits, input_numbers) # prepare the points and fit the solved board # to the original picture first_point = np.float32([[0, 0], [widthImg, 0], [0, heightImg], [widthImg, heightImg]]) second_point = np.float32(biggest_square) matrix = cv2.getPerspectiveTransform(first_point, second_point) image_in_warp_colored = image.copy() image_in_warp_colored = cv2.warpPerspective(image_solved_digits, matrix, (widthImg, heightImg)) weight_perspective = cv2.addWeighted(image_in_warp_colored, 1, image, 0.5, 1) imageDetectedDigits = draw_grid(imageDetectedDigits) imageDetectedDigits = draw_grid(imageDetectedDigits) return [weight_perspective]
plotter.SCREEN.draw.text((10, 60), 'Sudoku puzzle not detected') plotter.SCREEN.update() plotter.unfeedPaper() plotter.beep('warning') plotter.waitButton(buttonType='any') continue cam.release() # solve sudoku originalSudoku = deepcopy(sudoku) plotter.SCREEN.clear() plotter.SCREEN.draw.text((65, 60), 'Solving...') plotter.SCREEN.update() retval, solvedSudoku = sudokusolver.solve(sudoku) if not retval: plotter.SCREEN.clear() plotter.SCREEN.draw.text((35, 60), 'Solution not found') plotter.SCREEN.update() plotter.unfeedPaper() plotter.beep('warning') plotter.waitButton(buttonType='any') continue # show solved sudoku on screen plotter.SCREEN.clear() lineY = 8 for i in range(3): for l in range(3):