1

I could not find any information on this problem in the Visual Basic language, but I am trying to generate 10 and only 10 random mines for a 5x5 Minesweeper game. My problem involves the number of mines. I often only generate 4 mines, or 10+ mines, and its always inconsistent. Here is my code:

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

Any help would be greatly appreciated.

2 Answers2

1

Use a standard for loop

Also since you are using an array assign the array only once after the loop:

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
Scott Craner
  • 148,073
  • 10
  • 49
  • 81
1

Build a dictionary of mine locations and keep adding/overwriting until you reach 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