蝙蝠脚本读取命令提示符的输出



我正在尝试从命令提示符中读取最后一行,因为我正在运行另一个程序,该程序将玩一场游戏,最后如果我是赢家、输家或我们打平,我会回显。我有这个样本代码:

编辑:部分"------"这只是我努力实现目标的一个例子。基本上,我想读一句话,比如";玩家:我赢了"或";这场比赛打成平局"所以这条线试图表明我想扫描这条线,检查它是否包含获胜或平局,否则就是失败

@set win=0
@set draw=0
@set lose=0
@set loopcount=10
:loop
C:battlesnakeCLIbattlesnake.exe play -W 11 -H 11 --name me --url http://localhost/api/gamev2 --name other --url http://localhost/api/gametest
------
if line.contains("win")
set /a win=win+1
else if (line.contains("draw")
set /a draw=draw+1
else
set /a lose=lose+1
------
set /a loopcount=loopcount-1
if %loopcount%==0 goto exitloop
goto loop
:exitloop
@ECHO Wins: %win% & echo:Draws: %draw% & echo:Losses:%lose%
pause

我最终想出了这个解决方案:

@set win=0
@set draw=0
@set lose=0
@set loopcount=10
:loop
C:battlesnakeCLIbattlesnake.exe play -W 11 -H 11 --name me --url http://localhost/api/gamev2 --name other --url http://localhost/api/gametest 1> out.txt 2>&1 | type out.txt
@findstr /c:"me is the winner" "out.txt" >nul 2>&1
@if %errorlevel%==0 (
@set /a win=win+1
) 
@findstr /c:"It was a draw" "out.txt" >nul 2>&1
@if %errorlevel%==0 (
@set /a draw=draw+1
) 
@findstr /c:"other is the winner" "out.txt" >nul 2>&1
@if %errorlevel%==0 (
@set /a lose=lose+1
)
@ECHO Wins: %win% & echo:Draws: %draw% & echo:Losses: %lose%
@del out.txt
@set /a loopcount=loopcount-1
@if %loopcount%==0 goto exitloop
@goto loop
:exitloop
@ECHO FINISHED RUNNING! Final scores: & echo:Wins: %win% & echo:Draws: %draw% & echo:Losses: %lose%
@PAUSE

未经测试的代码的缩短版本:

@echo off
set win=0 & set draw=0 & set lose=0 & set loopcount=10
:loop
"C:battlesnakeCLIbattlesnake.exe" play -W 11 -H 11 --name me --url http://localhost/api/gamev2 --name other --url http://localhost/api/gametest 1> out.txt 2>&1
findstr /c:"me is the winner" "out.txt" >nul 2>&1 && set /a win=win+1
findstr /c:"It was a draw" "out.txt" >nul 2>&1 && set /a draw=draw+1
findstr /c:"other is the winner" "out.txt" >nul 2>&1 && set /a lose=lose+1
ECHO Wins: %win% & echo:Draws: %draw% & echo:Losses: %lose%
del out.txt
set /a loopcount-=1
if %loopcount% gtr 0 goto loop
:exitloop
ECHO FINISHED RUNNING! Final scores: & echo:Wins: %win% & echo:Draws: %draw% & echo:Losses: %lose%
pause

条件运算符&&有助于不必设置带括号的代码块。同时消除了@无处不在的开销,使用了老旧的@echo off

最新更新