You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python扫雷游戏作业问题:点击无法触发探雷功能排查

解决扫雷游戏点击无响应与自动揭开单元格的问题

你的代码里有两个核心问题导致了当前的异常表现,咱们一步步来修正:

1. 错误的事件绑定逻辑

你现在写的 s.onscreenclick(closure()) 是直接执行了closure函数,而不是把函数本身绑定到点击事件上。这就导致程序一开始就调用了 mine.probe(board,board),直接揭开了棋盘中心的单元格(因为你把棋盘尺寸当成坐标传了进去),同时点击事件根本没成功绑定。

正确的写法是去掉括号,把函数对象传递给 onscreenclick:

s.onscreenclick(closure)

2. 传递错误的参数给probe方法

probe 方法需要接收鼠标点击的 (x,y) 坐标,但你的closure函数里硬传了 (board,board),这显然不是鼠标的实际点击位置。你需要让closure函数接收点击事件的x和y参数,再传给probe:

def closure(x, y):
    find, rem = mine.probe(x, y)
    # 后续逻辑不变

3. 补充窗口主循环(关键)

Turtle程序需要主循环来维持窗口运行并监听用户事件,否则程序初始化后可能直接退出。建议在main函数末尾加上:

wn.mainloop()

修改后的完整代码

import turtle
import game

def main():
    wn = turtle.Screen()
    board = wn.numinput("Numeric Input", "Enter desired board size: ")
    board = int(board)
    mine = game.Game(board)
    nummine = wn.numinput("Numeric Input", "Enter desired number of mines: ")
    nummine = int(nummine)
    mine.hideMines(nummine)
    
    def closure(x, y):
        find, rem = mine.probe(x, y)

        if rem == 0:
            over = wn.textinput("Text Input", "Would you like to play again? (Y)es or (N)o")
            if over == 'Y':
                # 递归调用main可能积累资源,重启前先清理屏幕
                turtle.clearscreen()
                main()
            else:
                turtle.bye()
    
    s = wn.getscreen()
    s.onscreenclick(closure)  # 传递函数对象,而非直接调用
    wn.mainloop()  # 启动事件监听主循环

main()

小提醒:递归调用main()重启游戏可能会积累Turtle的资源,后续如果遇到卡顿问题,可以考虑单独写一个重置游戏状态的函数,而不是递归重启整个main函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:11:22