简体   繁体   中英

C# Example Beginner

I'm trying to display in 3 different PictureBoxes random images. Like a slot Machine. I added my images to an imagelist. When i run the program however, I keep getting the exact same pictures in all 3 boxes. Any help is greatly appreciated. Here is my code snipet.

 private void button1_Click(object sender, EventArgs e)
 {
     Random rand = new Random();
     int index = rand.Next(imageList1.Images.Count);
     pictureBox1.Image = imageList1.Images[index];
     pictureBox2.Image = imageList1.Images[index];
     pictureBox3.Image = imageList1.Images[index];
  }

Try this. Put the initialization of Random in the global scope. Now it doesn't need to recreate the object each time you call Next. It's faster and uses less memory. It also prevents it from returning the same number, because Random uses the current time to generate numbers. If you keep recreating it and generating a number, it tends to return the same value repeatedly.

So last part: Make a function to get a random image index, this will make your code cleaner, and concise. :)

Good luck man, programming is a great hobby. Hope it serves you well!

    private readonly Random rand = new Random();
    private int[] _imgIndexes = new int[3];

    private void button1_Click(object sender, EventArgs e)
    {
        // generate the random index, and pick that image with that index, then store the index number in an array so we can compare the results afterwards.
        var randomIndex = getRandomImageIndex();
        pictureBox1.Image = imageList1.Images[randomIndex];
        _imgIndexes[0] = randomIndex;

        randomIndex = getRandomImageIndex();
        pictureBox2.Image = imageList1.Images[randomIndex];
        _imgIndexes[1] = randomIndex;

        randomIndex = getRandomImageIndex();
        pictureBox3.Image = imageList1.Images[randomIndex];
        _imgIndexes[2] = randomIndex;

        if (_imgIndexes[0] == _imgIndexes[1] && _imgIndexes[1] == _imgIndexes[2])
        {
            MessageBox.Show("same");
        }
        // reset the result array so we can compare again.
        _imgIndexes = new int[3];
    }

    private int getRandomImageIndex()
    {
        return rand.Next(imageList1.Images.Count);
    }

Because your index will never changed after rand.Next(imageList1.Images.Count);

Assign index with the rand.Next before every image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM