用python代码实现扫雷小游戏
时间: 2023-09-05 20:09:48 浏览: 82
用python写扫雷游戏实例代码分享
5星 · 资源好评率100%
好的,以下是一个简单的扫雷游戏的 Python 代码实现:
```python
import random
# 初始化游戏棋盘
def init_board(board_size, mine_num):
board = [[0 for i in range(board_size)] for j in range(board_size)]
for i in range(mine_num):
x = random.randint(0, board_size - 1)
y = random.randint(0, board_size - 1)
while board[x][y] == -1:
x = random.randint(0, board_size - 1)
y = random.randint(0, board_size - 1)
board[x][y] = -1
for a in range(max(0, x - 1), min(x + 2, board_size)):
for b in range(max(0, y - 1), min(y + 2, board_size)):
if board[a][b] != -1:
board[a][b] += 1
return board
# 显示游戏棋盘
def show_board(board):
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == -1:
print("*", end=' ')
elif board[i][j] == 0:
print(".", end=' ')
else:
print(board[i][j], end=' ')
print()
# 判断游戏是否结束
def check_game_over(board, status):
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] != -1 and status[i][j] == 0:
return False
return True
# 更新游戏状态
def update_status(board, status, x, y):
if board[x][y] == -1:
status[x][y] = 2
return False
status[x][y] = 1
if board[x][y] == 0:
for a in range(max(0, x - 1), min(x + 2, len(board))):
for b in range(max(0, y - 1), min(y + 2, len(board))):
if status[a][b] == 0:
update_status(board, status, a, b)
return True
# 扫雷游戏主函数
def play_minesweeper(board_size, mine_num):
board = init_board(board_size, mine_num)
status = [[0 for i in range(board_size)] for j in range(board_size)]
show_board(status)
while True:
x = int(input("请输入要翻开的格子的横坐标:"))
y = int(input("请输入要翻开的格子的纵坐标:"))
if not update_status(board, status, x, y):
print("你炸了!")
show_board(board)
break
show_board(status)
if check_game_over(board, status):
print("你赢了!")
show_board(board)
break
# 测试函数
if __name__ == '__main__':
play_minesweeper(8, 10)
```
这个程序可以让用户玩一个 8×8 的扫雷游戏,其中有 10 个地雷。用户输入要翻开的格子的横纵坐标,程序会更新棋盘状态并显示出来,如果翻到了地雷,游戏结束。如果用户成功翻开了所有非地雷格子,游戏也结束并显示胜利信息。
阅读全文