linux环境下环境下C++实现俄罗斯方块实现俄罗斯方块
本文实例为大家分享了C++实现俄罗斯方块的具体代码,供大家参考,具体内容如下
本程序的运行环境是linux,用到了多线程。创建了一个用来绘图的线程和一个获取按键的线程。程序中有一些需要改善的地
方,比如336-338行定义的全局变量以及声明的对象。本来声明的Block和Table对象应该在main函数里面,然后将这两个对象
作为参数传递给线程函数getkey。但是好像只能传递一个对象参数给线程函数。希望高手能够对程序进行改进。
ps:由于用到了多线程,而pthread不是linux的默认库,所以编译的时候需要指定线程库。即:g++ -o block -lpthread
block.cpp
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <time.h>
#include<termios.h>
#include<fcntl.h>
#define TABLE_SIZE 20
#define BLOCK_SIZE 4
#define SLEEP_TIME 500
using namespace std;
struct grid{int x; int y;}; //坐标
/////////////////////Block 类//////////////////////
class Block
{
public:
enum direct{UP, DOWN, LEFT, RIGHT}; //定义方向
grid g[BLOCK_SIZE]; //方块的坐标信息
void def_block(grid g1, grid g2, grid g3, grid g4); //定义方块
void rotate(); //旋转方块
void move(int dir); //移动方块
void set_cen(grid g); //设置方块旋转中心
grid get_cen(); //获取方块旋转中心
void set_type(int t); //设置方块种类
int get_type(); //获取方块种类
void back(); //旋转还原
void creat_block(int x, int y); //随机生成方块
private:
grid center; //方块旋转中心
int type; //方块类型
};
void Block::def_block(grid g1, grid g2, grid g3, grid g4) {
g[0]=g1; g[1]=g2; g[2]=g3; g[3]=g4;
}
void Block::rotate() {
int x, y, i=0;
for(i; i<=3; i++) {
x=g[i].x-center.x; y=g[i].y-center.y;
g[i].x=center.x+y; g[i].y=center.y-x;
}
}
void Block::move(int dir) {
int d=dir, i=0;
switch(d) {
case UP: {
for(i; i<=3; i++) g[i].y++;
center.y++; break;