python 游戏扫雷_Python游戏:扫雷
时间: 2023-06-27 07:07:30 浏览: 232
扫雷是一款经典的休闲益智游戏,Python也可以开发出一个简单的扫雷游戏。下面是一个简单的Python扫雷游戏的实现:
```python
import random
# 游戏主函数
def play():
# 游戏设置
rows = 10
cols = 10
mines = 10
# 扫雷地图
board = []
for i in range(rows):
row = []
for j in range(cols):
row.append(0)
board.append(row)
# 布置地雷
count = 0
while count < mines:
row = random.randint(0, rows-1)
col = random.randint(0, cols-1)
if board[row][col] == 0:
board[row][col] = '*'
count += 1
# 显示地图
for i in range(rows):
for j in range(cols):
if board[i][j] == 0:
board[i][j] = count_mines(board, i, j)
# 开始游戏
while True:
print_board(board)
row = int(input('Please enter row: '))
col = int(input('Please enter col: '))
if board[row][col] == '*':
print('Game over!')
break
elif board[row][col] > 0:
board[row][col] = str(board[row][col])
else:
expand(board, row, col)
if count_empty(board) == mines:
print('You win!')
break
# 计算周围地雷数量
def count_mines(board, row, col):
count = 0
for i in range(row-1, row+2):
for j in range(col-1, col+2):
if i >= 0 and i < len(board) and j >= 0 and j < len(board[0]):
if board[i][j] == '*':
count += 1
return count
# 显示地图
def print_board(board):
for row in board:
for col in row:
print(col, end=' ')
print()
# 展开空白区域
def expand(board, row, col):
if row < 0 or row >= len(board) or col < 0 or col >= len(board[0]):
return
if board[row][col] == '*' or board[row][col] > 0:
return
board[row][col] = '-'
expand(board, row-1, col)
expand(board, row+1, col)
expand(board, row, col-1)
expand(board, row, col+1)
# 计算未翻开的方块数量
def count_empty(board):
count = 0
for row in board:
for col in row:
if col == 0:
count += 1
return count
# 开始游戏
play()
```
这段代码实现了一个简单的扫雷游戏,玩家可以输入行和列来翻开对应的方块,如果翻开的方块是地雷,则游戏结束;如果所有非地雷方块都被翻开,则游戏胜利。
阅读全文