用python写一个扫雷
时间: 2023-07-01 08:13:12 浏览: 236
使用Python的扫雷游戏
5星 · 资源好评率100%
好的,以下是一个简单的Python扫雷游戏的实现,仅供参考。
```python
import random
# 游戏难度,决定了游戏面板大小和雷的数量
EASY = {'rows': 9, 'cols': 9, 'mines': 10}
MEDIUM = {'rows': 16, 'cols': 16, 'mines': 40}
HARD = {'rows': 16, 'cols': 30, 'mines': 99}
# 游戏状态
GAME_WIN = 0
GAME_LOSE = -1
GAME_CONTINUE = 1
# 游戏面板
class Board:
def __init__(self, difficulty):
self.rows = difficulty['rows']
self.cols = difficulty['cols']
self.mines = difficulty['mines']
self.board = [[Cell() for col in range(self.cols)] for row in range(self.rows)]
self.num_uncovered = 0
self.status = GAME_CONTINUE
self.create_mines()
def create_mines(self):
# 在随机位置生成雷
count = 0
while count < self.mines:
row = random.randint(0, self.rows-1)
col = random.randint(0, self.cols-1)
if not self.board[row][col].is_mine:
self.board[row][col].is_mine = True
count += 1
def get_cell(self, row, col):
# 获取指定位置的Cell对象
if row < 0 or row >= self.rows or col < 0 or col >= self.cols:
return None
return self.board[row][col]
def get_adjacent_cells(self, row, col):
# 获取指定位置周围的Cell对象
cells = []
for r in range(row-1, row+2):
for c in range(col-1, col+2):
cell = self.get_cell(r, c)
if cell and cell != self.board[row][col]:
cells.append(cell)
return cells
def uncover(self, row, col):
# 翻开指定位置的Cell
cell = self.get_cell(row, col)
if not cell or cell.is_uncovered:
return
cell.uncover()
self.num_uncovered += 1
if cell.is_mine:
self.status = GAME_LOSE
elif self.num_uncovered == self.rows * self.cols - self.mines:
self.status = GAME_WIN
elif cell.num_adjacent_mines == 0:
for adj_cell in self.get_adjacent_cells(row, col):
self.uncover(adj_cell.row, adj_cell.col)
def flag(self, row, col):
# 在指定位置插旗
cell = self.get_cell(row, col)
if cell and not cell.is_uncovered:
cell.toggle_flag()
def __str__(self):
# 以字符串形式返回游戏面板
lines = []
lines.append(' ' + ' '.join(str(i) for i in range(self.cols)))
lines.append(' +' + '-'*self.cols*2 + '+')
for i in range(self.rows):
row = [str(i)]
for j in range(self.cols):
cell = self.board[i][j]
if cell.is_uncovered:
if cell.is_mine:
row.append('* ')
elif cell.num_adjacent_mines > 0:
row.append(str(cell.num_adjacent_mines) + ' ')
else:
row.append(' ')
else:
if cell.is_flagged:
row.append('F ')
else:
row.append('. ')
lines.append(' |' + ' '.join(row) + '|')
lines.append(' +' + '-'*self.cols*2 + '+')
return '\n'.join(lines)
# 单个格子
class Cell:
def __init__(self):
self.is_mine = False
self.is_uncovered = False
self.is_flagged = False
self.row = None
self.col = None
self.num_adjacent_mines = 0
def uncover(self):
self.is_uncovered = True
def toggle_flag(self):
self.is_flagged = not self.is_flagged
def __str__(self):
return 'X'
# 游戏主循环
def main():
print('Welcome to Minesweeper!')
while True:
print('Select a difficulty (easy, medium, hard) or quit:')
choice = input().lower()
if choice == 'quit':
break
elif choice == 'easy':
difficulty = EASY
elif choice == 'medium':
difficulty = MEDIUM
elif choice == 'hard':
difficulty = HARD
else:
print('Invalid choice.')
continue
board = Board(difficulty)
print(board)
while board.status == GAME_CONTINUE:
print('Enter a row and column (e.g. 2,3) or flag (e.g. f,2,3):')
move = input().lower().split(',')
if len(move) == 2:
row, col = int(move[0]), int(move[1])
board.uncover(row, col)
elif len(move) == 3 and move[0] == 'f':
row, col = int(move[1]), int(move[2])
board.flag(row, col)
else:
print('Invalid move.')
continue
print(board)
if board.status == GAME_WIN:
print('Congratulations, you won!')
elif board.status == GAME_LOSE:
print('Game over, you lose!')
print()
if __name__ == '__main__':
main()
```
这个实现是基于命令行的,需要输入行列数和操作来进行游戏。但是可以通过修改代码实现更好的交互方式。
阅读全文