给我一份用python制作简单扫雷游戏的约200行代码
时间: 2023-12-05 12:05:54 浏览: 69
好的,以下是一个简单的扫雷游戏的 Python 代码,注释已经尽量写得详细了,希望对您有所帮助:
```python
import random
# 定义常量
BOARD_ROWS = 10
BOARD_COLS = 10
MINE_NUM = 10
# 定义图标
HIDDEN_ICON = '■'
MINE_ICON = 'x'
FLAG_ICON = 'F'
# 定义游戏状态
GAME_STATE_WIN = 0
GAME_STATE_LOSE = 1
GAME_STATE_PLAYING = 2
# 初始化游戏面板
def init_board(rows, cols, num):
board = [[0 for i in range(cols)] for j in range(rows)]
mines = random.sample(range(rows * cols), num)
for m in mines:
row = m // cols
col = m % cols
board[row][col] = MINE_ICON
return board
# 计算周边地雷数量
def count_mines_around(row, col, board):
count = 0
for i in range(max(0, row - 1), min(row + 2, len(board))):
for j in range(max(0, col - 1), min(col + 2, len(board[0]))):
if board[i][j] == MINE_ICON:
count += 1
return count
# 显示游戏面板
def display_board(board, visible):
print(' ', end='')
for j in range(len(board[0])):
print(j, end=' ')
print()
for i in range(len(board)):
print(i, end=' ')
for j in range(len(board[0])):
if visible[i][j]:
print(board[i][j], end=' ')
else:
print(HIDDEN_ICON, end=' ')
print()
# 处理玩家输入
def handle_input(board, visible):
while True:
try:
row, col = map(int, input('请输入行列号(空格隔开):').split())
if row < 0 or row >= BOARD_ROWS or col < 0 or col >= BOARD_COLS:
print('输入错误,请重新输入!')
elif visible[row][col]:
print('该位置已经翻开,请重新输入!')
else:
return row, col
except ValueError:
print('输入错误,请重新输入!')
# 翻开一个格子
def flip(row, col, board, visible):
if board[row][col] == MINE_ICON:
return GAME_STATE_LOSE
else:
visible[row][col] = True
if count_mines_around(row, col, board) == 0:
for i in range(max(0, row - 1), min(row + 2, len(board))):
for j in range(max(0, col - 1), min(col + 2, len(board[0]))):
if not visible[i][j]:
flip(i, j, board, visible)
return GAME_STATE_PLAYING
# 标记一个格子
def flag(row, col, visible):
visible[row][col] = not visible[row][col]
# 判断游戏是否胜利
def check_win(board, visible):
for i in range(len(board)):
for j in range(len(board[0])):
if not visible[i][j] and board[i][j] != MINE_ICON:
return False
return True
# 主函数
def main():
board = init_board(BOARD_ROWS, BOARD_COLS, MINE_NUM)
visible = [[False for i in range(BOARD_COLS)] for j in range(BOARD_ROWS)]
game_state = GAME_STATE_PLAYING
while game_state == GAME_STATE_PLAYING:
display_board(board, visible)
row, col = handle_input(board, visible)
if input('请输入操作(f: 标记;r: 翻开):') == 'f':
flag(row, col, visible)
else:
game_state = flip(row, col, board, visible)
display_board(board, visible)
if game_state == GAME_STATE_WIN:
print('恭喜你,游戏胜利!')
else:
print('很遗憾,游戏失败!')
if __name__ == '__main__':
main()
```
这份代码实现了一个简单的扫雷游戏,包括初始化游戏面板、计算周边地雷数量、显示游戏面板、处理玩家输入、翻开格子、标记格子、判断游戏是否胜利等功能。
阅读全文