first post and a very noob question. I tried for many hours to get this program to work and eventually had to cheat and look up the answer from someone else.
When I run the following code, each greyhound array element receives the same random number. When I then initialized the array elements with a a random variable on the form, it then does generate different random numbers, but I don't understand why my initial code doesn't work. Can anyone please explain?
The code I had that didn't work: (relevant code)
firstly the class i made:
public class Greyhound
{
public PictureBox MyPictureBox = new PictureBox(); //My picturebox object
public int Location = 0; //My location on the racetrack
public Random Randomizer = new Random();
public Run()
{
Location += Randomizer.Next(15);
MyPictureBox.Left = Location;
}
}
And then the form:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Greyhound[] GreyhoundArray = new Greyhound[4];
private void setupTrack()
{
for (int i = 0; i < 4; i++)
{
GreyhoundArray[i] = new Greyhound();
}
GreyhoundArray[0].MyPictureBox = pictureBox1;
GreyhoundArray[1].MyPictureBox = pictureBox2;
GreyhoundArray[2].MyPictureBox = pictureBox3;
GreyhoundArray[3].MyPictureBox = pictureBox4;
}
private void timer1_Tick(object sender, EventArgs e)
{
for (int i = 0; i < 4; i++)
{
GreyhoundArray[i].Run();
}
}