我试图在 3x3 显示屏中使用另一个变量的数值来定义一个变量,用户将输入一个按键来“移动”光标(在本例中为 O)并能够选择某些内容。
## $1-$9 are set to _
if (y) {$hello = 4}
if (x) {$hello = 6}
$[$hello] = "O"
$1$2$3
$4$5$6
$7$8$9
PowerShell 没有本机“变量变量”语法 - 您需要利用
Set-Variable
cmdlet,或针对 Variable:\
驱动器使用提供程序 cmdlet:
$hello = 6
Set-Variable -Name $hello -Value 'O'
# or
'O' |Set-Content -Path Variable:\$hello
不要使用单独的变量来存储每个细胞状态,而是考虑使用数组:
$width = 3
# create an array consisting of 3x3 strings `_`
$cells = ,'_' * ($width * $width)
现在您可以直接在索引操作中使用该变量:
$hello = 4
# array indices are 0-based in .NET, so it goes 0-8, not 1-9
$cells[$hello - 1] = 'O'
打印网格:
for ($i = 0; $i -lt $width; $i++) {
# calculate row offset
$offset = $i * $width
# collect cells in row, print as one line
$cells[$offset..($offset + $width - 1)] -join ''
}