C + + make Tetris _c language

Source: Internet
Author: User
Tags getmessage message queue sprintf textout

Origin:

It feels good to play Codeblocks's own Tetris, but there are time limits. So I want to write another one.

Program Effect:

Main content:

There is a board array in the program, which has the parts to display, there are not displayed parts, the parts that do not appear are stored 1.

The following figure:

Shape is saved with a 4*4 array (shape). Such as:

0 0 0 0
0 1 0 0
1 1 1 0
0 0 0 0

In addition, save the position of the upper-left corner of the shape array in board with the variable row and column.

Each drop or move around, first change row and column, and then detect the current row and column, Shape is coincident with 1 of the lattice, if there is a coincidence, the shape is out of bounds or reached the lowest point, to restore the row and column values. In addition, if it is falling, place the shape on the board and produce a new shape.

Rotate, the shape array is rotated first, then the detection is coincident, if there is coincidence, then the reverse rotation back.

Code:

#if defined (Unicode) &&!defined (_unicode) #define _UNICODE #elif defined (_unicode) &&!defined (Unicode ) #define UNICODE #endif #include <tchar.h> #include <windows.h> #include <pthread.h> #include <stdi o.h> #include <time.h>/*-----------------macro Definition--------------------------------------------------------* * Define WIDTH 180 #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};//top three elements store highest score, last element stores this score static int **shape;//the current shape static int **board; static int m=15;//Display the number of columns static int n= 30;//displayed number of rows static int mm=m+8;//board number of columns static int nn=n+4;//board number of rows static int left=4;//the leftmost column static int right=left+m-1
;//The most right column of static int top=0;//display the last column of static int bottom=n-1;//display the last list of static int score=0; static int row=0;//shape is in 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;//left white static int lattices_left=20;//left white static int width=width/m;//width of each lattice static int height = (height-lattices_top)/n;//the height of each lattice/*-----------------
function-----------------------------------------------------------*/void Add_score ();
BOOL Check_is_lose ();
void Clear_up ()//Eliminate void* down_thread_function (void * args) without empty grid;//shape drop process to perform 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 ()//detect 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 shape void Lose_game from file (HWND
HWND); int Move_down (HWND hwnd);/Shape drops int move_lr (HWND hwnd,int LR);/shape moves around void Paint_lattice (HDC hdc,int x,int y,int color);/shows a lattice void paint_ui (HDC
HDC);//Draw interface void Reset_rc (); void Rerotate_matrix (int mn);//clockwise rotate a matrix void Rotate_matrix (int mn) with a row number of MN;/counterclockwise rotate a matrix int rotate_shape with a row number of MN (HWND HWND); Rotate the current shape and update the interface bool Save_score (HWND hwnd);//save highest cent data void Shape_to_ground ()//After the current shape Lands, update board bool Sort_scores ( Int* a); The highest score and this score are sorted, and if a new record is created, return true void UPDATE_UI (HWND hwnd);/update interface, update only the Rect region (the rows where the shape is located) void Update_ui_all (hwnd HWND);//update interface, update the entire interface int write_scores (int* a);//write Highest score/* Declare Windows procedure/lresult CALLBACK windowprocedu

Re (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, in        T ncmdshow) {HWND hwnd;      /* This are the handle for our Windows/MSG messages; /* Here messages to the applicationAre 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 ' default colour as the background of the window * * * * WINCL.HBRBAC
  Kground =bk_brush; /* Register the window class, and if it fails quit the program */if (!

  RegisterClassEx (&AMP;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,/* Windows decides the position * * cw_usedefault, * where the window ends Up on the screen */width+200,/* The programs WIDTH/height+70,/* and HEIGHT in pixel S/hwnd_desktop,/* The window is a child-window to DESKTOP/NULL,/* No menu */hth

  Isinstance,/* Program Instance Handler * * * NULL/No Window creation Data * *);

  /* Make the Windows visible on the screen * * * * * ShowWindow (hwnd, ncmdshow); /* Run the message loop. It would run until GetMessage () returns 0 */while (GetMessage (&messages, NULL, 0, 0)) {/* Translate Virtual-ke Y messages into character messages * * TranslatemessaGE (&messages);
  /* Send Message to Windowprocedure * * DispatchMessage (&messages);
}/* The program Return-value was 0-the value that PostQuitMessage () gave */return messages.wparam;
  ///Load 7 shapes int load_shape () {file* f=fopen ("Shapes.txt", "RB") from the 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 + +) {Shape[i][j]=shapes[shape_num][i][j]; }} void Add_score () {score+=100}//eliminate row void without empty grid clear_up () {for (int i=row; i<=row+3; i++) {if (i>
    BOTTOM) continue;
    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 (that is, whether the non-empty grid is coincident) 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;
  //counterclockwise rotate a matrix void Rotate_matrix (int mn) {int** a=shape with a row number of MN;
  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][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 rotate a matrix void Rerotate_matrix (int mn) {int** a=shape with a row number of MN;
  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++; }//show 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 to update only the RECT area (the rows where 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) {S
  Etbkcolor (Hdc,bkcolor); SelectObject (Hdc,hpen);
  Select 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)); (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]);
  }}//rotate the current shape and update the interface int Rotate_shape (HWND hwnd) {int mn=4;
  Rotate_matrix (MN);
  if (!is_legel ()) {Rerotate_matrix (MN);
} update_ui (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==null) 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;
    (int i=0; i<n; i++) {for (int j=0; j<left; J + +) {board[i][j]=1;
    (int i=0; i<n; i++) {for (int j=right+1; j<mm; J + +) {board[i][j]=1;
    (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;
  The highest score and this score are sorted, and if a new record is created, return 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 (Temp>a[3]) return true;
return false;
  //write highest score 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 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 highest 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 (message, "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[ro
    W+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 structure body struct Thread_arg {HWND arg_hwnd;}; Shape drop process The function to execute void* down_thread_function (void * args) {ThreaD_arg *arg= (thread_arg*) args;
  HWND dhwnd=arg->arg_hwnd;
      while (true) {if (Is_pause) {sleep (300);
    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 (&AMP;T,NULL,DOWN_THREAD_FUNCTION,ARGP);
  Delete ARGP;
  if (ret!=0) {return-1;
return 0;
  }//initialization game 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 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 exit Exit_game (HWND);
  } if (Wparam==vk_space) {//Space paused is_pause=!is_pause;
    } if (is_pause==true) {sleep (300);
  return 0;
  } if (wparam==vk_up) {Rotate_shape (HWND);
  } if (Wparam==vk_down) {Move_down (HWND);
  } if (Wparam==vk_left) {MOVE_LR (hwnd,0);
  } if (wparam==vk_right) {MOVE_LR (hwnd,1);
return 0;
}/* This function is called by the Windows function DispatchMessage ()/HWND hwnd;
  LRESULT CALLBACK Windowprocedure (HWND hwnd, UINT message, WPARAM WPARAM, LPARAM LPARAM) {static HDC HDC;
  Static HDC Hdcbuffer;
  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, &AMP;PS);
    PAINT_UI (HDC);
    EndPaint (hwnd, &AMP;PS);
  Break
  Default:/* For messages so we don ' t deal with/return DefWindowProc (HWND, message, WParam, LParam);
return 0;
 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.