首页 > 解决方案 > 将按钮事件参数添加到方法

问题描述

我正在开发一个游戏,用户在 10x10 的按钮网格中移动。按钮被添加到二维数组中,并显示如下。目前,当表单加载时,我将起始位置(黑色播放器图块)设置为索引 1。我想弄清楚的是如何引入一个按钮事件方法,我可以用它来导航图块。

这是网格的样子:

在此处输入图像描述

这是代码:

    private readonly int _xAxis = 10;

    private readonly int _yAxis = 10;

    private int _count = 1;

    private void DrawButtonArray()
    {
        Button[] buttons = new Button[_xAxis * _yAxis];
        int index = 0;
        for (int i = 0; i < _xAxis; i++)
        {
            for (int j = 0; j < _yAxis; j++)
            {
                Button gridBtn = new Button
                {
                    Size = new Size(60, 55),
                    Location = new Point(175 + j * 60, 55 + i * 55),
                    Text = _count.ToString()
                };

                gridBtn.ForeColor = Color.FromArgb(64, 64, 64);

                buttons[index++] = gridBtn;
                _count++;
                Controls.Add(gridBtn);

                if (index == 1)
                {
                    gridBtn.BackColor = Color.Black;
                }
            }
        }
    }

我希望实现的是一个鼠标单击事件(或者可能是 WASD 按键),它将“播放器”从一个按钮移动到另一个按钮。我目前的想法是将单击的下一个按钮设置为当前位置的颜色,然后将当前位置颜色设置为默认灰色。我只需要知道如何将这些事件参数添加到不包含它们的方法中。我该如何添加它们?

标签: c#winformsbuttonevents

解决方案


我创建了一个有效的方法,但它可能不是最好的:

    private void DrawButtonArray()
    {
        Button[] buttons = new Button[_xAxis * _yAxis];
        int currentIndex = 0;
        for (int i = 0; i < _xAxis; i++)
        {
            for (int j = 0; j < _yAxis; j++)
            {
                Button gridBtn = new Button
                {
                    Size = new Size(60, 55),
                    Location = new Point(175 + j * 60, 55 + i * 55),
                    Text = _count.ToString()
                };

                gridBtn.ForeColor = Color.FromArgb(64, 64, 64);

                if (currentIndex == 0)
                {
                    gridBtn.BackColor = Color.FromArgb(0, 0, 0);
                }

                buttons[currentIndex++] = gridBtn;

                _count++;

                Controls.Add(gridBtn);
            }
        }

        currentIndex = 1;

        foreach (Button nextIndex in buttons)
        {
            nextIndex.Click += (s, e) =>
            {
                if (nextIndex.Text == (currentIndex + 1).ToString()
                    || nextIndex.Text == currentIndex.ToString()
                    || nextIndex.Text == (currentIndex - 1).ToString()
                    || nextIndex.Text == (currentIndex + 10).ToString()
                    || nextIndex.Text == (currentIndex - 10).ToString())
                {
                    buttons[currentIndex - 1].BackColor = Color.FromArgb(64, 64, 64);
                    currentIndex = int.Parse(nextIndex.Text);
                    nextIndex.BackColor = Color.Black;
                }
                else
                {
                    MessageBox.Show("Invalid Move");
                }
            };
        }
    }

推荐阅读