Full Version: A Simple Dice Rolling Application (VB.NET)
Dream.In.Code > Programming Tutorials > VB.NET Tutorials
aceofspades686
Alright, this will be my first tutorial so bear with me.

This tutorial will teach how to use the random number generation in VB.NET to create a simple application to roll a 6-sided die. The steps in this can be further applied to include more than 1 die, different sizes of dice, or anything you want to think of that requires a random number generator. For simplicity's sake, I'll only be coding this into a single form, but the same techniques can be applied to custom classes as well.

First things first, let's create a simple form.
Click to view attachment

It doesn't take much for this application, just a button and an output label. Sure you can get fancy and add in images or a combo box to let them choose the number of sides, I'll even give you a screen shot and code snippet at the end of this tutorial showing you how, but for now let's keep it simple.

Note: The name of my output label is lblDiceOutput and the name of my "Roll the Die" button is btnRoll

Okay, now that we have a form in place, let's move on to the simplistic code behind this app.
CODE

Public Class frmD6
    Private Sub btnRoll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRoll.Click
        Dim oDice As New Random
        Dim iDiceResult As Integer = oDice.Next(1, 7)
        lblDiceOutput.Text = iDiceResult.ToString
    End Sub
End Class


I'll break this down line by line for you so you understand what's going on.
  1. Public Class frmD6 - This line is the opening of my form, frmD6 is what I decided to name it
  2. Private Sub btnRoll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRoll.Click - Starts the handler for the click event of btnRoll. Put simply, anything between this and End Sub will happen when you click the "Roll the Die" button.
  3. Dim oDice As New Random - Creates a new object of the type random. oDice has now become our random number generator.
  4. Dim iDiceResult As Integer = oDice.Next(1, 7) - This one can be a little hard to grasp at first. First I have to say this. Random is not entirely random. All computers can do in the end is perform math, and through math there are only a few limited ways to create "random" numbers, and then those go in a recurring pattern (it may only start recurring after 64,000 digits or so, but it is recurring). So this kept in mind, what this line does is it creates the iDiceResult variable as an Integer and then it sets it to the next random number in the sequence. 1 and 7 represent the lower and upper bounds respectively, remember when setting this that the second argument will always be greater than the random number generated. In this case we only want the die to go to 6, so the upperbound is 7.
  5. lblDiceOutput.Text = iDiceResult.ToString - This simply sets the now "random" value stored in iDiceResult to the text property of lblDiceOutput to display what the "dice rolled."
  6. End Sub - As I mentioned earlier, this closes the handler for the btnRoll.Click event.
  7. End Class - And this ends my form code altogether.

So now you have a working digital 6-sided-die. Simple wasn't it? Now as I promised, here's the code for if you wanted to add a little flair to your form. I won't be adding images in this case for simplicities sake, but I will be adding a combobox to allow you to select how many sides the die has, and a list box to keep track of past rolls.

The slightly more stylish form:
Click to view attachment

The code behind it:
CODE

Public Class frmD6
    Private Sub btnRoll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRoll.Click
        If cmbDieSize.Text = String.Empty Then
            MessageBox.Show("Please choose the size of die you wish to roll", "Error") 'Quick error handling in case the user tries to roll without selecting a die size
        Else
            Dim oDice As New Random
            Dim iDieSize As Integer = CInt(cmbDieSize.Text)
            Dim iDiceResult As Integer = oDice.Next(1, iDieSize + 1)
            lstDiceRolls.Items.Add("D" & iDieSize.ToString & ControlChars.Tab & iDiceResult.ToString)
        End If
    End Sub

    Private Sub frmD6_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        lstDiceRolls.Items.Add("Size" & ControlChars.Tab & "Roll")
    End Sub
End Class


Notes: I kept my form name the same out of laziness. cmbDieSize is the combobox above the roll button containing the die sizes, it was populated in the design view. lstDiceRolls is the listbox on the left of the form that records the rolls.

Well, that's all for this tutorial. Any and all corrections and feedback are welcome (especially since its my first one).
Shadow 1.2
Thanks alot I've been wondering how to do this for quite some time now.
y0ttabyte
i have a problem, my code always generate a same number(2 var random) while in same event.
this exam my code :

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim one As New Random
Dim oneResult As Integer = one.Next(1, 7)
textbox1 = satuResult


Dim two As New Random
Dim twoResult As Integer = two.Next(1, 7)
textbox2.text = twoResult


(mostly they generate a same number, why?)
robertelder
QUOTE(y0ttabyte @ 20 May, 2008 - 07:14 PM) *

i have a problem, my code always generate a same number(2 var random) while in same event.
this exam my code :

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim one As New Random
Dim oneResult As Integer = one.Next(1, 7)
textbox1 = satuResult


Dim two As New Random
Dim twoResult As Integer = two.Next(1, 7)
textbox2.text = twoResult


(mostly they generate a same number, why?)


y0ttabyte,

I believe you are getting the same numbers (usually) because of the seed. RANDOM works by running a value (called a seed) against its algorithm. If you do not specify what that seed is, it will be based on the system clock. Because you are creating 2 RANDOM objects so close to each other, the seed will usually be the same, which means you will often get identical results.

If there isn't a need to create two separate RANDOM objects, you could just try the following:
CODE

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim one As New Random
        TextBox1.Text = one.Next(1, 7)
        TextBox2.Text = one.Next(1, 7)
End Sub


Alternately, if you want two RANDOM objects, you can specify their seed values when you initialize the RANDOM object like this:
CODE

     Dim one As New Random(My.Computer.Clock.TickCount)
     TextBox1.Text = one.Next(1, 7)

     Dim two As New Random(My.Computer.Clock.TickCount + 1)
     TextBox2.Text = two.Next(1, 7)


Another "random" function you may want to consider is the "RND" function. The syntax is a bit more complicated, but it seems to work better for me. If you look up the RND function in the MSDN Help, you'll find a lot of information about how it works.

The syntax is: "value = CInt(Int((upperbound - lowerbound + 1) * Rnd() + lowerbound))". If you want, you could specify the seed value by putting it inside the parenthesis immediately after "Rnd".

For getting random values between (and including) 1 and 6 for the 6-sided dice:
CODE

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim Lowerbound, Upperbound As Integer
        Lowerbound = 1
        Upperbound = 6
        TextBox1.Text = CInt(Int((Upperbound - Lowerbound + 1) * Rnd() + Lowerbound))
        TextBox2.Text = CInt(Int((Upperbound - Lowerbound + 1) * Rnd() + Lowerbound))
End Sub


Personally, I like my code to look nice and simple whereever possible so that when I come back in a year or so I can still easily figure out what was going on. I would probably create a separate function that would hold all the complicated looking code and leave the Button_Click subroutine easier to read:
CODE

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim Lowerbound, Upperbound As Integer
        Lowerbound = 1
        Upperbound = 6
        TextBox1.Text = GetRandomValue(Lowerbound, UpperBound)
        TextBox2.Text = GetRandomValue(Lowerbound, UpperBound)
End Sub

Function GetRandomValue(ByVal Lowerbound As Integer, ByVal Upperbound As Integer) As Integer
        Return CInt(Int((Upperbound - Lowerbound + 1) * Rnd() + Lowerbound))
End Function


I hope this helps you out!

-Rob
Bort
I have something very similar to this in the Code Snippets section of d.i.c.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2008 Invision Power Services, Inc.