你能用python写一个扫雷游戏的代码吗
时间: 2023-12-05 21:04:46 浏览: 80
使用Python的扫雷游戏
5星 · 资源好评率100%
当然可以!以下是一个简单的扫雷游戏实现:
```python
import random
# 雷区大小
ROWS = 10
COLS = 10
MINES = 10
# 定义格子状态
HIDDEN = 0
VISIBLE = 1
MARKED = 2
# 定义雷区
minefield = [[0 for j in range(COLS)] for i in range(ROWS)]
# 安放地雷
count = 0
while count < MINES:
row = random.randint(0, ROWS - 1)
col = random.randint(0, COLS - 1)
if minefield[row][col] == 0:
minefield[row][col] = -1
count += 1
# 计算周围雷的数量
for i in range(ROWS):
for j in range(COLS):
if minefield[i][j] == -1:
continue
for x in range(max(0, i - 1), min(ROWS, i + 2)):
for y in range(max(0, j - 1), min(COLS, j + 2)):
if minefield[x][y] == -1:
minefield[i][j] += 1
# 定义游戏状态
game_over = False
game_win = False
# 显示雷区
def show_minefield():
for i in range(ROWS):
for j in range(COLS):
if minefield[i][j] == -1:
print("*", end=" ")
elif minefield[i][j] == HIDDEN:
print(".", end=" ")
elif minefield[i][j] == VISIBLE:
print(minefield[i][j], end=" ")
elif minefield[i][j] == MARKED:
print("P", end=" ")
print()
# 点击格子
def click(row, col):
global game_over, game_win
if minefield[row][col] == -1:
game_over = True
else:
minefield[row][col] = VISIBLE
if minefield[row][col] == 0:
for x in range(max(0, row - 1), min(ROWS, row + 2)):
for y in range(max(0, col - 1), min(COLS, col + 2)):
if minefield[x][y] == HIDDEN:
click(x, y)
if all(minefield[i][j] != HIDDEN for i in range(ROWS) for j in range(COLS) if minefield[i][j] != -1):
game_win = True
# 标记格子
def mark(row, col):
if minefield[row][col] == HIDDEN:
minefield[row][col] = MARKED
elif minefield[row][col] == MARKED:
minefield[row][col] = HIDDEN
# 游戏循环
while not game_over and not game_win:
show_minefield()
row = int(input("请输入行号(0~{}): ".format(ROWS - 1)))
col = int(input("请输入列号(0~{}): ".format(COLS - 1)))
action = input("请输入操作(C表示标记,其他表示点击): ")
if action == "C":
mark(row, col)
else:
click(row, col)
# 游戏结束
show_minefield()
if game_win:
print("恭喜你,你赢了!")
else:
print("很遗憾,你输了!")
```
此程序包含了一个简单的命令行界面,可以让玩家点击格子来揭开地图或标记可能的地雷位置。游戏结束后会显示整个雷区,告诉玩家是否胜利。
阅读全文