python写一份扫雷的完整代码
时间: 2023-11-02 22:03:36 浏览: 75
这里是一个简单的扫雷游戏的 Python 代码示例:
```python
import random
# 定义方格类
class Square:
def __init__(self):
self.is_bomb = False # 是否是雷
self.is_revealed = False # 是否已经被揭开
self.num_adjacent_bombs = 0 # 相邻方格中雷的数量
# 定义扫雷游戏类
class Minesweeper:
def __init__(self, width, height, num_bombs):
self.width = width
self.height = height
self.num_bombs = num_bombs
# 初始化方格列表
self.squares = []
for x in range(width):
column = []
for y in range(height):
column.append(Square())
self.squares.append(column)
# 布雷
bombs_placed = 0
while bombs_placed < num_bombs:
x = random.randint(0, width - 1)
y = random.randint(0, height - 1)
if not self.squares[x][y].is_bomb:
self.squares[x][y].is_bomb = True
bombs_placed += 1
# 计算相邻方格中雷的数量
def calculate_adjacent_bombs(self, x, y):
if self.squares[x][y].is_bomb:
return
num_bombs = 0
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
if x + i < 0 or x + i >= self.width or y + j < 0 or y + j >= self.height:
continue
if self.squares[x + i][y + j].is_bomb:
num_bombs += 1
self.squares[x][y].num_adjacent_bombs = num_bombs
# 显示游戏状态
def display(self):
for y in range(self.height):
for x in range(self.width):
if not self.squares[x][y].is_revealed:
print(".", end="")
elif self.squares[x][y].is_bomb:
print("*", end="")
else:
print(self.squares[x][y].num_adjacent_bombs, end="")
print()
# 揭开方格
def reveal(self, x, y):
if self.squares[x][y].is_revealed:
return
self.squares[x][y].is_revealed = True
if self.squares[x][y].is_bomb:
print("Game over!")
return
if self.squares[x][y].num_adjacent_bombs == 0:
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
if x + i < 0 or x + i >= self.width or y + j < 0 or y + j >= self.height:
continue
self.reveal(x + i, y + j)
# 判断是否胜利
def is_win(self):
for y in range(self.height):
for x in range(self.width):
if not self.squares[x][y].is_revealed and not self.squares[x][y].is_bomb:
return False
return True
# 创建扫雷游戏对象
game = Minesweeper(10, 10, 10)
# 游戏循环
while True:
game.display()
x = int(input("Enter x coordinate: "))
y = int(input("Enter y coordinate: "))
game.reveal(x, y)
if game.is_win():
print("You win!")
break
```
这是一个非常基础的示例,你可以根据自己的需求对其进行修改和扩展。
阅读全文