0

The following code is attempting to position pieces at random positions on a board:

Function selectPlayer()
    Dim rand As New Random()
    Dim player As Integer = rand.Next(0, 3)
    Return player
End Function

Function selectPiece()
    Dim rand As New Random()
    Dim piece As Integer = rand.Next(0, 4)
    Return piece
End Function


Sub randomiseBoard(ByRef Board(,) As String)

    Dim players() As String = {"W", "B", "  "}
    Dim pieces() As String = {"G", "E", "N", "M"}

    For RankNo = 1 To BoardDimension
        For FileNo = 1 To BoardDimension
            Board(RankNo, FileNo) = players(selectPlayer) & pieces(selectPiece)
        Next
    Next

End Sub

The type of piece is chosen from an array, containing the character which represents them, and combined with the player (B / W) to uniquely define a piece.

When executed, the board is generated, however the same piece is positioned in every square.

Each time the code is run, a new piece is generated and displayed. Yet - it does not select a unique piece for each iteration.

Why is this? How can I solve this?

  • 1
    get rid of the `Dim rand As New Random()` inside those 2 methods. By creating a new Random each time, you assure that the same number comes up. Declare it as `Private rand As New Random()` and reuse it for both. – Ňɏssa Pøngjǣrdenlarp May 14 '15 at 20:04
  • It seems like there are some flaws your logic. Picking randomly from `Players` will not guarantee an even distribution, same for `Pieces` where there is likely some kind of limits. If there are supposed to be only 3 G's but up to 7 M's, for instances there is nothing there to assure that. – Ňɏssa Pøngjǣrdenlarp May 14 '15 at 20:16

1 Answers1

0

Initialize the random-number generator.

Randomize()

Then generate your random value

Top Systems
  • 951
  • 12
  • 24