public partial class Form1 : Form
{
int n = 0, m = 0;
int i=1, j=1;
Button[,] buttons=new Button[3,3];//3,3為(0~2,0~2)
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int j = 0; j < 3; j++)
{
for (int i = 0; i < 3; i++)
{
buttons[i, j] = new System.Windows.Forms.Button();
buttons[i, j].Location = new Point(50 * i, 50 * j);
buttons[i, j].Click += new EventHandler(buttons_Click);//宣告點擊事件
buttons[i, j].Width = 50;
buttons[i, j].Height = 50;
this.Controls.Add(buttons[i, j]);//將物件顯示
}
}
}
private void buttons_Click(object sender, EventArgs e)//當事件被處發時,處發者為sander
{
Button but = sender as Button;//宣告but為跟sander一樣的按鈕
if (n == 0) { n = 1; but.Text = "O"; }
else if (n == 1) { n = 0; but.Text = "X"; }
but.Enabled = false;
for (m = 0; m <= 2; m++)
{
if (buttons[m, 0].Text == buttons[m, 1].Text && buttons[m, 0].Text == buttons[m, 2].Text && buttons[m, 0].Text != "")
{
if (n == 1) { MessageBox.Show("O勝利"); } else if (n == 0) { MessageBox.Show("X勝利"); }
}
if (buttons[0, m].Text == buttons[1, m].Text && buttons[0, m].Text == buttons[2, m].Text && buttons[0, m].Text != "")
{
if (n == 1) { MessageBox.Show("O勝利"); } else if (n == 0) { MessageBox.Show("X勝利"); }
}
}
if (buttons[0, 0].Text == buttons[1, 1].Text && buttons[0, 0].Text == buttons[2, 2].Text && buttons[0, 0].Text != "")
{
if (n == 1) { MessageBox.Show("O勝利"); } else if (n == 0) { MessageBox.Show("X勝利"); }
}
if (buttons[0, 2].Text == buttons[1, 1].Text && buttons[0, 2].Text == buttons[2, 0].Text && buttons[0, 2].Text != "")
{
if (n == 1) { MessageBox.Show("O勝利"); } else if (n == 0) { MessageBox.Show("X勝利"); }
}
}
}
--------------------------------------------------------------------
沒有留言:
張貼留言