最近由於工作需要,做一個C#的簡單程式。學習了一些基礎東西先記下來。 主要有: 1.生成初始框架 2.打亂順序 3.游戲部分,點擊按鈕後與空白部分交換的只是Text和Visible部分 ...
最近由於工作需要,做一個C#的簡單程式。學習了一些基礎東西先記下來。
主要有:
1.生成初始框架
2.打亂順序
3.游戲部分,點擊按鈕後與空白部分交換的只是Text和Visible部分
1 const int N = 4; //行列數 2 Button[,] buttons = new Button[N, N]; 3 4 private void Form1_Load(object sender, EventArgs e) 5 { 6 //產生所有按鈕 7 GenerateAllButtons(); 8 } 9 10 private void button1_Click(object sender, EventArgs e) 11 { 12 //打亂順序 13 Shuffle(); 14 } 15 16 //生成按鈕 17 void GenerateAllButtons() 18 { 19 int x0 = 100, y0 = 10, w = 45, d = 50; 20 for( int row = 0; row < N; row++ ) 21 for ( int col = 0; col < N; col++ ) 22 { 23 int num = row * N + col; //數字編號 24 Button btn = new Button(); 25 btn.Text = (num + 1).ToString(); 26 btn.Top = y0 + row * d; 27 btn.Left = x0 + col * d; 28 btn.Width = w; 29 btn.Height = w; 30 btn.Visible = true; 31 btn.Tag = row * N + col; //button位置 32 33 //註冊button點擊事件 34 btn.Click += new EventHandler(btn_Click); 35 36 buttons[row, col] = btn; 37 this.Controls.Add(btn); 38 } 39 buttons[N - 1, N - 1].Visible = false; 40 } 41 42 void Shuffle() 43 { 44 Random rnd = new Random(); 45 for (int i = 0; i < 100; i++ ) 46 { 47 int a = rnd.Next(N); 48 int b = rnd.Next(N); 49 int c = rnd.Next(N); 50 int d = rnd.Next(N); 51 Swap(buttons[a, b], buttons[c, d]); 52 } 53 } 54 // 進行游戲 55 private void btn_Click(object sender, EventArgs e) 56 { 57 Button btn = sender as Button; 58 Button blank = FindHiddenButton(); 59 60 // 判斷是否相鄰 61 if ( IsNeighbor(btn, blank) ) 62 { 63 Swap(btn, blank); 64 blank.Focus(); 65 } 66 67 // 判斷是否完成 68 if ( ResultIsOk() ) 69 { 70 MessageBox.Show("OK!"); 71 } 72 } 73 74 // 查找空白按鈕 75 Button FindHiddenButton() 76 { 77 for (int row = 0; row < N; row++) 78 for (int col = 0; col < N; col++) 79 { 80 if (!buttons[row,col].Visible) 81 { 82 return buttons[row, col]; 83 } 84 } 85 return null; 86 } 87 88 // 判斷是否相鄰 89 bool IsNeighbor(Button btnA, Button btnB) 90 { 91 int a = (int)btnA.Tag; 92 int b = (int)btnB.Tag; 93 int r1 = a / N, c1 = a % N; 94 int r2 = b / N, c2 = b % N; 95 96 if ( (r1 == r2 && (c1 == c2 + 1 || c1 == c2 - 1)) 97 || (c1 == c2 && (r1 == r2 + 1 || r1 == r2 - 1)) ) 98 return true; 99 return false; 100 } 101 102 //檢查是否完成 103 bool ResultIsOk() 104 { 105 for (int r = 0; r < N; r++) 106 for (int c = 0; c < N; c++) 107 { 108 if (buttons[r, c].Text != (r * N + c + 1).ToString()) 109 { 110 return false; 111 } 112 } 113 return true; 114 } 115 //交換兩個按鈕 116 void Swap(Button btna, Button btnb) 117 { 118 string t = btna.Text; 119 btna.Text = btnb.Text; 120 btnb.Text = t; 121 122 bool v = btna.Visible; 123 btna.Visible = btnb.Visible; 124 btnb.Visible = v; 125 }