This program was written for those of you who are into RPG's and other games that require rolling of different types of dice a set number of times.
Setting It Up
The first step to writing this was to create a GUI for the interaction. This GUI would allow the user to specify how many sides the die has and how many times to roll it. For specifying how many sides the die has, I used the Windows Forms Control,
ComboBox. I then added the different sides that the die could have (2 - 21*). For how many times to roll, I used a simple Windows Forms Control,
Rolling The Die (Updated May 30)
For setting up the code for the die rolling, all you need is a simple Random. First off, you must make sure that if the user specified how many times to roll, and that what he typed in the
TextBox is a number. As a default, you may want to make the roll number "1". In testing to see if the roll number is a number, I added a very simple
if statement to the
txtFrom_KeyPress method (thanks to Richard Day for his suggestion):
if (char.IsNumber(e.KeyChar) == false)
e.Handled = true;
txtFrom.Text = string.Empty;
This ensures that no non-number can be entered into the text box.
Next, I initialize the Random by using the clock's millisecond ticks to ensure as much randomness as possible. Then, depending upon how many times the user has specified that the die be rolled, I generate a random number between 1 and however many sides are specified, a set number of times. Each number is then put into another
TextBox and displayed to the user.
I added a button to add the total of all the numbers rolled together. All I do to accomplish this is set up an array of type
int and fill it as I generate the numbers. Then, I simply iterate through the array, adding each of the numbers together and then displaying that in another text box.
for (int i = 0; i < numbers.Length; i++)
total += numbers[i];
*Note: While there may be no 21 sided die, I decided to add it anyways.