帮我用python写一个数独游戏
时间: 2023-08-28 09:54:37 浏览: 111
当然可以帮你写一个数独游戏的Python代码!下面是一个简单的实现:
```python
def print_board(board):
for i in range(9):
if i % 3 == 0 and i != 0:
print("- - - - - - - - - - -")
for j in range(9):
if j % 3 == 0 and j != 0:
print("|", end=" ")
if j == 8:
print(board[i][j])
else:
print(str(board[i][j]) + " ", end="")
def find_empty(board):
for i in range(9):
for j in range(9):
if board[i][j] == 0:
return (i, j)
return None
def is_valid(board, num, pos):
# 检查行
for i in range(9):
if board[pos[0]][i] == num and pos[1] != i:
return False
# 检查列
for i in range(9):
if board[i][pos[1]] == num and pos[0] != i:
return False
# 检查小方块
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if board[i][j] == num and (i, j) != pos:
return False
return True
def solve_board(board):
find = find_empty(board)
if not find:
return True
else:
row, col = find
for i in range(1, 10):
if is_valid(board, i, (row, col)):
board[row][col] = i
if solve_board(board):
return True
board[row][col] = 0
return False
# 测试代码
board = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
]
solve_board(board)
print_board(board)
```
这个代码包括了打印数独棋盘、寻找空格、检查数字是否合法、解决数独以及一个简单的测试代码。你可以将这段代码复制到一个Python文件中运行,就可以开始玩数独游戏了。
阅读全文