Page 1 of 1

A Simple Dice Rolling Application (VB.NET) Introduction to random number generation in VB.NET Rate Topic: -----

#1 aceofspades686  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 6
  • View blog
  • Posts: 334
  • Joined: 08-October 07

Post icon  Posted 16 October 2007 - 05:09 PM

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.
Attached Image

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.
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.
  • Public Class frmD6 - This line is the opening of my form, frmD6 is what I decided to name it

  • 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.

  • Dim oDice As New Random - Creates a new object of the type random. oDice has now become our random number generator.

  • 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.

  • 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."

  • End Sub - As I mentioned earlier, this closes the handler for the btnRoll.Click event.

  • 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:
Attached Image

The code behind it:
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).

Is This A Good Question/Topic? 0
  • +

Replies To: A Simple Dice Rolling Application (VB.NET)

#2 Shadow 1.2  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 7
  • View blog
  • Posts: 70
  • Joined: 17-October 07

Posted 19 October 2007 - 10:55 PM

Thanks alot I've been wondering how to do this for quite some time now.
Was This Post Helpful? 0
  • +
  • -

#3 y0ttabyte  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 20-May 08

Posted 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?)
Was This Post Helpful? 0
  • +
  • -

#4 robertelder  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 30
  • Joined: 06-June 08

Posted 06 June 2008 - 05:45 AM

View Posty0ttabyte, on 20 May, 2008 - 07:14 PM, said:

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:
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:
	 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:
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:
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
Was This Post Helpful? 0
  • +
  • -

#5 Bort  Icon User is offline

  • Ill-informed Mongoloid
  • member icon

Reputation: 404
  • View blog
  • Posts: 2,980
  • Joined: 18-September 06

Posted 11 June 2008 - 08:31 AM

I have something very similar to this in the Code Snippets section of d.i.c.
Was This Post Helpful? 0
  • +
  • -

#6 Koodud  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 16-April 09

Posted 30 June 2009 - 04:55 AM

i have another thing to add to this,
1.Add a button
2.Name it btnEmptyDiceRolls
3.Add this code to the button
   Private Sub btnEmptyDiceRolls_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEmptyDiceRolls.Click
		lstDiceRolls.Items.Clear()
		lstDiceRolls.Items.Add("Size" & ControlChars.Tab & "Roll")
	End Sub

Was This Post Helpful? 0
  • +
  • -

#7 Koodud  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 16-April 09

Posted 30 June 2009 - 05:01 AM

Oh and i just located a problem:
The User can "cheat" by changing the text at the top of the combobox. how can i make the combobox readonly

This post has been edited by Koodud: 30 June 2009 - 05:01 AM

Was This Post Helpful? 0
  • +
  • -

#8 Viper2KX  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 195
  • Joined: 25-January 09

Posted 09 April 2011 - 02:37 PM

View PostKoodud, on 30 June 2009 - 06:01 AM, said:

Oh and i just located a problem:
The User can "cheat" by changing the text at the top of the combobox. how can i make the combobox readonly


In the Appearance section of the properties, there is a function (probably not what it is called) named DropDownStyle. I suggest selecting DropDownList. As seen in picture.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1