扫雷(Minesweeper)是一款经典的逻辑游戏,玩家需要在一个网格中找出所有不包含地雷的格子,同时避免触发地雷。下面是一个简单的扫雷游戏的 Python 实现:
import random
class Minesweeper:
def __init__(self, rows, cols, num_mines):
self.rows = rows
self.cols = cols
self.num_mines = num_mines
self.board = [['.' for _ in range(cols)] for _ in range(rows)]
self.mines = set()
self.revealed = set()
self.plant_mines()
self.fill_hints()
def plant_mines(self):
while len(self.mines) < self.num_mines:
r = random.randint(0, self.rows - 1)
c = random.randint(0, self.cols - 1)
if (r, c) not in self.mines:
self.mines.add((r, c))
def fill_hints(self):
for r in range(self.rows):
for c in range(self.cols):
if (r, c) in self.mines:
continue
count = 0
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
if dr == 0 and dc == 0:
continue
nr, nc = r + dr, c + dc
if 0 <= nr < self.rows and 0 <= nc < self.cols and (nr, nc) in self.mines:
count += 1
self.board[r][c] = str(count) if count > 0 else '.'
def reveal(self, row, col):
if (row, col) in self.revealed or (row, col) in self.mines:
return
self.revealed.add((row, col))
if self.board[row][col] == '.':
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
nr, nc = row + dr, col + dc
if 0 <= nr < self.rows and 0 <= nc < self.cols and (nr, nc) not in self.revealed:
self.reveal(nr, nc)
def print_board(self, reveal_mines=False):
for r in range(self.rows):
for c in range(self.cols):
if reveal_mines and (r, c) in self.mines:
print('*', end=' ')
elif (r, c) in self.revealed:
print(self.board[r][c], end=' ')
else:
print('#', end=' ')
print()
def play(self):
while True:
self.print_board()
try:
row = int(input("Enter row index: "))
col = int(input("Enter column index: "))
if not (0 <= row < self.rows and 0 <= col < self.cols):
raise ValueError
self.reveal(row, col)
if (row, col) in self.mines:
print("Game Over!")
self.print_board(reveal_mines=True)
break
if len(self.revealed) + len(self.mines) == self.rows * self.cols:
print("Congratulations! You've cleared the board!")
self.print_board(reveal_mines=True)
break
except ValueError:
print("Invalid input. Please enter a valid row and column index.")
# Example game
game = Minesweeper(10, 10, 10)
game.play()
这段代码定义了一个 Minesweeper
类,它包含了扫雷游戏的基本逻辑。游戏开始时,会随机在网格中布置一定数量的地雷,然后计算每个非地雷格子周围的地雷数量,并填充到网格中。玩家通过输入行和列的索引来揭示格子,如果揭示的是地雷,则游戏结束;如果所有非地雷格子都被揭示,则玩家获胜。