版本:写出爆炸类,实现爆炸功能
1.爆炸类创建及测试:
public class Explode {
int x,y;
private boolean live = true;
private TankClient tc;
int[] diameter = {4,6,12,19,26,32,50,30,14,5};
int step = 0;
public Explode(int x,int y,TankClient tc){
this.x=x;
this.y=y;
this.tc=tc;
}
public void draw(Graphics g){
if(!live) return;
if(step== diameter.length) {
live=false;
step = 0;
return;
}
Color c = g.getColor();
g.setColor(Color.ORANGE);
g.fillOval(x, y, diameter[step], diameter[step]);
g.setColor(c);
step++;
}
}
然后在主类中创建对象,测试爆炸:
Explode e = new Explode(122,123,this);
public void paint(Graphics g) {
g.drawString("missiles count:"+missiles.size(), 10,50);
for (int i = 0; i < missiles.size(); i++) {
Missile m = missiles.get(i);
m.draw(g);
m.hitTank(enemyTank);
}
e.draw(g);
myTank.draw(g);
enemyTank.draw(g);
}
2.爆炸很多,应该写在坦克类中(list)
List<Missile> missiles = new ArrayList<Missile>(); //泛型 删加 效率相对高
List<Explode> explodes = new ArrayList<Explode>();
同样,利用循环创建爆炸对象
public void paint(Graphics g) {
g.drawString("missiles count:"+missiles.size(), 10,50);
for (int i = 0; i < missiles.size(); i++) {
Missile m = missiles.get(i);
m.draw(g);
m.hitTank(enemyTank);
}
for (int i = 0; i < explodes.size(); i++) {
Explode e = explodes.get(i);
e.draw(g);
}
myTank.draw(g);
enemyTank.draw(g);
}
3.当子弹打到敌方坦克时,画出爆炸
public boolean hitTank(Tank t){
if(this.getRect().intersects(t.getRect()) && t.isLive()){
t.setLive(false);
this.live=false;
Explode e = new Explode(x, y, tc);
tc.explodes.add(e);
return true;
}
return false;
}
4.同理,要处理集合,remove
if(!live) {
tc.explodes.remove(this);
return;
}
总结:添加爆炸类还是运用了面向对象的思想,集合的应用。
下一个版本:添加多辆坦克
附爆炸类代码:
public class Explode {
int x,y;
private boolean live = true;
private TankClient tc;
int[] diameter = {4,6,12,19,26,32,50,30,14,5,2};
int step = 0;
public Explode(int x,int y,TankClient tc){
this.x=x;
this.y=y;
this.tc=tc;
}
public void draw(Graphics g){
if(!live) {
tc.explodes.remove(this);
return;
}
if(step== diameter.length) {
live=false;
step = 0;
return;
}
Color c = g.getColor();
g.setColor(Color.ORANGE);
g.fillOval(x, y, diameter[step], diameter[step]);
g.setColor(c);
step++;
}
}