1. Automatically generate Puzzle button when loading window
Const intN =4;//the number of rows and columns of the buttonbutton[,] buttons =NewButton[n, N];//array of buttons intStep =0;//record number of steps Private voidForm3_load (Objectsender, EventArgs e) { //Generate all Buttonsgenerateallbuttons (); } Private voidButton1_Click (Objectsender, EventArgs e) { //Scramble Order This. button1. Text ="Start Again"; Shuffle (); } voidgenerateallbuttons () {intx0 = -, y0 =Ten, W = $, d = -; for(intR =0; R < N; r++) { for(intc =0; c < N; C++) { intnum = R * N +C; Button btn=NewButton (); Btn. Text= (num +1). ToString (); Btn. Top= y0 + R *D; Btn. Left= x0 + c *D; Btn. Width=W; Btn. Height=W; Btn. Visible=true; Btn. Tag=num; //Registering EventsBtn. Click + =NewEventHandler (Btn_click); Buttons[r, c]= BTN;//put in an array This. Controls.Add (BTN);//add to the interface}} buttons[n-1N1]. Visible =false;//last btn not to meet . } Private voidBtn_click (Objectsender, EventArgs e) {Step++; Button btn= Sender asButton;//the currently selected buttonButton blank = Findhiddenbutton ();//a blank button//determine if it is adjacent to the blank block, and if it is, swap if(Isneighbor (btn, blank)) {Swap (btn, blank); Blank. Focus (); } //Judging if it's done. if(Resultisok ()) {stringresult ="you are so good! "+"it's all used."+step. ToString () +"Step"; MessageBox.Show (result); }} Button Findhiddenbutton () { for(intR =0; R < N; r++) { for(intc =0; c < N; C++) { if(!Buttons[r, C]. Visible) {returnButtons[r, c]; } } } return NULL; } BOOLIsneighbor (Button Btna, button BTNB) {intA = (int) Btna.tag;//get the value of the button record intB = (int) Btnb.tag; intR1 = a/n;intC1 = a% N;//get the line number and column number of the button intr2 = b/n;intC2 = b%N; if(r1 = = R2 && (c1-c2 = =1|| C2-C1 = =1))//left and right adjacent|| (C1 = = C2 && (r1-r2 = =1|| R2-R1 = =1))//Up and down adjacent ) { return true; } return false; } //Check if complete BOOLResultisok () { for(intR =0; R < N; r++) for(intc =0; c < N; C++) { if(Buttons[r, C]. Text! = (R * N + C +1). ToString ()) {return false; } } return true; } //Scramble Order voidShuffle () {//multiple random exchange of two buttonsRandom rnd =NewRandom (); for(inti =0; I < -; i++) { intA =Rnd. Next (N); intb =Rnd. Next (N); intc =Rnd. Next (N); intD =Rnd. Next (N); Swap (Buttons[a, b], buttons[c, d]); } } //swap two buttons voidSwap (Button Btna, button BTNB) {stringt =Btna. Text; Btna. Text=BTNB. Text; BTNB. Text=T; BOOLv =Btna. Visible; Btna. Visible=BTNB. Visible; BTNB. Visible=v; } }
C#winfrom Writing Puzzle Games