首页 > 未分类 > 来来来,打飞机游戏
2018
09-04

来来来,打飞机游戏

要求:地上一个可平动的加农炮,可发射数量有限的炮弹。天上有个random高度的飞机,以恒定速度循环飞。当炮弹击中飞机时,加5发炮弹,加100分。炮弹耗光后游戏结束。

首先进行面向对象分析,分析实体个数,实体包含的属性和方法。从要求描述中可以看出有三个实体,加农炮,炮弹和飞机。

炮弹:属性:坐标,标志量判断是否被发射。方法:飞行(被发射后坐标开始持续变化,并且改变标志量)。绘制(三个实体都需要这个方法,将自己绘制到屏幕上)。

加农炮:属性:坐标。方法:发射炮弹(遍历炮弹,如果有没被发射的,则发射)。绘制。

飞机:属性:坐标,标志量判断是否被击中。方法:飞行。击中判断(遍历所有炮弹,判断距离)。绘制。

然后就是使用mousePressed和keyPressed响应鼠标和键盘了。

操作:鼠标控制炮左右移动,左键开火,如果击中,则飞机加速。’q‘和‘e’可以更改飞机速度。r键重置。

代码如下所示:

//use mouse to control the cannon
//mouse click to shoot
//’p’,’q’ to increase or decrease the speed
//’r’ to reset
//when you hit the plane, you get 3 bullet and 100 points
// for reward
int remain=20;
int credit=0;
int hit=0;
PFont font;
class plane
{
int x;
int y;
int flag;
int speed;
plane(int x,int y)
{
this.x=x;
this.y=y;
speed=3;
flag=-1;
}
void fly()
{
if(flag==-1)
{
x+=speed;
if(x>=600)
{
x-=600;
y=(int)random(20,300);
}
}
if(flag==1)
{
flag=-1;
x=0;
speed++;
}
}
void crash(cannonball c)
{
if(dist(x,y,c.x,c.y)<30)
{
credit+=100;
flag=1;
hit=1;
}
}
void display()
{
if(x<600)
{
fill(20);
rect(x,y,60,20);
ellipse(x+15,y,10,20);
ellipse(x+15,y+20,10,20);
}
}
}
class cannonball
{
int x;
int y;
int flag;
cannonball()
{
x=600;
y=600;
flag=1;//can be fired
}
void fire(int x,int y)
{
this.x=x;
this.y=y;
flag=-1;//fired
}
void fly()
{
if(flag==-1) y-=5;
}
void display()
{
if(y<600)
{
fill(100);
ellipse(x,y,20,20);
}
}
}
class cannon
{
int x;
cannon(int x)
{
this.x=x;
}
void display()
{
fill(0);
rect(mouseX,580,40,20);
rect(mouseX+10,560,20,40);
}
void fire(cannonball c)
{
c.fire(mouseX,580);
}
}
cannon a=new cannon((int)random(20,500));
cannonball[] c=new cannonball[20];
plane p=new plane(0,(int)random(20,200));
void setup()
{
size(600,600);
smooth();
background(255);
for(int i=0;i<20;i++)
{
c[i]=new cannonball();
}
}
void keyPressed()
{
if(key==’r’)
{
remain=20;
credit=0;
for(int i=0;i<20;i++)
c[i]=new cannonball();
p.flag=-1;
p.speed=3;
}
if(key==’e’) p.speed+=3;
if(key==’q’)
{
if(p.speed<=3) return;
else p.speed-=3;
}
}
void mousePressed()
{
int i=0;
for(i=0;i<20;i++)
{
if(c[i].flag==1) break;
}
if(i==20) return;
a.fire(c[i]);
remain–;
}
void draw()
{
background(255);
a.display();
for(int i=0;i<20;i++)
{
if(c[i].flag==-1)
{
c[i].fly();
c[i].display();
}
}
for(int i=0;i<20;i++)
{
p.crash(c[i]);
}
p.fly();
p.display();
if(hit==1)
{
hit=0;
int j=5;
for(int i=0;i<20;i++)
{
if(c[i].flag==-1)
{
c[i]=new cannonball();
j–;
remain++;
if(j==0) break;
}
}
}
textSize(20);
text(“remain: “+remain,500,50);
text(“credit: “+credit,500,100);
if(remain==0)
{
textSize(50);
text(“run out of ammo…”,100,150);
text(“final score is: “+credit,100,220);
text(“press ‘r’ to restart..”,100,280);
}

}
本文转自网络,版权归原作者,如果您觉得不好,请联系我删除!
微信公众号:processing与arduino



最后编辑:
作者:xiaoxiongmao
什么都不会的小熊猫

来来来,打飞机游戏》有 4 条评论

留下一个回复

你的email不会被公开。