飞机小游戏(出现异常过!已解决!)

飞机小游戏

声明:模仿【尚学堂】制作的飞机小游戏

  • 所需图片
    【背景图】
    飞机小游戏(出现异常过!已解决!)_第1张图片
    【飞机图】
    fj
    【爆炸图】
    1.gif2.gif3.gif4.gif5.gif6.gif7.gif8.gif9.gif10.gif11.gif12.gif13.gif14.gif15.gif16.gif
  • 主窗口类
package cn.gdlgxy.game03;
/**
 * 创建图形注窗口
 */

import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


//解决闪烁问题,继承Frame类,增加双缓冲技术
public class MyGameFrame extends Frame {
	
	Image  ballground = GameUtil.getImage("images/ballground.jpg");
	Image  fj = GameUtil.getImage("images/fj.png");

	
	//创建对象画飞机,移动飞机,方便创建多个对象
	Plane plane =new Plane(fj,250,250);
	Shell[] shells = new Shell[30];
	
	Explode ball;
	
	//Shell shell = new Shell();
	
	public void paint(Graphics g) {
			
			//画背景图
			g.drawImage(ballground, 0, 0, null);
			
			//画出飞机,飞机调用drawSelf方法
			plane.drawSelf(g);
			
			//画出炮弹
			for(int i=0;i<shells.length;i++) {
				shells[i].draw(g);
				
				//每生成一颗炮弹,检测飞机跟炮弹是否碰撞
				boolean crash = shells[i].getRect().intersects(plane.getRect());
				if(crash) {
					
					plane.live = false;
					//System.out.println("飞机与炮弹相撞了!");
					if(ball==null) {
						
						ball = new Explode(plane.x,plane.y);
						
						}
						
						ball.draw(g);
					
					//运行无反应,观察飞机与炮弹是否为对象设置了宽度跟高度(发现plane没有!)
					//所以在plane类中设置宽度和高度
					//飞机死掉:在飞机类中增加一个变量:boolean live。
					//如果 = true,则画,否则不画
				}
				
			}	
			/*
			Color c = g.getColor(); //目前没改的颜色存起来
			g.setColor(Color.BLUE); //更改为自己的颜色
			
			g.drawLine(100, 100, 200, 200); 
			g.drawRect(100, 100, 200, 200); //开始点的坐标--宽高
			g.drawString("小黑", 200, 200); 
			
			g.setColor(c);   //把颜色改回原来的颜色
		
		*/
		}
		
		//Thread----多线程
	class PainThread extends Thread{
		@Override
		public void run() {
			
			while(true) {
				repaint();//重画窗口
				
				try {
					Thread.sleep(40);  //1s = 1000ms
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
		}
	}
	
	//添加键盘监听的内部类
	class KeyMonitor extends KeyAdapter{
		public void keyPressed(KeyEvent e) {
			//飞机对象调用按键方法
			plane.addDirection(e);
			//测试:System.out.println("按下:" + e.getKeyCode());
		}
		public void keyReleased(KeyEvent e) {
			//飞机对象调用松开方法
			plane.stopDirection(e);
			//System.out.println("松开:" + e.getKeyCode());
		}
		
	}
	
	
	
	//添加双缓冲技术
	private Image offScreenImage = null;
	public void update(Graphics g) {
		if(offScreenImage == null)
			offScreenImage = this.createImage(Constan.GAME_WIDTH,Constan.GAME_HEIGHT);//这是游戏窗口的高度和宽度
		Graphics gOff= offScreenImage.getGraphics();
		paint(gOff);
		g.drawImage(offScreenImage, 0, 0, null);
	}
	
	
	public void launchFrame() {
		this.setTitle("学院—小黑作品");
		this.setVisible(true); //窗口默认不可见,设置窗口可见
		this.setSize(Constan.GAME_WIDTH,Constan.GAME_HEIGHT); //设置长,宽
		this.setLocation(400,250); //以左上角为坐标原点。右边为x轴,下边为y轴
		
		/**
		 * 关闭窗口后自动结束程序
		 * alt+/ 提示
		 */	
		this.addWindowListener(new WindowAdapter() {
			
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
			
		});
		
		new PainThread().start(); //启动重画窗口的线程
		addKeyListener(new KeyMonitor());//给窗口增加键盘监听
		
		//初始化25个数组
		for(int i=0;i<shells.length;i++) {
			shells[i] = new Shell();
		}
		
	}
	
	public static void main(String[] args) {
		MyGameFrame j = new MyGameFrame();
		j.launchFrame();
		
		
	}
}

  • 图片加载类(GameUtil)
package cn.gdlgxy.game03;
/*
 * 图片加载类
 */

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;

public class GameUtil {
	
		private GameUtil() {
			
		}
		
		public static Image getImage(String path) {
			BufferedImage bi = null;
			try {
				URL u = GameUtil.class.getClassLoader().getResource(path);
				bi = ImageIO.read(u);
			}catch(IOException e) {
				e.printStackTrace();
			}
			return bi;
		}

}

  • 游戏物体父类(GameObject)
package cn.gdlgxy.game03;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;

/**
 * 游戏物体的父类
 * @author 卟淡
 *
 */
public class GameObject {
	Image img;
	double x,y;
	int speed;
	int width,height;
	
	public void drawSelf(Graphics g) {
		g.drawImage(img, (int)x, (int)y, null);
	}
	public GameObject(Image img, double x, double y, int speed, int width, int height) {
		super();
		this.img = img;
		this.x = x;
		this.y = y;
		this.speed = speed;
		this.width = width;
		this.height = height;
	}
	public GameObject(Image img, double x, double y) {
		super();
		this.img = img;
		this.x = x;
		this.y = y;
	}
	public GameObject() {
		
	}
	/**
	 * 返回物体所在的矩形。便于后续的碰撞检测
	 */
	public Rectangle getRect() {
		return  new Rectangle((int)x,(int)y,width,height);
	}

}

  • 飞机类(plane)
package cn.gdlgxy.game03;

/**
 * 创建飞机类,方便myGameFrame调用
 */
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;

public class Plane extends GameObject {
	
	boolean left,up,right,down;
	boolean live = true;//boolean型的默认值为false
	
	public void drawSelf(Graphics g) {
		if(live) {
			g.drawImage(img, (int)x, (int)y, null);

			//按键时以一定的速度跟方向移动
			if(left) {
				x -=speed;
			}
			if(right) {
				x +=speed;
			}
			if(up) {
				y -=speed;
			}

			if(down) {
				y +=speed;
			}
		}else {
			
		}

	}
	public Plane(Image img,double x,double y) {
		this.img = img;
		this.x = x;
		this.y = y;
		
		this.speed = 4; //若无这句话,程序按键无反应。因为开始时速度被初始化,此时要定义速度的大小
		this.width = img.getWidth(null); //null为无观察者
		this.height = img.getHeight(null);
	}
	
	//按下某个键增加相应的方向
	//键盘控制物体方法.keyEvent 包含了你按哪个键的信息,所以把KeyEvent传进来
	public void addDirection(KeyEvent e) {
		//e调用获取键码方法
		switch(e.getKeyCode()) {
		/*case 37:
			left = true;
			break;
		case 38:
			up = true;
			break;
		case 39:
			right = true;
			break;
		case 40:
			down = true;
			break;*/
		
		//直接用KeyEvent里的常量
		case KeyEvent.VK_LEFT:
			left = true;
			break;
		case KeyEvent.VK_UP:
			up = true;
			break;
		case KeyEvent.VK_RIGHT:
			right = true;
			break;
		case KeyEvent.VK_DOWN:
			down = true;
			break;
		}
		
	}
	
	//松开时
	public void  stopDirection(KeyEvent e) {
		switch(e.getKeyCode()) {
		case KeyEvent.VK_LEFT:
			left = false;
			break;
		case KeyEvent.VK_UP:
			up = false;
			break;
		case KeyEvent.VK_RIGHT:
			right = false;
			break;
		case KeyEvent.VK_DOWN:
			down = false;
			break;
		/*case 37:
			left = false;
		case 38:
			up = false;
		case 39:
			right = false;
		case 40:
			down = false;*/	
		}
		
	}

}

  • 炮弹类(shell)
package cn.gdlgxy.game03;

import java.awt.Color;
import java.awt.Graphics;

/**
 * 炮弹类
 * @author 卟淡
 *
 */
public class Shell extends GameObject{
	double degree;//定义弧度
	
	public Shell() {
		//设置开始位置,
		//在MyGameFrame类中增加Shell对象,画出炮弹(shell.draw(g))
		x = 200;  
		y = 200;
		width = 10;
		height = 10;
		speed = 3;
		degree = Math.random()*Math.PI*2;  //弧度为:0-2π
	}
	
	public void draw(Graphics g) {
		Color c = g.getColor(); //保留原来的颜色
		
		g.setColor(Color.YELLOW);
		g.fillOval((int)x,(int)y, width, height);
		
		//炮弹任意角度飞行路径,用三角函数:见下图
		x+=speed*Math.cos(degree);
		y+=speed*Math.sin(degree);
		
		//因为窗口有边框,运行炮弹反弹时有一些细节问题,所以要减一些宽度和高度
		//弹到y轴上
		if(x<10||x>Constan.GAME_WIDTH-20) {
			degree = Math.PI-degree;
		}
		if(y<30||y>Constan.GAME_HEIGHT-20) {
			degree = -degree;
		}
		
		g.setColor(c);  //恢复原来的颜色
		
	}
	
	
	
}

  • 把窗口的长度跟宽度定义成常量,方便修改
package cn.gdlgxy.game03;
/**
 * 设置final变量方便shell类中设置碰撞反弹的边界
 * @author 卟淡
 *
 */
public class Constan {
	public static final int GAME_WIDTH = 500;
	public static final int GAME_HEIGHT = 500;
	

}

  • 爆炸类(Explode)
package cn.gdlgxy.game03;
/**
 * 爆炸类
 */
import java.awt.Graphics;
import java.awt.Image;
 
/*
 * 爆炸类
 */
public class Explode {
    double explodeX,explodeY;
    static Image[] imgs = new Image[16];
    static {
        for(int i=0;i<16;i++){
            imgs[i] = GameUtil.getImage("images/explode"+(i+1)+".gif");
            imgs[i].getWidth(null);
        }
    }
     
    int count;
     
    public void draw(Graphics g){
        if(count<=15){
            g.drawImage(imgs[count], (int)explodeX, (int)explodeY, null);
            count++;
        }
    }
     
    public Explode(double explodeX,double explodeY){
        this.explodeX = explodeX;
        this.explodeY = explodeY;
    }
}

没增加爆炸类时运行无错误,当增加爆炸类在主窗口调用后运行出现以下问题:
飞机小游戏(出现异常过!已解决!)_第2张图片

  • 问题解决方法
    在这里首先非常感谢一位博主(BoRoBoRoMe)给予的提示。
    提示:看起来是Explode的静态块出问题了。在Explode.java Line15的静态块中增加try catch,看异常信息
    飞机小游戏(出现异常过!已解决!)_第3张图片
    执行结果:
    图片无法加载
    由上面的输出可知是:图片无法加载问题

由此可发现:图片的命名不用单一的数字命名,即可解决!!
加载图片问题

  • 在MyGameFrame类中为飞机增加计时
    飞机小游戏(出现异常过!已解决!)_第4张图片
    飞机小游戏(出现异常过!已解决!)_第5张图片

你可能感兴趣的:(Java基础笔记)