想实现一个场景,类似连连看的逻辑

在一个WINFORM中,我定义了多个按钮,我想实现的逻辑是,点击一个按钮后,如果再点击一个按钮,这两个按钮的名字如果一样的话,两个按钮就消失。

按照惯性,还是先看效果:

img

步骤和说明都在代码注释里,示例代码如下:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp1.Forms.Demo2
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            _random = new Random();
            InitializeComponent();
        }

        private readonly Random _random;
        private readonly List<string> _textList = new List<string> { "苹果", "香蕉", "桔子", "草莓" };
        // 第一个被点击的按钮
        private Button _sourceButton;
        private void Form2_Load(object sender, EventArgs e)
        {
            // 在窗体中初始化20个按钮
            for (var i = 0; i < 20; i++)
            {
                // 每个按钮的x坐标
                var x = (i % 5) * 50 + 5;
                // 每个按钮的y坐标
                var y = (i / 5) * 35;
                // 按钮实例
                var button = new Button
                {
                    Name = Guid.NewGuid().ToString(),                       // 按钮的Name属性,这里使用GUID作为惟一标识
                    Location = new Point(x, y),                             // 按钮的坐标位置 
                    Size = new Size(50, 30),                                // 按钮的尺寸
                    Text = _textList[_random.Next(0, _textList.Count)]      // 按钮的显示文本
                };
                // 注册按钮的点击事件
                button.Click += Button_Click;
                // 将按钮添加到窗体中
                Controls.Add(button);
            }
        }

        private void Button_Click(object sender, EventArgs e)
        {
            // 当有按钮被点击时,第一个按钮如果为null,则直接把当前按钮赋值给_sourceButton
            if (_sourceButton == null)
            {
                _sourceButton = (Button)sender;
                label1.Text = $"已选中:{_sourceButton.Text}";
                return;
            }

            var target = (Button)sender;
            if (_sourceButton.Name == target.Name)
            {
                // 点击的是同一个按钮
                return;
            }
            // 当被点击的两个按钮的文本相同时,执行消除按钮的操作
            if (_sourceButton.Text == target.Text)
            {
                // 把第一个按钮从窗体中移除
                Controls.Remove(_sourceButton);
                // 把第二个按钮从窗体中移除
                Controls.Remove((Button)sender);
                // 将第一个按钮变量设置为null
                _sourceButton = null;
                label1.Text = "成功消除";
            }
            else
            {
                _sourceButton = target;
                label1.Text = $"已选中:{_sourceButton.Text}";
            }
        }
    }
}