请写一段扫雷代码 python
时间: 2024-02-25 12:51:26 浏览: 122
好的,以下是一个简单的扫雷游戏的 Python 代码,用于在控制台上实现扫雷游戏。
```python
import random
# 游戏难度,1为简单,2为中等,3为困难
difficulty = 2
if difficulty == 1:
rows = 6
cols = 6
num_mines = 5
elif difficulty == 2:
rows = 10
cols = 10
num_mines = 15
else:
rows = 16
cols = 16
num_mines = 40
# 生成扫雷地图
def generate_board(rows, cols, num_mines):
board = [[0 for _ in range(cols)] for _ in range(rows)]
mines = 0
while mines < num_mines:
row = random.randint(0, rows-1)
col = random.randint(0, cols-1)
if board[row][col] == 0:
board[row][col] = "M"
mines += 1
return board
# 显示扫雷地图
def print_board(board):
for row in board:
print(" ".join(str(cell) for cell in row))
# 计算周围雷的数量
def count_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] == "M":
count += 1
return count
# 点击格子
def click_cell(board, row, col):
if board[row][col] == "M":
return False
elif board[row][col] == 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] != "M":
click_cell(board, i, j)
else:
board[row][col] = count_mines(board, row, col)
return True
# 运行游戏
def play_game():
board = generate_board(rows, cols, num_mines)
print_board(board)
while True:
row = int(input("Enter row to click: "))
col = int(input("Enter column to click: "))
if click_cell(board, row, col):
print_board(board)
if all(all(cell != 0 for cell in row) for row in board):
print("You win!")
break
else:
print("Game over!")
break
play_game()
```
这个代码可以生成不同难度的扫雷地图,并且允许玩家在控制台上点击格子进行扫雷。也可以判断玩家是否胜利或失败。
阅读全文