Batch file 如何仅选择可用的批处理文件选项
我发现这篇教程是在Notepad++上制作一个游戏,并在CMD上制作一个批处理文件。到目前为止,我得到的是:Batch file 如何仅选择可用的批处理文件选项,batch-file,Batch File,我发现这篇教程是在Notepad++上制作一个游戏,并在CMD上制作一个批处理文件。到目前为止,我得到的是: :ChooseWeapon cls echo "I almost forgot. Here are the weapons I have avaliable, choose one and begin your quest." echo. set /p weapon=What is your weapon? (Sword, Double-Bladed Axe, Dagge
:ChooseWeapon
cls
echo "I almost forgot. Here are the weapons I have avaliable, choose one and begin your quest."
echo.
set /p weapon=What is your weapon? (Sword, Double-Bladed Axe, Dagger):
这一点是通过键入你想要的来选择你想要使用的武器。现在,问题是我能输入“ghregff”,它会说那是我的武器。我该怎么做才能让你选择:剑、双刃斧或匕首?你可以将其设置为如下所示的选择菜单,如果他们选择的数字不是1、2或3,它会将他们踢回以再次输入选择
@echo off
:chooseweapon
cls
echo "I almost forgot. Here are the weapons I have avaliable, choose one and begin your quest."
echo.
echo What is your weapon? (Sword, Double-Bladed Axe, Dagger):
echo 1 - Sword
echo 2 - Double-Bladed Axe
echo 3 - Dagger
echo.
set /P Weapon="Enter a choice: "
echo --------------------------------------------------------------------
for %%I in (1 2 3) do if #%Weapon%==#%%I goto wp%%I
goto chooseweapon
:wp1
Set weapon=Sword
goto end
:wp2
Set weapon=Double-Bladed Axe
goto end
:wp3
Set weapon=Dagger
goto end
:end
echo %weapon%
pause
这是一段灵活的代码,允许您通过以下三种方式进行选择:
使用chooselist
,参数列表被附加到setprompt
中,用户可以选择完整地输入任何响应,或者只输入足够明确定义需求的响应。例如,“s”将定义剑,但“双刃斧”需要“do”,而“匕首”则需要“da”,因为“d”是不明确的
使用chooselist2
类似,它只是在单独的行中列出每个选项并请求输入
最后,choosemeu
也会这样做,但是可以使用数字或明确的起始字符串对行和选项进行编号
响应总是在
response
中,最简单的方法似乎是通过findstr命令完成
:Choice
set /p weapon=What is your weapon? (Sword, Double-Bladed Axe, Dagger):
echo %weapon%| findstr /r "^Sword$ ^Double-Bladed Axe$ ^Dagger$">nul
if errorlevel 1 (
echo %weapon% was sadly not an option.
goto :Choice
)
echo you chose %weapon%.
(您需要^和$.^表示行的开始,$表示行的结束)
或
如果要多次使用该系统,可以使用带有参数和返回值的findstr
:MakeChoice
set /p answer= :
echo %answer%| findstr /r "^%~2$ ^%~3$ ^%~4$ ^%~5$ ">nul
if errorlevel 1 (
echo "%answer%" is sadly not a valid choice, choose again.
goto :MakeChoice
)
set %~1=%answer%
goto :eof
您可以通过以下方式调用函数:
echo choose a weapon(Sword, Axe, Dagger)
call :MakeChoice chosenOption "Sword" "Double-Bladed Axe" "Dagger"
echo you chose %chosenOption%
这适用于1-4个变量,但如果您需要更多变量,则始终可以添加^%~6$^%~7$。。。在^%~5美元之后
:MakeChoice
set /p answer= :
echo %answer%| findstr /r "^%~2$ ^%~3$ ^%~4$ ^%~5$ ">nul
if errorlevel 1 (
echo "%answer%" is sadly not a valid choice, choose again.
goto :MakeChoice
)
set %~1=%answer%
goto :eof
echo choose a weapon(Sword, Axe, Dagger)
call :MakeChoice chosenOption "Sword" "Double-Bladed Axe" "Dagger"
echo you chose %chosenOption%