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.
vb.net Code:
Public Class Die
Private Shared faceSelector As New Random
Private _faceCount As Integer
Private _value As Integer
Public Property FaceCount() As Integer
Get
Return Me._faceCount
End Get
Set(ByVal value As Integer)
Me._faceCount = value
End Set
End Property
Public ReadOnly Property Value() As Integer
Get
Return Me._value
End Get
End Property
Public Sub New(ByVal faceCount As Integer)
If faceCount <= 0 Then
Throw New ArgumentOutOfRangeException("faceCount", "Dice must have one or more faces.")
End If
Me._faceCount = faceCount
End Sub
Public Function Roll() As Integer
Me._value = faceSelector.Next(1, Me.FaceCount + 1)
Return Me.Value
End Function
End Class
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.
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.
vb.net Code:
Public Class DieCollection
Inherits System.
Collections.
ObjectModel.
Collection(Of Die
)
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()
Next
Return values
End Function
End Class
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.
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:
vb.net Code:
'Create the collection to store the dice.
Dim dice As New DieCollection
'Add two six-sided dice.
dice.Add(New Die(6))
dice.Add(New Die(6))
'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 ...")
Next
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.