1.窗口载入时自动生成拼图按钮

  const int N = ;//按钮的行、列数
Button[,] buttons = new Button[N, N];//按钮的数组
int step = ;//记录步数 private void Form3_Load(object sender, EventArgs e)
{
//产生所有按钮
GenerateAllButtons();
} private void button1_Click(object sender, EventArgs e)
{
//打乱顺序
this.button1.Text = "重新开始";
Shuffle();
}
void GenerateAllButtons()
{
int x0 = , y0 = , w = , d = ;
for (int r = ; r < N; r++)
{
for (int c = ; c < N; c++)
{
int num = r * N + c;
Button btn = new Button();
btn.Text = (num + ).ToString();
btn.Top = y0 + r * d;
btn.Left = x0 + c * d;
btn.Width = w;
btn.Height = w;
btn.Visible = true;
btn.Tag = num;
//注册事件
btn.Click += new EventHandler(Btn_Click);
buttons[r, c] = btn; //放到数组中
this.Controls.Add(btn); //加到界面上
}
}
buttons[N - , N - ].Visible = false;//最后一个btn不可见面
} private void Btn_Click(object sender, EventArgs e)
{
step++;
Button btn = sender as Button;//当前选中的按钮
Button blank = FindHiddenButton();//空白的按钮
//判断是否与空白块相邻,如果是,则交换
if (IsNeighbor(btn, blank))
{
Swap(btn, blank);
blank.Focus();
}
//判断是否完成了
if (ResultIsOk())
{
string result = "你真棒!"+"\n一共用了"+step.ToString()+"步";
MessageBox.Show(result);
} }
Button FindHiddenButton()
{
for (int r = ; r < N; r++)
{
for (int c = ; c < N; c++)
{
if (!buttons[r, c].Visible)
{
return buttons[r, c];
}
}
}
return null;
}
bool IsNeighbor(Button btnA, Button btnB)
{
int a = (int)btnA.Tag;//获得按钮记录的值
int b = (int)btnB.Tag;
int r1 = a / N;int c1 = a % N;//得到按钮的行号和列号
int r2 = b / N; int c2 = b % N;
if ((r1 == r2 && (c1 - c2 == || c2 - c1 == ))//左右相邻
|| (c1 == c2 && (r1 - r2 == || r2 - r1 == ))//上下相邻
)
{
return true;
}
return false;
}
//检查是否完成
bool ResultIsOk()
{
for (int r = ; r < N; r++)
for (int c = ; c < N; c++)
{
if (buttons[r, c].Text != (r * N + c + ).ToString())
{
return false;
}
}
return true;
}
//打乱顺序
void Shuffle()
{
//多次随机交换两个按钮
Random rnd = new Random();
for (int i = ; i < ; i++)
{
int a = rnd.Next(N);
int b = rnd.Next(N);
int c = rnd.Next(N);
int d = rnd.Next(N);
Swap(buttons[a, b], buttons[c, d]);
}
}
//交换两个按钮
void Swap(Button btna, Button btnb)
{
string t = btna.Text;
btna.Text = btnb.Text;
btnb.Text = t; bool v = btna.Visible;
btna.Visible = btnb.Visible;
btnb.Visible = v;
}
}
05-11 18:10