ImSleepless
ImSleepless

Reputation: 29

How to give each button individual values

I have this program which makes buttons move across the screen. What I'm trying to achieve is that all the buttons can go in all different directions. The problem is that I can't seem to find a clean solution to my goal. This is my code so far.

private void MoveTimer_Tick(object sender, EventArgs e)
        {
            KeerBewogen++;

            foreach (Button button in this.Controls.OfType<Button>())
            {
                if (KeerBewogen == 150)
                {
                    RichtingX = rnd.Next(-1, 2);
                    RichtingY = rnd.Next(-1, 2);
                    KeerBewogen = 0;
                }

                button.Location = new Point(button.Location.X + RichtingX, button.Location.Y + RichtingY);

                if (button.Location.X == 1 || button.Location.Y == 1)
                {
                    RichtingX = rnd.Next(0, 2);
                    RichtingY = rnd.Next(0, 2);
                }

                if (button.Location.X == 550 || button.Location.Y == 750)
                {
                    RichtingX = rnd.Next(-1, 0);
                    RichtingY = rnd.Next(-1, 0);
                }
            }

            if (btnEend1.Location.X == 1 || btnEend1.Location.Y == 1)
            {
                RichtingX = rnd.Next(0, 2);
                RichtingY = rnd.Next(0, 2);
            }

            if (btnEend1.Location.X == 550 || btnEend1.Location.Y == 750)
            {
                RichtingX = rnd.Next(-1, 0);
                RichtingY = rnd.Next(-1, 0);
            }
        }

With this code the buttons do move across the screen at different angles, but they ALL go the same way. Is there a way to set the RichtingY and RichtingX individualy for each button?

Thanks in advance!

Upvotes: 0

Views: 49

Answers (1)

Zaelin Goodman
Zaelin Goodman

Reputation: 896

Use a dictionary to store the relation between a button and the X,Y move values For example:

Dictionary<Button,Tuple<int,int>> angledict = new Dictionary<Button,Tuple<int,int>>();

Then add each button to the dictionary:

foreach (Button button in this.Controls.OfType<Button>()) {
    angleDict.Add(button, new Tuple<int,int>(0,0))
}

To update the button's location and change the X,Y values:

foreach (Button button in this.Controls.OfType<Button>()) {
    **...**
    var kvpair = angleDict(button);
    button.Location = new Point(button.Location.X + kvpair.Value.Item1, button.Location.Y + kvpair.Value.Item2);
    **...**
    angleDict(button) = new Tuple<int,int>(rnd.Next(2),rnd.Next(2));
}

Upvotes: 1

Related Questions