batch-file

bat game. Adding a timer with set /p


Im making a .bat game, and currently when putting in a command the code is

set /p command=

What i want to know is if you can somehow have a time limit for inputting the commands. For example if your fighting a guard, and you haven't put a command in for say 5 seconds, the guard attacks.

This is not something of dire need, I am just wondering more about the limitations im bound to, and i think i know the anawer anyway (the answer being that you cant)

Thanks


Solution

  • It can also be done with batch only.

    You can create a second thread (in the same window) with start /b.
    If this thread wait with set /p for user input, the main thread is not affected.
    This sample will wait for 5 seconds for userinput, if the user inputs text it is moved into a file, so the first thread can access it.

    @echo off
    setlocal EnableDelayedExpansion
    if "%1" NEQ "" goto %1
    
    del enter.tmp 2>nul >nul
    start /b cmd /c %0 :secondThread
    
    :FirstThread
    set n=0
    echo Enter Text (5 seconds timeout):
    
    :loop
    set /a n+=1
    ping -n 2 localhost > nul
    if !n! LSS 5 (
        if not exist entER.tmp goto :loop
        < Enter.tmp (
            set /p input=
        )
        echo !input!
    ) ELSE (
        echo Timeout for input
    )
    
    exit /b
    
    :secondThread
    set /p var=
    > enter.tmp echo !var!
    exit /b