我正在进行编程考试,我几乎完成了游戏。我决定使用connect 4,因为它似乎是处理一些algrothicy功能的好机会,因为我不习惯那种编码。
问题很简单:我需要为按钮着色以创建掉落砖的效果。我想做一个像大屁股的事情,如果陈述检查coodinates ==这然后它的按钮被着色。否则如果......
但那会痛苦而且不是很漂亮。我想是否有可能通过任何机会或多或少地接受表单中的所有按钮,然后从函数中获取x和y生成一个字符串,然后找到一个具有该名称的按钮
我的按钮是标签btxy 但是我弄乱了数组第一个按钮是:0,0 第一个按钮的名称是bt11,x上的下一个是bt12
我来自丹麦所以有些变量是丹麦语,所以这个函数是这样的:
private void farv(int x, int y)
{
x += 1;
y += 1;
MessageBox.Show("bt" + y.ToString() + x.ToString());
foreach (Control c in this.Controls)
{
if (c is Button)
{
if (c.Name == "bt" + x.ToString() + y.ToString())
{
if (playerValue == 1)
{
c.BackColor = Color.Blue;
}
else if (playerValue == 10)
{
c.BackColor = Color.Red;
}
}
}
}
}
这就是着色方法。 我这叫它:
temp = 0;
while (temp < 6)
{
MessageBox.Show("While");
farv(rowNr, temp);
temp += 1;
}
我真的无法以任何方式工作。有什么建议吗?事实证明这比我想象的要难,哈哈。
答案 0 :(得分:3)
不确定哪个部分&#34;不起作用&#34;,但这对我有用:
private void farv(int x, int y)
{
var buttonName = string.Format("bt{0}{1}", x + 1, y + 1);
var buttonControl = Controls.Find(buttonName, true).FirstOrDefault();
if (buttonControl != null)
{
buttonControl.BackColor = GetColorForPlayer(playerValue);
}
}
private Color GetColorForPlayer(int playerValue)
{
Color defaultColor = SystemColors.Control;
switch (playerValue)
{
case 1:
return Color.Blue;
case 10:
return Color.Red;
default:
return defaultColor;
}
}
假设你有一个6 x 6的电路板,你可以使用它:
for (int x = 0; x < 6; x++)
{
for (int y = 0; y < 6; y++)
{
farv(x, y);
}
}