用python编写一个扫雷游戏
时间: 2023-09-09 10:06:56 浏览: 281
扫雷 python
5星 · 资源好评率100%
好的,以下是一个简单的Python扫雷游戏的实现,具体实现思路和代码注释见下方代码:
```python
import random
# 初始化游戏地图,0代表未翻开的方块,-1代表地雷,其他数字代表周围地雷数量
def init_game_map(rows, cols, num_mines):
map = [[0 for i in range(cols)] for j in range(rows)] # 初始化地图
while num_mines > 0: # 随机布置地雷
row = random.randint(0, rows - 1)
col = random.randint(0, cols - 1)
if map[row][col] == -1:
continue
map[row][col] = -1
num_mines -= 1
# 计算每个方块周围地雷数量
for row in range(rows):
for col in range(cols):
if map[row][col] == -1:
continue
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
if row + i < 0 or row + i >= rows or col + j < 0 or col + j >= cols:
continue
if map[row + i][col + j] == -1:
map[row][col] += 1
return map
# 显示游戏地图
def show_game_map(map, rows, cols):
for row in range(rows):
for col in range(cols):
if map[row][col] == -2:
print('🚩', end=' ') # 标记为地雷的方块
elif map[row][col] == -3:
print('?', end=' ') # 标记为可能为地雷的方块
elif map[row][col] == 0:
print('_', end=' ') # 未翻开的方块
elif map[row][col] == -1:
print('*', end=' ') # 翻开的地雷方块
else:
print(map[row][col], end=' ') # 翻开的数字方块
print()
# 点击方块
def click_block(map, rows, cols, row, col):
if map[row][col] == -1:
return False # 点到地雷,游戏结束
elif map[row][col] == 0:
map[row][col] = -4 # 标记为已翻开
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
if row + i < 0 or row + i >= rows or col + j < 0 or col + j >= cols:
continue
if map[row + i][col + j] == 0:
click_block(map, rows, cols, row + i, col + j) # 递归翻开周围的方块
elif map[row + i][col + j] > 0:
map[row + i][col + j] = -4 # 翻开周围数字方块
else:
map[row][col] = -4 # 翻开数字方块
return True
# 标记为地雷或可能为地雷的方块
def mark_block(map, rows, cols, row, col):
if map[row][col] == 0:
map[row][col] = -2 # 标记为地雷
elif map[row][col] == -2:
map[row][col] = -3 # 标记为可能为地雷
elif map[row][col] == -3:
map[row][col] = 0 # 取消标记
return True
# 判断游戏是否结束
def is_game_over(map, rows, cols):
for row in range(rows):
for col in range(cols):
if map[row][col] >= 0 and map[row][col] < -1:
return False
return True
# 游戏主函数
def main():
rows = 10 # 地图行数
cols = 10 # 地图列数
num_mines = 10 # 地雷数量
map = init_game_map(rows, cols, num_mines) # 初始化地图
while not is_game_over(map, rows, cols): # 游戏未结束
show_game_map(map, rows, cols) # 显示游戏地图
row = int(input('请输入行号(0~{}):'.format(rows - 1)))
col = int(input('请输入列号(0~{}):'.format(cols - 1)))
action = input('请输入操作(c-点击方块,m-标记为地雷或可能为地雷):')
if action == 'c':
if not click_block(map, rows, cols, row, col):
print('Game Over!')
show_game_map(map, rows, cols)
break
elif action == 'm':
mark_block(map, rows, cols, row, col)
else:
print('无效操作,请重新输入!')
if is_game_over(map, rows, cols):
print('You Win!')
if __name__ == '__main__':
main()
```
需要注意的是,由于本实现中使用了emoji图标,因此需要在支持emoji的终端环境下运行。
阅读全文