import random
# 扫雷游戏
class Minesweeper:
def __init__(self, rows, cols, mines):
self.rows = rows
self.cols = cols
self.mines = mines
self.game_over = False
self.board = [[0 for _ in range(cols)] for _ in range(rows)]
self.visible = [[False for _ in range(cols)] for _ in range(rows)]
self.place_mines(mines)
# 显示当前游戏状态
def display(self):
for i in range(self.rows):
for j in range(self.cols):
if self.visible[i][j]:
print(self.board[i][j], end=' ')
else:
print('-', end=' ')
print()
# 放置指定数量的地雷
def place_mines(self, mines):
count = 0
while count < mines:
row = random.randint(0, self.rows-1)
col = random.randint(0, self.cols-1)
if self.board[row][col] == 0:
self.board[row][col] = '*'
count += 1
self.calculate_counts()
# 计算每个方格周围地雷的数量
def calculate_counts(self):
for i in range(self.rows):
for j in range(self.cols):
if self.board[i][j] == '*':
continue
count = 0
if i > 0 and self.board[i-1][j] == '*': # 上
count += 1
if i < self.rows-1 and self.board[i+1][j] == '*': # 下
count += 1
if j > 0 and self.board[i][j-1] == '*': # 左
count += 1
if j < self.cols-1 and self.board[i][j+1] == '*': # 右
count += 1
if i > 0 and j > 0 and self.board[i-1][j-1] == '*': # 左上
count += 1
if i > 0 and j < self.cols-1 and self.board[i-1][j+1] == '*': # 右上
count += 1
if i < self.rows-1 and j > 0 and self.board[i+1][j-1] == '*': # 左下
count += 1
if i < self.rows-1 and j < self.cols-1 and self.board[i+1][j+1] == '*': # 右下
count += 1
self.board[i][j] = count
# 点击指定方格
def click(self, row, col):
if self.game_over:
return
if self.board[row][col] == '*':
self.game_over = True
print('你输了,地雷爆炸了!')
elif self.visible[row][col]:
print('这个位置已经被翻开了。')
else:
self.visible[row][col] = True
if self.board[row][col] == 0:
self.clear_zeros(row, col)
if self.check_win():
self.game_over = True
print('你赢了,所有地雷都被找到了!')
# 翻开周围所有空白方格
def clear_zeros(self, row, col):
if self.board[row][col] != 0:
return
if self.visible[row][col]:
return
self.visible[row][col] = True
if row > 0:
self.clear_zeros(row-1, col) # 上
if row < self.rows-1:
self.clear_zeros(row+1, col) # 下
if col > 0:
self.clear_zeros(row, col-1) # 左
if col < self.cols-1:
self.clear_zeros(row, col+1) # 右
# 检查是否已经找到所有地雷
def check_win(self):
for i in range(self.rows):
for j in range(self.cols):
if self.board[i][j] == '*' and not self.visible[i][j]:
return False
return True
# 开始游戏
def play_game():
rows = int(input("请输入行数:"))
cols = int(input("请输入列数:"))
mines = int(input("请输入地雷数量:"))
game = Minesweeper(rows, cols, mines)
while not game.game_over:
game.display()
row = int(input("请输入行号:"))
col = int(input("请输入列号:"))
game.click(row, col)
play_again = input("再来一局?(y/n)")
if play_again == 'y':
play_game()
else:
print("游戏结束")
# 启动游戏
play_game()
在这个游戏中,玩家可以自定义行数、列数和地雷数量,然后输入方格的横纵坐标,并尝试找到所有的地雷。如果玩家点击到地雷,游戏将结束。如果玩家找到了所有地雷,游戏也将结束。游戏结束后,程序会询问玩家是否再玩一局游戏。