North5014
North5014

Reputation: 93

Dynamicly created panels location distance

I'm beginner in programming and I want to create a little "game" with Panels.
(Later maybe I'll change for PictureBox, but for now it's OK)

Code:

private void Form1_Load(object sender, EventArgs e)
{
    int size = 20;
    int quantity = 10;

    Random rnd = new Random();

    for (int y = 0; y < quantity; y++)
    {
        for (int x = 0; x < quantity; x++)
        {
            Color randomColor = Color.FromArgb(
              rnd.Next(256), rnd.Next(256), rnd.Next(256)
            );

            Panel panel = new Panel
            {
                Size        = new Size(size, size),
                Location    = new Point(x * size, y * size),
                BorderStyle = BorderStyle.FixedSingle,
                BackColor   = randomColor
            };

            Controls.Add(panel);
            //panel.Click += Panel_Click;
        }
    }
}

I have two questions:

Upvotes: 0

Views: 37

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

You have to include additional 5 pixels padding into Location:

 ...
 int padding  =  5;
 ... 
 Location = new Point(x * (size + padding), y * (size + padding))
 ...

Let's extract a method:

 private void CreateGameField() {
   int size     = 20;
   int padding  =  5;
   int quantity = 10;

   Random rnd = new Random();

   for (int y = 0; y < quantity; ++y)
     for (int x = 0; x < quantity; ++x) 
       new Panel() {
         Size        = new Size(size, size),
         Location    = new Point(x * (size + padding), y * (size + padding)),
         BorderStyle = BorderStyle.FixedSingle,
         BackColor   = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256)), 
         Parent      = this, // instead of Controls.Add(panel);
       };
 }

Then

 private void Form1_Load(object sender, EventArgs e) {   
   CreateGameField();
 }

FromLoad event handler is a good place to create the game field; if you want you can place CreateGameField() in the constructor, but put it after InitializeComponent():

 public Form1() {
   InitializeComponent();

   CreateGameField(); 
 }

Upvotes: 1

Related Questions