C # implement 15 sub-Games,
Recently, as a result of work needs, we have made a simple C # program. I learned some basic things and wrote them down first.
Mainly include:
1. Generate the initial framework
2. disordered order
3. In the game section, after clicking the button, only the Text and Visible sections are exchanged with the blank section.
1 const int N = 4; // number of rows and columns 2 Button [,] buttons = new Button [N, N]; 3 4 private void Form1_Load (object sender, EventArgs e) 5 {6 // generate all buttons 7 GenerateAllButtons (); 8} 9 10 private void button#click (object sender, EventArgs e) 11 {12 // disrupt the order 13 Shuffle (); 14} 15 16 // generate button 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; // number 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 location 32 33 // register button click event 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 // perform game 55 private void btn_Click (object sender, eventArgs e) 56 {57 Button btn = sender as Butto N; 58 Button blank = FindHiddenButton (); 59 60 // determine whether adjacent 61 if (IsNeighbor (btn, blank) 62 {63 Swap (btn, blank); 64 blank. focus (); 65} 66 67 // determine if 68 is completed if (ResultIsOk () 69 {70 MessageBox. show ("OK! "); 71} 72} 73 74 // search blank Button 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 // determine whether 89 bool IsNeighbor (Button btnA, Button btnB) is adjacent) 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 re Turn false; 100} 101 102 // check whether 103 bool ResultIsOk () 104 {105 for (int r = 0; r <N; r ++) is complete) 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 // exchange two buttons 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}