#include<iostream>
#include<graphics.h>
using namespace std;
class Plane
{
public:
Plane();
Plane(int x, int y, const char* imgURL,const char* imgURLY, int speed);//comst作用是什么?
void drawPlane();
void movePlane();
void keyDown(char userKey);
int& getx();
int& gety();
int& getspeed();
protected:
int x;
int y;
int speed;
IMAGE img[2];
};
#include"plane.h"
Plane:: Plane()
{
}
Plane::Plane(int x, int y,const char* imgURL,const char* imgURLY, int speed)
{
this->x = x;
this->y = y;
loadimage(img + 1, imgURL);
loadimage(img + 0, imgURLY);
this->speed = speed;
}
void Plane::drawPlane()
{
putimage(x, y, img + 0, SRCAND);
putimage(x, y, img + 1, SRCPAINT);
}
void Plane::keyDown(char userKey)
{
switch (userKey)
{
case'w':
case'W':
case 72:
if (y > 0)
this->y -= this->speed;//范围控制;
break;
case's':
case'S':
case 80:
if (y < 570)
this->y += this->speed;
break;
case'a':
case'A':
case 75:
if (x > -15)
this->x -= this->speed;
break;
case'd':
case'D':
case 77:
if(x<740)
this->x += this->speed;
break;
}
}
int& Plane::getx()
{
return x;
}
int& Plane::gety()
{
return y;
}
int& Plane::getspeed()
{
return speed;
}
void Plane::movePlane()
{
this->y += this->speed;
};
#include<graphics.h>
#include<conio.h>
#include"plane.h"
#include<time.h>
#include<list>
using namespace std;
char planeName1[2][20] = { "resources\\1.bmp","resources\\1y.bmp" };
char planeName2[2][20] = { "resources\\2.bmp","resources\\2y.bmp" };
char planeName3[2][20] = { "resources\\3.bmp","resources\\3y.bmp" };
int main()
{
srand((unsigned int)time(NULL));
initgraph(800, 600);
IMAGE background;
loadimage(&background,"resources\\background.bmp");
Plane *pRole=new Plane(300,600-70,"resources\\role.bmp","resources\\roly.bmp",10);
list<Plane*>myPlane;//链表创建
list<Plane*>::iterator iterPlane;
Plane* pOject = NULL;
while (1)
{
BeginBatchDraw();//一个封装的双缓存:双缓存讲解,所有的绘图都不再显示在屏幕上,而是在内存中进行
putimage(0, 0, &background);
if (myPlane.size() < 3)
{
int pos = rand() % 3;
switch (pos)
{
case 0:
pOject = new Plane(rand() % 3* 100, -200, planeName1[0], planeName1[1], 1);
break;
case 1:
pOject = new Plane(rand() % 3 * 150, -100, planeName2[0], planeName2[1], 1);
break;
case 2:
pOject = new Plane(rand() % 3 *200 , -300, planeName3[0], planeName3[1], 1);
break;
}
myPlane.push_back(pOject);//
}
pRole->drawPlane();
if (_kbhit())//判断是否存在输入
{
char userKey = _getch();
pRole->keyDown(userKey);
}
for (iterPlane = myPlane.begin(); iterPlane!=myPlane.end(); iterPlane++)
{
(*iterPlane)->drawPlane();
(*iterPlane)->movePlane();
}
for (iterPlane = myPlane.begin(); iterPlane != myPlane.end(); iterPlane++)
{
if ((*iterPlane)->gety() >= 800)
{
iterPlane=myPlane.erase(iterPlane);
if (iterPlane == myPlane.end())
break;
}
}
EndBatchDraw();//之前所有在内存中绘图的成品将一并展示在屏幕中
}
_getch();
closegraph();
return 0;
}
keyDown(userKey)那部分为什么 X,Y的变化都牵扯到speed?第一版是Plane.h 第二版是Plane.cpp,最后面是原函数