python实现扫雷
时间: 2023-07-07 17:05:44 浏览: 20
扫雷是一个经典的小游戏,以下是一个简单的Python实现:
```python
import random
# 初始化游戏棋盘
def init_board(width, height, mines):
board = [[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 board[y][x] == -1:
x = random.randint(0, width - 1)
y = random.randint(0, height - 1)
board[y][x] = -1
for i in range(height):
for j in range(width):
if board[i][j] == -1:
continue
count = 0
if i > 0 and j > 0 and board[i - 1][j - 1] == -1:
count += 1
if i > 0 and board[i - 1][j] == -1:
count += 1
if i > 0 and j < width - 1 and board[i - 1][j + 1] == -1:
count += 1
if j > 0 and board[i][j - 1] == -1:
count += 1
if j < width - 1 and board[i][j + 1] == -1:
count += 1
if i < height - 1 and j > 0 and board[i + 1][j - 1] == -1:
count += 1
if i < height - 1 and board[i + 1][j] == -1:
count += 1
if i < height - 1 and j < width - 1 and board[i + 1][j + 1] == -1:
count += 1
board[i][j] = count
return board
# 显示游戏棋盘
def show_board(board, status):
for i in range(len(board)):
for j in range(len(board[i])):
if status[i][j] == 0:
print('_', end=' ')
elif status[i][j] == 1:
if board[i][j] == -1:
print('*', end=' ')
elif board[i][j] == 0:
print(' ', end=' ')
else:
print(board[i][j], end=' ')
else:
print('F', end=' ')
print()
# 游戏主循环
def main_loop(width, height, mines):
board = init_board(width, height, mines)
status = [[0 for i in range(width)] for j in range(height)]
show_board(board, status)
while True:
x = int(input('请输入要翻开的格子的横坐标:'))
y = int(input('请输入要翻开的格子的纵坐标:'))
if board[y][x] == -1:
print('你输了!')
status[y][x] = 1
show_board(board, status)
break
else:
status[y][x] = 1
show_board(board, status)
```
你可以通过调用 `main_loop()` 函数来开始游戏,需要输入游戏棋盘的宽度、高度和雷的数量。在游戏中,你需要输入要翻开的格子的坐标,程序会自动进行处理并显示游戏棋盘。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)