请给我一个扫雷的py代码
时间: 2024-06-07 14:11:57 浏览: 16
以下是一个简单的扫雷游戏的 Python 代码:
```python
import random
class Minesweeper:
def __init__(self, width, height, bombs):
self.width = width
self.height = height
self.bombs = bombs
self.board = [[0 for x in range(width)] for y in range(height)]
self.visible_board = [[False for x in range(width)] for y in range(height)]
self.generate_board()
def generate_board(self):
bomb_list = random.sample(range(self.width * self.height), self.bombs)
for i in bomb_list:
x = i % self.width
y = i // self.width
self.board[y][x] = -1
for i in range(max(0, y-1), min(self.height, y+2)):
for j in range(max(0, x-1), min(self.width, x+2)):
if self.board[i][j] != -1:
self.board[i][j] += 1
def print_board(self):
for y in range(self.height):
for x in range(self.width):
if self.visible_board[y][x]:
if self.board[y][x] == -1:
print('*', end=' ')
else:
print(self.board[y][x], end=' ')
else:
print('.', end=' ')
print()
def reveal(self, x, y):
if self.visible_board[y][x]:
return
self.visible_board[y][x] = True
if self.board[y][x] == -1:
return False
if self.board[y][x] == 0:
for i in range(max(0, y-1), min(self.height, y+2)):
for j in range(max(0, x-1), min(self.width, x+2)):
self.reveal(j, i)
return True
def play(self):
while True:
self.print_board()
x = int(input('Enter the x coordinate: '))
y = int(input('Enter the y coordinate: '))
if not self.reveal(x, y):
print('Game over!')
return
if self.check_win():
print('You won!')
return
def check_win(self):
for y in range(self.height):
for x in range(self.width):
if not self.visible_board[y][x] and self.board[y][x] != -1:
return False
return True
game = Minesweeper(8, 8, 10)
game.play()
```
在这个代码中,我们定义了一个 `Minesweeper` 类来表示扫雷游戏。类的属性包括宽度、高度、炸弹数量和游戏板的状态。`generate_board()` 方法用于生成随机的炸弹位置并计算每个格子周围的炸弹数量。`print_board()` 方法用于打印当前游戏板的状态。`reveal()` 方法用于揭示指定位置的格子,如果揭示到炸弹则游戏结束,否则递归地揭示周围的格子。`play()` 方法用于循环地接收玩家输入并更新游戏状态,直到游戏结束。`check_win()` 方法用于检查是否胜利。
你可以根据自己的需求修改代码,比如增加计时功能、美化输出等。
相关推荐
![](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)