Simple Minesweeper: How to use Randomize/Rnd() . - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Simple Minesweeper: How to use Randomize/Rnd() .

mpetersenmpetersen Posts: 6Member
Help, Im fairly new to VB and trying to use the ramdomize/rnd() to select 10 random cells to mark with a mine. The total number of cells is 64(an 8x8 control array). Im using a 2d array for placement of the mines.

My code presently marks mines based upon the following code, but I get variable mines set rather than getting a constant number of mines(10).

Below is my code:

condOdds is set in the global as
Dim conOdds = 10/64 'ten mines in 64 squares(control array).

Private Sub setmines()

Dim i As Integer ' control outer loop

Dim j As Integer 'control inner loop

Dim intNum As Integer 'use in optional codemakes mines
' visible when debug

Dim mines As Integer

'call randomize to initialize random number generator
'set global variable intCntr(declared in general section) to 0

'initialize intNum to 1. use set optional debug inf. about loc. mine

intNum = 1
intCntr = 0

mines = 0

'use nested loop to perform test on ea
'cell in minefield:
'compare return value of vbfunction Rnd to constant
'conOdds. if return value < constant = lay mine
'by setting blnMinesOn property to True. and add
'1 to intCntr(counts mines).
'"else"; if value returned > than constant
'set blnMinesOn property to False.

For i = 1 To conSize
For j = 1 To conSize

If Rnd < conOdds Then

blnMinesOn(i, j) = True
'keep below as use to debug the rand placement of mines
lblMines(intNum).Caption = "MINE"
intCntr = intCntr + 1 'need
to check this be sure is ok
blnMinesOn(i, j) = False

End If
intNum = intNum + 1
mines = mines + 1

Next j

Next i

'use intCntr to display number mines set in lblNumMines:

lblNumMines.Caption = Format(intCntr, "#0")
mines = mines + 1

End Sub

This sort of works, but open to suggestions to change if need be.

Thanks in advance for your input and direction. Any good resources would be also appreciated.



  • PrzemekG_PrzemekG_ Posts: 595Member
    dim Mines(0 to 63) as boolean

    private sub SetMines
    dim i,j
    dim found as boolean


    for i = 0 to 63
    Found = false
    j = int(rnd * 64) ' 0 to 63
    if not Mines(j) Then ' There is no mine here
    Mines(j) = true
    Found = true
    end if
    loop until Found
    end sub
Sign In or Register to comment.