lundi 28 septembre 2015

C# Array within for loop produces the same random integar values

this is my first time posting. Hopefully this question isn't too confusing. I'm working on a lab for a beginners C# book and am now stuck. I'm creating a "Dog Race Simulator" program. When I click the "Start Race" button, dogs are to move to the right with every tick of the timer at a random integer between 1 and 30 until they reach the finish. I've tried switching up the code a ton of different ways, reading about arrays, the Random class, and for loops online, yet for some reason, no matter what, the dogs always move at the same rate. They need to be moving at different random rates with each tick.

A solution would be nice, but what I really want to know, why is my code not working? Shouldn't each dog be assigned a different random number as it cycles through the 'i' values of the array?

Image can be found here: http://ift.tt/1iXTTdC

Here is the Form1 code:

Greyhound[] dogs = new Greyhound[4];

    private void startRaceButton_Click(object sender, EventArgs e)
    {
        timer1.Start();
        dogs[0] = new Greyhound() { MyPictureBox = dog1PictureBox };
        dogs[1] = new Greyhound() { MyPictureBox = dog2PictureBox };
        dogs[2] = new Greyhound() { MyPictureBox = dog3PictureBox };
        dogs[3] = new Greyhound() { MyPictureBox = dog4PictureBox };
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        for (int i = 0; i < 4 ; i++)
        {
            if (dogs[i] != null)
            {
                dogs[i].Randomizer = new Random();
                dogs[i].Distance = dogs[i].Randomizer.Next(1, 30);
                dogs[i].Move(); 
            }
        }
    }

And this is the Greyhound class code:

class Greyhound
{
    public PictureBox MyPictureBox; 
    public bool GoingForward = true;
    public Random Randomizer; 
    public int Distance;

    public void Move() 
    {
        if (MyPictureBox != null)
        {
            if (GoingForward == true)
            {
                MyPictureBox.Left += Distance; 
                if (MyPictureBox.Left >= MyPictureBox.Parent.Width - MyPictureBox.Width)
                {
                    GoingForward = false; 
                }
            }
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire