欢迎访问宙启技术站
智能推送

使用Python制作一个简易的扫雷游戏

发布时间:2023-12-04 13:26:54

下面是一个使用Python编写的简易扫雷游戏的代码。在这个游戏中,玩家需要揭开地图上的方块,并避免踩到地雷。

import random

# 定义地图的大小和地雷数量
map_size = 10
mine_count = 10

# 生成地图
def create_map():
    map = []
    for i in range(map_size):
        row = []
        for j in range(map_size):
            row.append('-')
        map.append(row)
    return map

# 随机生成地雷的位置
def create_mines(map):
    count = 0
    while count < mine_count:
        x = random.randint(0, map_size-1)
        y = random.randint(0, map_size-1)
        if map[x][y] != '*':
            map[x][y] = '*'
            count += 1

# 显示地图
def print_map(map):
    for i in range(map_size):
        for j in range(map_size):
            print(map[i][j], end=" ")
        print()

# 检查相邻方块的地雷数量
def count_mines(map, x, y):
    if map[x][y] == '*':
        return '*'
    count = 0
    # 检查相邻的8个方块
    for i in range(-1, 2):
        for j in range(-1, 2):
            nx, ny = x+i, y+j
            if nx >= 0 and nx < map_size and ny >= 0 and ny < map_size:
                if map[nx][ny] == '*':
                    count += 1
    return count

# 揭开方块
def uncover(map, x, y):
    if map[x][y] != '-':
        return
    map[x][y] = str(count_mines(map, x, y))
    # 如果揭开的方块周围没有地雷,则继续递归地揭开周围的方块
    if map[x][y] == '0':
        for i in range(-1, 2):
            for j in range(-1, 2):
                nx, ny = x+i, y+j
                if nx >= 0 and nx < map_size and ny >= 0 and ny < map_size:
                    uncover(map, nx, ny)

# 主游戏循环
def game_loop():
    map = create_map()
    create_mines(map)

    game_over = False
    while not game_over:
        print_map(map)

        x = int(input("请输入要揭开的方块的行号:"))
        y = int(input("请输入要揭开的方块的列号:"))

        if map[x][y] == '*':
            print("很抱歉,你踩到地雷了!")
            game_over = True
        else:
            uncover(map, x, y)

        if len([1 for row in map for cell in row if cell == '-']) == mine_count:
            print("恭喜你,揭开了所有的方块,你胜利了!")
            game_over = True

# 启动游戏
game_loop()

使用例子:

请输入要揭开的方块的行号:3

请输入要揭开的方块的列号:5

- - - - - - - - - -

- - - - - - - - - -

- - - - - - - - - -

- - - - - 0 - - - -

- - - - 1 * 1 - - -

- - - - 1 2 2 2 - -

- - - - * * * 1 - -

- - - - * 2 * 1 - -

- - - 2 2 2 1 - - -

- - - - - - - - - -

请输入要揭开的方块的行号:6

请输入要揭开的方块的列号:6

- - - - - - - - - -

- - - - - - - - - -

- - - - - - - - - -

- - - - - 0 - - - -

- - - - 1 * 1 - - -

- - - - 1 2 2 2 - -

- - - - 0 2 * 1 - -

- - - - * 2 * 1 - -

- - - 2 2 2 1 - - -

- - - - - - - - - -

请输入要揭开的方块的行号:5

请输入要揭开的方块的列号:4

- - - - - - - - - -

- - - -