本文實例講述了Java基于Swing實現(xiàn)的打獵射擊游戲代碼。分享給大家供大家參考。
具體實現(xiàn)代碼如下:
package Game;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
public class BackgroundPanel extends JPanel {
private static final long serialVersionUID = 1L;
private Image image;// 背景圖片
public BackgroundPanel() {
setOpaque(false);
setLayout(null);
}
public void setImage(Image image) {
this.image = image;
}
/**
* 畫出背景
*/
protected void paintComponent(Graphics g) {
if (image != null) {
// 圖片寬度
int width = getWidth();
// 圖片高度
int height = getHeight();
// 畫出圖片
g.drawImage(image, 0, 0, width, height, this);
}
super.paintComponent(g);
}
}
package Game;
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;
public class BirdLabel extends JLabel implements Runnable {
private static final long serialVersionUID = 1L;
// 隨機生成線程的休眠時間,即控制小鳥移動速度
private int sleepTime = (int) (Math.random() * 300) + 5;
private int y = 100;
private Thread thread;// 將線程作為成員變量
private Container parent;
private int score = 15;// 該類角色對應(yīng)的分?jǐn)?shù)
/**
* 構(gòu)造方法
*/
public BirdLabel() {
super();
// 創(chuàng)建小鳥圖標(biāo)對象
ImageIcon icon = new ImageIcon(getClass().getResource("bird.gif"));
setIcon(icon);// 設(shè)置控件圖標(biāo)
addMouseListener(new MouseAction());// 添加鼠標(biāo)事件監(jiān)聽器
// 添加控件事件監(jiān)聽器
addComponentListener(new ComponentAction());
thread = new Thread(this);// 創(chuàng)建線程對象
}
/**
* 控件的控件事件監(jiān)聽器
*/
private final class ComponentAction extends ComponentAdapter {
public void componentResized(final ComponentEvent e) {
thread.start();// 線程啟動
}
}
/**
* 控件的鼠標(biāo)事件監(jiān)聽器
*/
private final class MouseAction extends MouseAdapter {
public void mousePressed(final MouseEvent e) {
if (!MainFrame.readyAmmo())// 如果子彈沒有準(zhǔn)備好
return;// 什么也不做
MainFrame.useAmmo();// 消耗子彈
appScore();// 加分
destory();// 銷毀本組件
}
}
public void run() {
parent = null;
int width = 0;
try {
while (width <= 0 || parent == null) {
if (parent == null) {
parent = getParent();// 獲取父容器
} else {
width = parent.getWidth();// 獲取父容器的寬度
}
Thread.sleep(10);
}
for (int i = width; i > 0 && parent != null; i -= 8) {
setLocation(i, y);// 從右向左移動本組件位置
Thread.sleep(sleepTime);// 休眠片刻
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if (parent != null) {
MainFrame.appScore(-score * 10); // 自然銷毀將扣分
}
destory();// 移動完畢,銷毀本組件
}
/**
* 從容器移除本組件的方法
*/
public void destory() {
if (parent == null)
return;
parent.remove(this);// 從父容器中移除本逐漸
parent.repaint();
parent = null; // 通過該語句終止線程循環(huán)
}
/**
* 加分的方法
*/
private void appScore() {
System.out.println("小鳥被擊中");
MainFrame.appScore(15);
}
}
package Game;
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;
public class PigLabel extends JLabel implements Runnable {
private static final long serialVersionUID = 1L;
// 隨機生成休眠時間,即野豬移動速度
private int sleepTime = (int) (Math.random() * 300) + 30;
private int y = 260;// 控件的垂直坐標(biāo)
private int score = 10;// 該角色對應(yīng)的分?jǐn)?shù)
private Thread thread;// 內(nèi)置線程對象
private Container parent;// 控件的父容器對象
/**
* 構(gòu)造方法
*/
public PigLabel() {
super();
ImageIcon icon = new ImageIcon(getClass().getResource("pig.gif"));// 加載野豬圖片
setIcon(icon);// 設(shè)置本組件的圖標(biāo)
// 添加鼠標(biāo)事件適配器
addMouseListener(new MouseAdapter() {
// 按下鼠標(biāo)按鍵的處理方法
public void mousePressed(final MouseEvent e) {
if (!MainFrame.readyAmmo())
return;
MainFrame.useAmmo();// 消耗子彈
appScore();// 給游戲加分
destory();// 銷毀本組件
}
});
// 添加組件事件適配器
addComponentListener(new ComponentAdapter() {
// 調(diào)整組件大小時
public void componentResized(final ComponentEvent e) {
thread.start();// 啟動線程
}
});
// 初始化線程對象
thread = new Thread(this);
}
public void run() {
parent = null;
int width = 0;
while (width <= 0 || parent == null) {// 獲取父容器寬度
if (parent == null)
parent = getParent();
else
width = parent.getWidth();
}
// 從左向右移動本組件
for (int i = 0; i < width && parent != null; i += 8) {
setLocation(i, y);
try {
Thread.sleep(sleepTime);// 休眠片刻
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (parent != null) {
MainFrame.appScore(-score * 10); // 自然銷毀將扣分
}
destory();
}
/**
* 從容器移除本組件的方法
*/
public void destory() {
if (parent == null)
return;
parent.remove(this);
parent.repaint();
parent = null; // 通過該語句終止線程循環(huán)
}
/**
* 加分的方法
*/
private void appScore() {
System.out.println("野豬被擊中");
MainFrame.appScore(10);
}
}
package Game;
import static java.lang.Math.random;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainFrame extends JFrame {
private static final long serialVersionUID = 1L;
private static long score = 0;// 分?jǐn)?shù)
private static Integer ammoNum = 5;// 子彈數(shù)量
private static JLabel scoreLabel;// 分?jǐn)?shù)
private BackgroundPanel backgroundPanel;
private static JLabel ammoLabel;
private static JPanel infoPane;
/**
* 構(gòu)造方法
*/
public MainFrame() {
super();
setResizable(false);// 進制調(diào)整窗體大小
setTitle("打獵游戲");
infoPane = (JPanel) getGlassPane();// 獲取玻璃面板
JLabel label = new JLabel("裝載子彈……");// 創(chuàng)建提示標(biāo)簽組件
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setFont(new Font("楷體", Font.BOLD, 32));
label.setForeground(Color.RED);
infoPane.setLayout(new BorderLayout());
infoPane.add(label);// 添加提示標(biāo)簽組件到玻璃面板
setAlwaysOnTop(true);// 是窗體保持在最頂層
setBounds(100, 100, 573, 411);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
backgroundPanel = new BackgroundPanel();// 創(chuàng)建帶背景的面板
backgroundPanel.setImage(new ImageIcon(getClass().getResource(
"background.jpg")).getImage());// 設(shè)置背景圖片
getContentPane().add(backgroundPanel, BorderLayout.CENTER);
// 添加鼠標(biāo)事件適配器
addMouseListener(new FrameMouseListener());
scoreLabel = new JLabel();// 顯示分?jǐn)?shù)的標(biāo)簽組件
scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
scoreLabel.setForeground(Color.ORANGE);
scoreLabel.setText("分?jǐn)?shù):");
scoreLabel.setBounds(25, 15, 120, 18);
backgroundPanel.add(scoreLabel);
ammoLabel = new JLabel();// 顯示自動數(shù)量的標(biāo)簽組件
ammoLabel.setForeground(Color.ORANGE);
ammoLabel.setHorizontalAlignment(SwingConstants.RIGHT);
ammoLabel.setText("子彈數(shù)量:" + ammoNum);
ammoLabel.setBounds(422, 15, 93, 18);
backgroundPanel.add(ammoLabel);
}
/**
* 加分方法
*/
public synchronized static void appScore(int num) {
score += num;
scoreLabel.setText("分?jǐn)?shù):" + score);
}
/**
* 消耗子彈的方法
*/
public synchronized static void useAmmo() {
synchronized (ammoNum) {
ammoNum--;// 子彈數(shù)量遞減
ammoLabel.setText("子彈數(shù)量:" + ammoNum);
if (ammoNum <= 0) {// 判斷子彈是否小于0
new Thread(new Runnable() {
public void run() {
// 顯示提示信息面板
infoPane.setVisible(true);
try {
// 1秒鐘裝載子彈的時間
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ammoNum = 5;// 恢復(fù)子彈數(shù)量
// 修改子彈數(shù)量標(biāo)簽的文本
ammoLabel.setText("子彈數(shù)量:" + ammoNum);
infoPane.setVisible(false);// 隱藏提示信息面板
}
}).start();
}
}
}
/**
* 判斷子彈是否夠用
*
*/
public synchronized static boolean readyAmmo() {
synchronized (ammoNum) {
return ammoNum > 0;
}
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
frame.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* 啟動游戲的方法
*/
public void start() {
new PigThread().start();
new BirdThread().start();
}
/**
* 窗體的鼠標(biāo)事件監(jiān)聽器
*
*/
private final class FrameMouseListener extends MouseAdapter {
public void mousePressed(final MouseEvent e) {
Component at = backgroundPanel.getComponentAt(e.getPoint());
if (at instanceof BackgroundPanel) {// 如果點到面板也扣除子彈
MainFrame.useAmmo();// 消耗子彈
}
/*
* if (at instanceof BirdLabel) {// 如果點到小鳥 MainFrame.appScore(32);//
* 加分 } if (at instanceof PigLabel) {// 如果點到野豬
* MainFrame.appScore(11);// 加分 }
*/
}
}
/**
* 生成豬角色的線程
*
*/
class PigThread extends Thread {
@Override
public void run() {
while (true) {
// 創(chuàng)建代表野豬的標(biāo)簽控件
PigLabel pig = new PigLabel();
pig.setSize(120, 80);// 設(shè)置控件初始大小
backgroundPanel.add(pig);// 添加控件到背景面板
try {
// 線程隨機休眠一段時間
sleep((long) (random() * 3000) + 500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 生成鳥角色的線程
*
*/
class BirdThread extends Thread {
@Override
public void run() {
while (true) {
// 創(chuàng)建代表小鳥的標(biāo)簽控件
BirdLabel bird = new BirdLabel();
bird.setSize(50, 50);// 設(shè)置控件初始大小
backgroundPanel.add(bird);// 添加控件到背景面板
try {
// 線程隨機休眠一段時間
sleep((long) (Math.random() * 3000) + 500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
希望本文所述對大家的Java程序設(shè)計有所幫助。