对敌人坦克死亡的处理
1.创建敌人坦克对象池
package util;
import tank.EnemyTank;
import java.util.ArrayList;
import java.util.List;
public class TankPool {
public static final int DEFAULT_POOL_SIZE=10;
public static final int DEFAULT_POOL_MAX_SIZE=20;
private static List<EnemyTank> pool =new ArrayList<>();
static {
for(int i=0;i<DEFAULT_POOL_SIZE;i++)
pool.add(new EnemyTank());
}
/**
* 从对象池中获取一个对象
* @return
*/
public static EnemyTank get()
{
EnemyTank enemyTank= null;
//判断对象池是否为空
if(pool.size()==0){
//生成对象
enemyTank = new EnemyTank();
}
else {
//拿走第一个位置上的对象
enemyTank= pool.remove(0);
}
return enemyTank;
}
//归还
public static void theReturn(EnemyTank enemyTank){
if(pool.size()==DEFAULT_POOL_MAX_SIZE)
return;
pool.add(enemyTank);
}
}
2.从敌人坦克容器中去掉死亡坦克
private void drawEnemies(Graphics g)
{
for(int i=0;i<enemies.size();i++)
{
Tank enemy=enemies.get(i);
enemy.draw(g);
}
for (int i = 0; i< enemies.size(); i++) {
EnemyTank enemyTank = (EnemyTank) enemies.get(i);
if(enemyTank.isDie())
{
TankPool.theReturn((EnemyTank) enemies.remove(i));
i--;
}
}
}
3。完善坦克的初始化
坦克的血量要重新初始化。
public static Tank createEnemy(){
int x= MyUtil.getRandomNumber(0,2)==0?RADIUS:
Constant.FRAME_WIDTH-RADIUS;
int y= GameFrame.titleBarh+RADIUS;
int dir=DIR_DOWN;
// Tank enemy=new EnemyTank(x,y,dir);
Tank enemy= TankPool.get();
enemy.setX(x);
enemy.setY(y);
enemy.setDir(dir);
enemy.setEnemy(true);
enemy.setState(STATE_MOVE);
enemy.setHp(Tank.DEFAULT_HP);
return enemy;
}