我目前正在 Tkinter 中开发自己的数独项目。我已经成功制作了一个带有标签和条目值的网格。我正在开发一个提交按钮,用于检查玩家是否获胜。我需要程序遍历所有数字并将每个数字与其行、列和网格进行比较。
global grid_entries
grid_entries = []
for i in range(9):
row_entries = []
for j in range(9):
cell_value = puzzle[i][j]
x = j * 40 + 20 + (j // 3) * 5
y = i * 40 + 20 + (i // 3) * 5
if cell_value == '':
entry = Entry(canvas, font=("Calibri", 20), width=2, justify='center', fg='Blue', bd=2, bg='white', relief='ridge')
entry.grid(row=i, column=j)
canvas.create_window(x, y, window=entry)
else:
label = Label(canvas, text=cell_value, fg='black', font=('Calbri', 20), bd = 2, bg = 'white', relief='ridge', width=2)
label.grid(row=i, column=j)
canvas.create_window(x, y, window=label)
row_entries.append(entry if cell_value == '' else label)
grid_entries.append(row_entries)
这是我的循环,用于为数独模式创建标签和输入框,并存储已添加的任何输入值。我不知道如何循环数字并比较它们。
我写这篇文章是为了看看我是否可以获得每个单独的值。
def submit_action():
for row in grid_entries:
for cell in row:
if isinstance(cell, Entry):
print(cell.get('text'), end=' ')
elif isinstance(cell, Label):
print(cell.cget('text'), end=' ')
else:
print('Empty', end=' ')
没成功。
要验证玩家是否在数独游戏中获胜,需要检查玩家输入的数字是否满足数独规则:
以下是执行
submit_action()
函数来检查播放器是否成功的方法:
def check_row(row):
# Ascertain if all entries in the row are distinct and non-empty
return len(set(row)) == 9 and all(entry != '' for entry in row)
def check_column(grid, col_index):
# Ascertain if all entries in the specified column are distinct and non-empty
return len(set(row[col_index] for row in grid)) == 9 and all(row[col_index] != '' for row in grid)
def check_grid(grid, start_row, start_col):
# Ascertain if all entries in the 3x3 grid are distinct and non-empty
numbers = set()
for i in range(start_row, start_row + 3):
for j in range(start_col, start_col + 3):
if grid[i][j] == '':
return False
numbers.add(grid[i][j])
return len(numbers) == 9
def submit_action():
# Obtain the current state of the Sudoku grid from the GUI
current_grid = []
for row in grid_entries:
current_row = []
for cell in row:
if isinstance(cell, Entry):
current_row.append(cell.get())
elif isinstance(cell, Label):
current_row.append(cell.cget('text'))
else:
current_row.append('')
current_grid.append(current_row)
# Ascertain if each row, column, and 3x3 grid is valid
for i in range(9):
if not check_row(current_grid[i]):
print(f"Row {i + 1} is not valid.")
return
for j in range(9):
if not check_column(current_grid, j):
print(f"Column {j + 1} is not valid.")
return
for i in range(0, 9, 3):
for j in range(0, 9, 3):
if not check_grid(current_grid, i, j):
print(f"Grid starting at ({i + 1}, {j + 1}) is not valid.")
return
print("Congratulations! You have won the Sudoku game.")
此代码定义了三个函数:
check_row()
、check_column()
和check_grid()
。然后,submit_action()
函数从 GUI 检索数独网格的当前状态,并使用定义的函数检查每一行、列和网格。如果其中任何一个无效,它会打印一条适当的消息。如果所有行、列和网格都有效,则会打印一条祝贺消息。