まるばつゲームの盤を作ります。クリックすると、○・×が現れる単純なものです。
前回作ったプログラムの無駄な繰り返しを減らしました。
public class TestApp
{
public static void Main()
{
System.Windows.Forms.Application.Run(new MainForm());
}
}
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Label[] c1;
private System.Windows.Forms.PictureBox c10;
private System.String c11;
public MainForm()
{
this.Text = "まるばつゲーム";
this.ClientSize = new System.Drawing.Size(300, 300);
c1 = new System.Windows.Forms.Label[9];
for (int i = 0; i < c1.Length; ++i)
{
c1[i] = new System.Windows.Forms.Label();
c1[i].Top = 5 + (i / 3) * 100;
c1[i].Left = 5 + (i % 3) * 100;
c1[i].Width = 90;
c1[i].Height = 90;
c1[i].Font = new System.Drawing.Font(System.Windows.Forms.Control.DefaultFont.Name, 50);
c1[i].TextAlign = System.Drawing.ContentAlignment.BottomCenter;
c1[i].Click += c1_Click;
this.Controls.Add(c1[i]);
}
c10 = new System.Windows.Forms.PictureBox();
c10.Width = 300;
c10.Height = 300;
System.Drawing.Bitmap canvas = new System.Drawing.Bitmap(c10.Width, c10.Height);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(canvas);
g.DrawLine(System.Drawing.Pens.Black, 0, 100, 300, 100);
g.DrawLine(System.Drawing.Pens.Black, 0, 200, 300, 200);
g.DrawLine(System.Drawing.Pens.Black, 100, 0, 100, 300);
g.DrawLine(System.Drawing.Pens.Black, 200, 0, 200, 300);
g.Dispose();
c10.Image = canvas;
this.Controls.Add(c10);
c11 = "○";
}
private void c1_Click(object o, System.EventArgs e)
{
System.Windows.Forms.Label x = (System.Windows.Forms.Label) o;
if (x.Text == "") {
x.Text = c11;
}
toggle_c11();
}
private void toggle_c11()
{
if (c11 == "○") {
c11 = "×";
} else {
c11 = "○";
}
}
}
ボタンの配列、for文による繰り返し処理などで、プログラムの重複した記述が減りました。
ここまでできたら、勝敗の判定、次のゲームの開始などの機能も追加したいですね。→ 次回へ続く。