最近由于工作需要,做一個C#的簡單程序。學習了一些基礎東西先記下來。
主要有:
1.生成初始框架
2.打亂順序
3.游戲部分,點擊按鈕后與空白部分交換的只是Text和Visible部分
const int N = 4; //行列數Button[,] buttons = new Button[N, N];private void Form1_Load(object sender, EventArgs e){  //產生所有按鈕  GenerateAllButtons();}private void button1_Click(object sender, EventArgs e){  //打亂順序  Shuffle();}//生成按鈕void GenerateAllButtons(){  int x0 = 100, y0 = 10, w = 45, d = 50;   for( int row = 0; row < N; row++ )    for ( int col = 0; col < N; col++ )    {      int num = row * N + col;  //數字編號      Button btn = new Button();      btn.Text = (num + 1).ToString();      btn.Top = y0 + row * d;      btn.Left = x0 + col * d;      btn.Width = w;      btn.Height = w;      btn.Visible = true;      btn.Tag = row * N + col;  //button位置      //注冊button點擊事件      btn.Click += new EventHandler(btn_Click);      buttons[row, col] = btn;      this.Controls.Add(btn);    }  buttons[N - 1, N - 1].Visible = false;}void Shuffle(){  Random rnd = new Random();  for (int i = 0; i < 100; 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]);  }}// 進行游戲private void btn_Click(object sender, EventArgs e){  Button btn = sender as Button;  Button blank = FindHiddenButton();  // 判斷是否相鄰  if ( IsNeighbor(btn, blank) )  {    Swap(btn, blank);    blank.Focus();  }  // 判斷是否完成  if ( ResultIsOk() )  {    MessageBox.Show("OK!");  }}// 查找空白按鈕Button FindHiddenButton(){  for (int row = 0; row < N; row++)    for (int col = 0; col < N; col++)    {      if (!buttons[row,col].Visible)      {        return buttons[row, col];      }    }  return null;}// 判斷是否相鄰bool IsNeighbor(Button btnA, Button btnB){  int a = (int)btnA.Tag;  int b = (int)btnB.Tag;  int r1 = a / N, c1 = a % N;  int r2 = b / N, c2 = b % N;  if ( (r1 == r2 && (c1 == c2 + 1 || c1 == c2 - 1))    || (c1 == c2 && (r1 == r2 + 1 || r1 == r2 - 1)) )    return true;  return false;}//檢查是否完成bool ResultIsOk(){  for (int r = 0; r < N; r++)    for (int c = 0; c < N; c++)    {      if (buttons[r, c].Text != (r * N + c + 1).ToString())      {        return false;      }    }  return true;}//交換兩個按鈕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;}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答