我正在参加掘金社区游戏创意投稿大赛个人赛,详情请看:游戏创意投稿大赛。
前言
在之前做了个飞机大战的小游戏,在飞机大战的基础上做修改,完成一个飞机躲子弹的小游戏,也可以叫做坚持三十秒。下面具体介绍下介绍思路,不会布置到网上,暂时没有可以体验的版本
设计及代码实现
1.首先画一个jframe窗口,设置title 和窗体大小
public void launchFrame(){
this.setTitle("躲避byYD");
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);
}
});
在grameFrame加入重写paint的方法,变量g相当于画笔,在窗体实例中画各种模型
public void paint(Graphics g) {
Color c = g.getColor();
g.drawImage(this.bg, 0, 0, (ImageObserver)null);
this.plane.drawSelf(g);
for(int i = 0; i < this.shells.length; ++i) {
this.shells[i].draw(g);
boolean peng = this.shells[i].getRect().intersects(this.plane.getRect());
if (peng) {
this.plane.live = false;
if (this.bao == null) {
this.bao = new Explode(this.plane.x, this.plane.y);
this.endTime = new Date();
this.period = (int)((this.endTime.getTime() - this.startTime.getTime()) / 1000L);
}
this.bao.draw(g);
}
if (!this.plane.live) {
g.setColor(Color.red);
Font f = new Font("宋体", 1, 50);
g.setFont(f);
g.drawString("时间:" + this.period + "秒", (int)this.plane.x, (int)this.plane.y);
}
}
g.setColor(c);
}
3.提供一个imageUtils类,用于加载静态图片(包括飞机,背景等)
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;
}
}
4.在MyGameFrame中建立image实例,放入图片,然后调用g.drawImage方法,在窗体中画出图片
通过线程thread使图片运动起来
Image planeImg = GameUtil.getImage("images/plane.png"); Image bg = GameUtil.getImage("images/bg.jpg");
class PaintThread extends Thread {
PaintThread() {
}
public void run() {
while(true) {
MyGameFrame.this.repaint();
try {
Thread.sleep(40L);
} catch (InterruptedException var2) {
var2.printStackTrace();
}
}
}
}
在初始化窗体是启动线程 (new MyGameFrame.PaintThread()).start();
在飞机类创建时继承GameObject,Plane类:设置飞机的图片,坐标,移动方向,移动速度,是否存活,然后再窗体中创建飞机 同理创建子弹类Bullet类设置子弹的坐标,速度,角度,宽度和高度
getRect 方法为后续碰撞做准备
public class GameObject {
Image img;
double x,y;
int speed =10;
int width,height;
public Rectangle getRect() {
return new Rectangle((int)x,(int)y,width,height);
}
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() {
}
}
这个是练习java的相关代码文章,不具备游玩的链接。