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

Microbit Python准确度检测函数内暂停时长不一致问题求助

问题根因分析
  • 核心逻辑错误:你当前的代码对单音符分配了两倍的预期时长。Timer_3_Accuracy(300)本身就会占用最多300ms的判定时间(玩家不按键就跑满300ms),之后你又调用了300ms的全局等待,二者叠加就导致玩家不按键时,两个音符间隔直接多了300ms,停顿明显变长。
  • 循环冗余:while not (input.pin_is_pressed(TouchPin.P2)):的循环条件和内部if input.pin_is_pressed(TouchPin.P2) or Overall_Timer == num: break的判断完全重复,属于无效冗余。
  • 变量逻辑混乱:Overall_Timer同时承担了判定窗口计时和全局间隔计时的两个功能,逻辑冲突导致等待时长计算错误。
优化方案

1. 修复时长计算逻辑

每个音符的总周期(从显示到下一个音符出现)是固定值,判定窗口只占总周期的一部分,不要重复叠加等待时间。示例调整逻辑:

# 假设单音符总周期为300ms,其中前250ms是判定窗口,后50ms是固定过渡等待
def Timer_3_Accuracy(judge_window: number, total_cycle: number):
    global Timer_Three, Score
    Timer_Three = 0
    # 判定窗口逻辑,最多跑judge_window毫秒
    while Timer_Three < judge_window:
        basic.pause(1)
        Timer_Three +=1
        if input.pin_is_pressed(TouchPin.P2):
            break
    # 计分逻辑不变
    if Timer_Three <= 125:
        Score +=50
    elif Timer_Three <= judge_window:
        Score +=30
    # 固定等待剩余时间,保证总周期稳定,不受玩家按键时机影响
    basic.pause(total_cycle - Timer_Three)

调用时直接用Timer_3_Accuracy(250, 300)即可,不需要额外调用全局等待函数。

2. 消除冗余循环

把重复的按键判断合并,简化循环逻辑,避免不必要的条件判断消耗性能。

双按键同时判定方案

不需要重构整体架构,只需要在判定窗口内同时监听两个按键,给每个按键分配独立的计时器即可:

def Dual_Key_Accuracy(judge_window: number, total_cycle: number):
    global Score, p1_timer, p2_timer
    p1_pressed = False
    p2_pressed = False
    p1_timer = 0
    p2_timer = 0
    elapsed = 0
    while elapsed < judge_window:
        basic.pause(1)
        elapsed +=1
        # 分别检测两个按键,按下后就不再计时
        if not p1_pressed:
            p1_timer +=1
            if input.pin_is_pressed(TouchPin.P1):
                p1_pressed = True
        if not p2_pressed:
            p2_timer +=1
            if input.pin_is_pressed(TouchPin.P2):
                p2_pressed = True
        # 两个键都按了可以提前退出
        if p1_pressed and p2_pressed:
            break
    # 分别计算两个按键的得分
    if p1_pressed:
        if p1_timer <=125:
            Score +=50
        elif p1_timer <= judge_window:
            Score +=30
    if p2_pressed:
        if p2_timer <=125:
            Score +=50
        elif p2_timer <= judge_window:
            Score +=30
    # 固定等待剩余时间,保证节奏稳定
    basic.pause(total_cycle - elapsed)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 19:36:03