我的目标是我想要将单词的每个字母命名为单个按钮,我也想要随机播放或重新排列按钮上的那些字母..所以基本上它看起来像这样...
H P E L (每个字母代表一个按钮)
单击按钮时应重新排列这些按钮(就像一个随机播放按钮)
因为我试图从头开始创建自己的文本扭曲游戏版本..所以我使用循环创建了我的按钮以节省工作量。
private void addButtonLetters()
{
string testabc = "abc";
shuffled = new string(testabc.OrderBy(r => RNDM.Next(i, 4)).ToArray());
for (int i = 0; i < 3; i++)
{
newButton = new Button();
newButton.Size = new Size(75, 41);
newButton.Location = new Point(11 + 80 * i, 66);
newButton.Text = shuffled[i].ToString();
newButton.Click += buttonClicked; //click handler
letters[i] = newButton;
this.Controls.Add(letters[i]);
}
}
从这一点开始,当我尝试点击一个假设要重新排列字母的按钮时,我想要将每个按钮上的字母洗牌.... 我试图做的就是调用&quot; addButtonLetter();&#39;事件我每次尝试点击(假设是洗牌),因为我假设它只是重新创建一组重新安排的按钮,但它没有做任何事情。所以我只是尝试做
string testabc = "abc";
shuffled = new string(testabc.OrderBy(r => RNDM.Next(i, 4)).ToArray());
for (int i = 0; i < 3; i++)
{
newButton.Text = shuffled[i].ToString();
}
它只会改变最后一个按钮的字母,但我想改变这三个字母!我甚至发现循环没用,因为当我删除它时,它仍然只会改变最后一个按钮......
我需要建议如何更改所有按钮文字,因为我无法手动将其重命名...
我是否需要遍历我创建的所有按钮并从那里开始执行?如果是这样的话?任何建议都会有所帮助。我试图让我的问题尽可能清楚,并提供尽可能多的信息,我希望我提供的所有信息都清楚,有助于那些想要帮助的人...如果不是只是问我任何我可以清理的东西!先感谢您!
注意:这是我的测试代码,所以我不会弄乱我原来的那个......我原来的那个会包含更多按钮,我首先尝试婴儿步骤......
答案 0 :(得分:0)
正如你所提到的那样,“我正试图从头开始制作我自己的文本扭曲游戏版本”,那么你可以随意洗牌,希望这会对你有所帮助: -
List<string> source =new List<string>();
public Form1()
{
InitializeComponent();
source.Add("a");
source.Add("b");
source.Add("c");
source.Add("d");
source.Add("e");
SetButtonText(source);
}
private void SetButtonText(List<string> source)
{
button1.Text = source[0];
button2.Text = source[1];
button3.Text = source[2];
button4.Text = source[3];
button5.Text = source[4];
}
private void button1_Click(object sender, EventArgs e)
{
var rnd = new Random();
var newsource = source.OrderBy(item => rnd.Next());
SetButtonText(newsource.ToList());
}
如果您想更改按钮位置,请尝试以下操作: -
private void GetAllControl(Control c, List<Control> list)
{
foreach (Control control in c.Controls)
{
list.Add(control);
if (control.GetType() == typeof(Panel))
GetAllControl(control, list);
}
}
private void button1_Click(object sender, EventArgs e)
{
List<Rectangle> btnLocation = new List<Rectangle>();
List<Control> btnList = new List<Control>();
GetAllControl(this, btnList);
foreach (Control control in btnList)
{
if (control.Text != "Shuffle")
{
btnLocation.Add(control.Bounds);
}
}
var rnd = new Random();
var newsource = btnLocation.OrderBy(item => rnd.Next()).ToList();
int i = 0;
foreach (Control control in btnList)
{
if (control.Text != "Shuffle")
{
control.Bounds = newsource[i];
}
i++;
}
}
我已经测试了它的工作情况;)