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

时间:2016-03-14 13:06:16

标签: vb.net conways-game-of-life

我正在尝试在视觉基础上编写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数组中单元格结构的正确值。 但是在第二次迭代中,在应用规则之后,它不会返回正确的值,这应该是: 12321 11211 12321

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

任何帮助都会受到赞赏,因为这个错误让我疯狂了大约2周。

1 个答案:

答案 0 :(得分:0)

你的规则是错误的。

' 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.Copyother methods