java游戏-飞机大战

来源:互联网 发布:coure crt软件 编辑:程序博客网 时间:2024/04/29 16:09

飞机大战项目:

文件夹结构:


com.czm.planefight包:


package com.czm.planefight;

/**

 * 道具类

 */

import java.awt.Graphics;

import java.awt.Image;

public classAward {

// 定义道具的坐标

int x, y;

// 定义存放道具的图片数组

Image img;

// 定义道具的存活

boolean isLive = false;

// 定义道具的类型

int type;

// 画道具

public Award(int x, int y, Image img, int type) {

super();

this.x = x;

this.y = y;

this.img = img;

this.type = type;

}

public void draw(Graphics g) {

g.drawImage(img, x, y, null);

}

// 道具移动

public void move() {

if (isLive) {

y += 5;

}

if (y >= 600) {

isLive = false;

}

}

// 英雄机吃道具

public boolean eatAward(MainGame panel) {

boolean f = false;

if (panel.hx + panel.p[0].getWidth() / 2 >= x && panel.hx + panel.p[0].getWidth() / 2 <= x + img.getWidth(null)

&& panel.hy + panel.p[0].getHeight() / 2 >= y

&& panel.hy + panel.p[0].getHeight() / 2 <= y + img.getHeight(null)) {

f = true;

isLive = false;

}

return f;

}

}


package com.czm.planefight;
/**
 * 子弹类
 */
import java.awt.Graphics;
import java.awt.Image;
public class Bullet {
// 只写炮弹的属性和行为
// 坐标
int x, y;
// 炮弹的图片
Image bImg;
// 炮弹的状态
boolean isLive = true;
// 子弹的级别
int type = 0;
// 定义子弹的方向
int bfx = 0;
// 定义子弹移动速度
int speed;
public Bullet(int x, int y, Image bImg, int bfx) {
super();
this.x = x;
this.y = y;
this.bImg = bImg;
this.bfx = bfx;
}
// 炮弹移动的方法
public void move() {
if (bfx == 0) {
if (type == 0)
y -= (10 + speed);
if (type == 1) {
y -= (10 + speed);
x -= (5 + speed / 2);
}
if (type == 2) {
y -= (10 + speed);
x += (5 + speed / 2);
}
}
if (bfx == 1) {
if (type == 0)
y += 8;
if (type == 1) {
y += 7;
x -= 2;
}
if (type == 2) {
y += 7;
x += 2;
}
if (type == 3) {
y += 6;
x += 4;
}
if (type == 4) {
y += 6;
x -= 4;
}
if (type == 5) {
y += 5;
x -= 6;
}
if (type == 6) {
y += 5;
x += 6;
}
}
if (y <= -bImg.getHeight(null) || y >= 600 || x <= -10 || x >= 400) {
isLive = false;
}
}
// 画炮弹
public void draw(Graphics g) {
if (isLive) {
g.drawImage(bImg, x, y, null);
}
}
// 敌机炮弹碰撞英雄机
public boolean eBulletHero(MainGame panel) {
boolean f = false;
if (bfx == 1) {
if (x + bImg.getWidth(null) / 2 >= panel.hx
&& x + bImg.getWidth(null) / 2 <= panel.hx + panel.p[0].getWidth()
&& y + bImg.getHeight(null) / 2 >= panel.hy
&& y + bImg.getHeight(null) / 2 <= panel.hy + panel.p[0].getHeight()) {
if (isLive)
panel.hhp--;
isLive = false;
}
} else
f = false;
return f;
}
}


package com.czm.planefight;
/**
 * 敌机类
 */
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
public class EnemyPlane {
// 定义敌机的图片
Image img;
// 定义敌机的坐标
int x, y;
// 定义敌机的存活
boolean isLive = true;
// 速度
int speed;
int time = 5;
// 敌机的生命
int hp;
// 分数
int score;
// 敌机移动方向
int fx = 0;
// 定义boss机移动方向
int bfx = 0;
// 判断是否是boss机
boolean isBoss = false;
public EnemyPlane(Image img, int x, int y, int speed, int hp, int score, int fx) {
super();
this.img = img;
this.x = x;
this.y = y;
this.speed = speed;
this.hp = hp;
this.score = score;
this.fx = fx;
}
// 画飞机
public void draw(Graphics g) {
g.drawImage(img, x, y, null);
}
// 飞机移动
public void move() {
if (isLive) {
if (fx == 0)
y += speed;
if (fx == 1) {
y += speed;
x -= speed - 2;
}
if (fx == 2) {
y += speed;
x += speed - 2;
}
}
// boss机的移动方向
if (bfx == 0)
x++;
if (bfx == 1)
x--;
if (fx == 3) {
y += speed;
if (y >= 50) {
y = 50;
if (x <= 0)
bfx = 0;
if (x + img.getWidth(null) >= 400)
bfx = 1;
}
}
if (y >= 600 || x + img.getWidth(null) <= 0 || x >= 400) {
isLive = false;
}
}
// 子弹撞敌机
public boolean bulletEp(Bullet bullet) {
boolean f = false;
if (bullet.isLive) {
if (bullet.x + bullet.bImg.getWidth(null) >= x && bullet.x <= x + img.getWidth(null) && bullet.y >= y
&& bullet.y <= y + img.getHeight(null)) {
if (isLive) {
hp--;
}
bullet.isLive = false;
if (hp == 0) {
time--;
isLive = false;
f = true;
}
}
}
return f;
}
// 英雄级撞敌机
public boolean heroEnemy(MainGame panel) {
boolean f = false;
if (panel.hx + panel.p[0].getWidth() / 2 >= x && panel.hx + panel.p[0].getWidth() / 2 <= x + img.getWidth(null)
&& panel.hy + panel.p[0].getHeight() / 2 >= y
&& panel.hy + panel.p[0].getHeight() / 2 <= y + img.getHeight(null)) {
if (isBoss) {
panel.isLive = false;
panel.hhp = 0;
} else {
if (isLive)
panel.hhp--;
isLive = false;
img = new ImageIcon("images/blast/blast_1.png").getImage();
if (panel.hhp == 0) {
panel.isLive = false;
f = true;
}
}
}
return f;
}
}



package com.czm.planefight;

/**
 * 游戏主界面
 */
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import com.czm.planefIghtUtil.Musisc;

public classMainGame extends JPanel implements MouseListener, MouseMotionListener, Runnable {

// 定义图片的高度
int x = 0, y = 0;
// 定义鼠标的状态
boolean ck = true;
// 定义游戏的开关
boolean gg = false;
// 定义一个线程
Thread thread;
// 定义一个放英雄机图片的数组
static BufferedImage p[] = new BufferedImage[2];
// 定义一个数组的坐标
int pc = 0;
// 定义英雄级的坐标
int hx = 200, hy = 500;
// 定义英雄机的生命值
int hhp = 10;
// 定义英雄机的存活
boolean isLive = true;
// 定义英雄机的级别
int grade = 1;
// 定义一个英雄机炮弹的集合,管理炮弹
List<Bullet> bullets = new ArrayList<Bullet>();
// 定义一个放敌机炮弹的集合
List<Bullet> Ebullets = new ArrayList<Bullet>();
int n = 0;
// 定义一个敌机的集合
List<EnemyPlane> ep = new ArrayList<EnemyPlane>();
// 定义一个存放道具的集合
List<Award> aw = new ArrayList<Award>(1);
// 定义一个存放敌机Boss的集合
List<EnemyPlane> boss = new ArrayList<EnemyPlane>(1);
// 定义一个放boss机子弹的集合
List<Bullet> bossBullets = new ArrayList<Bullet>();
// 爆炸数量
int bnum = 0;
// 定义得分
int score = 0;
// 定义一个判断是否击毁boss机
boolean bossdie = false;
// 放炮弹图片
static Image bImg;
// 放敌机炮弹的图片
static Image ebImg;
// 定义一个图片
static Image icon;
// 定义一个存放英雄机爆炸的图片
static Image hb;
// 定义两个存放boss机炮弹的图片
static Image bb;
static Image bb2;
static {
try {
hb = ImageIO.read(new File("images/blast/blast_3.png")); // 英雄机爆炸的图片
icon = ImageIO.read(new File("images/GameInterface/interface_1.png")); // 开始游戏图片
p[0] = ImageIO.read(new File("images/1.png")); // 英雄机图片的
p[1] = ImageIO.read(new File("images/2.png"));
bImg = ImageIO.read(new File("images/bullet/bullet_1.png"));
ebImg = ImageIO.read(new File("images/bullet/bullet_7.png"));
bb = ImageIO.read(new File("images/bullet/bullet_5.png"));
bb2 = ImageIO.read(new File("images/bullet/bullet_8.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public MainGame() {
addMouseListener(this);
addMouseMotionListener(this);
thread = new Thread(this);
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(icon, x, y, this);
if (ck == false) {
// 画英雄机
pc = pc == 0 ? 1 : 0;
g.drawImage(p[pc], hx, hy, null);
// 画子弹
for (int i = 0; i < bullets.size(); i++) {
Bullet bullet = bullets.get(i);
bullet.draw(g);
}
// 画敌机
for (int i = 0; i < ep.size(); i++) {
EnemyPlane ePlane = ep.get(i);
ePlane.draw(g);
}
// 画英雄机生命值和得分
g.drawImage(new ImageIcon("images/award/award_1.png").getImage(), 20, 500, null);
g.setColor(Color.red);
g.drawString("X" + hhp, 60, 520);
g.drawString("得分:" + score, 300, 30);
// 画道具
for (int i = 0; i < aw.size(); i++) {
Award a = aw.get(i);
a.draw(g);
}
// 画敌机子弹
for (int i = 0; i < Ebullets.size(); i++) {
Bullet ebullet = Ebullets.get(i);
ebullet.draw(g);
}
// 画敌机boss
for (int i = 0; i < boss.size(); i++) {
EnemyPlane epl = boss.get(i);
epl.draw(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.white);
g2.fillRect(epl.x, epl.y, 102, 10);
g2.setColor(Color.red);
g2.fillRect(epl.x + 1, epl.y + 1, epl.hp, 8);
}
// 画boss机子弹
for (int i = 0; i < bossBullets.size(); i++) {
Bullet b = bossBullets.get(i);
b.draw(g);
}
// 画英雄机爆炸
if (isLive == false)
g.drawImage(hb, hx - 20, hy - 20, null);
}
// 游戏结束
if (bossdie) {
g.setFont(new Font("微软雅黑", Font.BOLD, 20));
g.setColor(Color.red);
g.drawString("你赢了", 150, 300);
}
// 游戏暂停
if (gg) {
g.setFont(new Font("微软雅黑", Font.BOLD, 20));
g.setColor(Color.red);
g.drawString("游戏暂停", 150, 300);
}
if (isLive == false) {
g.setFont(new Font("微软雅黑", Font.BOLD, 20));
g.setColor(Color.red);
g.drawString("游戏结束", 150, 300);
}
}
@Override
public void run() { // 处理游戏主界面中相应功能
new Musisc("musisc/1.wav", true).start(); // 启动音频播放器
// TODO Auto-generated method stub
synchronized (this) {
while (isLive && bossdie == false) {
if (hhp == 0) {
isLive = false;
}
n++;
// 先清理掉没有的子弹
for (int i = 0; i < bullets.size(); i++) {
Bullet b = bullets.get(i);
if (b.isLive == false) {
bullets.remove(i);
break;
}
}
// 清理敌机炮弹
for (int i = 0; i < Ebullets.size(); i++) {
Bullet b = Ebullets.get(i);
if (b.isLive == false) {
Ebullets.remove(i);
break;
}
}
// 清理敌机
if (n % 10 == 0) {
for (int i = 0; i < ep.size(); i++) {
EnemyPlane epl = ep.get(i);
if (epl.isLive == false) {
ep.remove(i);
break;
}
}
// 清除敌机boss
for (int i = 0; i < boss.size(); i++) {
EnemyPlane epl = boss.get(i);
if (epl.isLive == false) {
boss.remove(i);
bossdie = true;
break;
}
}
}
// 清除道具
for (int i = 0; i < aw.size(); i++) {
Award ad = aw.get(i);
if (ad.isLive == false) {
aw.remove(i);
break;
}
}
// 清除boos机子弹
for (int i = 0; i < bossBullets.size(); i++) {
Bullet b = bossBullets.get(i);
if (b.isLive == false) {
bossBullets.remove(i);
break;
}
}
// 敌机加载
if (n % 30 == 0 && y <= 0) {
int num = (int) (Math.random() * 5 + 2);
int nn = (int) (Math.random() * 3);
EnemyPlane ePlane = new EnemyPlane(
new ImageIcon("images/LittlePlane/plane" + num + ".png").getImage(),
(int) (Math.random() * 350), -30, num, num, num, nn);
ep.add(ePlane);
}
// 添加敌机子弹
if (n % 20 == 0) {
for (int i = 0; i < ep.size(); i++) {
EnemyPlane epl = ep.get(i);
Bullet ebullet = new Bullet(epl.x + epl.img.getWidth(null) / 2, epl.y + epl.img.getHeight(null),
ebImg, 1);
Ebullets.add(ebullet);
}
}
// 添加boss机子弹
if (n % 80 == 0) {
for (int i = 0; i < boss.size(); i++) {
EnemyPlane epl = boss.get(i);
Bullet bullet = new Bullet(epl.x + epl.img.getWidth(null) / 2, epl.y + epl.img.getHeight(null),
bb, 1);
bullet.type = 0;
bossBullets.add(bullet);
Bullet bullet1 = new Bullet(epl.x + epl.img.getWidth(null) / 2, epl.y + epl.img.getHeight(null),
bb, 1);
bullet1.type = 1;
bossBullets.add(bullet1);
Bullet bullet2 = new Bullet(epl.x + epl.img.getWidth(null) / 2, epl.y + epl.img.getHeight(null),
bb, 1);
bullet2.type = 2;
bossBullets.add(bullet2);
Bullet bullet3 = new Bullet(epl.x + epl.img.getWidth(null) / 2, epl.y + epl.img.getHeight(null),
bb, 1);
bullet3.type = 3;
bossBullets.add(bullet3);
Bullet bullet4 = new Bullet(epl.x + epl.img.getWidth(null) / 2, epl.y + epl.img.getHeight(null),
bb, 1);
bullet4.type = 4;
bossBullets.add(bullet4);
Bullet bullet5 = new Bullet(epl.x + epl.img.getWidth(null) / 2, epl.y + epl.img.getHeight(null),
bb, 1);
bullet5.type = 5;
bossBullets.add(bullet5);
Bullet bullet6 = new Bullet(epl.x + epl.img.getWidth(null) / 2, epl.y + epl.img.getHeight(null),
bb, 1);
bullet6.type = 6;
bossBullets.add(bullet6);
Bullet bullet7 = new Bullet(epl.x + epl.img.getWidth(null) / 2 - 20,
epl.y + epl.img.getHeight(null), bb2, 1);
bullet7.type = 0;
bossBullets.add(bullet7);
Bullet bullet8 = new Bullet(epl.x + epl.img.getWidth(null) / 2 + 20,
epl.y + epl.img.getHeight(null), bb2, 1);
bullet8.type = 0;
bossBullets.add(bullet8);
}
}
// boss机子弹移动
for (int i = 0; i < bossBullets.size(); i++) {
Bullet b = bossBullets.get(i);
b.move();
}
// 敌机子弹移动
for (int i = 0; i < Ebullets.size(); i++) {
Bullet b = Ebullets.get(i);
b.move();
// 撞英雄机
b.eBulletHero(this);
}
// boss机子弹撞英雄机
for (int i = 0; i < bossBullets.size(); i++) {
Bullet b = bossBullets.get(i);
b.eBulletHero(this);
}
// 敌机移动
for (int i = 0; i < ep.size(); i++) {
EnemyPlane ePl = ep.get(i);
ePl.move();
}
if (y <= 0) {
if (ck == false) {
y += 2;
}
}
// 添加boss
else {
Ebullets.clear();
ep.clear();
if (boss.size() == 0 && bossdie == false) {
EnemyPlane epl = new EnemyPlane(new ImageIcon("images/BossPlane/plane_6.png").getImage(), 150,
-50, 2, 100, 1000, 3);
epl.isBoss = true;
boss.add(epl);
}
}
// boss移动
for (int i = 0; i < boss.size(); i++) {
EnemyPlane epl = boss.get(i);
epl.move();
}
// 英雄机子弹移动
for (int i = 0; i < bullets.size(); i++) {
Bullet bullet = bullets.get(i);
bullet.move();
}
// 添加道具
if (n % 300 == 0 && aw.size() == 0) {
int num = (int) (Math.random() * 3 + 1);
Award ad = new Award((int) (Math.random() * 350), -30,
new ImageIcon("images/award/award_" + num + ".png").getImage(), num);
ad.isLive = true;
aw.add(ad);
}
// 道具移动
for (int i = 0; i < aw.size(); i++) {
Award ad = aw.get(i);
ad.move();
}
// 子弹敌机相撞
for (int i = 0; i < bullets.size(); i++) {
Bullet bullet = bullets.get(i);
for (int j = 0; j < ep.size(); j++) {
EnemyPlane ePl = ep.get(j);
boolean f = ePl.bulletEp(bullet);
if (f) {
bnum++;
ePl.img = new ImageIcon("images/blast/blast_1.png").getImage();
score += ePl.score;
}
}
}
// 子弹和boss相撞
for (int i = 0; i < bullets.size(); i++) {
Bullet bullet = bullets.get(i);
for (int j = 0; j < boss.size(); j++) {
EnemyPlane epl = boss.get(j);
boolean f = epl.bulletEp(bullet);
if (f) {
epl.img = new ImageIcon("images/blast/blast_3.png").getImage();
score += epl.score;
}
}
}
// 英雄机吃道具
for (int i = 0; i < aw.size(); i++) {
Award ad = aw.get(i);
boolean f = ad.eatAward(this);
if (f) {
// 如果吃的是爱心
if (ad.type == 1) {
if (hhp < 10)
hhp++;
else
hhp = 10;
}
// 如果吃的是三颗子弹
if (ad.type == 2) {
if (grade == 1)
grade++;
else
grade = 2;
}
// 如果吃的是第三种道具
if (ad.type == 3) {
ep.clear();
Ebullets.clear();
}
}
if (n % 300 == 0 && grade == 2)
grade = 1;
}
// 英雄机撞敌机
for (int i = 0; i < ep.size(); i++) {
EnemyPlane epl = ep.get(i);
epl.heroEnemy(this);
}
// 英雄级撞boss
for (int i = 0; i < boss.size(); i++) {
EnemyPlane epl = boss.get(i);
epl.heroEnemy(this);
}
// 添加炮弹
if (n % 5 == 0) {
if (grade == 1) {
Bullet bullet = new Bullet(hx + p[pc].getWidth() / 2 - bImg.getWidth(null) / 2, hy, bImg, 0);
bullets.add(bullet);
}
if (grade == 2) {
Bullet bullet = new Bullet(hx + p[pc].getWidth() / 2 - bImg.getWidth(null) / 2, hy, bImg, 0);
bullets.add(bullet);
Bullet bullet1 = new Bullet(hx + p[pc].getWidth() / 2 - bImg.getWidth(null) / 2, hy, bImg, 0);
bullet1.type = 1;
bullets.add(bullet1);
Bullet bullet2 = new Bullet(hx + p[pc].getWidth() / 2 - bImg.getWidth(null) / 2, hy, bImg, 0);
bullet2.type = 2;
bullets.add(bullet2);
}
}
repaint();
if (gg) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Override
public void mouseDragged(MouseEvent e) { // 鼠标拖动
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) { // 鼠标移动
// TODO Auto-generated method stub
if (e.getX() >= 130 && e.getX() <= 260 && e.getY() >= 390 && e.getY() <= 430 && ck) {
setCursor(new Cursor(Cursor.HAND_CURSOR)); // 设置光标为手形
} else if (ck == false) {
setCursor(new Cursor(Cursor.HAND_CURSOR));
} else {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
// 英雄机跟着鼠标移动
if (ck == false) {
hx = e.getX() - p[pc].getWidth() / 2;
hy = e.getY() - p[pc].getHeight() / 2;
if (hx <= 0)
hx = 0;
if (hx + p[pc].getWidth() >= 400)
hx = 400 - p[pc].getWidth();
if (hy <= 0)
hy = 0;
if (hy + p[pc].getHeight() >= 580)
hy = 580 - p[pc].getHeight();
}
}
@Override
public void mouseClicked(MouseEvent e) { // 鼠标点击
if (e.getX() >= 130 && e.getX() <= 260 && e.getY() >= 390 && e.getY() <= 430 && ck
&& e.getModifiers() == e.BUTTON1_MASK) {
ck = false;
y = -5400;
try {
icon = ImageIO.read(new File("images/background/background_1.png")); // 游戏主界面移动的长背景图片
} catch (IOException e1) {
e1.printStackTrace();
}
thread.start();
}
if (e.getModifiers() == e.BUTTON3_MASK) {
gg = gg ? resume() : suspend();
}
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if (isLive == false) {
System.out.println("游戏结束!");
JOptionPane.showMessageDialog(null, "游戏结束!");
System.exit(3);
}
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
// 定义两个方法 唤醒和阻塞
public boolean suspend() {
gg = true;
return gg;
}
public synchronized boolean resume() {
gg = false;
notify();
return gg;
}
}


com.czm.planefIghtDao包:

package com.czm.planefIghtDao;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import com.czm.planefIghtUtil.JdbcUtil;

import com.czm.planefIghtUtil.User;

import com.mysql.jdbc.Statement;

public classUserDao {

Connection conn = null;

PreparedStatement stmt = null;

ResultSet resultSet = null;

public User selectByUsernameAndPassword(User user) {

try {

// 获取连接

conn = JdbcUtil.getConnection();

// 发送sql语句

String sql = "select * from users1 where username = ? and password = ?";

stmt = conn.prepareStatement(sql);

// 替换占位符

stmt.setObject(1, user.getUsername());

stmt.setObject(2, user.getPassword());

// 返回执行sql语句结果

resultSet = stmt.executeQuery();

while (resultSet.next()) {

int id = resultSet.getInt("id");

String name = resultSet.getString("name");

String sex = resultSet.getString("sex");

String username = resultSet.getString("username");

String password = resultSet.getString("password");

user.setId(id);

user.setName(name);

user.setSex(sex);

user.setUsername(username);

user.setPassword(password);

System.out.println("id: " + id + "name: " + name + "sex: " + sex + "username: " + username

+ "password: " + password);

return user;

}

} catch (SQLException e) {

// e.printStackTrace();

} finally {

JdbcUtil.close(null, (Statement) stmt, conn);

}

return null;

}

public User insertUsernameAndPassword(User user) {

try {

// 获取连接

conn = JdbcUtil.getConnection();

// 发送sql语句

String sql = "insert into users1(username,password,name,sex) values(?,?,?,?)";

stmt = conn.prepareStatement(sql);

// 替换占位符

stmt.setObject(1, user.getUsername());

stmt.setObject(2, user.getPassword());

stmt.setObject(3, user.getName());

stmt.setObject(4, user.getSex());

// ④返回执行sql处理的结果

int executeUpdate = stmt.executeUpdate();

return user;

} catch (SQLException e) {

e.printStackTrace();

} finally {

JdbcUtil.close(null, (Statement) stmt, conn);

}

return null;

}

}



package com.czm.planefIghtDao;
import com.czm.planefIghtUtil.User;
public class UserService {
UserDao userDao = new UserDao();
public UserService(User user) {
// TODO Auto-generated constructor stub
}
public User login(User user) {
return userDao.selectByUsernameAndPassword(user);
}
public User registe(User user) {
return userDao.insertUsernameAndPassword(user);
}
}


com.czm.planefightUI包:


package com.czm.planefightUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import com.czm.planefIghtDao.UserService;
import com.czm.planefIghtUtil.StringUtil;
import com.czm.planefIghtUtil.User;
public class LoginUI extends JFrame implements ActionListener {
public static void main(String[] args) {
new LoginUI().initUI();
}
public void initUI() {
setSize(354, 240);
setTitle("飞机大战登录界面");
setLayout(null);
setResizable(false);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
addBgImg("images/7.gif");
addComponent();
setIconImage(new ImageIcon("images/fly.jpg").getImage()); // 设置最小化图标
// this.getContentPane().setBackground(Color.LIGHT_GRAY);
setVisible(true);
}
private void setIconImages(ImageIcon imageIcon) {
// TODO Auto-generated method stub
}
// 添加背景图片
public void addBgImg(String path) {
JPanel contenPane = (JPanel) getContentPane();
contenPane.setOpaque(false); // 设置透明
Icon imageIcon = new ImageIcon(path);
JLabel jLabel = new JLabel(imageIcon);
jLabel.setBounds(0, 0, imageIcon.getIconWidth(), imageIcon.getIconHeight());
JLayeredPane layeredPane = getLayeredPane();
// 把图片添加到layeredPane的最底层
layeredPane.add(jLabel, new Integer(Integer.MIN_VALUE));
}
JComboBox<String> cbbUsername;
JPasswordField passwordfiled;
JButton loginBtn;
JButton registerBtn;
// 添加组件
private void addComponent() {
// 用户名标签
JLabel usernameLabel = new JLabel("用户名: ");
usernameLabel.setBounds(20, 30, 100, 50);
usernameLabel.setFont(new Font("宋体", Font.BOLD, 15));
usernameLabel.setForeground(Color.white);
add(usernameLabel);
// 用户名下拉列表输入框
cbbUsername = new JComboBox<String>();
cbbUsername.setBorder(null);
cbbUsername.setBounds(90, 40, 180, 25);
cbbUsername.addItem("1234");
cbbUsername.addItem("1111");
cbbUsername.addItem("12345");
cbbUsername.setEditable(true);
add(cbbUsername);
// 密码标签
JLabel passwordLabel = new JLabel("密  码: ");
passwordLabel.setBounds(20, 80, 100, 50);
passwordLabel.setFont(new Font("宋体", Font.BOLD, 15));
passwordLabel.setForeground(Color.white);
add(passwordLabel);
// 密码框
passwordfiled = new JPasswordField(20);
passwordfiled.setBounds(90, 90, 180, 25);
passwordfiled.setText("6666");
add(passwordfiled);
// 登录按钮
loginBtn = new JButton("登录");
loginBtn.setBounds(50, 140, 80, 30);
loginBtn.setBorder(null);
loginBtn.addActionListener(this);
add(loginBtn);
this.setFocusable(true);
KeyAdapter keyAdapter = new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("键盘按下");
if (e.getKeyCode() == 10) {
System.out.println("回车键按下");
loginBtn.doClick();
}
}
};
this.addKeyListener(keyAdapter);
// cbbUsername.addKeyListener(keyAdapter);
passwordfiled.addKeyListener(keyAdapter);
// 注册按钮
registerBtn = new JButton("注册");
registerBtn.setBounds(170, 140, 80, 30);
registerBtn.setBorder(null);
registerBtn.addActionListener(this);
add(registerBtn);
}
@Override
public void actionPerformed(ActionEvent e) {
// 判断是哪个按钮被按下
Object source = e.getSource();
if (loginBtn == source) { // 登录
// 获取用户名和密码
String username = cbbUsername.getSelectedItem().toString();
String password = passwordfiled.getText();
// 判断数据是否为空
if (StringUtil.isEmpty(username)) {
JOptionPane.showMessageDialog(null, "用户名不能为空!");
return;
}
if (StringUtil.isEmpty(password)) {
JOptionPane.showMessageDialog(null, "密码不能为空!");
return;
}
User user = new User();
user.setUsername(username);
user.setPassword(password);
UserService userService = new UserService(user);
if (userService.login(user) != null) {
JOptionPane.showMessageDialog(null, "登录成功");
dispose();
new StartGameUI();
} else {
JOptionPane.showMessageDialog(null, "登录失败");
}
} else {// 注册
new registeUI().initUI();
}
}
}


package com.czm.planefightUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import com.czm.planefIghtDao.UserService;
import com.czm.planefIghtUtil.StringUtil;
import com.czm.planefIghtUtil.User;
public class registeUI extends JFrame implements ActionListener {
public static void main(String[] args) {
new registeUI().initUI();
}
public void initUI() {
setSize(300, 400);
setTitle("飞机大战注册界面");
setLayout(null);
setResizable(false);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
setIconImage(new ImageIcon("images/fly2.jpg").getImage());
addComponent();
this.getContentPane().setBackground(Color.LIGHT_GRAY);
setVisible(true);
}
JTextField usernameTextField;
JPasswordField passwordfiled;
JTextField nameTextField;
JRadioButton radioButton1;
JRadioButton radioButton2;
JButton registerBtn;
JButton cancelBtn;
// 添加组件
private void addComponent() {
// 用户名标签
JLabel usernameLabel = new JLabel("用户名: ");
usernameLabel.setBounds(20, 30, 100, 50);
usernameLabel.setFont(new Font("宋体", Font.BOLD, 15));
add(usernameLabel);
// 用户名输入框
usernameTextField = new JTextField(20);
usernameTextField.setBounds(90, 40, 180, 25);
add(usernameTextField);
// 密码标签
JLabel passwordLabel = new JLabel("密  码: ");
passwordLabel.setBounds(20, 80, 100, 50);
// passwordLabel.setText("6666");
passwordLabel.setFont(new Font("宋体", Font.BOLD, 15));
add(passwordLabel);
// 密码框
passwordfiled = new JPasswordField(20);
passwordfiled.setBounds(90, 90, 180, 25);
// passwordfiled.setText("6666");
add(passwordfiled);
// 姓名标签
JLabel nameLabel = new JLabel("姓  名: ");
nameLabel.setBounds(20, 130, 100, 50);
nameLabel.setFont(new Font("宋体", Font.BOLD, 15));
add(nameLabel);
// 姓名输入框
nameTextField = new JTextField(20);
nameTextField.setBounds(90, 140, 180, 25);
add(nameTextField);
// 性别单选框
ButtonGroup buttonGroup = new ButtonGroup();
radioButton1 = new JRadioButton("男");
radioButton1.setLocation(50, 190);
radioButton1.setSize(50, 30);
buttonGroup.add(radioButton1);
add(radioButton1);
radioButton2 = new JRadioButton("女");
radioButton2.setLocation(200, 190);
radioButton2.setSize(50, 30);
buttonGroup.add(radioButton2);
add(radioButton2);
// 登录按钮
registerBtn = new JButton("注册");
registerBtn.setBounds(50, 250, 80, 30);
registerBtn.setBorder(null);
registerBtn.addActionListener(this);
add(registerBtn);
// 注册按钮
cancelBtn = new JButton("取消");
cancelBtn.setBounds(170, 250, 80, 30);
cancelBtn.setBorder(null);
cancelBtn.addActionListener(this);
add(cancelBtn);
}
@Override
public void actionPerformed(ActionEvent e) {
// 判断是哪个按钮被按下
Object source = e.getSource();
if (registerBtn == source) { // 注册
// 获取用户名和密码
String username = usernameTextField.getText().toString();
String password = passwordfiled.getText().toString();
String name = nameTextField.getText().toString();
String regex = "([\u4e00-\u9fa5]+)"; // 中文匹配
String sex = radioButton1.isSelected() ? radioButton1.getText():
radioButton2.getText(); 
if (!name.matches(regex)) {
JOptionPane.showMessageDialog(null, "姓名必须为中文");
System.out.println("中文匹配失败");
return;
}
// 判断数据是否为空
if (StringUtil.isEmpty(username)) {
JOptionPane.showMessageDialog(null, "用户名不能为空!");
return;
}
if (StringUtil.isEmpty(password)) {
JOptionPane.showMessageDialog(null, "密码不能为空!");
return;
}
if (StringUtil.isEmpty(name)) {
JOptionPane.showMessageDialog(null, "姓名不能为空!");
return;
}
if (StringUtil.isEmpty(sex)) {
JOptionPane.showMessageDialog(null, "性别不能为空!");
return;
}
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setName(name);
user.setSex(sex);
UserService userService = new UserService(user);
if (userService.registe(user) != null) {
JOptionPane.showMessageDialog(null, "注册成功");
new LoginUI().initUI();
dispose();
}
} else {// 取消
// dispose();
System.exit(3);
}
}
}


package com.czm.planefightUI;
import javax.swing.ImageIcon;
/**
 * 开始游戏界面
 */
import javax.swing.JFrame;
import com.czm.planefight.MainGame;
public class StartGameUI extends JFrame {
public StartGameUI() {
this.setTitle("飞机大战");
this.setBounds(200, 300, 400, 600);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(3);
this.setResizable(false);
setIconImage(new ImageIcon("images/fly3.jpg").getImage());
// 跳转界面
MainGame panel = new MainGame();
this.add(panel);
this.setVisible(true);
}
public static void main(String[] args) {
new StartGameUI();
}
}


package com.czm.planefightUI;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Test extends JFrame {
private Container contentPane;
private JTextField textField;
public static void main(String[] args) {
// String regex = "([\u4e00-\u9fa5]+)";
// String str = "我";
// if (str.matches(regex)) {
// System.out.println("中文匹配成功");
// } else {
// System.out.println("...");
// }
new Test();
}
public Test() {
setSize(300, 400);
setTitle("飞机大战注册界面");
setLayout(null);
setResizable(false);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
contentPane = getContentPane();
addComponent();
// URL url = this.getClass().getResource("/images/01.jpg");
// Image img = Toolkit.getDefaultToolkit().getImage(url);
// this.setIconImage(img);
setVisible(true);
}
private void addComponent() {
JButton btn = new JButton("回车键进入");
btn.setBounds(20, 20, 100, 50);
btn.setFocusPainted(false); // 取消鼠标外观
btn.setContentAreaFilled(false); // 取消边框绘制
// btn.setToolTipText("这是按钮");
contentPane.add(btn);
// contentPane.setFocusable(true);
textField = new JTextField(30);
textField.setBounds(130, 20, 100, 30);
contentPane.add(textField);
// this.addKeyListener(arg0);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("11111111111");
}
});
this.setFocusable(true);
KeyAdapter keyAdapter = new KeyAdapter() {
public void keyPressed(KeyEvent e) {
// if (e.getKeyText(e.getKeyCode()).compareToIgnoreCase("Enter")
// == 0) {
// btn.doClick();
// JOptionPane.showMessageDialog(null, "登录成功");
// }
// if (e.getKeyCode() == 10) {
// System.out.println("1111");
// btn.doClick();
// JOptionPane.showMessageDialog(null, "登录成功");
// }
// if (e.getKeyChar() == e.VK_ENTER) {
// System.out.println("ok..............");
// }
if (e.getKeyChar() == '\n') {
System.out.println("回车键登录");
}
}
};
this.addKeyListener(keyAdapter);
textField.addKeyListener(keyAdapter);
}
}


com.czm.planefIghtUtil包:

package com.czm.planefIghtUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Statement;
public class JdbcUtil {
static {
// 1、注入驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// e.printStackTrace();
}
}
static String url = "jdbc:mysql://localhost:3306/hx1706";
static String user = "root";
static String password = "6666";
// 获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
// 关闭
public static void close(ResultSet resultSet, Statement stmt, Connection conn) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
resultSet = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}


package com.czm.planefIghtUtil;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
/**
 * 音频类
 * 
 * @author asus2
 *
 */
public class Musisc extends Thread {
String filePath; // 文件路径
boolean flag; // 是否循环播放
SourceDataLine dataLine = null; // 混频器,即声卡上音频输出文件
// public static void main(String[] args) {
// new Musisc("musisc/1.wav", true).start();
// }
public Musisc(String filePath, boolean flag) {
this.filePath = filePath;
this.flag = flag;
}
public void run() {
// 创建文件对象
File file = new File(filePath);
AudioInputStream audioInputStream = null;
do {
try {
// 获取音频输入流
audioInputStream = AudioSystem.getAudioInputStream(file);
// 获取文件格式
AudioFormat format = audioInputStream.getFormat();
// 创建数据行的信息对象
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
// 从混频器获得 源数据行
dataLine = (SourceDataLine) AudioSystem.getLine(info);
// 打开指定格式的行
dataLine.open(format);
// 启动混频器
dataLine.start();
// 从音频输入流中获取数据并发送到混频器
byte[] b = new byte[1024]; // 字节(缓冲)数组
int length;
while ((length = audioInputStream.read(b)) != -1) {
dataLine.write(b, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataLine != null) {
dataLine.drain(); // 清空数据
dataLine.close(); // 关闭混频器
}
if (audioInputStream != null) {
try {
audioInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} while (flag);
}
}


package com.czm.planefIghtUtil;
public class StringUtil {
// 判断当前字符串是否为空的
public static boolean isEmpty(String text) {
if (text == null || "".equals(text)) {
return true;
}
return false;
}
}


package com.czm.planefIghtUtil;
import java.io.Serializable;
/**
 * 用户实体类
 */
public class User implements Serializable {
private int id;
private String name;
private String sex;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Users [id=" + id + ", name=" + name + ", sex=" + sex + ", username=" + username + ", password="
+ password + "]";
}
}


mysql数据库设计:


create table user1(
id  int(20)  auto_increment,
name  varchar(11),
sex  varchar(2),
username  varchar(20),
password  varchar(20)
);

insert  into  user1(name,sex,username,password)  values("小红","女","1234","6666");







登录界面:




注册界面:




游戏开始界面:




游戏主界面: