请用Python写一个扫雷程序
时间: 2024-03-30 16:13:14 浏览: 30
好的,我可以帮你写一个扫雷程序。这是一个示例代码:
```
import random
class MineSweeper:
def __init__(self, rows=10, cols=10, mines=10):
self.rows = rows
self.cols = cols
self.mines = mines
self.board = [[0 for _ in range(cols)] for _ in range(rows)]
self.hidden = [[True for _ in range(cols)] for _ in range(rows)]
self.place_mines()
self.count_mines()
def place_mines(self):
mines_placed = 0
while mines_placed < self.mines:
row = random.randint(0, self.rows - 1)
col = random.randint(0, self.cols - 1)
if self.board[row][col] != -1:
self.board[row][col] = -1
mines_placed += 1
def count_mines(self):
for i in range(self.rows):
for j in range(self.cols):
if self.board[i][j] == -1:
self.update_adjacent(i, j)
def update_adjacent(self, row, col):
for i in range(row - 1, row + 2):
for j in range(col - 1, col + 2):
if (0 <= i < self.rows) and (0 <= j < self.cols) and (self.board[i][j] != -1):
self.board[i][j] += 1
def check(self, row, col):
if self.board[row][col] == -1:
print("You hit a mine!")
return False
if not self.hidden[row][col]:
return True
self.hidden[row][col] = False
if self.board[row][col] == 0:
for i in range(row - 1, row + 2):
for j in range(col - 1, col + 2):
if (0 <= i < self.rows) and (0 <= j < self.cols):
self.check(i, j)
return True
def play(self):
while True:
self.print_board()
row = int(input("Enter row: "))
col = int(input("Enter col: "))
if not self.check(row, col):
break
def print_board(self):
for i in range(self.rows):
for j in range(self.cols):
if self.hidden[i][j]:
print("*", end=" ")
else:
print(self.board[i][j], end=" ")
print()
game = MineSweeper()
game.play()
```
这个程序可以帮助你玩