首页 > 解决方案 > 如何给每个按钮单独的值

问题描述

我有这个程序可以让按钮在屏幕上移动。我想要实现的是所有按钮都可以朝不同的方向移动。问题是我似乎无法为我的目标找到一个干净的解决方案。到目前为止,这是我的代码。

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);
            }
        }

使用此代码,按钮确实以不同的角度在屏幕上移动,但它们都以相同的方式移动。有没有办法为每个按钮单独设置 RichtingY 和 RichtingX?

提前致谢!

标签: c#button

解决方案


使用字典来存储按钮和 X、Y 移动值之间的关系 例如:

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

然后将每个按钮添加到字典中:

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

要更新按钮的位置并更改 X、Y 值:

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));
}

推荐阅读