给我一个扫雷游戏的源代码
时间: 2023-06-12 09:05:35 浏览: 79
以下是一个简单的扫雷游戏的Python源代码,你可以在自己的电脑上运行:
```python
import random
class Minesweeper:
def __init__(self, width, height, bomb_count):
self.width = width
self.height = height
self.bomb_count = bomb_count
self.grid = [[0 for _ in range(width)] for _ in range(height)]
self.visible = [[False for _ in range(width)] for _ in range(height)]
self.generate_bombs()
# 生成地雷
def generate_bombs(self):
bombs = random.sample(range(self.width * self.height), self.bomb_count)
for b in bombs:
x = b % self.width
y = b // self.width
self.grid[y][x] = 9
for i in range(-1, 2):
for j in range(-1, 2):
if 0 <= x+j < self.width and 0 <= y+i < self.height and self.grid[y+i][x+j] != 9:
self.grid[y+i][x+j] += 1
# 显示地图
def display(self):
print(" " + "".join([str(i%10) for i in range(self.width)]))
for y in range(self.height):
line = ""
for x in range(self.width):
if self.visible[y][x]:
if self.grid[y][x] == 0:
line += " "
elif self.grid[y][x] == 9:
line += "*"
else:
line += str(self.grid[y][x])
else:
line += "?"
print(str(y%10) + line)
# 点开一个格子
def click(self, x, y):
if self.grid[y][x] == 9:
self.visible[y][x] = True
return False
elif self.grid[y][x] == 0:
self.visible[y][x] = True
for i in range(-1, 2):
for j in range(-1, 2):
if 0 <= x+j < self.width and 0 <= y+i < self.height and not self.visible[y+i][x+j]:
self.click(x+j, y+i)
else:
self.visible[y][x] = True
return True
# 游戏循环
def play_game():
width = 10
height = 10
bomb_count = 10
game = Minesweeper(width, height, bomb_count)
while True:
game.display()
x = int(input("Enter x coordinate: "))
y = int(input("Enter y coordinate: "))
if not game.click(x, y):
game.display()
print("You lose!")
break
if all([all(v) for v in game.visible]):
game.display()
print("You win!")
break
play_game()
```
这个游戏使用数字代表每个方格周围地雷的数量,当你点击一个没有地雷的方格时,会自动展开周围的方格,直到遇到数字为止。当你点击一个有地雷的方格时,游戏结束,你输了。当你成功展开所有没有地雷的方格时,你赢了。