天空移动
package day19;
import java.awt.image.BufferedImage;
public class Sky extends FlyingObject{
private static BufferedImage image;
static{
image = loadImage("background.png");
}
private int speed;
private int y1;
public Sky(){
super(World.WINTH,World.HEIGHT,0,0);
speed = 1;
y1 = -World.HEIGHT;
}
public void step(){
y+=speed;
y1+=speed;
if(y>=World.HEIGHT){
y-=World.HEIGHT;
}
if(y1>=World.WINTH){
y1-=World.HEIGHT;
}
}
public BufferedImage getImage(){
return image;
};
}
主程序
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 stepAction(){
sky.step();
for(int i=0;i<enemies.length;i++){
enemies[i].step();
}
for(int i=0;i<bullets.length;i++){
bullets[i].step();
}
}
public void action(){
Timer timer = new Timer();
int intervel = 10;
timer.schedule(new TimerTask(){
public void run(){
enterAction();
shootAction();
stepAction();
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();
}
}