Origin: Feel good when playing Codeblocks's own Tetris, however there is a time limit. So I want to write one more. Program effect: Main content: There is a board array in the program, there are parts to be displayed, there are no parts to display, the parts that do not display are stored 1. Such as: Shape is saved with the 4*4 array (shape). such as: 0 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 Additionally, the variable row and column are used to save the position of the upper-left corner of the shape array in the board. Each drop or move around, first change the row and column, and then detect the current row and column, shape is coincident with the grid of 1, if there is a coincidence, the shape is out of bounds or to reach the lowest point of drop, you want to restore the row and column values. Also, if it is a drop, place the shape on the board and create a new shape. When rotated, the shape array is rotated first, then the coincident is detected, and if there is a coincidence, the reverse is rotated back. Code:? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 8 5 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 11 9 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 2 02 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 2 63 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 3 24 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 3 85 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 4 52 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 5 13 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 #if defined (UNICODE) &&!defined (_unicode) #define _UNICODE #elif defined (_unicode) &&!defined (Unicode) #define Unicode #endif #include #include #include #include/* #include ------macro Definition--------------------------------------------------------*/#define WIDTH #define HEIGHT #define Long_ SLEEP #define Bkcolor RGB (238,238,238)//Background color/*----------------- Variable----------------------------------------------------------*/static int shapes[7][4][4];//store 7 shapes static int high_score[4]= {0,0,0,0};//first three elements store highest score, last element stores this score static int **shape;//current shape static int * * Board static int m=15;//The number of columns that are displayed in static int n=30;//The number of rows that are displayed by the static int mm=m+8;//board The row number of the static int nn=n+4;//board static int left= 4;//displays the leftmost column of the static int right=left+m-1;//displays the most right column of the static int top=0;//displays the most previous column of the static int bottom=n-1;//displays the most next column of the static int Scor e=0; static int row=0;//shape is located in the row static int column=mm/2;//shape sits in column static bool Is_pause=false; Static Hbrush Grey_brush =createsolidbrush (RGB (210,210,210)); Static Hbrush White_brush =createsolidbrush (RGB (130,130,130)); Static Hbrush Bk_brush =createsolidbrush (Bkcolor); static Hpen Hpen = CreatePen (Ps_solid,1,rgb (147,155,166)); static int lattices_top=40;//leave white static int lattices_left=20;//left white static int width=width/m;//each lattice width static int height = (height-lattices_top)/n;//the height of each lattice/*----------------- function-----------------------------------------------------------*/void Add_score (); BOOL Check_is_lose (); void Clear_up ();//Eliminate No spacesThe line void* down_thread_function (void * args);//Shape drop process to execute the function void Exit_game (HWND hwnd); void Give_new_shape ();//randomly generate a new shape int handle_key (HWND hwnd,wparam WPARAM); int Init_down_thread (HWND hwnd);//Initialize shape drop process int Init_game (HWND hwnd);//Initialize Game program void Init_play ();//Initialize game data bool Is_legel ();//Check whether the shape is valid at the current position (that is, whether the non-empty lattice is coincident) int load_scores (int* a);//Read the game highest data int load_shape ();//Load 7 shapes from a file void Lose_game (HWND HWND); int Move_down (HWND hwnd);//Shape Drop int MOVE_LR (hwnd hwnd,int LR);//shape move around void Paint_lattice (HDC hdc,int x,int y,int color) ;//display a lattice void paint_ui (hdc hdc);//Draw interface void Reset_rc (); void Rerotate_matrix (int mn);//clockwise rotation of a square with a row number of MN rotate_matrix (int mn);//Counter-clockwise rotation of a square number of mn matrix int Rotate_shape (HWND HWND);//rotate the current shape and update the interface bool Save_score (HWND hwnd);//Save the highest sub-data void Shape_to_ground ();//After the current shape has landed, update board BOOL Sort_scores ( Int* a);//for the highest score and the rank of this score, if a new record is created returns true void UPDATE_UI (HWND hwnd);//update interface, update only the Rect area (the lines in which the shape resides) void Update_ui_all (HWND HWND);//update interface, update the entire interface int write_scores (int* a);//writeHighest score Data/* Declare Windows procedure */LRESULT CALLBACK windowprocedure (HWND, UINT, WPARAM, LPARAM); /* Make the class name into a global variable */TCHAR szclassname[] = _t ("Tris"); int WINAPI WinMain (hinstance hthisinstance, hinstance hprevinstance, LPSTR lpszargument, int ncmdshow) {HWND hwnd; */* Th Is are the handle for our window */MSG messages; /* Here messages to the application is saved */Wndclassex wincl; /* Data structure for the windowclass */* The WINDOW structure */wincl.hinstance = hthisinstance; Wincl.lpszclassname = Szclassname; Wincl.lpfnwndproc = windowprocedure; /* This function was called by Windows */Wincl.style = cs_dblclks; /* Catch double-clicks */wincl.cbsize = sizeof (wndclassex); /* Use default icon and Mouse-pointer */Wincl.hicon = LoadIcon (NULL, idi_application); WINCL.HICONSM = LoadIcon (NULL, idi_application); Wincl.hcursor = LoadCursor (NULL, Idc_arrow); Wincl.lpszmenuname = NULL; /* No Menu */wincl.cbclsextra = 0; /* No Extra bytes after the Window class */Wincl.cbwndextra = 0; /* structure or the window instance */* Use Windows's default colour as the background of the window */Wincl.hbrbackgro und =bk_brush; /* Register the window class, and if it fails quit the program */if (! RegisterClassEx (&WINCL)) return 0; /* The class is registered, let's create the program*/hwnd = CreateWindowEx (0,/* Extended possibilites for variation * /Szclassname,/* Classname */_t ("Tris"),/* Title Text */ws_overlappedwindow,/* Default window */Cw_usedefault,/* Wi Ndows decides the position */cw_usedefault,/* Where the window ends up on the screen */width+200,/* The Programs WIDTH */height+70,/* and HEIGHT in pixels */hwnd_desktop,/* The window is a child-window to DESKTOP */NULL,/* No Menu */ Hthisinstance,/* Program Instance Handler */NULL */No Window Creation Data */); /* Make the window visible in the screen */ShowWindow (hwnd, ncmdshow); /* Run the message loop. It'll run until GetMessage () returns 0 */ while (GetMessage (&messages, NULL, 0, 0)) {/* Translate Virtual-key messages into character messages */Translateme Ssage (&messages); /* Send message to Windowprocedure */DispatchMessage (&messages); }/* The program Return-value are 0-the value that PostQuitMessage () gave */return messages.wparam; }//Load 7 shapes int load_shape () {file* f=fopen ("Shapes.txt", "RB") from a file, if (f==null) {return-1;} for (int i=0; i<7; i++) { for (int j=0; j<4; J + +) {for (int k=0; k<4; k++) {if (fscanf (F, "%d", &shapes[i][j][k])!=1) {return-1;}}} Fclose (f); return 0; }//randomly generate a new shape void Give_new_shape () {int shape_num=rand ()%7; for (int. i=0; i<4; i++) {for (int j=0; j<4; J + +) {Shap E[I][J]=SHAPES[SHAPE_NUM][I][J]; }}}} void Add_score () {score+=100;}//Eliminate empty lattice rows void clear_up () {for (int i=row; i<=row+3; i++) {if (i>bottom) con Tinue; BOOL There_is_blank=false; for (int j=left; j<=right; J + +) {if (board[i][j]==0) {there_is_blank=true; break;}} if (!there_is_blank){Add_score (); for (int r=i, r>=1; r--) {for (int c=left; c<=right; C + +) {board[r][c]=board[r-1][c];}}} }}//Detect whether the shape is valid at the current position (i.e. whether it is coincident with a non-empty lattice) bool Is_legel () {for (int i=0; i<4; i++) {for (int j=0; j<4; J + +) {if (shape[i][j]= =1&&board[row+i][column+j]==1) {return false;}} } return true; The square void Rotate_matrix (int mn) {int** a=shape; int s=0; for (int n=mn; n>=1; n-=2) {n = (int. i=0), or counterclockwise). ; n-1; i++) {int t=a[s+i][s]; a[s+i][s]=a[s][s+n-i-1]; a[s][s+n-i-1]=a[s+n-i-1][s+n-1]; a[s+n-i-1][s+n-1]=a[s+n-1][s+i]; a[ s+n-1][s+i]=t; } s++; }}//Clockwise rotation of a square block of MN rerotate_matrix (int mn) {int** a=shape; int s=0; for (int n=mn; n>=1; n-=2) {for (int i=0; i<n-1; i++) {int t=a[s+i][s]; a[s+i][s]=a[s+n-1][s+i]; a[s+n-1][s+i]=a[s+n-i-1][s+n-1]; a[s+n-i-1][s+n-1]=a[s][s+n-i-1]; a[ s][s+n-i-1]=t; } s++; }}//displays a lattice void Paint_lattice (HDC hdc,int x,int y,int color) {if (x<top| | x>bottom| | y<left| | Y>right) {return;} x-=top; Y-=left; int left=Lattices_left+y*width; int right=lattices_left+y*width+width; int top=lattices_top+x*height; int bottom=lattices_top+x*height+height; Movetoex (Hdc,left,top, NULL); LineTo (Hdc,right,top); Movetoex (Hdc,left,top, NULL); LineTo (Hdc,left,bottom); Movetoex (Hdc,left,bottom, NULL); LineTo (Hdc,right,bottom); Movetoex (Hdc,right,top, NULL); LineTo (Hdc,right,bottom); SelectObject (hdc, Grey_brush); if (color==0) {SelectObject (hdc, White_brush);} Rectangle (Hdc,left,top,right,bottom); }//update interface, update only the RECT area (the lines in which the shape is located) void Update_ui (HWND hwnd) {static Rect rect; rect.left=lattices_left; rect.right=lattices _left+m*width+width; rect.top=lattices_top+ (row-1) *height; rect.bottom=lattices_top+ (row+4) *height; InvalidateRect (Hwnd,&rect, false); }//update interface, update the entire interface void Update_ui_all (HWND hwnd) {InvalidateRect (Hwnd,null, False);}//Draw interface void PAINT_UI (HDC hdc) {SETBK Color (Hdc,bkcolor); SelectObject (Hdc,hpen); Selection Brush Char score_str[20]; sprintf (Score_str, "score:%d", score); TextOut (hdc,10,10, Score_str,strlen (SCORE_STR)); sprintf (Score_str, "highest Scores:"); TextOut (Hdc,width+50,50,score_str,strlen (SCORE_STR)); for (int i=0; i<3; i++) {sprintf (Score_str, "%d", high_score[i]); TextOut (hdc,width+50,50+ (i+1) *20,score_str,strlen (SCORE_STR)); } for (int i=top, i<=bottom; i++) {for (int j=left; j<=right; J + +) {Paint_lattice (hdc,i,j,board[i][j]);}} for (int i=0; i<4; i++) {for (int j=0; j<4; J + +) {if (shape[i][j]==1) Paint_lattice (Hdc,row+i,column+j,shape[i][j]);}}} Rotates the current shape and updates the interface int Rotate_shape (HWND hwnd) {int mn=4; Rotate_matrix (MN); if (!is_legel ()) {Rerotate_matrix (MN);} Update_u I (HWND); } void Reset_rc () {row=0; column=mm/2-2;}//Read game highest data int load_scores (int* a) {file* f=fopen ("Scores.txt", "R"); if (f==n ULL) return-1; FSCANF (F, "%d%d%d", &a[0],&a[1],&a[2]); return 0; }//Initialize game data void Init_play () {load_scores (High_score); for (int i=0; i<nn; i++) {for (int j=0; j<mm; J + +) {Board[i] [J]=0; }} for (int i=0, i<n; i++) {for (int j=0; J< Left; J + +) {board[i][j]=1;}} for (int i=0, i<n; i++) {for (int j=right+1; j<mm; J + +) {board[i][j]=1;}} for (int i=bottom+1; i<nn; i++) {for ( int j=0; j<mm; J + +) {board[i][j]=1;}} RESET_RC (); score=0; Give_new_shape (); Is_pause=false; return; } bool Check_is_lose () {if (row==0) return true; return false;}//for the highest score and the rank of this score, if a new record is created returns true bool Sort_scores (int* a) {int TEMP=A[3]; for (int i=0, i<4; i++) {for (int j=0; j<3; J + +) {if (a[j]<a[j+1]) {int t=a[j]; a[j]=a[j+1]; a[j+1]=t;}}} if (t EMP>A[3]) return true; return false; }//write highest data int write_scores (int* a) {file* f=fopen ("Scores.txt", "w"), if (f==null) return-1; fprintf (F, "%d\n%d\n%d\n", a[ 0],A[1],A[2]); return 0; }//Save highest sub-data bool Save_score (HWND hwnd) {High_score[3]=score; bool Made_record=sort_scores (High_score); if (write_scores (High_score)!=0) {MessageBox (hwnd, "Write file error.) Program would exit. "," Error ", NULL); DestroyWindow (HWND); } return Made_record; } void Lose_game (HWND hwnd) {if (is_pause) RetuRN; Is_pause=true; Char message[200]= "You lose the game.\n"; Char title[50]= "Game over"; if (Save_score (hwnd)) {strcat (message, "You have made a new record.\n"); char score_str[100]; sprintf (Score_str, "the Highe St scores:\n%d\n%d\n%d\n ", high_score[0],high_score[1],high_score[2]); strcat (MESSAGE,SCORE_STR); } strcat (Message, "\nplay again?\n"); if (MessageBox (Hwnd,message,title,mb_yesno) ==idyes) {init_play (); Update_ui_all (hwnd);} else {exit (0);}} void Exit_game (HWND hwnd) {is_pause=true; char message[200]= ""; char title[50]= "exit"; if (Save_score (hwnd)) {strcat (mes Sage, "You have made a new record.\n"); Char score_str[100]; sprintf (Score_str, "the highest scores:\n%d\n%d\n%d\n", high_score[0],high_score[1],high_score[2]); strcat (MESSAGE,SCORE_STR); MessageBox (Hwnd,message,title,null); } exit (0); }//After the current shape has landed, update board void Shape_to_ground () {for (Int. i=0; i<4; i++) {for (int j=0; j<4; J + +) {board[row+i][column+ J]=SHAPE[I][J]==1?1:BOARD[ROW+I][COLUMN+J]; }}}//Shape drop int Move_down(HWND hwnd) {row++; if (!is_legel ()) {row--; if (Check_is_lose ()) {Lose_game (HWND); return 0;} shape_to_ground (); clear_up (); update _ui_all (HWND); RESET_RC (); Give_new_shape (); } update_ui (HWND); }//process parameter struct body struct Thread_arg {HWND arg_hwnd;}; Shape drop process to execute function void* down_thread_function (void * args) {Thread_arg *arg= (thread_arg*) args; HWND dhwnd=arg->arg_hwnd; while (true) {if (is_pause) {Sleep]; continue;} move_down (Dhwnd); Sleep (Long_sleep); }}//Initialize shape drop process int Init_down_thread (HWND hwnd) {int ret; pthread_t t; thread_arg *argp=new Thread_arg; argp->arg_hwnd =hwnd; Ret=pthread_create (&T,NULL,DOWN_THREAD_FUNCTION,ARGP); Delete ARGP; if (ret!=0) {return-1;} return 0; }//Initialize the game program int Init_game (HWND hwnd) {board=new int*[nn]; for (int i=0; i<nn; i++) {board[i]=new int[mm];} shape=new INT*[4]; for (int i=0; i<4; i++) {shape[i]=new int[4];} srand (Time (0)); if (Load_shape ()!=0) {MessageBox (hwnd, "Read file error. Program would exit. "," Error ", NULL); Exit (-1); } init_play (); Update_ui_all (HWND); if (Init_down_thread (HWND)!=0) {MessageBox (hwnd, "thread error. Program would exit. "," Error ", NULL); Exit (-1); } return 0; }//shape move around int move_lr (HWND hwnd,int lr) {int temp=column; if (lr==0) column--; else {column++;} if (!is_legel ()) {column =temp; } update_ui (HWND); } int Handle_key (hwnd Hwnd,wparam WPARAM) {if (wparam==vk_escape) {//esc exits Exit_game (hwnd);} if (wparam==vk_space) {//Space temporary Stop Is_pause=!is_pause; if (is_pause==true) {Sleep], return 0;} if (wparam==vk_up) {Rotate_shape (HWND);} if (Wparam==vk_down) {Move_down (H WND); } if (Wparam==vk_left) {MOVE_LR (hwnd,0);} if (Wparam==vk_right) {MOVE_LR (hwnd,1);} return 0; }/* This function was called by the Windows function DispatchMessage () */HWND hwnd; LRESULT CALLBACK Windowprocedure (HWND hwnd, UINT message, WPARAM WPARAM, LPARAM LPARAM) {static HDC hdc; static HDC HDCB Uffer; static Hbitmap hbitmap; Static Paintstruct PS; Switch (message) {/* Handle the messages * * Case Wm_create:init_game (hwnd); Break Case Wm_keydown:handle_key (Hwnd,wparam); Break Case Wm_destroy:exit_game (HWND); PostQuitMessage (0); /* Send a wm_quit to the message queue */break; Case WM_PAINT:HDC = BeginPaint (hwnd, &PS); PAINT_UI (HDC); EndPaint (hwnd, &PS); Break Default:/* For messages so we don ' t deal with */return DefWindowProc (HWND, message, WParam, LParam); } return 0; }
C + + make Tetris