【问题标题】:Dynamically programming a grid consisting of 64 buttons (8x8)动态编程由 64 个按钮 (8x8) 组成的网格
【发布时间】:2011-12-06 02:37:46
【问题描述】:

我正在尝试创建一个纯粹用于学习 C# 和国际象棋的国际象棋游戏。刚开始,我想通过代码而不是设计器创建一个 8x8 的按钮网格。这将节省我单独对每个按钮进行硬编码。

按钮数组似乎是一个不错的开始方式,但我不知道如何实现。

【问题讨论】:

  • 只是为了使用 Visual Studio 2010 添加即时消息并正在创建这个 suign winforms
  • 更新您的问题,而不是添加此类评论。

标签: c# winforms arrays button grid


【解决方案1】:

也许您可以使用下面的代码来解决您的问题。此代码是 C# 中的 Windows 窗体应用程序。而对于控制按钮。

    for (int i = 0; i< 8; i++)    
{
    for (int j = 0; j < 8; j++)
      {
        Button BtnNew = new Button;
        BtnNew.Height = 80;
        BtnNew.Width = 80;
        BtnNew.Location = new Point(80*i, 80*j);
        this.Controls.Add(BtnNew);
       }
}

【讨论】:

  • 谢谢。与上面的代码非常相似,我肯定会在我的模型中尝试这个。
【解决方案2】:
        int ButtonWidth = 40;
        int ButtonHeight = 40;
        int Distance = 20;
        int start_x = 10;
        int start_y = 10;

        for (int x = 0; x < 8; x++)
        {
            for (int y = 0; y < 8; y++)
            {
                Button tmpButton = new Button();
                tmpButton.Top = start_x + (x * ButtonHeight + Distance);
                tmpButton.Left = start_y + (y * ButtonWidth + Distance);
                tmpButton.Width = ButtonWidth;
                tmpButton.Height = ButtonHeight;
                tmpButton.Text = "X: " + x.ToString() + " Y: " + y.ToString();
                // Possible add Buttonclick event etc..
                this.Controls.Add(tmpButton);
            }

        }

【讨论】:

    【解决方案3】:

    你可以创建一个“方形”类:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    
    class Square:PictureBox
    {
       private bool color;
       private char piece;
    }
    

    并定义一个数组来放置 8x8 的正方形。

    public partial class Form1 : Form
    {
     Square[,] square = new Square[8, 8];
    
     public Form1()
     {
      InitializeComponent();
      int i, j;
    
      for (i = 0; i < 8; i++)
      {
         for (j = 0; j < 8; j++)
         {
           this.square[i, j] = new Square();//Creating the chess object//
           this.square[i, j].BackColor = System.Drawing.SystemColors.ActiveCaption;
           this.square[i, j].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
           this.square[i, j].Location = new System.Drawing.Point(57 + i * 40, 109 + j * 40);
           this.square[i, j].Name = "chessBox1";
           this.square[i, j].Size = new System.Drawing.Size(40, 40);
           this.square[i, j].TabIndex = 2;
           this.square[i, j].TabStop = false;
           this.Controls.Add(this.square[i, j]);
         }
      }
     }
    }
    

    【讨论】:

    • 虽然 StephanE 的答案更适合 id 现在想要实现的东西,但您的代码对于替代的做事方式来说是任何开放的,我当然会更多地研究这个,我非常感谢您的帮助。谢谢。
    猜你喜欢
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多