首页 > 解决方案 > 尝试匹配按钮的颜色及其图片

问题描述

基本上,我需要匹配图片和颜色,这样结果就是每当我按下汉堡时它变成蓝色,当我点击其他东西时它变成绿色。

现在,只要我单击按钮,它就会随机变为绿色或蓝色,而不依赖于单击的图片。

同样,我需要匹配以匹配图片和颜色,这样结果就是每当我按下汉堡时它变成蓝色,当我点击其他东西时它变成绿色。

我现在将添加表单启动时的屏幕截图和发生的情况,以及整个代码。

提前致谢。

开始:https : //prnt.sc/jnad9j 单击时:https ://prnt.sc/jnadie

代码:

for (int i = 0; i < arr.GetLength(0); i++)
{
    cx = x;

    for (int j = 0; j<arr.GetLength(1); j++)
    {
        value = rnd.Next(0, 2);
        t     = new Button();
        t.Tag = new Place(i, j);

        if (value == 0)
                rndmimg = rnd.Next(1, 2);
        else rndmimg = rnd.Next(2, 6);

        t.BackColor = Color.Red;
        t.BackgroundImageLayout = ImageLayout.Stretch;
        t.BackgroundImage = Image.FromFile("..\\..\\Pictures\\"+rndmimg+".png");
        t.Bounds = new Rectangle(cx, y, w, h);
        t.Click += new System.EventHandler(this.qqq_Click);

        this.Controls.Add(t);
        arr [i, j] = t;
        cx += w;

    }

    y += h;
}

public Form1() => InitializeComponent();

private void Form1_Load(object sender, EventArgs e) => rnd = new Random();

private void qqq_Click(object sender, EventArgs e)
{
    int px;
    int py;

    Place pl = (Place)(((Button)sender).Tag);
    px = pl.GetR();
    py = pl.C;
    rndmcus = rnd.Next(0, 2);   // Rndmcus determines color when button is clicked

    if (rndmcus == 0)
    {
        mishvalue = 0;
        arr[px, py].BackColor = Color.Green;
        arr[px, py].Enabled = false;
    }

    if (rndmcus == 1)
    {
        mishvalue = 1;
        arr[px, py].BackColor = Color.Blue;
        arr[px, py].Enabled = false;
    }

    ((Button)sender).Text = " ";
    scanner();
}

public void scanner()
{
    int counter = 0;
    for (int i = 0; i < arr.GetLength(0); i++)
        for (int j = 0; j < arr.GetLength(0); j++)
            if (arr[i, j].Text == " ")
                counter++;

    if (counter == boardsize * boardsize)
        this.Close();
}

class Place
{
    private int r;
    private int c;

    public Place(int r, int c)
    {
        this.r = r;
        this.c = c;
    }
    public int GetR()       => r;
    public int C            => c;
    public void SetR(int r) => this.r = r;
    public void SetC(int c) => this.c = c;
}

标签: c#

解决方案


为所有按钮分配一个 id,然后在事件中访问它

for (int j = 0; j < arr.GetLength(1); j++)
{
    value = rnd.Next(0, 2);
    t = new Button();
    t.ID = j.ToString();

Button button = (Button)sender;
string buttonId = button.ID;

将颜色与字典中的 id 相关联。


推荐阅读