0

我正在尝试在我正在创建的批处理游戏中获取嵌套变量。我想要它,以便它选择一个随机变量并将其更改为 X,但如果它已经被选择,它应该返回并选择一个不同的数字。

set 1=a
set 2=b
set 3=c
set 4=d
set 5=e

这些是变量,这是代码

setlocal enabledelayedexpansion

:eliminator
set /a eliminate=(%random * 5) / 32767 + 1
if %%eliminate%%==X goto eliminator
echo The letter !!eliminate!! was chosen
timeout 5
set %%eliminate%%=X
goto eliminator 

现在,问题是,当我尝试回显它时,它会写入变量的名称而不是值。此外,已经选择的变量正在被再次选择。有什么办法可以解决这个问题?谢谢。

4

2 回答 2

2

试试这个:

@echo off&setlocal
set "var1=a"
set "var2=b"
set "var3=c"
set "var4=d"
set "var5=e"
:loop
set /a rd=%random%%%5+1
if defined var%rd% call echo %%var%rd%%%
set "var%rd%="
set "var" >nul 2>&1 && goto:loop

..输出(可能会有所不同):

d
一种
C
b
e
于 2013-06-06T14:15:30.667 回答
1

%您发布的代码缺少结束语random- 它应该是%random%.

您的 1 到 5 之间随机数的公式比需要的要复杂。我会使用:

set /a eliminate=%random% %% 5 + 1

要扩展“嵌套变量”,您需要!%eliminate%!

But I would completely rewrite your algorithm. I think the following does what you want:

@echo off
setlocal enableDelayedExpansion
set "chars=abcde"
set charCnt=5
:loop
set /a "pos=%random% %% charCnt, pos2=pos+1, charCnt-=1"
set "letter=!chars:~%pos%,1!"
echo The letter %letter% was chosen
set "chars=!chars:~0,%pos%!!chars:~%pos2%!"
if defined chars goto loop

The script is optimized to always pick a valid unused letter on each iteration.

于 2013-06-06T15:53:09.340 回答