用python写一个数独游戏
时间: 2024-05-13 20:15:57 浏览: 103
好的,以下是一个简单的数独游戏代码示例:
```python
import random
# 初始化数独盘面,用0表示未填空格
def init_board():
board = [[0 for i in range(9)] for j in range(9)]
return board
# 随机填充数独
def fill_board(board):
# 首先填充第一行
for i in range(9):
board[0][i] = i + 1
# 其余行随机填充
for i in range(1, 9):
for j in range(9):
board[i][j] = random.randint(1, 9)
while not check_board(board, i, j):
board[i][j] = random.randint(1, 9)
# 检查数独是否符合规则
def check_board(board, row, col):
# 检查行
for i in range(9):
if i != col and board[row][i] == board[row][col]:
return False
# 检查列
for i in range(9):
if i != row and board[i][col] == board[row][col]:
return False
# 检查宫
for i in range(row // 3 * 3, row // 3 * 3 + 3):
for j in range(col // 3 * 3, col // 3 * 3 + 3):
if i != row and j != col and board[i][j] == board[row][col]:
return False
return True
# 打印数独盘面
def print_board(board):
for i in range(9):
for j in range(9):
print(board[i][j], end=' ')
if j % 3 == 2:
print('|', end=' ')
print()
if i % 3 == 2:
print('-' * 21)
# 主函数
def main():
board = init_board()
fill_board(board)
print_board(board)
if __name__ == '__main__':
main()
```
运行以上代码,即可生成一个随机填充的数独盘面。可以根据需要对代码进行修改,比如增加游戏交互界面等。
阅读全文