不用pygame写一个扫雷
时间: 2024-02-05 17:04:31 浏览: 20
好的,以下是一个简单的命令行扫雷游戏的实现,使用Python语言编写。
```python
import random
# 初始化地图
def init_map(width, height, mines):
# 用二维列表表示地图,0表示未翻开,-1表示地雷
map = [[0 for i in range(width)] for j in range(height)]
# 随机放置地雷
for i in range(mines):
x = random.randint(0, width-1)
y = random.randint(0, height-1)
while map[y][x] == -1:
x = random.randint(0, width-1)
y = random.randint(0, height-1)
map[y][x] = -1
# 计算每个方块周围的地雷数
for i in range(height):
for j in range(width):
if map[i][j] != -1:
count = 0
for dx in range(-1, 2):
for dy in range(-1, 2):
if i+dy >= 0 and i+dy < height and j+dx >= 0 and j+dx < width and map[i+dy][j+dx] == -1:
count += 1
map[i][j] = count
return map
# 翻开指定位置的方块
def dig(map, x, y):
if map[y][x] == -1:
return False
map[y][x] = -2 # -2表示已翻开
if map[y][x] == 0:
for dx in range(-1, 2):
for dy in range(-1, 2):
if x+dx >= 0 and x+dx < len(map[0]) and y+dy >= 0 and y+dy < len(map) and map[y+dy][x+dx] == 0:
dig(map, x+dx, y+dy)
return True
# 打印地图
def print_map(map):
for row in map:
print(" ".join([str(x) for x in row]))
# 主函数
def main():
width = 10
height = 10
mines = 10
map = init_map(width, height, mines)
while True:
print_map(map)
x = int(input("请输入要翻开的方块的横坐标:"))
y = int(input("请输入要翻开的方块的纵坐标:"))
if not dig(map, x, y):
print("你输了!")
print_map(map)
break
if all(map[i][j] in (-1, -2) for i in range(height) for j in range(width)):
print("你赢了!")
print_map(map)
break
if __name__ == '__main__':
main()
```
这个扫雷游戏使用命令行界面,玩家通过输入坐标来进行操作。地图用二维列表表示,-1表示地雷,-2表示已翻开,其他数字表示周围地雷的数量。玩家每次翻开一个方块,如果翻开的是地雷,则游戏结束,否则继续。如果所有非地雷方块都被翻开,则游戏胜利。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)