用Python写一个数独游戏
时间: 2023-05-12 21:03:40 浏览: 152
好的,以下是一个简单的Python数独游戏代码:
```python
import numpy as np
def print_board(board):
for i in range(9):
for j in range(9):
print(board[i][j], end=" ")
if j == 2 or j == 5:
print("|", end=" ")
print()
if i == 2 or i == 5:
print("-" * 21)
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 valid(board, num, pos):
# Check row
for i in range(9):
if board[pos[0]][i] == num and pos[1] != i:
return False
# Check column
for i in range(9):
if board[i][pos[1]] == num and pos[0] != i:
return False
# Check box
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):
find = find_empty(board)
if not find:
return True
else:
row, col = find
for i in range(1, 10):
if valid(board, i, (row, col)):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0
return False
board = np.array([[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]])
# Sample board
board[0][2] = 4
board[0][3] = 3
board[0][5] = 2
board[0][7] = 9
board[1][0] = 6
board[1][1] = 7
board[1][4] = 1
board[1][6] = 2
board[2][1] = 4
board[2][2] = 9
board[2][3] = 5
board[2][4] = 8
board[2][5] = 7
board[2][6] = 1
board[3][2] = 5
board[3][3] = 2
board[3][5] = 1
board[3][6] = 8
board[4][0] = 2
board[4][8] = 1
board[5][2] = 7
board[5][3] = 6
board[5][5] = 5
board[5][6] = 3
board[6][1] = 1
board[6][2] = 3
board[6][3] = 4
board[6][4] = 6
board[6][5] = 9
board[6][6] = 7
board[7][2] = 6
board[7][4] = 3
board[7][7] = 5
board[8][1] = 8
board[8][3] = 7
board[8][5] = 4
board[8][6] = 6
print("Original board:")
print_board(board)
print("\nSolved board:")
solve(board)
print_board(board)
```
这个代码可以生成一个数独游戏,并且可以自动解决它。
阅读全文