子弹入场
package day19;
import java.awt.image.BufferedImage;
public class Hero extends FlyingObject{
private static BufferedImage[] images;
static{
images = new BufferedImage[2];
images[0] = loadImage("hero0.png");
images[1] = loadImage("hero1.png");
}
private int life;
private int doubleFire;
public Hero(){
super(97,124,140,400);
life = 3;
doubleFire = 0;
}
public void step(){
System.out.println("英雄机切换图片");
}
void moveTo(int x,int y){
System.out.println("英雄机随着鼠标移动");
}
int index = 0;
public BufferedImage getImage(){
if(isLife()){
return images[index++%images.length];
}
return null;
};
public Bullet[] shoot(){
int xStep = this.width/4;
int yStep = 20;
if(doubleFire>0){
Bullet [] bs = new Bullet[2];
bs[0] = new Bullet(this.x+1*xStep,this.y-yStep);
bs[1] = new Bullet(this.x+3*xStep,this.y-yStep);
doubleFire -=2;
return bs;
}else{
Bullet [] bs = new Bullet[1];
bs[0] = new Bullet(this.x+2*xStep,this.y-yStep);
return bs;
}
}
}
package day19;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.TimerTask;
import java.util.Timer;
import java.awt.Graphics;
import java.util.Random;
import java.util.Arrays;
public class World extends JPanel{
public static final int WINTH = 400;
public static final int HEIGHT = 700;
private Sky sky = new Sky();
private Hero hero = new Hero();
private FlyingObject[] enemies = {
new Airplane(),
new BigAirplane(),
new Bee()
};
private Bullet[] bullets = {};
public FlyingObject nextOne(){
Random rand = new Random();
int type = rand.nextInt(20);
if(type<5){
return new Bee();
}else if(type<12){
return new Airplane();
}else{
return new BigAirplane();
}
}
int enterIndex = 0;
public void enterAction(){
enterIndex++;
if(enterIndex%40==0){
FlyingObject obj = nextOne();
enemies = Arrays.copyOf(enemies,enemies.length+1);
enemies[enemies.length-1] = obj;
}
}
int shootIndex =0;
public void shootAction(){
shootIndex++;
if(shootIndex%30==0){
Bullet[] bs = hero.shoot();
bullets =Arrays.copyOf(bullets,bullets.length+bs.length);
}
}
public void action(){
Timer timer = new Timer();
int intervel = 10;
timer.schedule(new TimerTask(){
public void run(){
enterAction();
shootAction();
repaint();
}
},intervel,intervel);
}
public void paint(Graphics g){
sky.paintObject(g);
hero.paintObject(g);
for(int i=0;i<enemies.length;i++){
enemies[i].paintObject(g);
}
for(int i=0;i<bullets.length;i++){
enemies[i].paintObject(g);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
World world = new World();
frame.add(world);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);;
frame.setSize(WINTH,HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
world.action();
}
}