下面是一个简单的扫雷程序的示例代码:

import random

def create_board(rows, cols, num_mines):
    board = [[0] * cols for _ in range(rows)]
    mines = random.sample(range(rows * cols), num_mines)
    for mine in mines:
        row = mine // cols
        col = mine % cols
        board[row][col] = 'X'
        for i in range(max(0, row - 1), min(rows, row + 2)):
            for j in range(max(0, col - 1), min(cols, col + 2)):
                if board[i][j] != 'X':
                    board[i][j] += 1
    return board

def print_board(board):
    for row in board:
        print(' '.join(map(str, row)))

def play_game(board):
    rows = len(board)
    cols = len(board[0])
    uncovered = [[False] * cols for _ in range(rows)]
    num_uncovered = 0

    while num_uncovered < rows * cols - num_mines:
        print_board(uncovered)
        row, col = map(int, input("Enter the row and column (0-indexed): ").split())
        if uncovered[row][col]:
            print("This cell has already been uncovered. Please choose another one.")
            continue
        if board[row][col] == 'X':
            print("Game over! You hit a mine.")
            return
        uncover_cells(board, uncovered, row, col)
        num_uncovered += 1

    print("Congratulations! You have uncovered all the safe cells.")

def uncover_cells(board, uncovered, row, col):
    if row < 0 or row >= len(board) or col < 0 or col >= len(board[0]) or uncovered[row][col]:
        return
    uncovered[row][col] = True
    if board[row][col] == 0:
        for i in range(max(0, row - 1), min(len(board), row + 2)):
            for j in range(max(0, col - 1), min(len(board[0]), col + 2)):
                uncover_cells(board, uncovered, i, j)

rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
num_mines = int(input("Enter the number of mines: "))

board = create_board(rows, cols, num_mines)
play_game(board)

这个程序使用随机生成的雷区创建了一个扫雷游戏。你可以输入行数、列数和雷的数量来设置游戏的难度。然后,你可以输入要翻开的行和列来进行游戏。如果你翻开了一个雷,游戏结束,否则你需要翻开所有的安全方块才能获胜

写个扫雷程序

原文地址: http://www.cveoy.top/t/topic/ilfp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录