qbasic如何在指定时间后退出循环?

qbasic how to exit the loop after a specified time?

cls

keyed$=inkey$

循环直到输入 $<>""

打印"the hello world"

结束

所以在这个程序中,正如您所看到的,直到在语句 "keyed$=inkey$" 中按下一个键,程序才会显示 hello world。所以我想要这样一个语句或程序,它会在特定时间退出循环。所以程序将等待 4 秒,如果用户在此之前按下该键,它将转到下一行,即使用户不按任何键,程序也会在 4 秒内移动到下一行。请帮助我!!!

您可以使用 SLEEP 语句:

PRINT "Press a key within 4 seconds to win!"

' Wait 4 seconds or until a key is pressed.
SLEEP 4

' Collect the key pressed, if any.
keyed$ = INKEY$

IF keyed$ <> "" THEN
    PRINT "You WON by typing: "; keyed$
ELSE
    PRINT "You LOST!"
END IF

请注意,某些键(例如箭头键)被视为 "extended" 键。 keyed$ 的第一个字符将等于 CHR$(0) 以告诉您检测到扩展键,第二个字符将允许您确定它是哪个键。如果您需要处理这些 "two byte codes",您可以 find more information on the QB64 wiki。对于此类键,上面的代码将无法正常工作,如下所示,当我按下向上箭头键 (CHR$(0) + CHR$(&H48)) 时:

Press a key within 4 seconds to win!
You WON by typing:  H
                   ^note the extra space for CHR$(0)

编辑

你可以用这个代替循环来做你想做的事:

' Wait 4 seconds for a key to be pressed.
SLEEP 4

' If a key was not pressed in 4 seconds, keyed$ = "".
keyed$ = INKEY$
IF keyed$ = "" THEN PRINT "Timeout (no key pressed)"

PRINT "the hello world"

换句话说,如果使用SLEEP语句并在之后立即使用INKEY$函数,则不需要循环来检测是否按下了键。

如果您仍然喜欢带循环的基于计时器的解决方案,那么您可以使用一些额外的变量、一个额外的循环条件和 TIMER 函数,其中 returns自午夜以来经过的秒数。以下与上面的 SLEEP 方法做同样的事情:

maxWait = 4
startTime = TIMER
DO
    ' Detect a key press.
    keyed$ = INKEY$

    ' Fix the start time if the loop started before midnight
    ' and the current time is after midnight.
    IF startTime > TIMER THEN startTime = startTime - 86400

' Loop until a key is pressed or maxWait seconds have elapsed.
LOOP UNTIL keyed$ <> "" OR startTime + maxWait < TIMER

' If a key was not pressed in 4 seconds, keyed$ = "".
IF keyed$ = "" THEN PRINT "Timeout (no key pressed)"

PRINT "the hello world"

这个更复杂的选项的优点是您可以在等待按键的同时在循环中做其他事情。当然,有个小问题。如果你做的太多,按键将被延迟检测到,因为 INKEY$ 不会在按键被按下时立即被调用。例如:

maxWait = 4
startTime = TIMER
DO
    ' Do some work.
    x = 0
    FOR i = 1 TO 1000000
        x = x + 1
    NEXT i

    ' Detect a key press and exit the loop if one is detected.
    keyed$ = INKEY$

    ' Fix the start time if the loop started before midnight
    ' and the current time is after midnight.
    IF startTime > TIMER THEN startTime = startTime - 86400

' Loop until a key is pressed or maxWait seconds have elapsed.
LOOP UNTIL keyed$ <> "" OR startTime + maxWait < TIMER

要避免这个问题很棘手。一个选项是 , except you can only use one timer event. This means you would need it to exit the loop after maxWait seconds rather than detect a key press, even if there is work occurring. Meanwhile, your key presses will still be detected noticeably later than desired. QB64 allows for the usage of multiple timers, allowing you to handle both. It also allows you to specify n with millisecond precision, unlike QBasic that only allows for 1-second precision at minimum. See ON TIMER(n) on the QB64 Wiki,以获取有关 QB64 对 ON TIMER(n).

改进的更多信息

由于我不知道您的使用情况,因此无法根据您提供的代码推荐一种或另一种解决方案。