获取单击旁边的按钮

时间:2015-10-15 23:29:42

标签: c# visual-studio-2013

我正在使用C#在Windows窗体上创建一个跳棋游戏。 this is my 4x4 checkers board

我正在使用按钮(我猜这不是最好的选择)。

让我们说黄色按钮是被点击的按钮,我想禁用除C1和C3之外的每个按钮。

我还是初学者,所以我不确定它是否可行,但我想要的是找到被点击的按钮旁边的按钮

以下是检查点击了哪个按钮的代码:

 private void buttonClick(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if ((b.Text == "W") && (turn == true))
        {
            b.BackColor = Color.Yellow;

        }
    }

2 个答案:

答案 0 :(得分:1)

虽然你得到了答案(这是正确答案),但我强烈建议你学习Object Oriented编程方法。在OOP中,您可以将对象可视化为真实世界对象。简而言之,它们具有状态(属性),展示行为(方法)并响应刺激(事件)。您还可以获取一个对象,引入更多属性/方法/事件,并从中创建一个新对象(继承)。

当我学习和编写我的第一个国际象棋游戏时,我做到了这样:

  1. 在我们的游戏板上代表Cell的项目中添加一个新类。让我们称之为CheckersCell。我们将其继承自Button(我在原始版本中使用了Label)。然后我们为它添加一个新属性,以便在板上保持其位置(坐标)。
  2. using System.Drawing;
    using System.Windows.Forms;
    
    class CheckersCell : Button
    {
        public Point Position { get; set; }
    }
    
    1. 接下来,我们添加另一个代表游戏板的类(CheckersBoard)。它包含所有64个单元格(CheckersCell)。 SetupBoard()方法创建单元格并按顺序排列单元格。 GetAdjescentCell方法为您提供有关板上单元格的周围单元格的信息。
    2. using System;
      using System.Drawing;
      using System.Linq;
      using System.Windows.Forms;
      using System.ComponentModel;
      
      [DefaultEvent("CellClick")]
      class CheckersBoard : Panel
      {
          public const int BoardSize = 8; // for standard 8x8 board
          public enum Direction { Left, Right, Up, Down, LeftUp, LeftDown, RightUp, RightDown }
      
          public event EventHandler CellClick = new EventHandler((s, e) => { });
      
          public CheckersCell[] Cells { get; set; }
      
          public CheckersBoard()
          {
              SetupBoard();
          }
      
          public CheckersCell GetCellByPosition(int x, int y)
          {
              foreach (CheckersCell cell in Cells)
              {
                  if (cell.Position.X == x && cell.Position.Y == y) return cell;
              }
              return null;
          }
      
          protected void SetupBoard()
          {
              // setup the board
              Cells = new CheckersCell[BoardSize * BoardSize];
              int cellNumber = 0;
              for (int x = 0; x < BoardSize; x++)
              {
                  for (int y = 0; y < BoardSize; y++)
                  {
                      CheckersCell currentCell = new CheckersCell();
                      Cells[cellNumber++] = currentCell;
                      this.Controls.Add(currentCell);
                      currentCell.Name = string.Concat(this.Name, "Cell", x, "x", y);
                      currentCell.Position = new Point(x + 1, y + 1);
                      currentCell.BackColor = ((x + y) % 2 == 0) ? Color.Brown : Color.White;
                      currentCell.Click += (s, e) => { CellClick(s, e); };
                  }
              }
              OnResize(null);
          }
      
          public CheckersCell GetAdjescentCell(CheckersCell referenceCell, Direction d)
          {
              return GetAdjescentCell(referenceCell, d, 1);
          }
      
          public CheckersCell GetAdjescentCell(CheckersCell referenceCell, Direction d, int steps)
          {
              // find the co-ordinates of adjescent cell we want to go to
              Point newPosition = referenceCell.Position;
              switch (d)
              {
                  case Direction.Left:
                      newPosition.X -= steps; break;
                  case Direction.Right:
                      newPosition.X += steps; break;
                  case Direction.Up:
                      newPosition.Y -= steps; break;
                  case Direction.Down:
                      newPosition.Y += steps; break;
                  case Direction.LeftUp:
                      newPosition.X -= steps; newPosition.Y -= steps; break;
                  case Direction.RightUp:
                      newPosition.X += steps; newPosition.Y -= steps; break;
                  case Direction.LeftDown:
                      newPosition.X -= steps; newPosition.Y += steps; break;
                  case Direction.RightDown:
                      newPosition.X += steps; newPosition.Y += steps; break;
              }
              foreach (CheckersCell cell in Cells)
              {
                  if (cell.Position == newPosition) return cell;
              }
              return null;
          }
      
          protected override void OnResize(System.EventArgs eventargs)
          {
              base.OnResize(eventargs);
              int cellWidth = this.Width / BoardSize;
              int cellHeight = this.Height / BoardSize;
              foreach (CheckersCell cell in Cells)
              {
                  cell.Size = new Size(cellWidth, cellHeight);
                  cell.Location = new Point((cell.Position.X - 1) * cellWidth, (cell.Position.Y - 1) * cellHeight);
              }
          }
      }
      

      这就是我们需要设置的所有内容(w.r.t你的问题)。让我们测试一下我们拥有的东西。

      编译项目后,您会在工具箱中看到两个新项目 - CheckersBoardCheckersCell。将CheckersBoard拖到您的表单上,然后根据您的意愿调整大小。

      Checkers Board

      双击电路板上的任意位置。它将使用名为checkersBoard1_CellClick的方法(事件)打开表单代码。将以下代码放在该方法中:

          private void checkersBoard1_CellClick(object sender, EventArgs e)
          {
              CheckersCell cell = (CheckersCell)sender;
              string msg = "";
              msg += "You clicked on Cell : " + cell.Position.ToString() + "\n";
              msg += "Left : " + checkersBoard1.GetAdjescentCell(cell, CheckersBoard.Direction.Left).Position.ToString() + "\n";
              msg += "Right : " + checkersBoard1.GetAdjescentCell(cell, CheckersBoard.Direction.Right).Position.ToString() + "\n";
              msg += "Up : " + checkersBoard1.GetAdjescentCell(cell, CheckersBoard.Direction.Up).Position.ToString() + "\n";
              msg += "Down : " + checkersBoard1.GetAdjescentCell(cell, CheckersBoard.Direction.Down).Position.ToString() + "\n";
              msg += "UpLeft : " + checkersBoard1.GetAdjescentCell(cell, CheckersBoard.Direction.LeftUp).Position.ToString() + "\n";
              msg += "UpRight : " + checkersBoard1.GetAdjescentCell(cell, CheckersBoard.Direction.RightUp).Position.ToString() + "\n";
              msg += "DownLeft : " + checkersBoard1.GetAdjescentCell(cell, CheckersBoard.Direction.LeftDown).Position.ToString() + "\n";
              msg += "DownRight : " + checkersBoard1.GetAdjescentCell(cell, CheckersBoard.Direction.RightDown).Position.ToString() + "\n";
              MessageBox.Show(msg);
          }
      

      保存所有内容,编译并运行。单击板上的任何单元格(不要单击角落行或列,因为这仅用于演示)。它应该显示一个看起来像这样的消息框:

      message box

      HTH。

答案 1 :(得分:0)

试图在屏幕上某处找到按钮绝对是可能的,但不是最简单的方法。最好生成它们并在创建时存储到一些方便的结构中:

int xCount = 4;
int yCount = 4;
int buttonSize = 40;
Dictionary<Button, Point> pointByButton = new Dictionary<Button, Point>();

for (int x = 0; x < xCount; ++x)
{
    for (int y = 0; y < yCount; ++y)
    {
        Button newButton = new Button();
        newButton.Location = new Point(100 + x * buttonSize, 150 + y * buttonSize);
        newButton.Size = new Size(buttonSize, buttonSize);
        newButton.Name = "" + (char)(y + 'A') + (x + 1);
        newButton.Text = newButton.Name;
        this.Controls.Add(newButton);

        pointByButton.Add(newButton, new Point(x, y));

        newButton.Click += new EventHandler((s, ev) =>
        {
            Point thisPoint = pointByButton[(Button)s];

            foreach (var btn in pointByButton)
            {
                if (btn.Value.Y - thisPoint.Y != -1 || Math.Abs(btn.Value.X - thisPoint.X) != 1)
                {
                    btn.Key.Enabled = false;
                }
            }
        });
    }
}