Advertisement
Guest User

Untitled

a guest
Feb 12th, 2021
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. #Imoprt Tkinter module
  2. import tkinter as tk
  3.  
  4. #F to set grid and button
  5. def set_grid():
  6.     for x in range(9):
  7.         for y in range(9):
  8.             cell = tk.Entry(window, width = 2)
  9.             cell.grid(row = x, column = y)
  10.             sudoku[x].append(cell)
  11.     solve_but = tk.Button(window, text = "Solve", command = solve_sudoku)
  12.     solve_but.grid(row = 0, column = 9)
  13.  
  14. #F to find empty cell
  15. def find_empty():
  16.     for x in range(9):
  17.         for y in range(9):
  18.             if sudoku[x][y].get() == "":
  19.                 return (x, y)
  20.     return False
  21.  
  22. #F to get if num in col
  23. def num_in_col(y, num):
  24.     for x in range(9):
  25.         if sudoku[x][y].get() == str(num):
  26.             return True
  27.     return False
  28.  
  29. #F to get if num in row
  30. def num_in_row(x, num):
  31.     for y in range(9):
  32.         if sudoku[x][y].get() == str(num):
  33.             return True
  34.     return False
  35.  
  36. #F to get if num in box
  37. def num_in_box(xbox, ybox, num):
  38.     for x in range(3):
  39.         for y in range(3):
  40.             if sudoku[x + xbox][y + ybox].get() == str(num):
  41.                 return True
  42.     return False
  43.  
  44. #F to validate cell
  45. def validate_cell(x, y, num):
  46.     return not (num_in_row(x, num)) and not (num_in_col(y, num)) and not (num_in_box(x - (x % 3), y - (y % 3), num))
  47.  
  48. #F to solve puzzle
  49. def solve_sudoku():
  50.     find = find_empty()
  51.     if not find_empty():
  52.         return True
  53.     else:
  54.         x, y = find
  55.     for num in range(1, 10):
  56.         if validate_cell(x, y, num):
  57.             sudoku[x][y].delete(0, "end")
  58.             sudoku[x][y].insert(0, str(num))
  59.             sudoku[x][y].config(fg = "SpringGreen3")
  60.             #==> here goes the delay <==
  61.             if solve_sudoku():
  62.                 return True
  63.             sudoku[x][y].delete(0, "end")  
  64.     return False
  65.  
  66. #----------------- Main -----------------
  67. if __name__ == "__main__":
  68.     # Set window
  69.     window = tk.Tk()
  70.  
  71.     # Set sudoku
  72.     sudoku = [[] for _ in range(9)]
  73.  
  74.     # Set GUIs grid
  75.     set_grid()
  76.  
  77.     # Keep the app running
  78.     window.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement