2011-10-12 6 views
8

私はC#とチェスの学習のためだけにチェスゲームを作成しようとしています。ちょうど始めに、私はデザイナーではなくコードでボタンの8x8グリッドを作成したいと思います。これにより、各ボタンを個別にコーディングするのが面倒になります。64個のボタン(8x8)で構成されるグリッドを動的にプログラミングする

ボタン配列は良い方法のようですが、これを実装する方法はわかりません。

+0

だけのVisual Studio 2010を使用してIMを追加すると、あなたの質問ではなくコメントのこの種の追加の更新 – Rg786

+3

このsuignリサイズを作成しています。 – Otiel

答えて

4
 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); 
      } 

     } 
+0

これは私が必要としていたものです。 – Rg786

8

あなたは「四角」クラスを作成することができます

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; 
} 

をし、8×8の正方形のための場所を作るために配列を定義します。

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]); 
    } 
    } 
} 
} 
+0

StephanEの答えは、今実装しようとしているものにもっと適していますが、あなたのコードは、やり方を変えるためのオープナーです。ありがとうございました。 – Rg786

+0

ようこそ。 –

1

あなたはあなたの問題を解決するために以下のコードを使用してCAおそれ。このコードは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); 
     } 
} 
+0

ありがとうございます。上記のコードに非常によく似ていますが、私のモデルではこれを確かに試してみてください。 – Rg786

関連する問題