热门标签 | HotTags
当前位置:  开发笔记 > 开发工具 > 正文

C++制作俄罗斯方块

俄罗斯方块写过好几次了,每次的感觉都不一样,都有新的收获。就像达芬奇画鸡蛋一样,虽然都是画同样的鸡蛋,但是每次都有不同的收获。 

缘起:

  在玩Codeblocks自带的俄罗斯方块时觉得不错,然而有时间限制。所以想自己再写一个。

程序效果:

主要内容:

  程序中有一个board数组,其中有要显示的部分,也有不显示的部分,不显示的部分都存储1。

  如下图:

  shape采用4*4数组(shape)保存。如:

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

  另外用变量row和column保存shape数组左上角在board中的位置。

  每次下落或左右移动,先对row和column做出改变,然后检测当前row和column下,shape是否重合了为1的格子,如果有重合,就说明shape出界了或者到达下落最低点,则要恢复row和column值。另外,如果是下落,还要将shape放在board上,并产生新的shape。

  旋转时,先对shape数组进行旋转操作,然后检测重合,如果有重合,则反向旋转回来。

代码:

#if defined(UNICODE) && !defined(_UNICODE)
#define _UNICODE
#elif defined(_UNICODE) && !defined(UNICODE)
#define UNICODE
#endif

#include 
#include 
#include 
#include 
#include 
/*-----------------宏定义--------------------------------------------------------*/
#define WIDTH 180
#define HEIGHT 400
#define LONG_SLEEP 300
#define BKCOLOR RGB(238,238,238)//背景色
/*-----------------变量----------------------------------------------------------*/
static int shapes[7][4][4];//存储7个形状
static int high_score[4]= {0,0,0,0};//前三个元素存储最高分,最后一个元素存储此次得分
static int **shape;//当前形状
static int **board;
static int M=15;//显示的列数
static int N=30;//显示的行数
static int MM=M+8;//board的列数
static int NN=N+4;//board的行数
static int LEFT=4;//显示的最左一列
static int RIGHT=LEFT+M-1;//显示的最右一列
static int TOP=0;//显示的最上一列
static int BOTTOM=N-1;//显示的最下一列
static int score=0;
static int row=0;//形状所在行
static int column=MM/2;//形状坐在列
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;//上面留白
static int lattices_left=20;//左侧留白
static int width=WIDTH/M;//每个格子的宽度
static int height=(HEIGHT-lattices_top)/N;//每个格子的高度
/*-----------------函数-----------------------------------------------------------*/
void add_score() ;
bool check_is_lose() ;
void clear_up() ;//消除没有空格子的行
void* down_thread_function(void * args) ;//形状下落进程要执行的函数
void exit_game(HWND hwnd) ;
void give_new_shape() ;//随机生成一个新形状
int handle_key(HWND hwnd,WPARAM wParam) ;
int init_down_thread(HWND hwnd) ;//初始化形状下落进程
int init_game(HWND hwnd) ;//初始化游戏程序
void init_play() ;//初始化游戏数据
bool is_legel() ;//检测形状在当前位置是否合法(即是否重合了非空的格子)
int load_scores(int* a) ;//读取游戏最高分数据
int load_shape() ;//从文件中加载7个形状
void lose_game(HWND hwnd) ;
int move_down(HWND hwnd) ;//形状下落
int move_lr(HWND hwnd,int lr) ;//形状左右移动
void paint_lattice(HDC hdc,int x,int y,int color) ;//显示一个格子
void paint_UI(HDC hdc) ;//画界面
void reset_rc() ;
void rerotate_matrix(int mn) ;//顺时针旋转一个行列数为mn的方阵
void rotate_matrix(int mn) ;//逆时针旋转一个行列数为mn的方阵
int rotate_shape(HWND hwnd) ;//旋转当前形状并更新界面
bool save_score(HWND hwnd) ;//保存最高分数据
void shape_to_ground() ;//当前形状落地之后,更新board
bool sort_scores(int* a) ;//对最高分和此次得分排序,若创造新纪录则返回true
void update_UI(HWND hwnd) ;//更新界面,仅更新Rect区域(形状所在的那几行)内
void update_UI_all(HWND hwnd) ;//更新界面,更新整个界面
int write_scores(int* a) ;//写最高分数据




/* 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;        /* This is the handle for our window */
  MSG messages;      /* Here messages to the application are saved */
  WNDCLASSEX wincl;    /* Data structure for the windowclass */

  /* The Window structure */
  wincl.hInstance = hThisInstance;
  wincl.lpszClassName = szClassName;
  wincl.lpfnWndProc = WindowProcedure;   /* This function is 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.hbrBackground =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,    /* Windows 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 on the screen */
  ShowWindow (hwnd, nCmdShow);

  /* Run the message loop. It will run until GetMessage() returns 0 */
  while (GetMessage (&messages, NULL, 0, 0)) {
    /* Translate virtual-key messages into character messages */
    TranslateMessage(&messages);
    /* Send message to WindowProcedure */
    DispatchMessage(&messages);
  }

  /* The program return-value is 0 - The value that PostQuitMessage() gave */
  return messages.wParam;
}
//从文件中加载7个形状
int load_shape() {
  FILE* f=fopen("shapes.txt","rb");
  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;
}
//随机生成一个新形状
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;
}
//消除没有空格子的行
void 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];
        }
      }
    }
  }
}
//检测形状在当前位置是否合法(即是否重合了非空的格子)
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;
}
//逆时针旋转一个行列数为mn的方阵
void rotate_matrix(int mn) {
  int** a=shape;
  int s=0;
  for(int n=mn; n>=1; n-=2) {
    for(int i=0; i=1; n-=2) {
    for(int i=0; iBOTTOM||yRIGHT) {
    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);
}
//更新界面,仅更新Rect区域(形状所在的那几行)内
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) ;
}
//更新界面,更新整个界面
void update_UI_all(HWND hwnd) {
  InvalidateRect (hwnd,NULL, false) ;
}
//画界面
void paint_UI(HDC hdc) {
  SetBkColor(hdc,BKCOLOR);
  SelectObject(hdc,hPen); //选用画笔
  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]);
    }
  }
}
//旋转当前形状并更新界面
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;
}
//读取游戏最高分数据
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;
}
//初始化游戏数据
void init_play() {
  load_scores(high_score);
  for(int i=0; ia[3])return true;
  return false;
}
//写最高分数据
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;
}
//保存最高分数据
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 will 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&#63;\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);
}
//当前形状落地之后,更新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&#63;1:board[row+i][column+j];
    }
  }
}
//形状下落
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);
}
//进程参数结构体
struct thread_arg {
  HWND arg_hwnd;
};
//形状下落进程要执行的函数
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);
  }
}
//初始化形状下落进程
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;
}
//初始化游戏程序
int init_game(HWND hwnd) {
  board=new int*[NN];
  for(int i=0; i


推荐阅读
  • 本文内容为asp.net微信公众平台开发的目录汇总,包括数据库设计、多层架构框架搭建和入口实现、微信消息封装及反射赋值、关注事件、用户记录、回复文本消息、图文消息、服务搭建(接入)、自定义菜单等。同时提供了示例代码和相关的后台管理功能。内容涵盖了多个方面,适合综合运用。 ... [详细]
  • 本文详细介绍了GetModuleFileName函数的用法,该函数可以用于获取当前模块所在的路径,方便进行文件操作和读取配置信息。文章通过示例代码和详细的解释,帮助读者理解和使用该函数。同时,还提供了相关的API函数声明和说明。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • windows便签快捷键_用了windows十几年,没想到竟然这么好用!隐藏的功能你知道吗?
    本文介绍了使用windows操作系统时的一些隐藏功能,包括便签快捷键、截图功能等。同时探讨了windows和macOS操作系统之间的优劣比较,以及人们对于这两个系统的不同看法。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • 本文是一位90后程序员分享的职业发展经验,从年薪3w到30w的薪资增长过程。文章回顾了自己的青春时光,包括与朋友一起玩DOTA的回忆,并附上了一段纪念DOTA青春的视频链接。作者还提到了一些与程序员相关的名词和团队,如Pis、蛛丝马迹、B神、LGD、EHOME等。通过分享自己的经验,作者希望能够给其他程序员提供一些职业发展的思路和启示。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • 本文介绍了在Hibernate配置lazy=false时无法加载数据的问题,通过采用OpenSessionInView模式和修改数据库服务器版本解决了该问题。详细描述了问题的出现和解决过程,包括运行环境和数据库的配置信息。 ... [详细]
  • Win10下游戏不能全屏的解决方法及兼容游戏列表
    本文介绍了Win10下游戏不能全屏的解决方法,包括修改注册表默认值和查看兼容游戏列表。同时提供了部分已经支持Win10的热门游戏列表,帮助玩家解决游戏不能全屏的问题。 ... [详细]
  • 如何在联想win10专业版中修改账户名称
    本文介绍了在联想win10专业版中修改账户名称的方法,包括在计算机管理中找到要修改的账户,通过重命名来修改登录名和属性来修改显示名称。同时指出了windows10家庭版无法使用此方法的限制。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • Windows下配置PHP5.6的方法及注意事项
    本文介绍了在Windows系统下配置PHP5.6的步骤及注意事项,包括下载PHP5.6、解压并配置IIS、添加模块映射、测试等。同时提供了一些常见问题的解决方法,如下载缺失的msvcr110.dll文件等。通过本文的指导,读者可以轻松地在Windows系统下配置PHP5.6,并解决一些常见的配置问题。 ... [详细]
author-avatar
chenyanni1030_430
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有