I am using Visual Studio 2010 and C#. I am having problems making my three dice generate different random numbers. All of the dice roll at the same time. I have pictures of dice that I want to pull up for each of 3 dice according to what random number was generated. But when the pictures generate, it is the same picture (aka same number) for all 3 dice. I tried at first to make all three dice pull a random number from the same method, then I tried to make a separate random method for each dice (i.e., randomNum1(), randomNum2(), etc,) but either way I still get the same pic (same random? number) on all dice. What am I doing wrong? (FYI, I am using a button_Click event handler to enable a timer, which in turn uses a timer_Tick event handler to simulate the dice being rolled. It works great until the rolls end and I want to show what random numbers were generated for the dice. The following code is shown at the end of the _Tick event.)

private void timer_Tick(object sender, EventArgs e) {
{...code for animated dice rolls...}
int num1 = randomNum(1, 6);
dice1PictureBox.Image = Image.FromFile("C:\\dice\\front" + num1 + ".jpg");
int num2 = randomNum(1,6);
dice2PictureBox.Image = Image.FromFile("C:\\dice\\front" + num2 + ".jpg");
int num3 = randomNum(1,6);
dice3PictureBox.Image = Image.FromFile("C:\\dice\\front" + num3 + ".jpg");
timer.Enabled = false;}

private int randomNum(int min, int max) {
Random random = new Random();
return random.Next(min, max); }

Recommended Answers

All 2 Replies

Hmmm..just a simple problem here i think...say for instance num2 is returned as 5...

The path to your .jpg file is say "\front5.jpg"...

I believe if you put another two backslashes where i put the stars..you should be good to go...let me know..

int num2 = randomNum(1,6);
dice2PictureBox.Image = Image.FromFile("C:\\dice\\front*****\\****" + num2 + ".jpg");

You are correct that my picture's filenames are front1.jpg, front2.jpg, etc. (If I substitute the variable name "num1" with just a number, the appropriate picture does pull up.) Adding the additional \\ does not help, I just get a "File not found" error because it is now looking for front\2.jpg instead of front2.jpg.

Huh, I just had to restart my computer. I had added then erased your suggestion of the additional \\ before I restarted. Now the program works like it's supposed to! What the heck? Don't you just love Microsoft (heavy with the sarcasm.)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.