基于java制作一个飞机小游戏(学习心得)

emmm,第一篇博客

   用了这么久的csdn,都是在观摩大佬们发帖,一只小萌新瑟瑟发抖,不敢说话,甚
至连代码也不能完全读懂。假期在b站自学(可以说是复习)了java课程,尚学堂的
2018版。链接如下:https://www.bilibili.com/video/av24496128/?p=101
   重新接触java这门语言,感触还是蛮多的,毕竟之前上课没有好好听讲(emmm,希
望老师不逛我这里)有好多的内容都处于空白状态,这次学习呢,将这些应该懂的也弄
懂了一点。
   这篇主要是在学习了一个阶段后,有一个设计小游戏的教学,跟着视频一步步来,
记录一下我的学习过程,顺便回顾一遍。(废话真多,我才不说是为了试着用下博
客功能)

飞机躲避小游戏

结果

这个项目非常简单,达到的结果就是一只飞机,在好多弹幕里面苟且偷生,看能坚持几秒。贴个图:
结果图

(你要问我飞机去哪里了,图中间有个炸掉的就是 )
好了接下来就让我理一理思路

一,主类

第一步,把窗口先画一下,要用到java里的JFrame函数

“` java
import java.awt.Color;
import java.awt.Font;
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.awt.event.WindowListener;
import java.util.Date;

import javax.swing.JFrame;

/**
* 游戏主窗口
* @author 13958
*
*/

public class MyGameFarme extends JFrame {

Image bgimg = GameUtil.getImage("images/bg.png");
Image planeimg =GameUtil.getImage("images/plane.png");
//先加载图片,在src中创建images文件夹,将图片存在images下。
Plane plane =new Plane(planeimg,250,250);
//画飞机,定义一个飞机类。
Shell[] shells =new Shell[50];
//画炮弹,同样一个炮弹类
Explode bao;
//定义一个爆炸效果的类,这里先定义一个爆炸方法。
Date startTime=new Date();
Date endTime;
int period;
//设置Data类来进行计时,程序开始时startTime计时,死亡时endTime计时。

@Override
//重写,可以右键->source->override快捷写出此函数。
public void paint(Graphics g) {
    g.drawImage(bgimg, 0, 0, null);//画背景
    plane.drawSelf(g);//画飞机
    for(int i=0;i<shells.length;i++) {
        shells[i].draw(g);//利用一个数组画炮弹,这里设定50个。
        boolean peng =shells[i].getRect().intersects(plane.getRect());
        //利用getRect来判断飞机和炮弹是否相交(图片本质都是矩形)。
        if(peng) {//利用if语句来设定结果
            System.out.println("相撞了!");//为了在控制台确定可以判断相撞,可以删掉的。
            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+"s", 100,100);
            //输出结果图,
        }
    }

}

class PaintThread extends Thread {//内部类,设定重画


    @Override
    public void run() {

        while(true) {
            repaint();   //重画 


            try {  
                Thread.sleep(40);//一般人眼为26帧,这就差不多
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                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("ly出品");//设置标题

    this.setSize(Contant.GAME_WIDTH, Contant.GAME_HEIGHT);
    this.setLocation(40, 40);
    this.setVisible(true);
    //设置窗口属性



    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
        System.exit(0);
        //设置关闭窗口事件
        }
    });

    new PaintThread().start();
    addKeyListener(new KeyMonitor());

    for(int i=0;i<shells.length;i++) {
        shells[i]=new Shell();

    }


}




public static void main(String[] args) {
    MyGameFarme f=new MyGameFarme();
    f.launchFrame();
}

/**
 * 下面画面缓冲,消除闪烁。
 */
private Image offScreenImage =null;
public void update(Graphics g) {
    if(offScreenImage==null) {
        offScreenImage=this.createImage(Contant.GAME_WIDTH,Contant.GAME_HEIGHT);
    }
    Graphics goff=offScreenImage.getGraphics();
    paint(goff);
    g.drawImage(offScreenImage, 0, 0, null);

}

}

二,根类

//因为飞机,子弹都有部分相似的属性,所以写一个父类,将共同属性写入。
“`java
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;

/**
* 物体属性设置
* @author 13958
*
*/
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() {

 }
 /**
  * 返回物体所在矩形,碰撞检测。
  * @return
  */
 public Rectangle getRect() {
     return new Rectangle((int)x,(int)y,width,height);
 }

}

三。飞机

“`java
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;
     }
     else if(right) {
         x+=speed;
     }
     else if(up) {
         y-=speed;
     }
     else if(down) {
         y+=speed;
     }
     }
 }



 public Plane(Image img, double x,double y) {
     this.img=img;
     this.x=x;
     this.y=y;
     this.speed=5;
     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_RIGHT:
         right=true;
         break;
     case KeyEvent.VK_UP:
         up=true;
         break;
     case KeyEvent.VK_DOWN:
         down=true;
         break;
     }
 }



 public void minusDirection(KeyEvent e) {
     switch(e.getKeyCode()) {
     case KeyEvent.VK_LEFT:
         left=false;
         break;
     case KeyEvent.VK_RIGHT:
         right=false;
         break;
     case KeyEvent.VK_UP:
         up=false;
         break;
     case KeyEvent.VK_DOWN:
         down=false;
         break;
     }
 }

}

四,子弹

“`java
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>Contant.GAME_WIDTH-width) {
        degree=Math.PI-degree;
    }
    if(y<30||y>Contant.GAME_HEIGHT-height-30)
        degree =-degree;    

    g.setColor(c);
}

}

五读取图片

“`java
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() {

}
/**
 * 返回指定路径图片
 * @param path
 * @return
 */
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;
}

}

六 爆炸类

“`
package com.ly.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/e”+(i+1)+”.png”);
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;
}

}

七 常量类

“`java

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/e”+(i+1)+”.png”);
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;
}

}
此次博客主要做个人笔记用,请勿滥用。。()大佬们应该是看不上的。。

  • 15
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值