c# - (C#,连接四)- 为下面的按钮着色

标签 c# .net vb.net button

我正在做编程考试,我快完成游戏了。我决定使用连接四,因为这似乎是处理一些算法功能的好机会,因为我不太习惯这种编码。

问题很简单:我需要为按钮着色以创建砖 block 掉落的效果。我想做一些类似 if 语句的事情来检查坐标 == this 那么它的这个按钮是否是彩色的。否则如果...

但这会很痛苦而且不太漂亮。我在想是否有可能或多或少地获取表单中的所有按钮,然后从函数中获取 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;
        }

我真的无法让它以任何方式工作。有什么建议吗?结果比我想象的要难,哈哈。

最佳答案

不确定哪一部分“不起作用”,但这对我有用:

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

假设您有一 block 6 x 6 板,您可以这样使用:

for (int x = 0; x < 6; x++)
{
    for (int y = 0; y < 6; y++)
    {
        farv(x, y);
    }
}

关于c# - (C#,连接四)- 为下面的按钮着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29042641/

相关文章:

c# - 运行时的 Expression.Lambda 和查询生成,最简单的 "Where"示例

Python 返回的字符串既是 str 又是 unicode 类型

vb.net - 从 vb.net 中的字符串末尾仅删除一个换行符

mysql - LINQ 生成错误查询,错误未知列 (VB.NET MySQL)

c# - 在跟踪查询数量时维护 CQS

c# - 如何在一个语句中分配给变量列表

c# - .NET Web 应用程序中的 native 依赖项未加载

c# - 在回调中重用回调时如何防止 StackOverflowException?

c# - 初始化 C# 委托(delegate)的 "correct"方法是什么?

javascript - UWP 应用中的 Web 请求