Пример #1
0
    def remove_nums_from_grid(self):

        # get all non-empty squares from the grid
        non_empty_squares = self.get_non_empty_squares(self.grid)
        non_empty_squares_count = len(non_empty_squares)

        # decremented for each non-unique solution found
        rounds = 3

        # minimum 17 clues
        while rounds > 0 and non_empty_squares_count >= self.num_min_clues:
            row, col = non_empty_squares.pop()
            non_empty_squares_count -= 1

            removed_square = self.grid[row][col]
            self.grid[row][col] = 0

            grid_copy = copy.deepcopy(self.grid)

            self.counter = 0

            if (sudoku_solver.solve(grid_copy)):
                sudoku_solver.solve(grid_copy)
                self.counter += 1

            if self.counter != 1:
                self.grid[row][col] = removed_square
                non_empty_squares_count += 1
                rounds -= 1
        return
Пример #2
0
def main():
    pygame.init()

    fps_clock = pygame.time.Clock()
    main_window = pygame.display.set_mode((WIDTH, HEIGHT))
    font = pygame.font.SysFont(None, 60)

    pygame.display.set_caption("Sudoku")
    pygame.display.set_icon(pygame.image.load("Logo.png"))

    run = True
    # Main loop
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    movement(RED, main_window, 1, point_zero)
                if event.key == pygame.K_UP:
                    movement(RED, main_window, 2, point_zero)
                if event.key == pygame.K_RIGHT:
                    movement(RED, main_window, 3, point_zero)
                if event.key == pygame.K_DOWN:
                    movement(RED, main_window, 4, point_zero)
                if event.key == pygame.K_KP0:
                    grid_change(0)
                if event.key == pygame.K_KP1:
                    grid_change(1)
                if event.key == pygame.K_KP2:
                    grid_change(2)
                if event.key == pygame.K_KP3:
                    grid_change(3)
                if event.key == pygame.K_KP4:
                    grid_change(4)
                if event.key == pygame.K_KP5:
                    grid_change(5)
                if event.key == pygame.K_KP6:
                    grid_change(6)
                if event.key == pygame.K_KP7:
                    grid_change(7)
                if event.key == pygame.K_KP8:
                    grid_change(8)
                if event.key == pygame.K_KP9:
                    grid_change(9)
                if event.key == pygame.K_KP_ENTER:
                    solve(sudoku_grid)
                if event.key == pygame.K_BACKSPACE:
                    clear_grid()

        main_window.fill(WHITE)
        movement(RED, main_window, 0, point_zero)
        draw_grid(BLACK, main_window, font)
        pygame.display.flip()
        fps_clock.tick(FPS)
Пример #3
0
def solve_sudoku(sudoku_unsolved, shape):
    sudoku_image = np.zeros(shape, np.uint8)
    y = -1
    x = 0
    sudoku_solved = sudoku_solver.solve("".join(sudoku_unsolved).replace(
        "0", "."))
    factor = shape[0] // 9
    for num in sudoku_unsolved:
        if (x % 9) == 0:
            x = 0
            y += 1
        textX = int(factor * x + factor / 2)
        textY = int(factor * y + factor / 2)
        font = cv2.FONT_HERSHEY_SIMPLEX
        if num != '0':
            cv2.putText(sudoku_image, str(num), (textX, textY), font, 1,
                        (255, 255, 255), 6)
        x += 1

    for i in range(10):
        cv2.line(sudoku_image, (0, factor * i), (shape[1], factor * i), (255),
                 2, 2)
        cv2.line(sudoku_image, (factor * i, 0), (factor * i, shape[0]), (255),
                 2, 2)

    return sudoku_solved, sudoku_image
Пример #4
0
def sudoku_solve():
    """calls solution methods"""
    solve_prompt1 = "Let's solve your board! Please enter your row line by line - comma separated in the format of num1, num2, num3, ..., num9. Use 0 to denote an empty sudoku square."
    grid_prompt = "The board you gave:"

    while True:
        try:
            board = gather_input(solve_prompt1)
            Solver.grid = board
            print(grid_prompt)
            Solver.print_grid()
            Solver.solve()
            print("Goodbye!")
            return
        except:
            input_error()
Пример #5
0
def test_already_solved():
    # fmt: off
    bd_solved = [
        3, 9, 6, 2, 7, 8, 4, 5, 1, 4, 8, 5, 9, 1, 3, 7, 2, 6, 2, 7, 1, 6, 4, 5,
        8, 3, 9, 5, 4, 7, 8, 2, 9, 6, 1, 3, 8, 1, 2, 7, 3, 6, 5, 9, 4, 6, 3, 9,
        4, 5, 1, 2, 8, 7, 1, 5, 8, 3, 6, 4, 9, 7, 2, 7, 6, 3, 5, 9, 2, 1, 4, 8,
        9, 2, 4, 1, 8, 7, 3, 6, 5
    ]
    # fmt: on
    assert solve(bd_solved) == bd_solved
Пример #6
0
        def generate_board(self):
            if (self.mode == "easy"):
                    self.sudoku_generator = sudoku_generator.SudokuGenerator(37)
            elif (self.mode == "medium"):
                self.sudoku_generator = sudoku_generator.SudokuGenerator(27)
            elif (self.mode == "hard"):
                self.sudoku_generator = sudoku_generator.SudokuGenerator(19)
            else:
                self.sudoku_generator = sudoku_generator.SudokuGenerator(17)

            self.board = self.sudoku_generator.get_puzzle()
            self.original = copy.deepcopy(self.board) # used when the user restarts the game
            self.board_copy = copy.deepcopy(self.board)
                        
            if(sudoku_solver.solve(self.board_copy)):
                sudoku_solver.solve(self.board_copy)
                self.solution = self.board_copy
            else:
                raise Exception('Error: This board cannot be solved.')
Пример #7
0
def test_full_and_invalid():
    # fmt: off
    # '1' twice in first column and row
    bd_full_invalid = [
        1, 9, 6, 2, 7, 8, 4, 5, 1, 4, 8, 5, 9, 1, 3, 7, 2, 6, 2, 7, 1, 6, 4, 5,
        8, 3, 9, 5, 4, 7, 8, 2, 9, 6, 1, 3, 8, 1, 2, 7, 3, 6, 5, 9, 4, 6, 3, 9,
        4, 5, 1, 2, 8, 7, 1, 5, 8, 3, 6, 4, 9, 7, 2, 7, 6, 3, 5, 9, 2, 1, 4, 8,
        9, 2, 4, 1, 8, 7, 3, 6, 5
    ]
    # fmt: on
    assert solve(bd_full_invalid) is False
Пример #8
0
def main():
    mainBoard = None

    while True:
        user_decision = str(input("Would you like to input a board(Yes/No): "))

        if user_decision[0].lower() == 'n':
            user_board_size = str(
                input("What size sudoku board?(4x4/6x6/9x9): "))
            if user_board_size[0] == '4':
                mainBoard = board_printer.boards()[0]
            elif user_board_size[0] == '6':
                mainBoard = board_printer.boards()[1]
            elif user_board_size[0] == '9':
                mainBoard = board_printer.boards()[2]
            else:
                print(f"Incorrect size {user_board_size}")
                break

        elif user_decision[0].lower() == 'y':
            board = []
            print("Empty cell should be marked as 0")
            print("Seperate cell values with a space or delimeter(,/./;)")
            i = 1
            board_size = 9
            while i <= board_size:
                if len(
                        board
                ) == 1:  # if user already inputed first sudoku board line
                    if len(board[0]) < 9:  # if the board is smaller then 9x9
                        # add the size difference to the i +2 because 1 for current row and one for starting row
                        i = 9 - len(board[0]) + 2

                user_line = input("> ")
                line = re.findall(r'\d+', user_line)
                if __checkInput(line, board_size):
                    board.append(line)
                    i += 1

            mainBoard = board

        if mainBoard is not None:
            print("Unsolved grid:")
            board_printer.printBoard(mainBoard)
            try:
                solvedBoard = solver.solve(mainBoard)
                print(" ")

                print("Solved grid:")
                board_printer.printBoard(solvedBoard)
            except (IndexError, NotImplementedError):
                break
            break
Пример #9
0
    def place(self, val):
        row, col = self.selected
        if self.cubes[row][col].value == 0:
            self.cubes[row][col].set(val)
            self.update_model()

            if valid(self.model, val, (row, col)) and solve(self.model):
                return True
            else:
                self.cubes[row][col].set(0)
                self.cubes[row][col].set_temp(0)
                self.update_model()
                return False
Пример #10
0
    def draw(self, window, board):
        """Draws the button

        Args:
            window: The main window instance
            board: A 2D array containing the current contents of the board

        Returns:
            A 2D array containing the solved board if the button is clicked
            Else it returns None
        """
        if self.clicked:
            pygame.draw.rect(window, (218, 132, 245), ((540/2)-40, 560, 80, 30))
            solve(board)
            return board
        else:
            pygame.draw.rect(window, (143, 220, 249), ((540/2)-40, 560, 80, 30))

        font = pygame.font.SysFont("verdana", 20)
        text = font.render("Solve", 1, (0, 0, 0))
        window.blit(text, ((540/2)-40+13, 565))
        return None
Пример #11
0
def removable(cell, sudoku):
    """
    checks if a cell can be removed from the grid keeping it valid (no
    multiple solutions).
    :param cell:
    :param sudoku:
    :param level:
    :return: bool
    """
    sudoku_temp = sudoku.copy()
    sudoku_temp[cell] = '123456789'
    if ss.solve(sudoku_temp)[1] == 'VALID':
        return True
Пример #12
0
def run(maxIter=20, dataSet=2):
    puzzles, solutions = data.get(dataSet)
    correct = 0
    start = timer()
    for i in range(len(puzzles)):
        puzzle, solution = puzzles[i], solutions[i]
        mySolution, myNotes = sudoku_solver.solve(puzzle, maxIter)
        if match(mySolution, solution) == True:
            correct += 1
    end = timer()
    #print("- " + str(correct) + " puzzle(s) solved correctly")
    #print("- Accuracy = " + str(int((correct/len(puzzles)) * 100)) + "%")
    #print("- Total amount of time used to solve the puzzles = " + str(end-start) + " seconds")
    return
Пример #13
0
def main():
    scanFrameNumber = 5
    frameCount = 0

    image = imageClass()

    if sys.argv[1] == "cam":

        cv2.namedWindow("preview")
        vc = cv2.VideoCapture(0)

        if vc.isOpened():  # try to get the first frame
            rval, frame = vc.read()
        else:
            rval = False

        while rval:
            img = image.captureAndCrop(frame)
            if img is not None:
                sudoku = image.readSudoku()
                if sudoku is not None:
                    grid = solver.sudokuToGrid(sudoku)
                    solvedGrid = solver.solve(grid)
                    if solvedGrid:
                        solution = solver.gridToSudoku(solvedGrid)
                        inverted = image.invertSudoku(sudoku, solution)
                        frame = image.writeSudoku(inverted)
                        cv2.imwrite("out/solution.png", frame)

            frame = iu.resize(frame, width=800)
            cv2.imshow("preview", frame)

            rval, frame = vc.read()
            frameCount += 1
            key = cv2.waitKey(20)
            if key == 27:  # exit on ESC
                break
        cv2.destroyWindow("preview")

    else:
        img = cv2.imread(sys.argv[1])

        solvedImg = getSolvedImage(img)

        #img = cv2.imread('out/cutted.png')
        cv2.imshow("ref", solvedImg)
        key = cv2.waitKey(0)
        if key == 27:
            sys.exit()
Пример #14
0
    def test_sudoku_solver_with_cs(self):
        """
        Tests with constraint satisfaction heuristics.
        """
        for case in self.cases:
            with self.subTest(case=case):
                puzzle, solution = case
                with open(puzzle) as f:
                    sample_input = f.read().strip()
                    actual_output = solve(sample_input, print_results=False)

                with open(solution) as f:
                    expected_output = f.read().strip()

                assert actual_output == expected_output
Пример #15
0
def getSolvedImage(img):
    image = imageClass()
    if img is not None:
        sudoku = image.captureAndCrop(img)
        if sudoku is not None:
            sudoku = image.readSudoku()
            if sudoku is not None:
                grid = solver.sudokuToGrid(sudoku)
                solvedGrid = solver.solve(grid)
                if solvedGrid:
                    solution = solver.gridToSudoku(solvedGrid)
                    inverted = image.invertSudoku(sudoku, solution)
                    frame = image.writeSudoku(inverted)
                    return frame
    return False
Пример #16
0
def random_grid_generator():
    """
    Generates a complete grid from random input
    :return: a completed sudoku dictionary
    """
    sudoku_list = ['0' * 9] * 9
    sudoku_list[0] = [str(i) for i in range(1, 10)]
    sudoku_list[4] = [str(i) for i in range(1, 10)]
    sudoku_list[8] = [str(i) for i in range(1, 10)]
    shuffle(sudoku_list[0])
    shuffle(sudoku_list[4])
    shuffle(sudoku_list[8])
    for i in range(len(sudoku_list)):
        sudoku_list[i] = ''.join(sudoku_list[i])
    solved_sudoku = ss.list_to_sudoku(sudoku_list)
    return ss.solve(solved_sudoku)
Пример #17
0
    def place(self, val):

        # sets selected cell with value
        row, col = self.selected
        if self.cells[row][col].value == 0:
            self.cells[row][col].set(val)
            self.update_model()

        # checks if value is correct (if correct place it, if not remove it)
        if valid(self.model, val, (row, col)) and solve(self.model):
            self.board[row][col] = val
            return True
        else:
            self.cells[row][col].set(0)
            self.cells[row][col].set_temp(0)
            self.update_model()
            return False
def test_missing_1_element(name, blank_indices):
    # fmt: off
    bd_solved = [3, 9, 6, 2, 7, 8, 4, 5, 1,
                 4, 8, 5, 9, 1, 3, 7, 2, 6,
                 2, 7, 1, 6, 4, 5, 8, 3, 9,
                 5, 4, 7, 8, 2, 9, 6, 1, 3,
                 8, 1, 2, 7, 3, 6, 5, 9, 4,
                 6, 3, 9, 4, 5, 1, 2, 8, 7,
                 1, 5, 8, 3, 6, 4, 9, 7, 2,
                 7, 6, 3, 5, 9, 2, 1, 4, 8,
                 9, 2, 4, 1, 8, 7, 3, 6, 5]

    bd_unsolved = bd_solved[:]
    for blank_index in blank_indices:
        bd_unsolved[blank_index] = B

    assert solve(bd_unsolved) == bd_solved
Пример #19
0
def test_solves_another_easy_puzzle():
    # arrange
    board: Board = [[1, 0, 0, 4, 8, 9, 0, 0, 6], [7, 3, 0, 0, 0, 0, 0, 4, 0],
                    [0, 0, 0, 0, 0, 1, 2, 9, 5], [0, 0, 7, 1, 2, 0, 6, 0, 0],
                    [5, 0, 0, 7, 0, 0, 0, 0, 8], [0, 0, 6, 0, 9, 5, 7, 0, 0],
                    [9, 1, 4, 6, 0, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 3, 7],
                    [8, 0, 0, 5, 1, 2, 0, 0, 4]]

    # act + assert
    expected_solution: Board = [[1, 5, 2, 4, 8, 9, 3, 7, 6],
                                [7, 3, 9, 2, 5, 6, 8, 4, 1],
                                [4, 6, 8, 3, 7, 1, 2, 9, 5],
                                [3, 8, 7, 1, 2, 4, 6, 5, 9],
                                [5, 9, 1, 7, 6, 3, 4, 2, 8],
                                [2, 4, 6, 8, 9, 5, 7, 1, 3],
                                [9, 1, 4, 6, 3, 7, 5, 8, 2],
                                [6, 2, 5, 9, 4, 8, 1, 3, 7],
                                [8, 7, 3, 5, 1, 2, 9, 6, 4]]
    assert solve(board) == expected_solution
Пример #20
0
def test_solves_easy_puzzle():
    # arrange
    board: Board = [[0, 0, 0, 2, 6, 0, 7, 0, 1], [6, 8, 0, 0, 7, 0, 0, 9, 0],
                    [1, 9, 0, 0, 0, 4, 5, 0, 0], [8, 2, 0, 1, 0, 0, 0, 4, 0],
                    [0, 0, 4, 6, 0, 2, 9, 0, 0], [0, 5, 0, 0, 0, 3, 0, 2, 8],
                    [0, 0, 9, 3, 0, 0, 0, 7, 4], [0, 4, 0, 0, 5, 0, 0, 3, 6],
                    [7, 0, 3, 0, 1, 8, 0, 0, 0]]

    # act + assert
    expected_solution: Board = [[4, 3, 5, 2, 6, 9, 7, 8, 1],
                                [6, 8, 2, 5, 7, 1, 4, 9, 3],
                                [1, 9, 7, 8, 3, 4, 5, 6, 2],
                                [8, 2, 6, 1, 9, 5, 3, 4, 7],
                                [3, 7, 4, 6, 8, 2, 9, 1, 5],
                                [9, 5, 1, 7, 4, 3, 6, 2, 8],
                                [5, 1, 9, 3, 2, 6, 8, 7, 4],
                                [2, 4, 8, 9, 5, 7, 1, 3, 6],
                                [7, 6, 3, 4, 1, 8, 2, 5, 9]]
    assert solve(board) == expected_solution
Пример #21
0
def test_solves_very_hard_puzzle():
    # arrange
    board: Board = [[0, 2, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 6, 0, 0, 0, 0, 3],
                    [0, 7, 4, 0, 8, 0, 0, 0, 0], [0, 0, 0, 0, 0, 3, 0, 0, 2],
                    [0, 8, 0, 0, 4, 0, 0, 1, 0], [6, 0, 0, 5, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 1, 0, 7, 8, 0], [5, 0, 0, 0, 0, 9, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 4, 0]]

    # act + assert
    expected_solution: Board = [[1, 2, 6, 4, 3, 7, 9, 5, 8],
                                [8, 9, 5, 6, 2, 1, 4, 7, 3],
                                [3, 7, 4, 9, 8, 5, 1, 2, 6],
                                [4, 5, 7, 1, 9, 3, 8, 6, 2],
                                [9, 8, 3, 2, 4, 6, 5, 1, 7],
                                [6, 1, 2, 5, 7, 8, 3, 9, 4],
                                [2, 6, 9, 3, 1, 4, 7, 8, 5],
                                [5, 4, 8, 7, 6, 9, 2, 3, 1],
                                [7, 3, 1, 8, 5, 2, 6, 4, 9]]
    assert solve(board) == expected_solution
Пример #22
0
def test_missing_6_and_1():
    # fmt: off
    bd = [
        1, 2, 3, 4, 5, 6, 7, 8, 9, 7, 8, 9, 1, 2, 3, 4, 5, 6, 4, 5, B, 7, 8, 9,
        1, 2, 3, 3, 1, 2, 8, 4, 5, 9, 6, 7, 6, 9, 7, 3, 1, 2, 8, 4, 5, 8, 4, 5,
        6, 9, 7, 3, 1, 2, 2, 3, 1, 5, 7, 4, 6, 9, 8, 9, 6, 8, 2, 3, 1, 5, 7, 4,
        5, 7, 4, 9, 6, 8, 2, 3, B
    ]

    assert solve(bd) == \
        [1, 2, 3, 4, 5, 6, 7, 8, 9,
         7, 8, 9, 1, 2, 3, 4, 5, 6,
         4, 5, 6, 7, 8, 9, 1, 2, 3,
         3, 1, 2, 8, 4, 5, 9, 6, 7,
         6, 9, 7, 3, 1, 2, 8, 4, 5,
         8, 4, 5, 6, 9, 7, 3, 1, 2,
         2, 3, 1, 5, 7, 4, 6, 9, 8,
         9, 6, 8, 2, 3, 1, 5, 7, 4,
         5, 7, 4, 9, 6, 8, 2, 3, 1]
def test_missing_3():
    # fmt: off
    bd = [
        2, 1, B, 4, 5, 6, 7, 8, 9, 7, 8, 9, 2, 1, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9,
        2, 1, 3, 3, 2, 1, 8, 4, 5, 9, 6, 7, 6, 9, 7, 3, 2, 1, 8, 4, 5, 8, 4, 5,
        6, 9, 7, 3, 2, 1, 1, 3, 2, 5, 7, 4, 6, 9, 8, 9, 6, 8, 1, 3, 2, 5, 7, 4,
        5, 7, 4, 9, 6, 8, 1, 3, 2
    ]

    assert solve(bd) == \
        [2, 1, 3, 4, 5, 6, 7, 8, 9,
         7, 8, 9, 2, 1, 3, 4, 5, 6,
         4, 5, 6, 7, 8, 9, 2, 1, 3,
         3, 2, 1, 8, 4, 5, 9, 6, 7,
         6, 9, 7, 3, 2, 1, 8, 4, 5,
         8, 4, 5, 6, 9, 7, 3, 2, 1,
         1, 3, 2, 5, 7, 4, 6, 9, 8,
         9, 6, 8, 1, 3, 2, 5, 7, 4,
         5, 7, 4, 9, 6, 8, 1, 3, 2]
def test_missing_4():
    # fmt: off
    bd = [
        5, 3, B, 6, 7, 8, 9, 1, 2, 6, 7, 2, 1, 9, 5, 3, 4, 8, 1, 9, 8, 3, 4, 2,
        5, 6, 7, 8, 5, 9, 7, 6, 1, 4, 2, 3, 4, 2, 6, 8, 5, 3, 7, 9, 1, 7, 1, 3,
        9, 2, 4, 8, 5, 6, 9, 6, 1, 5, 3, 7, 2, 8, 4, 2, 8, 7, 4, 1, 9, 6, 3, 5,
        3, 4, 5, 2, 8, 6, 1, 7, 9
    ]

    assert solve(bd) == \
        [5, 3, 4, 6, 7, 8, 9, 1, 2,
         6, 7, 2, 1, 9, 5, 3, 4, 8,
         1, 9, 8, 3, 4, 2, 5, 6, 7,
         8, 5, 9, 7, 6, 1, 4, 2, 3,
         4, 2, 6, 8, 5, 3, 7, 9, 1,
         7, 1, 3, 9, 2, 4, 8, 5, 6,
         9, 6, 1, 5, 3, 7, 2, 8, 4,
         2, 8, 7, 4, 1, 9, 6, 3, 5,
         3, 4, 5, 2, 8, 6, 1, 7, 9]
def test_missing_6():
    # fmt: off
    bd = [
        3, 9, B, 2, 7, 8, 4, 5, 1, 4, 8, 5, 9, 1, 3, 7, 2, 6, 2, 7, 1, 6, 4, 5,
        8, 3, 9, 5, 4, 7, 8, 2, 9, 6, 1, 3, 8, 1, 2, 7, 3, 6, 5, 9, 4, 6, 3, 9,
        4, 5, 1, 2, 8, 7, 1, 5, 8, 3, 6, 4, 9, 7, 2, 7, 6, 3, 5, 9, 2, 1, 4, 8,
        9, 2, 4, 1, 8, 7, 3, 6, 5
    ]

    assert solve(bd) == \
        [3, 9, 6, 2, 7, 8, 4, 5, 1,
         4, 8, 5, 9, 1, 3, 7, 2, 6,
         2, 7, 1, 6, 4, 5, 8, 3, 9,
         5, 4, 7, 8, 2, 9, 6, 1, 3,
         8, 1, 2, 7, 3, 6, 5, 9, 4,
         6, 3, 9, 4, 5, 1, 2, 8, 7,
         1, 5, 8, 3, 6, 4, 9, 7, 2,
         7, 6, 3, 5, 9, 2, 1, 4, 8,
         9, 2, 4, 1, 8, 7, 3, 6, 5]
Пример #26
0
def test_missing_1_and_2():
    # fmt: off
    bd = [
        B, B, 3, 4, 5, 6, 7, 8, 9, 7, 8, 9, 1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9,
        1, 2, 3, 3, 1, 2, 8, 4, 5, 9, 6, 7, 6, 9, 7, 3, 1, 2, 8, 4, 5, 8, 4, 5,
        6, 9, 7, 3, 1, 2, 2, 3, 1, 5, 7, 4, 6, 9, 8, 9, 6, 8, 2, 3, 1, 5, 7, 4,
        5, 7, 4, 9, 6, 8, 2, 3, 1
    ]

    assert solve(bd) == \
        [1, 2, 3, 4, 5, 6, 7, 8, 9,
         7, 8, 9, 1, 2, 3, 4, 5, 6,
         4, 5, 6, 7, 8, 9, 1, 2, 3,
         3, 1, 2, 8, 4, 5, 9, 6, 7,
         6, 9, 7, 3, 1, 2, 8, 4, 5,
         8, 4, 5, 6, 9, 7, 3, 1, 2,
         2, 3, 1, 5, 7, 4, 6, 9, 8,
         9, 6, 8, 2, 3, 1, 5, 7, 4,
         5, 7, 4, 9, 6, 8, 2, 3, 1]
Пример #27
0
def test_missing_9():
    # fmt: off

    bd = [
        9, 1, 2, 3, 4, 5, 6, 7, 8, 6, 7, 8, 9, 1, 2, 3, 4, 5, 3, 4, 5, 6, 7, 8,
        9, 1, 2, 2, 9, 1, 7, 3, 4, 8, 5, 6, 5, 8, 6, 2, 9, 1, 7, 3, 4, 7, 3, 4,
        5, 8, 6, 2, 9, 1, 1, 2, 9, 4, 6, 3, 5, 8, 7, 8, 5, 7, 1, 2, 9, 4, 6, 3,
        4, 6, 3, 8, 5, 7, 1, 2, B
    ]

    assert solve(bd) == \
        [9, 1, 2, 3, 4, 5, 6, 7, 8,
         6, 7, 8, 9, 1, 2, 3, 4, 5,
         3, 4, 5, 6, 7, 8, 9, 1, 2,
         2, 9, 1, 7, 3, 4, 8, 5, 6,
         5, 8, 6, 2, 9, 1, 7, 3, 4,
         7, 3, 4, 5, 8, 6, 2, 9, 1,
         1, 2, 9, 4, 6, 3, 5, 8, 7,
         8, 5, 7, 1, 2, 9, 4, 6, 3,
         4, 6, 3, 8, 5, 7, 1, 2, 9]
Пример #28
0
    def place_value(self, val):
        """Places the value inside the cell

        Args:
            val: An integer representing the value to be placed

        Returns:
            A boolean indicating whether the placement was valid and successful
        """

        row, col = self.selected_cell
        if self.cells[row][col].value == 0:
            self.cells[row][col].set_value(val)
            self.update_model()
            print(is_valid(self.model, val, (row, col)))
            if is_valid(self.model, val, (row, col)) and solve(self.model):
                return True
            else:
                self.cells[row][col].set_value(0)
                self.cells[row][col].set_temp(0)
                self.update_model()
                return False
Пример #29
0
if use_default_image:
    opencv_image = cv2.imread('default.png')

elif uploaded_file is not None:
    file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
    opencv_image = cv2.imdecode(file_bytes, 1)

if opencv_image is not None:
    sudoku_image = extract(opencv_image)
    ex_digits = extract_number_from_image(sudoku_image)

    with st.spinner('Running a Neural Net to extract Sudoku from image'):
        time.sleep(2)
        st.success('Sudoku Has Been Successfully Extracted')

    #ex_digits = [[0 for _ in range(9)] for _ in range(9)]
    #print(ex_digits)
    st.markdown(ipmes + display(ex_digits))
    st.write('\n\n')

    with st.spinner('Sudoku is being solved'):
        time.sleep(1)
        sol = solve(ex_digits)

    if not sol:
        st.error("**This Sudoku can't be solved**.")
    else:
        st.title("**Solution**")
        st.markdown(opmes + display(ex_digits))
Пример #30
0
def main():
    global line_length
    global square_width, square_height
    global grid_topleft, grid_bottomright
    global answer1_pos, answer_dist
    global debug_folder_suffix
    
    # Create debug folder, if it's not exists
    try:
        os.mkdir("debug")
    except FileExistsError:
        pass

    # debug value: when set to True, all squares, lines etc. will be saved on thisk
    debug = True
    
    # If debug is enabled, create folder to save our images
    if debug:
        try:
            os.mkdir("debug/Images {}".format(debug_folder_suffix))
        except FileExistsError:
            pass

    t0 = time.time()

    # Connect
    my_device = connect()
    print('Connected ({} seconds elapsed)'.format(round(time.time() - t0, 2)))
    print('Creating sudoku grid...')

    # Take screenshot
    screenshot = takeScreenshot(my_device, save=debug)

    # Crop grid from screenshot
    picture_grid = screenshot.crop((grid_topleft[0], grid_topleft[1], grid_bottomright[0], grid_bottomright[1]))
    if debug:
        picture_grid.save('debug/Images {}/grid.png'.format(debug_folder_suffix))

    # find lines
    lines = getLines(picture_grid, save=debug)

    # Convert picture grid to list grid
    grid = list()
    for i in range(9):
        squares = getSquares(lines[i], suffix=i, save=debug)
        line = list()
        for square in squares:
            n = proccessSquare(square)
            line.append(n)
        grid.append(line)

    print('Sudoku grid created ({} seconds elapsed)'.format(round(time.time() - t0, 2)))
    print('Solving...')

    # Solve
    sudoku_solver.solve(grid)
    result = sudoku_solver.result

    print('Solved! ({} seconds elapsed)'.format(round(time.time() - t0, 2)))
    print('Solving the sudoku on your phone...')

    # Solve on phone (adb is so slow :( )
    for y in range(9):
        for x in range(9):
            if grid[y][x] == 0:
                tap_x = grid_topleft[0] + x * square_width + line_length[x] + square_width // 2
                tap_y = grid_topleft[1] + y * square_height + line_length[y] + square_height // 2
                my_device.shell('input tap {} {}'.format(tap_x, tap_y))
                answer = result[y, x]
                answer = answer - 1
                my_device.shell('input tap {} {}'.format(answer1_pos[0] + answer * answer_dist, answer1_pos[1]))
    print('Done!')
    print('Total time: {} seconds'.format(round(time.time() - t0, 2)))