Home > Back-end >  Randomly put an image in specific places using C#
Randomly put an image in specific places using C#

Time:11-28

I am absolutely new with C#, so I hope my question is not completely off.

enter image description here

As you can see in the picture above, I have a form, in which there is a table (image) and a button. In the resources of the project, I have another image (black_rectangle.png), which is a black rectangle, exactly at the same size of each the table's cell. This is what I'm trying to achieve: Each time the 'Again' button is clicked, I want the six black rectangles to cover two of the tree cells in each column, in a random manner. For example, after the first try, the table could look like this: enter image description here

I'm basically stuck at the beginning:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Random rand = new Random();
        List<PictureBox> items = new List<PictureBox>();
        PictureBox newPic= new PictureBox();
        newPic.Height = 50;
        newPic.Width = 50;
        newPic.BackColor = Color.Maroon;

        int x = rand.Next(10, this.ClientSize.Width - newPic.Width);
        int y = rand.Next(10, this.ClientSize.Height - newPic.Height);
        newPic.Location = new Point(x, y);
    }
}

CodePudding user response:

Assuming the table (image) is in "pictureBox1", you could try something like:

private Random rnd = new Random();
private List<int> positions = new List<int> { 0, 1, 2 };
private List<PictureBox> prevBoxes = new List<PictureBox>();

private void button1_Click(object sender, EventArgs e)
{
    prevBoxes.ForEach(pb => pb.Dispose()); // remove previous boxes
    for(int col=0; col<3; col  )
    {
        positions = positions.OrderBy(i => rnd.Next()).ToList(); // shuffle positions
        for(int i=0; i<2; i  )
        {
            PictureBox newPic = new PictureBox();
            newPic.Height = 50;
            newPic.Width = 50;
            newPic.BackColor = Color.Maroon;
            newPic.Location = new Point(pictureBox1.Left   (col * 50), pictureBox1.Top   (positions[i] * 50));
            this.Controls.Add(newPic);
            newPic.BringToFront();
            prevBoxes.Add(newPic);
        }               
    }            
}

Output:

enter image description here

  • Related