多线程--飞机大战原形

首先新建一个子弹类来存子弹

public class Bullet(){
//子弹的坐标、大小
    public int x,y;
    public int r=30;
    //创建子弹初始化坐标
    public Bullet(int x, int y) {
        this.x = x;
        this.y = y;
    }
    //封装 移动子弹
    public void move(){
        x+=2;
    }
    //封装 绘制子弹
    public void draw(Graphics g){
        g.setColor(Color.GREEN);
        g.fillOval(x,y,r,r);
    }
}
}

写一个线程来画子弹,移动子弹(运用双缓冲使其更丝滑)

public class ThreadDraw extends Thread {
    //画子弹的线程
    private ArrayList<Bullet> bs;//存子弹的队列
    private Graphics g;

    public ThreadDraw (ArrayList<Bullet> bs,Graphics g) {
        this.bs = bs;
        this.g = g;
    }

    public void run(){
        while(true){

            //创建一个内存绘图区
            BufferedImage bi = new BufferedImage(1600,800,BufferedImage.TYPE_INT_RGB);
            //存取缓冲区的画布
            Graphics bg = bi.getGraphics();
            
            for(int i=0;i<bs.size();i++){
                Bullet b =bs.get(i);//遍历队列,取出子弹
                b.draw(bg);//画子弹
                b.move();//移动子弹
            }

            //将内存画布画到界面上
            g.drawImage(bi,100,100,null);
            try{
                Thread.sleep(20);
            }catch(Exception e){}
            //清屏
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, 1600, 800);
            }
        }
    }

设置监听器,实现点击鼠标即发射子弹

public class MouseLis extends MouseAdapter {

    private ArrayList<Bullet> bs;
    public MouseLis(ArrayList<Bullet> bs){
        this.bs=bs;
    }

    public void mouseReleased(MouseEvent e) {
        Bullet bu = new Bullet(e.getX(), e.getY());
        this.bs.add(bu);

    }
}

最后设置界面,把监听器,线程类都加到上面去

public class Game extends JFrame {
    private ArrayList<Bullet> bs= new ArrayList<>();
    public Game() {
        super();
    }
    public void initUI(){
        this.setTitle("对战系统");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(1600, 800);
        this.setVisible(true);
        Graphics g = this.getGraphics();

        MouseLis ms = new MouseLis(bs);
        this.addMouseListener(ms);

        ThreadDraw td = new ThreadDraw(bs,g);
        td.start();
    }
    public static void main(String[] args) {
        Game g = new Game();
        g.initUI();
    }
    }

运行效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值