我需要一个用Python制作出来的扫雷游戏,不要有报错的代码
时间: 2024-04-09 13:29:12 浏览: 54
当然,我可以帮你创建一个用Python编写的扫雷游戏。以下是一个基本的实现示例:
```python
import random
def create_board(rows, cols, num_mines):
board = [[' ' for _ in range(cols)] for _ in range(rows)]
mines = []
while len(mines) < num_mines:
mine = (random.randint(0, rows-1), random.randint(0, cols-1))
if mine not in mines:
mines.append(mine)
board[mine[0]][mine[1]] = 'X'
return board
def count_adjacent_mines(board, row, col):
count = 0
for i in range(max(0, row-1), min(row+2, len(board))):
for j in range(max(0, col-1), min(col+2, len(board[0]))):
if board[i][j] == 'X':
count += 1
return count
def reveal_cell(board, row, col):
if board[row][col] != ' ':
return
num_mines = count_adjacent_mines(board, row, col)
board[row][col] = str(num_mines) if num_mines > 0 else ' '
if board[row][col] == ' ':
for i in range(max(0, row-1), min(row+2, len(board))):
for j in range(max(0, col-1), min(col+2, len(board[0]))):
if i != row or j != col:
reveal_cell(board, i, j)
def print_board(board):
for row in board:
print(' '.join(row))
def play_game(rows, cols, num_mines):
board = create_board(rows, cols, num_mines)
game_over = False
while not game_over:
print_board(board)
row = int(input("Enter row: "))
col = int(input("Enter col: "))
if (row < 0 or row >= rows) or (col < 0 or col >= cols):
print("Invalid cell!")
continue
if board[row][col] == 'X':
print("Game over! You hit a mine.")
game_over = True
else:
reveal_cell(board, row, col)
if all(all(cell != ' ' for cell in row) for row in board):
print("Congratulations! You won!")
game_over = True
# 游戏设置
rows = 8
cols = 8
num_mines = 10
play_game(rows, cols, num_mines)
```
这是一个简单的扫雷游戏实现示例,你可以根据自己的需要进行修改和扩展。请确保在运行代码之前已经安装了Python。
阅读全文