Linux下用C++实现俄罗斯方块

本文实例为大家分享了C++实现俄罗斯方块游戏代码,供大家参考,具体内容如下

1.block.c

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <stdlib.h>
#include <setjmp.h>
#include <sys/time.h>
#include <string.h>
#include "block.h"
 
//init for globle
void
init_for_globle(void)
{
  x = X / 2 - 2;   // the first diamond appear postion
  flag_erase = 1;
  srand(getpid());  //srand
  num = rand() % 7;  // random appear first diamond
  mode = rand() % 4; // random appear first diamond mode
  color = rand() % 7 + 41;  // random first diamond color
 
  next_num = rand() % 7;
  next_mode = rand() % 4;
  save_color = rand() % 7 + 41;
 
  print_start_interface();  // print game start interface
// print_score();   // print init score 0
// print_level();   // print init level 1
}
 
//print start interface
void
print_start_interface(void)
{
  int x,y;
  printf("\33[2J");
  printf("\33[%d;%dH\33[32m分数:\33[0m",p_y + 10,p_x + 25);
  printf("\33[%d;%dH\33[32m等级:\33[0m",p_y + 14,p_x + 25);
  for (x = p_x,y = p_y; x <= 46; x++)
    printf("\33[%d;%dH\33[41m==\33[0m",y,x);
  for (x = p_x,y = p_y + 1; y <= 25; y++)
    printf("\33[%d;%dH\33[41m||\33[0m",x);
  for (x = p_x + 22,x);
  for (x = p_x + 36,x);
  for (x = p_x + 24,y = p_y + 8; x <= 44; x++)
    printf("\33[%d;%dH\33[41m--\33[0m",y = p_y + 21; x <= 46; x++)
    printf("\33[%d;%dH\33[41m==\33[0m",x);
  printf("\33[?25l");
  fflush(stdout);
}
 
//erase last diamonds
void
erase_last(void)
{
  int j,x1,y1,n;
  x1 = save_x + p_x + 2;
  for (j = 0,n = 0; j < 16; j++) {
    if (j / 4 >= shape[num][save_mode][16] && j % 4 == 0) {
      y1 = save_y + p_y + 1 + n;
      printf("\33[%d;%dH",x1);
      n++;
    }
    if (j / 4 >= shape[num][save_mode][16]
      && j % 4 >= shape[num][save_mode][17]) {
      if (shape[num][save_mode][j] == 0) {
        printf("\33[2C");
      }
      if (shape[num][save_mode][j] == 1) {
        printf(" ");
      }
    }
  }
  fflush(stdout);
}
 
//print modes shape
void
print_mode_shape(void)
{
  int j,n;
  int left_flag = 0;
  if (flag_erase == 0) {
    erase_last();
  }
  x1 = x + p_x + 2;
  for (j = 0,n = 0; j < 16; j++) {
    if (j / 4 >= shape[num][mode][16] && j % 4 == 0) {
      y1 = y + p_y + 1 + n;
      printf("\33[%d;%dH",x1);
      n++;
    }
    if (j / 4 >= shape[num][mode][16]
      && j % 4 >= shape[num][mode][17]) {
      if (shape[num][mode][j] == 0) {
        printf("\33[2C");
      }
      if (shape[num][mode][j] == 1) {
        printf("\33[%dm[]\33[0m",color);
      }
    }
    fflush(stdout);
  }
  printf("\33[0m");
  fflush(stdout);
  save_x = x;
  save_y = y;
  save_mode = mode;
  save_row = 4 - shape[num][mode][16];
  save_col = 4 - shape[num][mode][17];
  flag_erase = 0;
 
}
 
//store diamonds to matrix by color to flag
void
store_flag_color(void)
{
  int i,a = 0,b = 0;
  for (i = 0; i < 16; i++) {
    if (i / 4 >= shape[num][mode][16] && i % 4 == 0) {
      a++;
      b = 0;
    }
    if (i / 4 >= shape[num][mode][16]
      && i % 4 >= shape[num][mode][17]) {
      if (shape[num][save_mode][i] == 0) {
        b = b + 2;
      }
      if (shape[num][save_mode][i] == 1) {
        matirx[save_y + a - 1][save_x + b] = color;
        b++;
        matirx[save_y + a - 1][save_x + b] = color;
        b++;
      }
    }
  }
}
 
//print the save matrix
void
print_save_matrix(void)
{
  int i,j,n = 0;
  for (i = 0; i < Y; i++) {
    printf("\33[%d;%dH",i + p_y + 1,p_x + 2);
    for (j = 0; j < X; j++) {
      if (matirx[i][j] != 0) {
        n = (n + 1) % 2;
        fprintf(stdout,"\33[%dm",matirx[i][j]);
        (n == 1) ? printf("[") : printf("]");
      }
      if (matirx[i][j] == 0) {
        printf("\33[0m");
        printf(" ");
      }
      fflush(stdout);
    }
  }
}
 
// change shape
void
change_shape(void)
{
  int i,n;
  for (i = 0; i < save_row; i++) {
    if (num == 6) {
      n = 4;
    } else {
      n = 0;
    }
    if (((x + n) >= X - save_col * 2 && save_col < save_row) ||
      judge_by_color(x,(mode + 1) % 4) == 1) {
      return;
    }
  }
  mode = (mode + 1) % 4;
  fflush(stdout);
  print_mode_shape();
  fflush(stdout);
}
 
//move right
void
move_right(void)
{
  int i;
  if (x >= X - save_col * 2 || judge_by_color(x + 2,mode) == 1) {
    return;
  }
  x = x + 2;
  print_mode_shape();
  fflush(stdout);
}
 
// move left
void
move_left(void)
{
  int i;
  if (x <= 0 || judge_by_color(x - 2,mode) == 1) {
    return;
  }
  x = x - 2;
  print_mode_shape();
  fflush(stdout);
}
 
// move down
void
move_down()
{
  y++;
  if (y >= Y - save_row + 1 || judge_by_color(x,mode) == 1) {
    store_flag_color();
    game_over();
    y = 0;
    save_row = 0;
    save_col = 0;
    x = X / 2 - 2;
 
    num = next_num;
    mode = next_mode;
    color = save_color;
    next_num = random() % 7;
    next_mode = random() % 4;
    save_color = random() % 7 + 41;
    print_next();
    flag_erase = 1;
    destroy_line();
    fflush(stdout);
    return;
  }
  print_mode_shape();
  fflush(stdout);
}
 
 
void
fall_down()
{
  while (1) {
    y++;
    if (y >= Y - save_row + 1 || judge_by_color(x,mode) == 1) {
      store_flag_color();
      game_over();
      y = 0;
      save_row = 0;
      save_col = 0;
      x = X / 2 - 2;
 
      num = next_num;
      mode = next_mode;
      color = save_color;
      next_num = rand() % 7;
      next_mode = rand() % 4;
      save_color = rand() % 7 + 41;
      print_next();
      flag_erase = 1;
      destroy_line();
      fflush(stdout);
      return;
    }
    print_mode_shape();
    fflush(stdout);
  }
 
}
 
//erase next tip diamond
void
erase_next(void)
{
  int i,n = 0;
  for (i = 0; i < 4; i++) {
    printf("\33[%d;%dH",p_y + 3 + n,p_x + X + 7);
    n++;
    for (j = 0; j < 4; j++) {
      printf(" ");
    }
  }
  printf("\33[30;4H\33[?25l");
  fflush(stdout);
}
 
//print next tip diamond
void
print_next(void)
{
  int j,n = 0;
  erase_next();
  for (j = 0; j < 16; j++) {
    if (j / 4 >= shape[next_num][next_mode][16] && j % 4 == 0) {
      printf("\33[%d;%dH",p_x + X + 7);
      n++;
    }
    if (j / 4 >= shape[next_num][next_mode][16]
      && j % 4 >= shape[next_num][next_mode][17]) {
      if (shape[next_num][next_mode] == 0) {
        printf("\33[2C");
      }
      if (shape[next_num][next_mode][j] == 1) {
        printf("\33[%dm[]\33[0m",save_color);
      }
    }
  }
}
 
//print scores info
void
print_score(void)
{
  printf("\33[%d;%dH\33[31m%d\33[0m",p_x + X + 10,score);
  fprintf(stdout,"\33[%d;0H",p_y + 20 + 2);
}
 
//print grades info
void
print_level(void)
{
  printf("\33[%d;%dH\33[31m%d\33[0m",level);
  fprintf(stdout,p_y + 20 + 2);
}
 
//destroy a line or lines  
void
destroy_line(void)
{
  int i,full;
  int a,b,c;
  for (i = 0; i < Y; i++) {
    full = 1;
    for (j = 0; j < X; j++) {
      if (matirx[i][j] == 0) {
        full = 0;
      }
    }
    if (full == 1) {
      for (a = 0; a < i; a++) {
        for (b = 0; b < X; b++) {
          matirx[i - a][b] = matirx[i - a - 1][b];
        }
      }
      print_save_matrix();
      score = score + 100;
      if (score % LEVEL_SCORE == 0) {
        level = level + 1;
        if (level >= 9)
          level = 9;
        change_level();
        print_level();
 
      }
      print_score();
    }
  }
}
 
//change level,change rate  
void
change_level(void)
{
  switch (level) {
  case 1:
    setitimer(ITIMER_REAL,&level_01,NULL);
    break;
  case 2:
    setitimer(ITIMER_REAL,&level_02,NULL);
    break;
  case 3:
    setitimer(ITIMER_REAL,&level_03,NULL);
    break;
  case 4:
    setitimer(ITIMER_REAL,&level_04,NULL);
    break;
  case 5:
    setitimer(ITIMER_REAL,&level_05,NULL);
    break;
  case 6:
    setitimer(ITIMER_REAL,&level_06,NULL);
    break;
  case 7:
    setitimer(ITIMER_REAL,&level_07,NULL);
    break;
  case 8:
    setitimer(ITIMER_REAL,&level_08,NULL);
    break;
  case 9:
    setitimer(ITIMER_REAL,&level_09,NULL);
    break;
  default:
    break;
  }
}
 
//by the color to judge whether went across or not
int
judge_by_color(int x,int mode)
{
  int i,b = 0;
  for (i = 0; i < 16; i++) {
    if (i / 4 >= shape[num][mode][16] && i % 4 == 0) {
      a++;
      b = 0;
    }
    if (i / 4 >= shape[num][mode][16]
      && i % 4 >= shape[num][mode][17]) {
      if (shape[num][mode][i] == 0) {
        b = b + 2;
      }
      if (shape[num][mode][i] == 1) {
        if (matirx[a + y - 1][b + x] != 0) {
          return 1;
        } else
          b = b + 2;
      }
    }
 
  }
}
 
//control the diamonds shape by the key    
void
key_control(void)
{
  int ch,flag = 1;
  struct termios save,raw;
 
  tcgetattr(0,&save);
  cfmakeraw(&raw);
  tcsetattr(0,&raw);
  if (setjmp(env) == 0) {
    while (flag) {
      ch = getchar();
      if (ch == '\r') {
        fall_down();
      }
      if (ch == '\33') {
        ch = getchar();
        if (ch == '[') {
          ch = getchar();
          switch (ch) {
          case 'A':
            change_shape();
            break;
          case 'B':
            move_down();
            break;
          case 'C':
            move_right();
            break;
          case 'D':
            move_left();
            break;
          }
        }
      }
 
      if (ch == 'q' || ch == 'Q') {
        flag = 0;
      }
    }
    printf("\33[%d;%dH\33[31m-----game interrupt exit!-----\33[0m",p_y + Y + 3,p_x);
    printf("\33[%d;0H\33[?25h",p_y + Y + 4);
  }
  tcsetattr(0,&save);
}
 
//reach the top line,the game is over    
void
game_over(void)
{
  int i;
  for (i = 0; i < X; i++) {
    if (matirx[1][i] != 0) {
      printf
        ("\33[31m\33[%d;%dH-------game over!--------\33[0m",p_x);
      printf("\33[0m\33[?25h\33[%d;0H",p_y + Y + 4);
      longjmp(env,2);
    }
  }
}

2.block.h

#ifndef _BLOCK_H_
#define _BLOCK_H_
 
#define p_x 10      //init postion row;
#define p_y 5      //init postion col;
#define X 20          // game_window_size
#define Y 20
#define LEVEL_SCORE 500     // need scores to upgrade
 
 
jmp_buf env;
static int x,y;                   //  current diamonds postion
static int flag_erase;                  //  erase flag
static int num,mode,next_num,next_mode;        //  current and next diamonds
static int save_row,save_col,save_x,save_y,save_mode;//  save coordinate,save graph
static int color,save_color,flag_color;           //  save the color of the next diamonds
static int matirx[Y][X] = { 0 };             //  save diamonds' matrix
static int level = 1;                   //  game levels
static int score = 0;           //  game scores
 
typedef struct itimerval LEVEL;
static LEVEL level_00 = { {0,0},{0,0} };
static LEVEL level_01 = { {0,800000},{1,0} };
static LEVEL level_02 = { {0,500000},500000} };
static LEVEL level_03 = { {0,400000},300000} };
static LEVEL level_04 = { {0,300000},300000} };
static LEVEL level_05 = { {0,200000},300000} };
static LEVEL level_06 = { {0,150000},300000} };
static LEVEL level_07 = { {0,100000},300000} };
static LEVEL level_08 = { {0,80000 },300000} };
static LEVEL level_09 = { {0,60000 },300000} };
 
//three-dimensional for saving diamonds and diamonds' shape :
//first-dimensional for kind of diamonds-shape
//second-dimensional for alterable's mode
//third-dimensional for reality value of row and col
static const int shape[7][4][18] = {
               {{0,1,2,1},//    
                {0,2},//  []  []  [][][]   []
                {0,// [][][] [][]  []   [][]
                {0,2}},//     []        []
 
               {{0,//
                {0,//     []      [][]
                {0,//   [] []  [][][]  []
                {0,// [][][] [][] []    []
 
               {{0,//     [][]      []
                {0,// []    []  [][][]  []
                {0,1}},// [][][]  []    [] [][]
 
               {{0,// 
                {0,//  []
                {0,//  [][]   [][]
                {0,//    []  [][]
 
               {{0,//   []
                {0,//  [][]  [][]
                {0,//  []    [][]
 
               {{0,//   [][]
                {0,//   [][]
 
               {{0,3},3,//   []   [][][][]
                {0,//   [] 
                {0,0}}  //   []   
               };
 
void init_for_globle(void);
void print_start_interface(void);
void print_mode_shape(void);
void print_save_matrix(void);
void change_shape(void);
void move_left(void);
void move_right(void);
void move_down();
void fall_down();
void store_flag_color(void);
void key_control(void);
void erase_last(void);
void destroy_line(void);
void print_next(void);
void erase_next(void);
void change_level(void);
void print_score(void);
void print_level(void);
int judge_by_color(int x,int mode);
void game_over(void);
 
#endif

3.main.c

#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
#include <setjmp.h>
#include "block.h"
 
int
main(int argc,char **argv)
{
  init_for_globle(); //init for globle
  print_mode_shape(); //print first diamond 
  print_next();    //print next diamond
  setitimer(ITIMER_REAL,NULL);  //init one leve ;interval 800ms
  signal(SIGALRM,move_down); //diamond down base on the interval time
  key_control();   //using zhe key to play games
 
  return 0;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


一.C语言中的static关键字 在C语言中,static可以用来修饰局部变量,全局变量以及函数。在不同的情况下static的作用不尽相同。 (1)修饰局部变量 一般情况下,对于局部变量是存放在栈区的,并且局部变量的生命周期在该语句块执行结束时便结束了。但是如果用static进行修饰的话,该变量便存
浅谈C/C++中的指针和数组(二) 前面已经讨论了指针和数组的一些区别,然而在某些情况下,指针和数组是等同的,下面讨论一下什么时候指针和数组是相同的。C语言标准对此作了说明:规则1:表达式中的数组名被编译器当做一个指向该数组第一个元素的指针; 注:下面几种情况例外 1)数组名作为sizeof的操作数
浅谈C/C++中的指针和数组(一)指针是C/C++的精华,而指针和数组又是一对欢喜冤家,很多时候我们并不能很好的区分指针和数组,对于刚毕业的计算机系的本科生很少有人能够熟练掌握指针以及数组的用法和区别。造成这种原因可能跟现在大学教学以及现在市面上流行的很多C或者C++教程有关,这些教程虽然通俗易懂,
从两个例子分析C语言的声明 在读《C专家编程》一书的第三章时,书中谈到C语言的声明问题,《C专家编程》这本书只有两百多页,却花了一章的内容去阐述这个问题,足以看出这个问题的重要性,要想透彻理解C语言的声明问题仅仅看书是远远不够的,需要平时多实践并大量阅读别人写的代码。下面借鉴《C专家编程》书中的两个
C语言文件操作解析(一)在讨论C语言文件操作之前,先了解一下与文件相关的东西。一.文本文件和二进制文件 文本文件的定义:由若干行字符构成的计算机文件,存在于计算机系统中。文本文件只能存储文件中的有效字符信息,不能存储图像、声音等信息。狭义上的二进制文件则指除开文本文件之外的文件,如图片、DOC文档。
C语言文件操作解析(三) 在前面已经讨论了文件打开操作,下面说一下文件的读写操作。文件的读写操作主要有4种,字符读写、字符串读写、块读写以及格式化读写。一.字符读写 字符读写主要使用两个函数fputc和fgetc,两个函数的原型是: int fputc(int ch,FILE *fp);若写入成功则
浅谈C语言中的位段 位段(bit-field)是以位为单位来定义结构体(或联合体)中的成员变量所占的空间。含有位段的结构体(联合体)称为位段结构。采用位段结构既能够节省空间,又方便于操作。 位段的定义格式为: type [var]:digits 其中type只能为int,unsigned int,s
C语言文件操作解析(五)之EOF解析 在C语言中,有个符号大家都应该很熟悉,那就是EOF(End of File),即文件结束符。但是很多时候对这个理解并不是很清楚,导致在写代码的时候经常出错,特别是在判断文件是否到达文件末尾时,常常出错。1.EOF是什么? 在VC中查看EOF的定义可知: #def
关于VC+ʶ.0中getline函数的一个bug 最近在调试程序时,发现getline函数在VC+ʶ.0和其他编译器上运行结果不一样,比如有如下这段程序:#include &lt;iostream&gt;#include &lt;string&gt;using namespace std;int
C/C++浮点数在内存中的存储方式 任何数据在内存中都是以二进制的形式存储的,例如一个short型数据1156,其二进制表示形式为00000100 10000100。则在Intel CPU架构的系统中,存放方式为 10000100(低地址单元) 00000100(高地址单元),因为Intel CPU
浅析C/C++中的switch/case陷阱 先看下面一段代码: 文件main.cpp#includeusing namespace std;int main(int argc, char *argv[]){ int a =0; switch(a) { case ...
浅谈C/C++中的typedef和#define 在C/C++中,我们平时写程序可能经常会用到typedef关键字和#define宏定义命令,在某些情况下使用它们会达到相同的效果,但是它们是有实质性的区别,一个是C/C++的关键字,一个是C/C++的宏定义命令,typedef用来为一个已有的数据类型
看下面一道面试题:#include&lt;stdio.h&gt;#include&lt;stdlib.h&gt;int main(void) { int a[5]={1,2,3,4,5}; int *ptr=(int *)(&amp;aʱ); printf(&quot;%d,%d&quot;,*(
联合体union 当多个数据需要共享内存或者多个数据每次只取其一时,可以利用联合体(union)。在C Programming Language 一书中对于联合体是这么描述的: 1)联合体是一个结构; 2)它的所有成员相对于基地址的偏移量都为0; 3)此结构空间要大到足够容纳最&quot;宽&quo
从一个程序的Bug解析C语言的类型转换 先看下面一段程序,这段程序摘自《C 专家编程》:#include&lt;stdio.h&gt;int array[]={23,34,12,17,204,99,16};#define TOTAL_ELEMENTS (sizeof(array)/sizeof(ar
大端和小端 嵌入式开发者应该对大端和小端很熟悉。在内存单元中数据是以字节为存储单位的,对于多字节数据,在小端模式中,低字节数据存放在低地址单元,而在大端模式中,低字节数据存放在高地址单元。比如一个定义一个short型的变量a,赋值为1,由于short型数据占2字节。在小端模式中,其存放方式为0X40
位运算和sizeof运算符 C语言中提供了一些运算符可以直接操作整数的位,称为位运算,因此位运算中的操作数都必须是整型的。位运算的效率是比较高的,而且位运算运用好的话会达到意想不到的效果。位运算主要有6种:与(&amp;),或(|),取反(~),异或(^),左移(&gt;)。1.位运算中的类型转换位
C语言文件操作解析(四)在文件操作中除了打开操作以及读写操作,还有几种比较常见的操作。下面介绍一下这些操作中涉及到的函数。一.移动位置指针的函数 rewind函数和fseek函数,这两个函数的原型是:void rewind(FILE *fp); 将位置指针移动到文件首 int fseek(FILE
结构体字节对齐 在用sizeof运算符求算某结构体所占空间时,并不是简单地将结构体中所有元素各自占的空间相加,这里涉及到内存字节对齐的问题。从理论上讲,对于任何变量的访问都可以从任何地址开始访问,但是事实上不是如此,实际上访问特定类型的变量只能在特定的地址访问,这就需要各个变量在空间上按一定的规则排
C语言文件操作解析(二)C语言中对文件进行操作必须首先打开文件,打开文件主要涉及到fopen函数。fopen函数的原型为 FILE* fopen(const char *path,const char *mode) 其中path为文件路径,mode为打开方式 1)对于文件路径,只需注意若未明确给出绝