C# version here.
Quite a few people have asked how to "roll dice" for games. Here's the "proper" way. First you define a Die class to represent a die.
Note that the Die class has a Shared variable of type Random. This means that there is one and only one Random object for the class. This same object is used to generate random sides for each and every instance of the class.
Public Class Die
Private Shared faceSelector As New Random
Private _faceCount As Integer
Private _value As Integer
Public Property FaceCount() As Integer
Set(ByVal value As Integer)
Me._faceCount = value
Public ReadOnly Property Value() As Integer
Public Sub New(ByVal faceCount As Integer)
If faceCount <= 0 Then
Throw New ArgumentOutOfRangeException("faceCount", "Dice must have one or more faces.")
Me._faceCount = faceCount
Public Function Roll() As Integer
Me._value = faceSelector.Next(1, Me.FaceCount + 1)
The Roll method generates the random number based on the number of faces the current die has. It returns this value and it is also available via the Value property thereafter.
Many games use multiple dice though, so it's appropriate to define a class that represents multiple Die objects.
There's very little code to write for this class because it inherits all the standard collection functionality from the generic Collection(Of Die) class. Inherited functionality includes an Item property of type Die and an Add method that takes a Die parameter.
Public Class DieCollection
Public Function RollAll() As Integer()
Dim values(Me.Count - 1) As Integer
For index As Integer = 0 To values.GetUpperBound(0)
values(index) = Me.Items(index).Roll()
Here's an example of using these classes. As is supposed to be the case in OOP, using the types is dead simple because all the work is done inside the classes themselves. You simply create a DieCollection, create and add as many Die objects as you need and call RollAll:
Obviously for a game you would assign your DieCollection to a member variable and then call it's RollAll method each time a player had to roll the dice. You would not create a new DieCollection and Die objects each time you wanted to roll.
'Create the collection to store the dice.
Dim dice As New DieCollection
'Add two six-sided dice.
'Roll all the dice.
Dim rolls As Integer() = dice.RollAll()
'Display the values rolled.
For Each roll As Integer In rolls
MessageBox.Show(roll.ToString(), "You rolled a ...")