processing圖形化程式設計例項:打飛機遊戲
阿新 • • 發佈:2019-02-19
接上篇面向物件程式設計的思想寫一個考試的遊戲例項:打飛機
要求:地上一個可平動的加農炮,可發射數量有限的炮彈。天上有個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); font=loadFont("font.vlw"); textFont(font); 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); } }