最近闲来无事复习下java基础,没有特别复杂的功能,一切从简,旨在回顾知识点!!!
游戏效果如下:
我们通过键盘控制飞机前后移动躲避炮弹,如果碰到炮弹则会爆炸,游戏结束并显示游戏坚持的时间
基本的功能实现
MyGameFrame类
package com.xiaodao.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;
/**
* 飞机游戏的主窗口
* @author 刘小叨
*
*/
public class MyGameFrame extends Frame {
Image plane = GameUtil.getImage("images/plane.png");
Image bg = GameUtil.getImage("images/bg.jpg");
Date startTime = new Date();//游戏起始时刻
Date endTime;
int gameTime;
Plane p = new Plane(plane,250,250);
Shell s = new Shell();
Shell[] shells = new Shell[50];
Explode bao;
@Override
public void paint(Graphics g) {//自动被调用 g 就是一支画笔
Color c = g.getColor();
g.drawImage(bg, 0, 0, null);
p.drawSelf(g);//画飞机
//画出所有炮弹
for(int i=0;i<shells.length;i++) {
shells[i].draw(g);
//飞机和炮弹的碰撞检测
boolean peng = shells[i].getRect().intersects(p.getRect());
if(peng) {
p.live = false;
if(bao == null) {
bao = new Explode(p.x, p.y);
endTime = new Date();
gameTime = (int)((endTime.getTime()-startTime.getTime())/1000);
}
bao.draw(g);
}
if(!p.live) {
g.setColor(Color.red);
Font f = new Font("宋体",Font.BOLD,50);
g.setFont(f);
g.drawString("时间:"+ gameTime + "秒",125,250);
}
}
g.setColor(c);
}
//帮助我们反复重画窗口
class PaintThread extends Thread{
@Override
public void run() {
while(true) {
// System.out.println("窗口画一次");
repaint();//重画
try {
Thread.sleep(40);