第十三章 J20飞机游戏项目完整代码(尚学堂java300集笔记)

第十三章 J20飞机游戏项目

DAY10-DAY11

通过键盘控制飞机前后移动,躲避炮弹,看谁坚持的时间长。如果碰到炮弹,则发生爆炸,游戏结束,并显示本次生存的时间。

图片资源

images包下存放:beijing.jpg(背景图)、feiji.png(飞机图)、explode文件夹(包含16张爆炸效果图,按顺序命名为bz1.gif - bz16.gif)

cn.sxt.game包下存放代码

  • 飞机游戏的主窗口
package cn.sxt.game;

import java.awt.Color;
import java.awt.Font;
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;
import java.util.Date;
import javax.swing.JFrame;

public class MyGameFrame extends Frame{
	
	Image beijing = GameUtil.getImage("images/beijing.jpg");
	Image feiji = GameUtil.getImage("images/feiji.png");
	
	Plane plane = new Plane(feiji,250,250);//创建飞机对象
	Shell[] shells = new Shell[50];//创建炮弹对象
	
	Explode bao;//创建爆炸对象
	Date startTime = new Date();//游戏开始时间
	Date endTime;//游戏结束时间
	int period;
	
	@Override
	public void paint(Graphics g) {  //自动被调用,g相当于一个画笔
		// TODO Auto-generated method stub
		super.paint(g); //不能省略
		Color c = g.getColor();
		g.drawImage(beijing, 0, 0, null);//画背景
		plane.drawSelf(g); //画飞机
		//shell.draw(g); //画炮弹
		
		//画出所有的炮弹
		for (int i = 0; i < shells.length; i++) {
			shells[i].draw(g);
			
			//飞机和炮弹的碰撞检测
			boolean peng = shells[i].getRect().intersects(plane.getRect());
			if (peng) {
				plane.live = false;//飞机死了
				
				if(bao==null){
                    bao = new Explode(plane.x,plane.y);
                    endTime = new Date();
                    period = (int)((endTime.getTime() - startTime.getTime())/1000);
                }
				
				bao.draw(g);
			}
			
			//计时功能,给出提示
			if(!plane.live) {	
			g.setColor(Color.red);
			Font f = new Font("宋体",Font.BOLD,50);
			g.setFont(f);
			g.drawString("时间:"+period+"秒",(int)plane.x,(int)plane.y);
			}
		}
		
		g.setColor(c);
		
	}
	//帮助我们反复重画窗口
	class PaintThread extends Thread{
		@Override
		public void run() {
			//super.run();
			while(true) {
				//System.out.println("窗口画一次!");
				repaint();//重画
				try {
					Thread.sleep(40); //1s=1000ms,停顿40毫秒,相当于1s25张左右的图片
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
		}
	}
	
	//定义键盘监听内部类
	class KeyMonitor extends KeyAdapter {

		@Override
		public void keyPressed(KeyEvent e) {
			plane.addDirection(e);
		}

		@Override
		public void keyReleased(KeyEvent e) {
			plane.minusDirection(e);
		}
		
	}
	
	/**
	 * 初始化窗口
	 */
	public void launchFrame() {
		this.setTitle("尚学堂JAVA300集实战小项目");
		this.setVisible(true);
		this.setSize(Constant.GAME_WIDTH, Constant.GAME_HEIGHT);
		this.setLocation(300, 300);
		
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		
		new PaintThread().start();//启动重画窗口的线程
		addKeyListener(new KeyMonitor());//给窗口增加键盘监听
		
		//初始化50个炮弹
		for (int i = 0; i < shells.length; i++) {
			shells[i] = new Shell();
		}
		
	}
	public static void main(String[] args) {
		MyGameFrame f = new MyGameFrame();
		f.launchFrame();
	}
    
	//添加双缓冲技术,解决闪屏问题
	private Image offScreenImage = null;
	 
	public void update(Graphics g) {
	    if(offScreenImage == null)
	        offScreenImage = this.createImage(Constant.GAME_WIDTH,Constant.GAME_HEIGHT);//这是游戏窗口的宽度和高度
	     
	    Graphics gOff = offScreenImage.getGraphics();
	    paint(gOff);
	    g.drawImage(offScreenImage, 0, 0, null);
	}  

}
  • Constant类:存放项目用到的常量,方便修改
package cn.sxt.game;

public class Constant {
	public static final int GAME_WIDTH = 500;
	public static final int GAME_HEIGHT = 500;
}
  • GameUtil类:加载图片代码
package cn.sxt.game;
 
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.sxt.game;

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

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() {
		super();
	}
	
	//返回物体所在的矩形,便于后续的碰撞检测
	public Rectangle getRect() {
		return new Rectangle((int)x,(int)y,width,height);
	}
	
}
  • Plane类:飞机
package cn.sxt.game;

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;
	
	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 {
			System.out.println("diy");
		}
		
	}
	
	public Plane (Image img,double x,double y) {
		this.img = img;
		this.x = x;
		this.y = y;
		this.speed = 3;
		this.width = img.getWidth(null);
		this.height = img.getHeight(null);
		
	}
	
	//按下某个键,增加相应方向
	public void addDirection(KeyEvent e) {
		switch (e.getKeyCode()) {
		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;
		default:
			break;
		}
	}
	
	//按下某个键,取消相应方向
		public void minusDirection(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;
			default:
				break;
			}
		}
}
  • Shell类:炮弹
package cn.sxt.game;

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

public class Shell extends GameObject{
	
	double degree;
	
	public Shell() {
		x = 200;
		y = 200;
		width = 10;
		height = 10;
		speed = 3;
		degree = Math.random()*Math.PI*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);
		
		if(x<0||x>Constant.GAME_WIDTH-width) {
			degree = Math.PI - degree;
		}
		if(y<30||y>Constant.GAME_HEIGHT-height) {
			degree = - degree;
		}
		
		g.setColor(c);
	}
}
  • Explode类:爆炸
package cn.sxt.game;

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

public class Explode {
	
    double x,y;
    
    static Image[] imgs = new Image[16];
    static {
        for(int i=0;i<16;i++){
            imgs[i] = GameUtil.getImage("images/explode/bz"+(i+1)+".gif");//一定要注意名字与图片一致,否则运行时提示空指针
            imgs[i].getWidth(null);
        }
    }
     
    int count;
     
    public void draw(Graphics g){
        if(count<=15){
            g.drawImage(imgs[count], (int)x, (int)y, null);
            count++;
        }
    }
     
    public Explode(double x,double y){
        this.x = x;
        this.y = y;
    }

	public Explode() {
		
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值