最近由于工作需要,做一个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 }