帮我写一个扫雷python代码
时间: 2024-03-02 20:42:31 浏览: 78
好的,以下是一个简单的扫雷Python代码,供参考:
```python
import random
class Minesweeper:
def __init__(self, n, m):
self.n = n
self.m = m
self.grid = [[0 for j in range(m)] for i in range(n)]
self.initialize_grid()
def initialize_grid(self):
num_bombs = int(self.n * self.m * 0.1) #设置地雷数量
count = 0
while count < num_bombs:
i = random.randint(0, self.n - 1)
j = random.randint(0, self.m - 1)
if self.grid[i][j] != -1:
self.grid[i][j] = -1
count += 1
for i in range(self.n):
for j in range(self.m):
if self.grid[i][j] == -1:
continue
for x in range(max(0, i - 1), min(self.n, i + 2)):
for y in range(max(0, j - 1), min(self.m, j + 2)):
if self.grid[x][y] == -1:
self.grid[i][j] += 1
def print_grid(self, show_bombs=False):
for i in range(self.n):
for j in range(self.m):
if show_bombs and self.grid[i][j] == -1:
print("*", end=" ")
elif self.grid[i][j] == -2:
print("-", end=" ")
else:
print(self.grid[i][j], end=" ")
print()
def play(self):
while True:
self.print_grid()
x = int(input("Enter row: "))
y = int(input("Enter column: "))
if self.grid[x][y] == -1:
print("Game over!")
self.print_grid(show_bombs=True)
return
self.reveal(x, y)
if self.check_win():
print("You win!")
self.print_grid(show_bombs=True)
return
def reveal(self, x, y):
if self.grid[x][y] == -2:
return
self.grid[x][y] = -2
if self.grid[x][y] == 0:
for i in range(max(0, x - 1), min(self.n, x + 2)):
for j in range(max(0, y - 1), min(self.m, y + 2)):
if i == x and j == y:
continue
self.reveal(i, j)
def check_win(self):
for i in range(self.n):
for j in range(self.m):
if self.grid[i][j] != -2 and self.grid[i][j] != -1:
return False
return True
if __name__ == "__main__":
minesweeper = Minesweeper(10, 10)
minesweeper.play()
```
这是一个基础的扫雷游戏,它会先随机生成地雷,并计算每个格子周围的地雷数量。然后玩家可以输入行和列来查看格子的内容,并且如果打开一个没有地雷的格子,周围的格子也会被打开。如果玩家不小心点到地雷,游戏就会结束,否则如果玩家成功打开所有没有地雷的格子,那么游戏就会结束并宣布获胜。
阅读全文