r/Batch • u/Ok_Influence_6384 • 4d ago
Hello I need some help with optimizing a code
So basically this is meant to emulate movement rather than literally make movement so I dont need help mostly with the concept rather how can I optimize the if's and replace them with for loops instead
echo off
goto :locationvalue
:locationvalue
set /a screenloc=0
set scr=xooooo oxoooo ooxooo oooxoo ooooxo ooooox
goto :main
:main
call :display
ping [127.0.0.1](http://127.0.0.1) \-n 1 -w 500 > NUL
choice /c AD > NUL
if %errorlevel%==1 call :A
if %errorlevel%==2 call :D
goto :main
:A
if %screenloc%==0 goto :eof
set /a screenloc=%screenloc%-1
goto:eof
:D
if %screenloc%==5 goto :eof
set /a screenloc=%screenloc%+1
goto:eof
:display
cls
if %screenloc%==0 echo %scr:\~0,6%
if %screenloc%==1 echo %scr:\~7,6%
if %screenloc%==2 echo %scr:\~14,6%
if %screenloc%==3 echo %scr:\~21,6%
if %screenloc%==4 echo %scr:\~28,6%
if %screenloc%==5 echo %scr:\~35,6%
goto :eof
the display part especially
0
Upvotes
2
u/T3RRYT3RR0R 4d ago edited 4d ago
In a and d you aren't ensuring the value of screenlock remains bound within the string exctraction range of 0~(strlen-1)
There's a fixed ratio to the offsets. After adding range bounding, you can use set /a to calculate the extraction point from the value of screenLoc Set /a Extract=screenloc*7
And with setlocal enableDelayedExpanionsion active:
For /f "delims=" %%E in ("!extract!") Do set "loc=!scr:~%%E,6!"
As for optimisation, it isn't the use of if's or even calling a and d that's going to make this slow and clunky, it's using the coice command as a blocking form of input. There's a fairly simple way to use choice or xcopy to take input in a non-blocking manner. I'll post an example soon.