def help_move(): user = UL.get_user(session['username']) csb = SudokuBoard(user.sb.grid) cds = [0, 0] csb.find_empty_space(cds) SudokuSolver.solve(csb) sb = user.sb sb.set_value(cds[0], cds[1], csb.grid[cds[0]][cds[1]]) user.csb = SudokuBoard(user.sb.grid) return redirect('/game')
def solution_search_display_setup(): title = "Solution Searching" SudokuPly.setDisplay(display_rtn, gb.Display_time) searching_mw = Toplevel() searching_mw.protocol("WM_DELETE_WINDOW", search_stop) searching_mw.title(title) x = 400 y = 600 searching_mw.geometry(f"+{x}+{y}") top_fr = Frame(searching_mw) top_fr.pack(side = 'top') c1 = Button(top_fr, text = "Close", # Guess one command = search_stop, ) c1.pack(side = 'left') if gb.res_group.get("searching_board") is not None: gb.res_group.destroy("searching_board") data = SudokuData.vals2data(gb.main_puzzle) searching_board = SudokuBoard(mw=searching_mw, data = data, bdWidth=gb.sSize*.8, bdHeight=gb.sSize*.8, initialData=gb.Initial_data, puzzle=gb.main_puzzle ) searching_board.showData(force=True) gb.res_group.add(ResourceEntry(searching_board), name="searching_board") gb.main_puzzle.set_start_time()
def set_puzzle(puzzle, file_name=None): """ Set/Reset main puzzle :puzzle: Puzzle to setup """ if file_name is not None: puzzle.file_name = file_name # override if desired if gb.main_puzzle is not None: gb.main_puzzle.destroy() gb.main_puzzle = None if gb.o_board is not None: gb.o_board.destroy() gb.main_puzzle = puzzle.copy() # Insulate from changes gb.puzzle = puzzle gb.o_board = SudokuBoard(mw=gb.Display_mw, frame=new_main_bd_frame(), data=puzzle, bdWidth=gb.bSize, bdHeight=gb.bSize, puzzle = puzzle) gb.o_board.showData(force=True) cF = SelectControl() cF.set_val("nRow", gb.main_puzzle.nRow) cF.set_val("nSubRow", gb.main_puzzle.nSubRow) cF.set_val("nCol", gb.main_puzzle.nCol) cF.set_val("nSubCol", gb.main_puzzle.nSubCol) cF.update_settings()#
def solve(self, boardString): sudoku_board = SudokuBoard() sudoku_board.from_string(boardString) if self.AC3(sudoku_board): return sudoku_board.to_string('AC3') else: return self.backtracking_search(sudoku_board)
def __init__(self, username): self.username = username self.easy_solved = 0 self.medium_solved = 0 self.hard_solved = 0 self.sb = SudokuBoard() self.csb = None self.logged_in = True self.solving = False
def __init__(self, game): root = Tk() console_frame = Frame(master=root) vertical_scrollbar = Scrollbar(console_frame) text = Text(console_frame, height=2, width=130, wrap=WORD) text.config(yscrollcommand=vertical_scrollbar.set) vertical_scrollbar.config(command=text.yview) label = Label(console_frame, text="Console: ", anchor="w") console_frame.pack(side=RIGHT, fill=BOTH, expand=1) label.pack(side=TOP, fill=X) vertical_scrollbar.pack(side=RIGHT, fill=Y) text.pack(side=RIGHT, fill=BOTH, expand=1) self.game_model = game self.solve_model = SudokuBoard(list(chain.from_iterable(game.board))) self.user_board = UserBoard(game, poss_dict=game.possible_values) self.console = text self.console_scrollbar = vertical_scrollbar Frame.__init__(self, root) self.row, self.col = 0, 0 root.title("Sudoku Solver") self.pack(fill=BOTH, side=LEFT) self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.pack(fill=BOTH, side=TOP) clear_button = Button(self, text="Clear Answers", command=self.clear_answers) clear_button.pack(fill=BOTH, side=BOTTOM) self.hint_button = Button(self, text="Hint", command=self.hint) self.hint_button['state'] = 'disabled' self.hint_button.pack(fill=BOTH, side=BOTTOM) self.solve_button = Button(self, text="Solve", command=self.solve) self.solve_button['state'] = 'disabled' self.solve_button.pack(fill=BOTH, side=BOTTOM) new_puzzle_button = Button(self, text="New Puzzle", command=self.new_puzzle) new_puzzle_button.pack(fill=BOTH, side=BOTTOM) self.draw_grid() self.draw_puzzle() self.canvas.bind("<Button-1>", self.cell_clicked) self.canvas.bind("<Key>", self.key_pressed) self.canvas.bind("<FocusOut>", self.clear_cursor) self.moves = [] thread = Thread(target=self.async_solve_model) thread.start() root.mainloop() thread.join()
def generateGame(self,cellsToBlank): from SudokuBoard import SudokuBoard sb = SudokuBoard(9*9) # from random import randint,sample # self.board = [sample(range(1,self.gridSize + 1),self.gridSize) for i in range(self.gridSize)] # while(difficultySetting > 0): # y,x = randint(0,self.gridSize - 1),randint(0,self.gridSize - 1) # if(self.board[y][x] != 0): # self.board[y][x] = 0 # difficultySetting -= 1 # self.board = sb.generateBoard(cellsToBlank) [self.board.append(i) for i in sb.generateBoard(cellsToBlank) for j in range(9)] for i in len(sb.)
def solve_main_puzzle_display(r_solution, title=None, nth=None, nsol=None): """ Add solution display :r_position of solution: :nth: ord positionof solution :nsol: Number of solutions """ if title is not None: title = "Solution" if nsol is not None: nsol = 1 mw = Toplevel() mw.protocol("WM_DELETE_WINDOW", search_stop) mw.title(title) x = 400 y = 200 x += 100 * nth y += 100 * nth mw.geometry(f"+{x}+{y}") # Find first empty slot, extending if necessary top_fr = Frame(mw) top_fr.pack(side='top') c1 = Button( top_fr, text="Close", # Guess one command=[solve_puzzle_close, nth], ) c1.pack(side='left') if nsol > 1: c2 = Button( top_fr, text="Close All", # Close all command=solve_puzzle_close_all, ) c2.pack(side='left') board = SudokuBoard( mw=mw, data=r_solution, bdWidth=g.sSize, bdHeight=g.sSize, initialData=g.Initial_data, ) g.res_group.add(ResourceEntry(mw), number=nth) board.showData(force=True)
def game(): user = UL.get_user(session['username']) sb = user.sb csb = user.copy_sb() if session.get('in_game') is None: session['in_game'] = True if request.method == "POST": csb = user.copy_sb() for num in request.form: input_value = request.form[num] if input_value != '': x, y = int(num[0]), int(num[1]) csb.set_value(x, y, int(input_value)) if SudokuSolver.solved_check(csb): sb = SudokuBoard(csb.grid) return render_template("board.html", board=sb, csb=csb) return render_template("board.html", board=sb, csb=csb)
def generate_puzzle(iterations): solution = SudokuBoard() solution.build() playable = solution.clone() difficult_coefficient = 1 for _ in range(iterations): new_playable = playable.clone() row_num, column_num = random.randrange(9), random.randrange(9) while new_playable.is_cell_empty(row_num, column_num): row_num, column_num = random.randrange(9), random.randrange(9) new_playable.clear_cell(row_num, column_num) solver = SudokuSolver(new_playable) try: solver.solve() playable = new_playable difficult_coefficient = solver.difficult_coefficient except: continue difficult_level = None if difficult_coefficient < DifficultLevel.VERY_EASY.value: difficult_level = DifficultLevel.VERY_EASY elif difficult_coefficient < DifficultLevel.EASY.value: difficult_level = DifficultLevel.EASY elif difficult_coefficient < DifficultLevel.MEDIUM.value: difficult_level = DifficultLevel.MEDIUM elif difficult_coefficient < DifficultLevel.HARD.value: difficult_level = DifficultLevel.HARD elif difficult_coefficient < DifficultLevel.VERY_HARD.value: difficult_level = DifficultLevel.VERY_HARD elif difficult_coefficient < DifficultLevel.MASTER.value: difficult_level = DifficultLevel.MASTER return SudokuGame(playable, solution, difficult_level, difficult_coefficient)
from SudokuBoard import SudokuBoard import os from View import SudokuView from tkinter import Tk, Frame, RIGHT, Scrollbar, X, Y, Text, BOTH, WORD, Label, TOP, LEFT, font from tkinter.font import Font if __name__ == '__main__': sudoku = SudokuBoard(file_path=r'TestCases/blockcolrow4.sdk') sudoku_view = SudokuView(sudoku)
reset_board_rect.center = ((SCREENWIDTH + TOTAL_SCREENWIDTH) // 2, 3 * SCREENHEIGHT // 6) solve = font.render("Solve", True, (0, 0, 0)) solve_rect = solve.get_rect() solve_rect.center = ((SCREENWIDTH + TOTAL_SCREENWIDTH) // 2, 4 * SCREENHEIGHT // 6) next_solution = font.render("Next Solution", True, (0, 0, 0)) next_solution_rect = next_solution.get_rect() next_solution_rect.center = ((SCREENWIDTH + TOTAL_SCREENWIDTH) // 2, 5 * SCREENHEIGHT // 6) # Main Loop Variables Initialization user_input = '' run = True counter = 0 board = SudokuBoard() def draw_menu(): w.blit(set_board, set_board_rect) w.blit(clear_board, clear_board_rect) w.blit(reset_board, reset_board_rect) w.blit(solve, solve_rect) w.blit(next_solution, next_solution_rect) while run: g.draw_grid(SCREENWIDTH, SCREENHEIGHT) draw_menu() for event in pygame.event.get():
def get_sudoku_object(self): return SudokuBoard([ self.board[x][y] if type(self.board[x][y]) is int else 0 for x, y in product(SudokuBoard.INDEX_RANGE, SudokuBoard.INDEX_RANGE) ])
# test_isinstance.py """ Not seeing SudokuData """ from SudokuBoard import SudokuBoard from SudokuData import SudokuData from SudokuPly import SudokuPly sb = SudokuBoard() sd = SudokuData() sp = SudokuPly() if isinstance(sd, SudokuData): print(f"Found sd{sd} to be SudokuData instance") else: print(f"Did not find sd{sd} to be SudokuData instance")
def make_puzzle(nfilled=None): """ Create puzzle with number of cells filled in Set reset_data to this :nfilled: Number of cells filled in, None = random """ ###global o_data, o_board display_close() if (gb.o_data is None): gb.o_data = SudokuData(cols=gb.nCol, rows=gb.nRow, gcols=gb.nSubCol, grows=gb.nSubRow, ) gb.o_data.clear() # Clear data if gb.o_board is None: gb.o_board = SudokuBoard(mw=gb.mw, frame=new_main_bd_frame(), data=gb.o_data, bdWidth=gb.bSize, bdHeight=gb.bSize) ncell = gb.nRow*gb.nCol if (nfilled is None): nfilled = int(ncell/3) if nfilled & 1 != 0 and ncell & 1 != 0: nfilled -= 1 # No possible symitry # with odd # and even row/col o_list = SudokuData(base=gb.o_data) a_start_list = o_list.startCells( nFilled=nfilled, symRules=gb.makePuzzleSym) if (a_start_list is None): SlTrace.lg(f"no such pattern for nRow=:{gb.nRow}, nCol=:{gb.nCol}" + f" nFilled={nfilled} symRules={gb.makePuzzleSym}") sys.exit("quitting") # Display start list sl = SudokuData(rows=gb.nRow, grows=gb.nSubRow, cols=gb.nCol, gcols=gb.nSubCol) # for diagnostic display SlTrace.lg(f"start list: ") n = 0 for sc in a_start_list: val = n if (n <= ord('Z')-ord('A')): val = chr(ord('A')+n) elif (n < 2*(ord('Z')-ord('A'))): val_ord = ord('a')+n-((ord('Z')-ord('A')-1)) val = chr(val_ord) sl.setCellVal(sc.row, sc.col, val) SlTrace.lg(f" (r:{sc.row}, c:{sc.col})") n += 1 sl.display() if (len(a_start_list) != nfilled): SlTrace.lg(f"Actual list = {len(a_start_list)}" + f" Requested list = {nfilled}") # Set starting arrangement o_sol = SudokuPly(base=gb.o_data) sols = o_sol.makePuzzle( startList=a_start_list) if sols is not None and len(sols) == 1 and sols[0] is not None: sol = sols[0] gb.o_data = sol.getData(subset=a_start_list) gb.o_board.showData(gb.o_data) gb.Initial_data = SudokuData(base=gb.o_data) return sols
# import numpy as np from SudokuBoard import SudokuBoard from SudokuDisplay import SudokuDisplay # input sudoku as 9x9 with 0s as empty spaces input_board = [ '006309005', '003000472', '805010030', '000407690', '002901008', '401080000', '080000204', '060570100', '030060700' ] if __name__ == "__main__": # init brett brett = SudokuBoard(input_board) # display window window = SudokuDisplay(brett)
def solver(inputBoard): sudokuBoard = solveIteration(sudokuSolver(SudokuBoard(inputBoard))) outputBoard = sudokuBoard.returnBoard() return outputBoard
def copy_sb(self): if self.csb is None: self.csb = SudokuBoard(self.sb.grid) return self.csb
def setup_method(self): self.board = SudokuBoard()
def reset(): user = UL.get_user(session['username']) user.csb = SudokuBoard(user.sb.grid) return redirect('/game')