为什么选择奇怪地返回错误级别?

时间:2020-06-14 23:03:33

标签: windows batch-file

choice /c 123456789 >NUL
if errorlevel = 9 if %ui9%==9 set "ui9=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 8 if %ui8%==8 set "ui8=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 7 if %ui7%==7 set "ui7=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 6 if %ui6%==6 set "ui6=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 5 if %ui5%==5 set "ui5=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 4 if %ui4%==4 set "ui4=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 3 if %ui3%==3 set "ui3=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 2 if %ui2%==2 set "ui2=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 1 if %ui1%==1 set "ui1=X" & set /a moves = %moves% + 1 & goto :medmodulebot
cls
echo That spot's already taken
ping localhost -n 3 >NUL
goto medmoduleuser

我正在制作井字游戏机器人。当输入数字(例如9),然后在下一回合再次输入该数字时,它将触发if errorlevel = 8 if %ui8%==8 set "ui8=X" & set /a moves = %moves% + 1 & goto :medmodulebot,而不是仅仅通过代码直到到达最低点为止……似乎choice是返回错误级别奇怪吗?我该怎么做才能防止这种情况?

1 个答案:

答案 0 :(得分:1)

除注释外,还可以完全避免错误级别测试。通过使用for / F循环元变量将选择值转换为文字值


@echo off & Setlocal ENABLEdelayedexpansion
Rem // script body
For /F "Delims=" %%C in ('Choice /N /C:123456789') do (
    if !ui%%C!==%%C (
        set "ui%%C=X"
        set /a moves+=1
        goto :medmodulebot
    )
)
cls
echo That spot's already taken
ping localhost -n 3 >NUL
goto medmoduleuser