VBA 扫雷的随机地雷生成

VBA Random Mine Generation for Minesweeper

我在 Visual Basic 语言中找不到关于此问题的任何信息,但我正在尝试为 5x5 扫雷游戏生成 10 个且仅生成 10 个随机地雷。我的问题涉及地雷的数量。我经常只生成 4 个地雷,或 10 个以上的地雷,而且总是不一致。这是我的代码:

Sub Minesweeper()
    Dim i As Single
    Dim Col As Single
    Dim Row As Single
    Dim BombArray(1 To 5, 1 To 5) As String


    'assignment of mines
    Do
        Row = Application.WorksheetFunction.RandBetween(1, 5)
        Col = Application.WorksheetFunction.RandBetween(1, 5)
    1
        If BombArray(Row, Col) <> "X" Then
            BombArray(Row, Col) = "X"
            Sheet1.Cells(4 + Row, 3 + Col).Value = BombArray(Row, Col)

        Else
            i = i + 1
            GoTo 1
        End If
    Loop Until i = 10

End Sub

如有任何帮助,我们将不胜感激。

使用标准 for 循环

此外,由于您使用的是数组,因此在循环后仅分配一次数组:

Sub Minesweeper()
    Dim i As Single
    Dim Col As Single
    Dim Row As Single
    Dim BombArray(1 To 5, 1 To 5) As String


    'assignment of mines
    For i = 1 To 10
        Row = Application.WorksheetFunction.RandBetween(1, 5)
        Col = Application.WorksheetFunction.RandBetween(1, 5)

        If BombArray(Row, Col) <> "X" Then
            BombArray(Row, Col) = "X"
        Else
            i = i - 1
        End If
    Next i

    Sheet1.Range("D5").Resize(UBound(BombArray, 1), UBound(BombArray, 2)).Value = BombArray

End Sub

建立矿井位置字典并保持 adding/overwriting 直到达到 10。

Option Explicit

Sub Minesweeper()
    Dim mines As Object

    Set mines = CreateObject("scripting.dictionary")

    Do While mines.Count < 10
        mines.Item(Cells(Application.RandBetween(5, 9), Application.RandBetween(4, 8)).Address(0, 0)) = vbNullString
    Loop

    Debug.Print Join(mines.keys, ", ")
    Sheet1.Range(Join(mines.keys, ", ")) = "x"
End Sub