Python扫雷代码分享 - 应用插件论坛 - 精品软件 - 小轻秀场

Python扫雷代码分享

```python
import random

# 定义常量
ROWS = 10    # 行数
COLS = 10    # 列数
MINES = 10   # 地雷数量

# 定义游戏状态常量
GAME_STATE_WIN = "win"
GAME_STATE_LOSE = "lose"
GAME_STATE_PLAYING = "playing"

# 初始化游戏状态
game_state = GAME_STATE_PLAYING

# 初始化地图(二维列表),0表示没有地雷,1表示有地雷
map_list = [[0 for i in range(COLS)] for j in range(ROWS)]

# 随机生成地雷位置,并在地图上标记为1
for i in range(MINES):
    row = random.randint(0, ROWS-1)
    col = random.randint(0, COLS-1)
    while map_list[row][col] == 1:
        row = random.randint(0, ROWS-1)
        col = random.randint(0, COLS-1)
    map_list[row][col] = 1

# 定义检查周围八个格子是否有地雷的函数
def count_mines_around(map_list, row, col):
    count = 0
    for i in range(max(row-1, 0), min(row+2, ROWS)):
        for j in range(max(col-1, 0), min(col+2, COLS)):
            if map_list[i][j] == 1:
                count += 1
    return count

# 定义递归展开空白区域的函数
def expand_blank_area(map_list, visited_map, row, col):
    visited_map[row][col] = True
    for i in range(max(row-1, 0), min(row+2, ROWS)):
        for j in range(max(col-1, 0), min(col+2, COLS)):
            if not visited_map[i][j]:
                visited_map[i][j] = True
                if map_list[i][j] == 0:
                    expand_blank_area(map_list, visited_map, i, j)

# 定义主循环,处理玩家输入和游戏逻辑
while game_state == GAME_STATE_PLAYING:

    # 打印当前地图状态
    print("Current Map:")
    for i in range(ROWS):
        for j in range(COLS):
            if map_list[i][j] == 1:
                print("*", end="")
            else:
                print(count_mines_around(map_list, i, j), end="")
        print()

    # 玩家输入坐标并进行处理
    input_str = input("Please enter the coordinate (row,col): ")
    inputs = input_str.split(",")
    row = int(inputs[0])
    col = int(inputs[1])

    # 如果玩家踩到地雷,则游戏失败
    if map_list[row][col] == 1:
        game_state = GAME_STATE_LOSE

    # 如果玩家踩到空白格子,则展开周围的空白区域
    elif map_list[row][col] == 0:
        visited_map = [[False for i in range(COLS)] for j in range(ROWS)]
        expand_blank_area(map_list, visited_map, row, col)

        # 检查是否还剩下未被展开的空白格子,如果没有则游戏胜利
        all_expanded = True
        for i in range(ROWS):
            for j in range(COLS):
                if not visited_map[i][j] and map_list[i][j] == 0:
                    all_expanded = False
                    break
            if not all_expanded:
                break

        if all_expanded:
            game_state = GAME_STATE_WIN

# 根据游戏状态打印相应信息
if game_state == GAME_STATE_WIN:
    print("Congratulations! You win!")
elif game_state == GAME_STATE_LOSE:
    print("Sorry! You lose!") 
```

这段代码实现了一个简单的扫雷游戏,玩家需要输入坐标来翻开格子。如果翻开的格子是地雷,则游戏失败;如果翻开的格子是空白格子,则会自动展开周围的空白区域。当所有空白格子都被展开时,游戏胜利。

请登录后发表评论

    没有回复内容