我有一个保存每个按钮特定坐标的二维字符串数组
string[,] gridPass = new string[20, 20];
private void Form1_Load(object sender, EventArgs e)
{
foreach (int row in Enumerable.Range(0, 20))
{
foreach (int col in Enumerable.Range(0, 20))
{
Button b = new Button();
b.Size = new System.Drawing.Size(30, 30);
b.Location = new Point(row * 30, col * 30);
gridPass[row, col] = row.ToString() + " - " + col.ToString();
b.Tag = gridPass[row, col];
b.Text = gridPass[row, col];
this.Controls.Add(b);
b.Click += new EventHandler(AttackHandler);
}
}
当我在按钮上使用事件处理程序进行攻击时
private void AttackHandler(object sender, EventArgs e)
{
Button clickedButton;
string tagValue = "";
clickedButton = (Button)sender;
tagValue = (string)clickedButton.Tag;
theSea.attackLocation(tagValue);
}
显然,无论按钮的坐标是什么,它都会发送一个像 0 - 1 或 8 - 4 这样的字符串。当我将该字符串传递给我的 Sea 类中的 attackLocation 方法时,我希望能够提取这两个数字以使用我的 Sea 类中的数组来引用它们,以查看那里是否有船。我需要那些 X 和 Y 值来引用另一个数组中完全相同的位置。所以我可以做类似的事情。
public void attackLocation(string attackCoords)
{
MessageBox.Show("Attacking " + attackCoords);
x = however to convert it back;
y = however to convert it back;
foreach (Ship s in shipList)
{
if (grid[x,y] == 0)
{
MessageBox.Show("Attacked this block before.");
}