使用python生成扫雷游戏代码
时间: 2023-07-23 22:13:05 浏览: 118
使用Python的扫雷游戏
5星 · 资源好评率100%
当然可以!下面是一个简单的扫雷游戏的代码示例:
```python
import random
# 创建一个空白的游戏板
def create_board(rows, cols, bombs):
board = [[' ' for _ in range(cols)] for _ in range(rows)]
placed_bombs = 0
# 随机放置炸弹
while placed_bombs < bombs:
row = random.randint(0, rows - 1)
col = random.randint(0, cols - 1)
if board[row][col] != 'B':
board[row][col] = 'B'
placed_bombs += 1
return board
# 计算每个方格周围的炸弹数量
def calculate_numbers(board):
rows = len(board)
cols = len(board[0])
for row in range(rows):
for col in range(cols):
if board[row][col] != 'B':
count = 0
# 检查周围的8个方格
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
new_row = row + i
new_col = col + j
if new_row >= 0 and new_row < rows and new_col >= 0 and new_col < cols and board[new_row][new_col] == 'B':
count += 1
if count > 0:
board[row][col] = str(count)
return board
# 显示游戏板
def display_board(board):
rows = len(board)
cols = len(board[0])
for row in range(rows):
for col in range(cols):
print(board[row][col], end=' ')
print()
# 主游戏循环
def play_game(rows, cols, bombs):
board = create_board(rows, cols, bombs)
board = calculate_numbers(board)
display_board(board)
# 测试游戏
play_game(5, 5, 5)
```
这只是一个简单的实现,你可以根据自己的需求进行定制和扩展。希望对你有所帮助!
阅读全文