VB 2D 数组可能未返回正确的值/需要帮助计算 2D 数组中的布尔值数



我正在尝试用Visual basic编写Conways生命游戏,但是计算周围活细胞数量的代码似乎存在问题。代码如下所示:

Module Module1
Dim ScreenHeight As Integer = 30
Dim ScreenWidth As Integer = 30
Dim Field(ScreenWidth - 1, ScreenHeight - 1) As Boolean
Dim FieldBuffer(ScreenWidth - 1, ScreenHeight - 1) As Boolean
Sub Main()
    Console.SetWindowSize(ScreenWidth, ScreenHeight)
    Field(10, 9) = True
    Field(10, 10) = True
    Field(10, 11) = True

    While True
        Dim x = 0
        While (x < ScreenWidth)
            Dim y = 0
            While (y < ScreenHeight)
                Console.SetCursorPosition(x, y)
                If ((x <> 0 And x <> ScreenWidth - 1) And (y <> 0 And y <> ScreenWidth - 1)) Then
                    Dim count = Field(x + 1, y) + Field(x - 1, y) + Field(x, y + 1) + Field(x, y - 1) _
                        + Field(x + 1, y + 1) + Field(x - 1, y - 1) + Field(x - 1, y + 1) + Field(x + 1, y - 1)
                    count = count * -1
                    If (Field(x, y) = True) Then
                        If (count < 2) Then
                            FieldBuffer(x, y) = False
                        End If
                        If (count > 3) Then
                            FieldBuffer(x, y) = False
                        End If
                        If (count = 3 Or count = 2) Then
                            FieldBuffer(x, y) = True
                        End If

                        Console.BackgroundColor = ConsoleColor.Blue
                    Else
                        If (count = 3) Then
                            FieldBuffer(x, y) = True
                        End If
                        Console.BackgroundColor = ConsoleColor.Black
                    End If
                    Console.Write(count)
                Else
                    Console.BackgroundColor = ConsoleColor.Red
                    Console.Write("X")
                End If

                y += 1
            End While
            x += 1
        End While
        Console.ReadKey()
        Field = FieldBuffer
    End While

End Sub
End Module

获取周围单元格值的代码为:

Dim count = Field(x + 1, y) + Field(x - 1, y) + Field(x, y + 1) + Field(x, y - 1) _
+ Field(x + 1, y + 1) + Field(x - 1, y - 1) + Field(x - 1, y + 1) + Field(x + 1, y - 1)
count = count * -1

对于程序的第一次迭代,它返回 Field 数组中单元格结构的正确值。但在第二次迭代中,应用规则后,它不会返回正确的值,这些值应该是:123211121112321

规则被正确地应用于数组,因为在第一次迭代之后,显示的结构是正确的。当单元格周围的每个位置都有"If(Field(x,y) = true)然后 Count+=1"时,也会出现此错误。

任何帮助将不胜感激,因为这个错误已经让我发疯了大约 2 周了。

你的规则是错误的。

' Any live cell with two or three neighbours lives
' Any dead cell with exactly three live
If count = 3 Then ' If (count = 3 Or count = 2) Then
    FieldBuffer(x, y) = True
End If

您也在复制引用。这意味着,在第二次传递中,Field 和 FieldBuffer 是相同的。

Field = FieldBuffer

您需要复制每个项目。使用循环,如 Array.Copy 或其他方法。

最新更新