dimanche 26 juillet 2015

A Day at the Races - Head first C#

I'm working on C# Lab in Head First C# book.

When I push start button - dogs should run until one of them reach the finish. Each dog should run with random speed, but all of my dogs run with same speed ;/

Dogs initialization:

 GreyhoundArray[0] = new Greyhound(){
            MyPictureBox = GreyhoundPictureBox1,
            StartingPosition = GreyhoundPictureBox1.Left,
            RacetrackLenght = TrackPictureBox.Width - GreyhoundPictureBox1.Width,
            MyRandom = MyRandom                
        };
        GreyhoundArray[1] = new Greyhound(){
            MyPictureBox = GreyhoundPictureBox2,
            StartingPosition = GreyhoundPictureBox2.Left,
            RacetrackLenght = TrackPictureBox.Width - GreyhoundPictureBox2.Width,
            MyRandom = MyRandom
        };
        GreyhoundArray[2] = new Greyhound(){
            MyPictureBox = GreyhoundPictureBox3,
            StartingPosition = GreyhoundPictureBox3.Left,
            RacetrackLenght = TrackPictureBox.Width - GreyhoundPictureBox3.Width,
            MyRandom = MyRandom
        };
        GreyhoundArray[3] = new Greyhound(){
            MyPictureBox = GreyhoundPictureBox4,
            StartingPosition = GreyhoundPictureBox4.Left,
            RacetrackLenght = TrackPictureBox.Width - GreyhoundPictureBox4.Width,
            MyRandom = MyRandom
        };

Start button code:

private void StartButton_Click(object sender, EventArgs e)
    {
        timer1.Enabled = true;
    }

Timer code:

private void timer1_Tick(object sender, EventArgs e)
    {
        for (int i = 0; i < 4; i++)
        {
            if (GreyhoundArray[i].Run())
                timer1.Enabled = true;
            else
                timer1.Enabled = false;
        }
    }

Run method:

public bool Run()
    {
        MyRandom = new Random();

        int distance = MyRandom.Next(1, 5);
        MyPictureBox.Left += distance;

        if(MyPictureBox.Left >= RacetrackLenght)
            return false;
        else
            return true;
    }




Aucun commentaire:

Enregistrer un commentaire