在vs上写了一个俄罗斯方块的小游戏,输出画面就靠windows.h 下面上代码。
首先写一个坐标类,方便后面的操作
#ifndef POINT_H
#define POINT_H
//坐标类
class Point
{
public:
Point(int x = 0, int y = 0) : m_x(x), m_y(y){};
~Point() {};
Point& operator=(const Point &p)
{
m_x = p.m_x;
m_y = p.m_y;
return *this;
}
void Set(const int x,const int y) {m_x = x;m_y = y;}
void SetX(const int x) { m_x = x; }
void SetY(const int y) { m_y = y; }
int GetX() const { return m_x; }
int GetY()const { return m_y; }
private:
int m_x;
int m_y;
};
#endif
再创建一个设置类,用来管理游戏中的数值。因为这些数值(分数、游戏速度等)是伴随着整个游戏过程的,所以设为静态
#include <list>
#ifndef SETTING_H
#define SETTING_H
using namespace std;
//数值设定类,用于计算分数和速度等
class Setting
{
public:
static int GetSumScore() { return m_SumScore; }
static void AddSpeed() { m_GameSpeed -= 3; }
static void AddScore() { m_SumScore++; }
static int GetGameSpeed() { return m_GameSpeed; }
static void HalfSpeed() { m_GameSpeed /= 2; }
static void DoubleSpeed(){ m_GameSpeed *= 2; }
private:
static int m_GameSpeed; //游戏速度,数字越小速度越快
static int m_SumScore; // 分数
};
#endif
#include "Setting.h"
int Setting::m_GameSpeed = 500;
int Setting::m_SumScore = 0;
创建一个Object类,是所有游戏对象都要继承的父类
#ifndef OBJECT
#define OBJECT
#include <list>
#include"Point.h"
#include<iostream>
#include<windows.h>
#include<time.h>
#include<conio.h>
using namespace std;
//物体类,一切游戏对象的基类
class Object
{
public:
virtual void Display() = 0;//输出画面
virtual void SetDisappear() = 0;//清除画面
protected:
Point m_Position;
};
#endif
然后是方块类,是指组成一个整体形状的每一个小方块
#ifndef SINGLE_BOX
#define SINGLE_BOX
#include"Object.h"
//小方块类
class SingleBox :Object
{
private:
int m_color;
public:
SingleBox() {}
SingleBox(Point pos, int color)
{
m_Position = pos;
m_color = color;
}
~SingleBox(){}
void Display();//输出小方块
void SetDisappear();//删除小方块
int GetBoxX() const{ return m_Position.GetX(); }
int GetBoxY()const{ return m_Position.GetY(); }
};
#endif
#include"SingleBox.h"
void SingleBox:: Display()
{
COORD pos;
pos.X = m_Position.GetX();
pos.Y = m_Position.GetY();
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), m_color);
cout << "■";
}
void SingleBox::SetDisappear()
{
COORD pos;
pos.X = m_Position.GetX();
pos.Y = m_Position.GetY();
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
cout << " ";
}
小方块类写好后,就可以写组合形状的类了,它包含一个存储小方块的数组,因为每个形状由四个小方块组成
#ifndef COMBO_BOX
#define COMBO_BOX
#include"SingleBox.h"
enum Type { A, B, C, D, E};//一共五种组合方块
enum Form { a, b, c, d };//每个组合方块最多四种形态
enum Dir { LEFT, RIGHT ,EMPTY};
//组合方块类
class ComboBox :Object
{
private:
SingleBox m_ComBox[4];//每个组合方块由四个小方块组成
Type m_Type;
Form m_Form;
Dir m_Direction;
int m_XDis;//每输出一个方块,x轴占两个坐标(y轴只占一个)
public:
ComboBox(Point pos, Type);
~ComboBox(){}
Type GetType()const{return m_Type;}
void SetDirection(const Dir dir) {