You need to enable JavaScript to run this app. 自定义网格与地雷数的终端Python扫雷游戏代码运行异常求助
优惠活动
大模型
产品
解决方案
定价
更多

自定义网格与地雷数的终端Python扫雷游戏代码运行异常求助

终端自定义扫雷Python代码修复

原代码问题列表

  • 缺少random标准库导入,放置地雷时调用random.randint会直接报错
  • Square类的status_get方法错误使用this关键字指代实例,Python中实例自引用需用self,该方法无实际调用可直接删除
  • 全局变量FLAGS未初始化,插旗操作访问该变量时会抛出未定义错误
  • 启动流程缺失first_move()调用,没有第一次挖雷、生成地雷的逻辑,直接进入普通回合会导致所有格子都没有地雷
  • 游戏启动后没有首次棋盘展示,用户操作前看不到当前棋盘状态
  • 部分格子状态赋值存在格式不一致问题:挖开无雷格子时有的赋值为"x"少了尾部空格,会导致棋盘对齐错乱
  • welfare(自动展开空白格子)函数使用可变对象[]作为默认参数,多次调用会残留历史记录,导致空白展开逻辑异常
  • 胜利判定逻辑不完整,仅校验了所有地雷都被正确插旗的情况,未覆盖所有非雷格子全部挖开的胜利场景
  • 插旗、取消插旗的逻辑存在计数错误,重复插旗会导致FLAGS计数异常

修复后完整可运行代码

import random

SIZE = 0
MINES = 0
BOARD = []
FLAGS = 0

def display():
    for x in range(SIZE):
        if x == 0:
            print(" ", end="")
            for i in range(SIZE):
                print("   " + str(i), end="")
            print("\n  |-" + "--|-" * (SIZE - 1) + "--|")
            print("0 |", end="")
            for y in range(SIZE):
                print(" " + str(BOARD[x][y].status) + "|", end="")
            print("\n  |-" + "--|-" * (SIZE -1) + "--|")
        elif x == SIZE -1:
            print(str(SIZE-1) + " |", end="")
            for y in range(SIZE):
                print(" " + str(BOARD[x][y].status) + "|", end="")
            print("\n  |-" + "--|-" * (SIZE -1) + "--|")
        else:
            print(str(x) + " |", end="")
            for y in range(SIZE):
                print(" " + str(BOARD[x][y].status) + "|", end="")
            print("\n  |-" + "--|-" * (SIZE-1) + "--|")

class Square:
    def __init__(self, x, y):
        self.status = "- "
        self.row = x
        self.column = y
        self.mine = False
        self.neighbours = []
        self.danger = 0

def first_move():
    print("""Where would you like to start?\n""")
    while True:
        a, b = input("Enter an x and y coodinate, comma separated, to dig the first square: ").split(",")
        x = int(a)
        y = int(b)
        if x >= SIZE or y >= SIZE:
            print("Out of bounds, try again.")
            continue
        else:
            for m in range(MINES):
                place_mines(x, y)
            welfare(BOARD[x][y])
            display()
            break

def place_mines(x, y):
    global BOARD
    h = random.randint(0, SIZE - 1)
    w = random.randint(0, SIZE - 1)
    if h == x and w == y:
        place_mines(x, y)
    else:
        if not BOARD[h][w].mine:
            BOARD[h][w].mine = True
            for sqr in BOARD[h][w].neighbours:
                sqr.danger += 1
        else:
            place_mines(x, y)

def next_turn():
    move = input("What would you like to do? ").lower()
    if move == "!quit":
        print("Thank you, come again.")
        quit(0)
    elif move == "d":
        dig()
        display()
    elif move == "f":
        flag()
        display()
    elif move == "r":
        unflag()
        display()
    elif move == "!help":
        print("!quit = Quit game.")
        print("d = Uncover a square.")
        print("f = Plant a flag marking a square as containing a mine.")
        print("r = Remove a flag.")
    else:
        print("You'll have to speak up... Try again.")

def unflag():
    while True:
        a, b = input("Supply an x and y coordinate to unflag: ").split(",")
        x = int(a)
        y = int(b)
        if x >= SIZE or y >= SIZE:
            print("Out of bounds, try again.")
            continue
        else:
            global BOARD, FLAGS
            if BOARD[x][y].status == "F ":
                BOARD[x][y].status = "- "
                if BOARD[x][y].mine:
                    FLAGS -= 1
            break

def flag():
    while True:
        a, b = input("Supply an x and y coordinate to flag: ").split(",")
        x = int(a)
        y = int(b)
        if x >= SIZE or y >= SIZE:
            print("Out of bounds, try again.") 
            continue
        else:
            global BOARD, FLAGS
            if BOARD[x][y].status == "- ":
                BOARD[x][y].status = "F "
                if BOARD[x][y].mine:
                    FLAGS += 1
            break

def dig():
    while True:
        a, b = input("Supply an x and y coordinate to dig: ").split(",")
        x = int(a)
        y = int(b)
        if x >= SIZE or y >= SIZE:
            print("Out of bounds, try again.")
            continue
        else:
            if BOARD[x][y].mine is True:
                print("BANG! You have died!")
                for x in range(SIZE):
                    for y in range(SIZE):
                        sqr = BOARD[x][y]
                        if sqr.mine:
                            sqr.status = "@ "
                display()
                quit(0)
            else:
                welfare(BOARD[x][y])
                break


def welfare(sqr, history=None):
    if history is None:
        history = []
    if sqr.danger == 0:
        sqr.status = "x "
        for box in sqr.neighbours:
            if box not in history:
                history.append(box)
                welfare(box, history)
    else:
        if not sqr.mine:
            sqr.status = str(sqr.danger) + " "

def win_state():
    global FLAGS, MINES, BOARD
    correct = 0
    all_uncovered = True
    if FLAGS == MINES:
        for x in range(SIZE):
            for y in range(SIZE):
                sqr = BOARD[x][y]
                if sqr.mine and sqr.status == "F ":
                    correct += 1
                if not sqr.mine and sqr.status in ("- ", "F "):
                    all_uncovered = False
        if correct == MINES or all_uncovered:
            print("Congratulations!\n")
            print("You found " + str(MINES) + " mines and didn't die.")
            exit(0)

def startup():
    print("It's Minesweeper, how wide do you want the board?")
    global SIZE, MINES, BOARD, FLAGS
    FLAGS = 0
    while True:
        SIZE = int(input("Give me a size, between 3 and 10 inclusive "))
        if SIZE not in range(3, 11):
            print("Did I stutter? Try again. ")
            continue
        else:
            while True:
                MINES = int(input("How many mines do you want? "))
                if MINES >= SIZE ** 2:
                    print("Whoa! That's too many. Try Again. ")
                    continue
                else:
                    break
            print("OKAY")
            BOARD = [[None for _ in range(SIZE)] for _ in range(SIZE)]
            
            for s in range(SIZE):
                for d in range(SIZE):
                    BOARD[s][d] = Square(s, d)
            
            for a in range(SIZE):
                for b in range(SIZE):
                    sqr = BOARD[a][b]
                    if a == 0:
                        sqr.neighbours.append(BOARD[a + 1][b])
                        if b != SIZE - 1:
                            sqr.neighbours.append(BOARD[a + 1][b + 1])
                            sqr.neighbours.append(BOARD[a][b + 1])
                        if b != 0:
                            sqr.neighbours.append(BOARD[a][b - 1])
                            sqr.neighbours.append(BOARD[a + 1][b - 1])
                    elif a == SIZE - 1:
                        sqr.neighbours.append(BOARD[a - 1][b])
                        if b != SIZE - 1:
                            sqr.neighbours.append(BOARD[a][b + 1])
                            sqr.neighbours.append(BOARD[a - 1][b + 1])
                        if b != 0:
                            sqr.neighbours.append(BOARD[a - 1][b - 1])
                            sqr.neighbours.append(BOARD[a][b - 1])
                    else:
                        sqr.neighbours.append(BOARD[a + 1][b])
                        sqr.neighbours.append(BOARD[a - 1][b])
                        if b != SIZE - 1:
                            sqr.neighbours.append(BOARD[a - 1][b + 1])
                            sqr.neighbours.append(BOARD[a][b + 1])
                            sqr.neighbours.append(BOARD[a + 1][b + 1])
                        if b != 0:
                            sqr.neighbours.append(BOARD[a - 1][b - 1])
                            sqr.neighbours.append(BOARD[a][b - 1])
                            sqr.neighbours.append(BOARD[a + 1][b - 1]) 
    first_move()

startup()
while True:
    next_turn()
    win_state()

内容的提问来源于stack exchange,提问作者user1019450

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 03:36:03