如何让代码在不使用 while 循环的情况下继续读取一段代码?

How to have the code continue to read a piece of code without using a while loop?

提问人:milk flood 提问时间:11/8/2023 最后编辑:milk flood 更新时间:11/9/2023 访问量:57

问:

我有一些代码使用 while 循环在某些文本行之间切换,但我想在循环中或按下此按钮时切断 while 循环。(按钮位于微型显示屏上)

目前,我只能弄清楚如何在 while 循环重新启动时使按钮工作(几乎没有时间按下它)。

我怎样才能做到,当按钮被读取时,无论代码在哪里,它都会被切断并过渡到一个新的场景?(我想澄清一下,我不希望按钮在函数之外工作,也就是我制作场景的方式,因为在代码的后面,同一个按钮用于其他事情)

def main():
    # Creates Game Ttile Screen
    clear()
    display.set_pen(GREEN)
    display.text("Blink of an Eye", 30, 25, 240, 5)
    display.update()
    time.sleep(2)
    clear()
    screen = 1
    # Switches between two "screens" 
    while True:
    #How To play Title Screen
        if screen == 1:
            display.set_pen(YELLOW)
            display.text('''How To Play: Press 'A' ''', 15, 35, 240, 4)
            display.update()
            time.sleep(1)
            clear()
            screen = 2
    
    # Play Title Screen
        elif screen == 2:
            display.set_pen(MAGENTA)
            display.text('''Play: Press 'B' ''', 15, 35, 240, 4)
            display.update()
            time.sleep(1)
            clear()
            screen = 1

目前还没有按钮的代码,因为没有一种方法有效,但我想添加的用于读取按钮的代码是:

button_a.read() 和 button_b.read()

接下来,也是一样的,是这段代码,我希望按钮无论代码在函数中的哪个位置都能工作。现在,它也只在代码的开头起作用。

def howToPlay():
    while True:
        if button_b.read():
            clear()
            play()
            break
        else:
            screen = 0
            display.set_pen(YELLOW)
            display.text('''How To Play''', 15, 55, 240, 4)
            display.update()
            time.sleep(0.5)
            clear()
            display.set_pen(YELLOW)
            display.text('''A few colors will flash on the screen; the player should wait to press 'Y' until green appears.''', 10, 35, 230, 2.5)
            display.update()
            time.sleep(4)
            clear()
            display.set_pen(YELLOW)
            display.text('''When 'Y' is pressed, your reaction time will appear on the screen. To play again, press 'X,' and to return to the menu, press 'A'.''', 10, 15, 230, 2.5)
            display.update()
            time.sleep(5)
            clear()
micropython 树莓派-pi-pico thonny

评论

0赞 Akshat Mahajan 11/8/2023
您的 Python 版本是什么?你先做了吗?import time
0赞 OM222O 11/8/2023
Pi pico 运行的是微型 python,而不是实际的 python。我猜那里没有定义性能计数器。你试过吗?time.time_ns()
0赞 Peter I. 11/10/2023
也许您想了解中断服务例程 (ISR)。通常“正常”方式是“轮询”(定期检查按钮),但正如您在 howToPlay() 例程中显示的那样,每 9.5 秒检查一次button_b,这有点慢。因此,您可以告诉 Pico 在按下按钮后立即调用函数 (ISR),而不是检查。

答: 暂无答案