吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 734|回复: 15
收起左侧

[Python 原创] python随机数独和解数独

  [复制链接]
矢岛舞美 发表于 2024-12-5 11:44
本帖最后由 矢岛舞美 于 2024-12-5 11:45 编辑


基于python3.11,其他版本的python可能会报错。
随机刷新一个数独
[Python] 纯文本查看 复制代码
import tkinter as tk
from tkinter import messagebox
import random

def is_valid(board, row, col, num):
    for x in range(9):
        if board[row][x] == num or board[x][col] == num:
            return False
    start_row, start_col = 3 * (row // 3), 3 * (col // 3)
    for i in range(3):
        for j in range(3):
            if board[start_row + i][start_col + j] == num:
                return False
    return True

def generate_puzzle():
    board = [[0] * 9 for _ in range(9)]
    for _ in range(17):  # Start with 17 clues
        row, col = random.randint(0, 8), random.randint(0, 8)
        num = random.randint(1, 9)
        while not is_valid(board, row, col, num) or board[row][col] != 0:
            row, col = random.randint(0, 8), random.randint(0, 8)
            num = random.randint(1, 9)
        board[row][col] = num
    return board

class SudokuGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("Sudoku")
        self.canvas = tk.Canvas(self.root, width=400, height=400, bg="white")
        self.canvas.grid(row=0, column=0, columnspan=9)
        self.puzzle = generate_puzzle()
        self.cells = [[None for _ in range(9)] for _ in range(9)]
        self.create_grid()
        self.create_check_button()
        self.draw_grid()

    def create_grid(self):
        for row in range(9):
            for col in range(9):
                cell_value = self.puzzle[row][col]
                entry = tk.Entry(self.root, width=3, font=('Arial', 18), justify='center')
                entry.place(x=20 + col * 40, y=20 + row * 40, width=40, height=40)
                if cell_value != 0:
                    entry.insert(0, str(cell_value))
                    entry.config(state='readonly')
                self.cells[row][col] = entry

    def draw_grid(self):
        # Draw thin grid lines
        for i in range(10):
            color = "black" if i % 3 == 0 else "gray"
            x0, y0, x1, y1 = 20 + i * 40, 20, 20 + i * 40, 380
            self.canvas.create_line(x0, y0, x1, y1, fill=color)
            x0, y0, x1, y1 = 20, 20 + i * 40, 380, 20 + i * 40
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

        # Draw thick grid lines
        for i in range(4):
            x0, y0, x1, y1 = 20 + i * 120, 20, 20 + i * 120, 380
            self.canvas.create_line(x0, y0, x1, y1, fill="red", width=2)
            x0, y0, x1, y1 = 20, 20 + i * 120, 380, 20 + i * 120
            self.canvas.create_line(x0, y0, x1, y1, fill="red", width=2)

    def create_check_button(self):
        check_button = tk.Button(self.root, text="Check", command=self.check_solution)
        check_button.grid(row=10, column=0, columnspan=9, pady=10)

    def check_solution(self):
        for row in range(9):
            for col in range(9):
                entry = self.cells[row][col]
                try:
                    value = int(entry.get())
                    if not (1 <= value <= 9) or not is_valid(self.puzzle, row, col, value):
                        raise ValueError
                    self.puzzle[row][col] = value
                except ValueError:
                    messagebox.showwarning("Invalid Input", f"Invalid number at row {row + 1}, column {col + 1}")
                    return
        messagebox.showinfo("Sudoku", "Congratulations! You've solved the puzzle!")

if __name__ == "__main__":
    root = tk.Tk()
    game = SudokuGUI(root)
    root.mainloop()


解数独
[Python] 纯文本查看 复制代码
import tkinter as tk
from tkinter import messagebox

def is_valid(board, row, col, num):
    for x in range(9):
        if board[row][x] == num or board[x][col] == num:
            return False
    start_row, start_col = 3 * (row // 3), 3 * (col // 3)
    for i in range(3):
        for j in range(3):
            if board[start_row + i][start_col + j] == num:
                return False
    return True

def solve_sudoku(board):
    for row in range(9):
        for col in range(9):
            if board[row][col] == 0:
                for num in range(1, 10):
                    if is_valid(board, row, col, num):
                        board[row][col] = num
                        if solve_sudoku(board):
                            return True
                        board[row][col] = 0
                return False
    return True

class SudokuSolverGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("Sudoku Solver")
        self.canvas = tk.Canvas(self.root, width=400, height=400, bg="white")
        self.canvas.grid(row=0, column=0, columnspan=9)
        self.cells = [[None for _ in range(9)] for _ in range(9)]
        self.create_grid()
        self.create_buttons()
        self.draw_grid()

    def create_grid(self):
        for row in range(9):
            for col in range(9):
                entry = tk.Entry(self.root, width=3, font=('Arial', 18), justify='center')
                entry.place(x=20 + col * 40, y=20 + row * 40, width=40, height=40)
                self.cells[row][col] = entry

    def draw_grid(self):
        # 画出细的网格线
        for i in range(10):
            color = "black" if i % 3 == 0 else "gray"
            x0, y0, x1, y1 = 20 + i * 40, 20, 20 + i * 40, 380
            self.canvas.create_line(x0, y0, x1, y1, fill=color)
            x0, y0, x1, y1 = 20, 20 + i * 40, 380, 20 + i * 40
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

        # 画出粗的网格线
        for i in range(4):
            x0, y0, x1, y1 = 20 + i * 120, 20, 20 + i * 120, 380
            self.canvas.create_line(x0, y0, x1, y1, fill="red", width=2)
            x0, y0, x1, y1 = 20, 20 + i * 120, 380, 20 + i * 120
            self.canvas.create_line(x0, y0, x1, y1, fill="red", width=2)

    def create_buttons(self):
        solve_button = tk.Button(self.root, text="Solve", command=self.solve_puzzle)
        solve_button.grid(row=10, column=0, columnspan=4, pady=10)

        clear_button = tk.Button(self.root, text="Clear", command=self.clear_grid)
        clear_button.grid(row=10, column=5, columnspan=4, pady=10)

    def solve_puzzle(self):
        board = [[0] * 9 for _ in range(9)]
        for row in range(9):
            for col in range(9):
                entry = self.cells[row][col]
                value = entry.get()
                if value.isdigit():
                    board[row][col] = int(value)

        if solve_sudoku(board):
            for row in range(9):
                for col in range(9):
                    self.cells[row][col].delete(0, tk.END)
                    self.cells[row][col].insert(0, str(board[row][col]))
        else:
            messagebox.showwarning("Sudoku Solver", "No solution exists for the given input.")

    def clear_grid(self):
        for row in range(9):
            for col in range(9):
                self.cells[row][col].delete(0, tk.END)

if __name__ == "__main__":
    root = tk.Tk()
    solver = SudokuSolverGUI(root)
    root.mainloop()

免费评分

参与人数 5威望 +1 吾爱币 +26 热心值 +4 收起 理由
苏紫方璇 + 1 + 20 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
asciibase64 + 1 + 1 热心回复!
wapjsx + 1 + 1 谢谢@Thanks!
solly + 3 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
ysgbaby + 1 我很赞同!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

gegegefei 发表于 2024-12-5 12:10
感谢楼主分享,正在学习python。
Ysanky 发表于 2024-12-5 13:13
kings0b 发表于 2024-12-5 14:21
maqangch 发表于 2024-12-5 15:07
谢谢分享,建议小九宫格也弄的明显一些。
hzy227724 发表于 2024-12-5 16:25
呜呜最近正在学习Python
rootbot007 发表于 2024-12-5 20:08
斗胆学习一波
dhsfb 发表于 2024-12-6 08:11
感谢楼主的分享
jeledong 发表于 2024-12-6 09:42
虽然不太懂,但谢谢分享
notice 发表于 2024-12-6 10:48
学习一下,刚好以前也挺喜欢玩数独的
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-1-7 19:03

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表