0

我觉得我一直在烦扰每个人,很抱歉“又是这个人”。

我的四连胜游戏现在可以正常工作,直到需要检查四连胜。X 和 O 像魅力一样添加到列中,并且网格显示正确。现在的重点是,我想在我的多维数组中连续检查四个,但是使用 if 语句似乎并不是真正适合我的方法,因为我必须这样写:

if ($CreateBoard[1,0] -and $CreateBoard[1,1] -and $CreateBoard[1,2] -and $CreateBoard[1,3] -eq "X") {Write-host "Exit script!"}
if ($CreateBoard[1,1] -and $CreateBoard[1,2] -and $CreateBoard[1,3] -and $CreateBoard[1,4] -eq "X") {Write-host "Exit script!"}
if ($CreateBoard[1,2] -and $CreateBoard[1,3] -and $CreateBoard[1,4] -and $CreateBoard[1,5] -eq "X") {Write-host "Exit script!"} 
if ($CreateBoard[1,3] -and $CreateBoard[1,4] -and $CreateBoard[1,5] -and $CreateBoard[1,6] -eq "X") {Write-host "Exit script!"} 
if ($CreateBoard[1,4] -and $CreateBoard[1,5] -and $CreateBoard[1,6] -and $CreateBoard[1,7] -eq "X") {Write-host "Exit script!"} 
if ($CreateBoard[1,5] -and $CreateBoard[1,6] -and $CreateBoard[1,7] -and $CreateBoard[1,8] -eq "X") {Write-host "Exit script!"} 
if ($CreateBoard[1,6] -and $CreateBoard[1,7] -and $CreateBoard[1,8] -and $CreateBoard[1,9] -eq "X") {Write-host "Exit script!"}
if ($CreateBoard[1,7] -and $CreateBoard[1,8] -and $CreateBoard[1,9] -and $CreateBoard[1,10] -eq "X") {Write-host "Exit script!"} 

对于每一列,然后是行,然后是对角线。现在的问题是:有没有一种快速的方法可以通过我的 10x10 网格(我想使用 for 循环的 Foreach-Object?),如果是,你能提供一个基本的例子吗?(如果重要的话,我正在尝试连续查找 4 次字符串“X”或“O”)

谢谢

4

1 回答 1

1

这更像是一个算法问题而不是 PowerShell 问题。:-) 也就是说,一种简单的方法是这样的:

function FindFourInARow($brd, $startRow, $startCol)
{
    $numRows = $brd.GetLength(0);
    $numCols = $brd.GetLength(0);

    #search horizontal
    $found = 0;
    $cnt  = 0;
    for ($col = $startCol; $col -lt $numCols -and $cnt -lt 4; $col++, $cnt++)
    {
        if ($brd[$startRow, $col] -eq 'X')
        {
            $found += 1
            if ($found -eq 4) { return $true }
        }
    }

    #search vertical
    $found = 0;
    $cnt = 0;
    for ($row = $startRow; $row -lt $numRows -and $cnt -lt 4; $row++, $cnt++)
    {
        if ($brd[$row, $startCol] -eq 'X')
        {
            $found += 1
            if ($found -eq 4) { return $true }
        }
    }

    #search diag forwards
    $found = 0;
    $row = $startRow
    $col = $startCol
    $cnt = 0;
    for (;$row -lt $numRows -and $col -lt $numCols -and $cnt -lt 4; 
          $row++, $col++, $cnt++)
    {
        if ($brd[$row, $col] -eq 'X')
        {
            $found += 1
            if ($found -eq 4) { return $true }
        }
    }

    return $false
}

# TODO: implement search diag backwards

$brd = New-Object 'char[,]' 10,10
$brd[2,2] = $brd[3,3] = $brd[4,4] = $brd[5,5] = 'X'

$numRows = 10
$numCols = 10
for ($r = 0; $r -lt ($numRows - 3); $r++)
{
    for ($c = 0; $c -lt ($numCols - 3); $c++)
    {
        if (FindFourInARow $brd $r $c)
        {
            "Found four in a row at $r,$c"
            $r = $numRows
            break;
        }
    }
}

我刚刚将其直接输入SO。它可能有一些错误,但它应该为您提供基本的要点。

于 2013-01-17T19:07:49.737 回答