c# - 将按钮事件参数添加到方法
问题描述
我正在开发一个游戏,用户在 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 按键),它将“播放器”从一个按钮移动到另一个按钮。我目前的想法是将单击的下一个按钮设置为当前位置的颜色,然后将当前位置颜色设置为默认灰色。我只需要知道如何将这些事件参数添加到不包含它们的方法中。我该如何添加它们?
解决方案
我创建了一个有效的方法,但它可能不是最好的:
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");
}
};
}
}
推荐阅读
- python - 如何使用 pymodbus 为将读取它们的外部 Modbus 客户端写入输入寄存器
- c - 编译器优化会影响动态内存分配吗?
- ios - 手动关闭并重新打开后无法访问 Xcode 环境变量
- java - 有时无法拖放
- c++ - 我如何才能真正使用 std::chrono 类型而不冒溢出和未定义行为的风险?
- pandas - 订购星期几
- github - 将项目文件移动到子目录中,github 仍然查看上层文件夹
- mapbox - Mapbox GL JS 相机中心直接移动到用户的位置
- matlab - 在 MATLAB 中打开 .mtx 文件
- python - 安装 Python 是否还会安装 scipy 和 numpy 等库?