Java基于Swing实现的打猎射击游戏代码_java

本文实例讲述了Java基于Swing实现的打猎射击游戏代码。分享给大家供大家参考。

具体实现代码如下:

复制代码 代码如下:

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;// 该类角色对应的分数

        /**
         * 构造方法
         */
        public BirdLabel() {
                super();
                // 创建小鸟图标对象
                ImageIcon icon = new ImageIcon(getClass().getResource("bird.gif"));
                setIcon(icon);// 设置控件图标
                addMouseListener(new MouseAction());// 添加鼠标事件监听器
                // 添加控件事件监听器
                addComponentListener(new ComponentAction());
                thread = new Thread(this);// 创建线程对象
        }

        /**
         * 控件的控件事件监听器
         */
        private final class ComponentAction extends ComponentAdapter {
                public void componentResized(final ComponentEvent e) {
                        thread.start();// 线程启动
                }
        }

        /**
         * 控件的鼠标事件监听器
         */
        private final class MouseAction extends MouseAdapter {
                public void mousePressed(final MouseEvent e) {
                        if (!MainFrame.readyAmmo())// 如果子弹没有准备好
                                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; // 通过该语句终止线程循环
        }

        /**
         * 加分的方法
         */
        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;// 控件的垂直坐标
        private int score = 10;// 该角色对应的分数
        private Thread thread;// 内置线程对象
        private Container parent;// 控件的父容器对象

        /**
         * 构造方法
         */
        public PigLabel() {
                super();
                ImageIcon icon = new ImageIcon(getClass().getResource("pig.gif"));// 加载野猪图片
                setIcon(icon);// 设置本组件的图标
                // 添加鼠标事件适配器
                addMouseListener(new MouseAdapter() {
                        // 按下鼠标按键的处理方法
                        public void mousePressed(final MouseEvent e) {
                                if (!MainFrame.readyAmmo())
                                        return;
                                MainFrame.useAmmo();// 消耗子弹
                                appScore();// 给游戏加分
                                destory();// 销毁本组件
                        }
                });
                // 添加组件事件适配器
                addComponentListener(new ComponentAdapter() {
                        // 调整组件大小时
                        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; // 通过该语句终止线程循环
        }

        /**
         * 加分的方法
         */
        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;// 分数
        private static Integer ammoNum = 5;// 子弹数量
        private static JLabel scoreLabel;// 分数
        private BackgroundPanel backgroundPanel;
        private static JLabel ammoLabel;
        private static JPanel infoPane;

        /**
         * 构造方法
         */
        public MainFrame() {
                super();
                setResizable(false);// 进制调整窗体大小
                setTitle("打猎游戏");
                infoPane = (JPanel) getGlassPane();// 获取玻璃面板
                JLabel label = new JLabel("装载子弹……");// 创建提示标签组件
                label.setHorizontalAlignment(SwingConstants.CENTER);
                label.setFont(new Font("楷体", Font.BOLD, 32));
                label.setForeground(Color.RED);
                infoPane.setLayout(new BorderLayout());
                infoPane.add(label);// 添加提示标签组件到玻璃面板

                setAlwaysOnTop(true);// 是窗体保持在最顶层
                setBounds(100, 100, 573, 411);
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                backgroundPanel = new BackgroundPanel();// 创建带背景的面板
                backgroundPanel.setImage(new ImageIcon(getClass().getResource(
                                "background.jpg")).getImage());// 设置背景图片
                getContentPane().add(backgroundPanel, BorderLayout.CENTER);
                // 添加鼠标事件适配器
                addMouseListener(new FrameMouseListener());
                scoreLabel = new JLabel();// 显示分数的标签组件
                scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
                scoreLabel.setForeground(Color.ORANGE);
                scoreLabel.setText("分数:");
                scoreLabel.setBounds(25, 15, 120, 18);
                backgroundPanel.add(scoreLabel);
                ammoLabel = new JLabel();// 显示自动数量的标签组件
                ammoLabel.setForeground(Color.ORANGE);
                ammoLabel.setHorizontalAlignment(SwingConstants.RIGHT);
                ammoLabel.setText("子弹数量:" + ammoNum);
                ammoLabel.setBounds(422, 15, 93, 18);
                backgroundPanel.add(ammoLabel);
        }

        /**
         * 加分方法
         */
        public synchronized static void appScore(int num) {
                score += num;
                scoreLabel.setText("分数:" + score);
        }

        /**
         * 消耗子弹的方法
         */
        public synchronized static void useAmmo() {
                synchronized (ammoNum) {
                        ammoNum--;// 子弹数量递减
                        ammoLabel.setText("子弹数量:" + 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;// 恢复子弹数量
                                                // 修改子弹数量标签的文本
                                                ammoLabel.setText("子弹数量:" + 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();
        }

        /**
         * 窗体的鼠标事件监听器
         *
         */
        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) {
                                // 创建代表野猪的标签控件
                                PigLabel pig = new PigLabel();
                                pig.setSize(120, 80);// 设置控件初始大小
                                backgroundPanel.add(pig);// 添加控件到背景面板
                                try {
                                        // 线程随机休眠一段时间
                                        sleep((long) (random() * 3000) + 500);
                                } catch (InterruptedException e) {
                                        e.printStackTrace();
                                }
                        }
                }
        }

        /**
         * 生成鸟角色的线程
         *
         */
        class BirdThread extends Thread {
                @Override
                public void run() {
                        while (true) {
                                // 创建代表小鸟的标签控件
                                BirdLabel bird = new BirdLabel();
                                bird.setSize(50, 50);// 设置控件初始大小
                                backgroundPanel.add(bird);// 添加控件到背景面板
                                try {
                                        // 线程随机休眠一段时间
                                        sleep((long) (Math.random() * 3000) + 500);
                                } catch (InterruptedException e) {
                                        e.printStackTrace();
                                }
                        }
                }
        }
}

希望本文所述对大家的Java程序设计有所帮助。

时间: 2024-10-26 05:32:28

Java基于Swing实现的打猎射击游戏代码_java的相关文章

java编写的简单移动方块小游戏代码_java

本文实例讲述了java编写的简单移动方块小游戏代码.分享给大家供大家参考,具体如下: 运行效果截图如下: 第一次用java编写图形化的界面,还是有些青涩..以后继续努力!!具体代码如下: //Little Box Game by AlexYui //Game.java By 1093710210@ HIT import javax.swing.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.*; import

java基于swing实现的五子棋游戏代码_java

本文实例讲述了java基于swing实现的五子棋游戏代码.分享给大家供大家参考. 主要功能代码如下: 复制代码 代码如下: import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Main extends JFrame implements ActionListener{         private static final long serialVersionUID = 1L;      

Java基于swing实现的弹球游戏代码_java

本文实例讲述了Java基于swing实现的弹球游戏代码.分享给大家供大家参考. 主要功能代码如下: 复制代码 代码如下: package Game; import java.awt.Graphics; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Random;

java基于swing实现的连连看代码_java

本文实例讲述了java基于swing实现连连看代码.分享给大家供大家参考. 主要功能代码如下: 复制代码 代码如下: package llkan; import javax.swing.*; import java.awt.*; import java.awt.event.*; /**  * 连连看游戏  * @author Administrator  *2014年10月17日  */ public class MainGame implements ActionListener {     

java代码-急求java高手,帮忙看下面的游戏代码,为何只能运行界面类然后其他都看不见也不能玩

问题描述 急求java高手,帮忙看下面的游戏代码,为何只能运行界面类然后其他都看不见也不能玩 //子弹Bullet类 package hy; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; public class Bullet { //坐标 public int x,y; //子弹大小 public int width,height; //子弹杀伤力 public int kill; //速度

基于C语言实现的扫雷游戏代码_C 语言

本文详细讲述了基于C语言实现的扫雷游戏代码,代码中备有比较详细的注释,便于读者阅读和理解.希望对学习游戏开发的朋友能有一点借鉴价值. 完整的实例代码如下: /* 模拟扫雷游戏 */ #include <graphics.h> #include <math.h> #include <stdio.h> #include <dos.h> #include <stdlib.h> #include <conio.h> #include <

基于jquery的地址栏射击游戏代码_jquery

演示地址:http://demo.jb51.net/js/2011/hunt/index.htm 玩法向下看 请看地址栏上的字母 O! 你使用O来向 a射击. 使用键盘上的 左箭头 和 右箭头 移动字母O. 当O移动到 a 上时,按 空格键射击! 游戏会定时30秒时间,按ESC键重新开始. 注:请使用系统自带的IE浏览器来打开本链接. 你使用O来向 a射击. 使用键盘上的 左箭头 和 右箭头 移动字母O. 当O移动到 a 上时,按 空格键射击!  核心代码: 复制代码 代码如下: (functi

基于C语言实现的迷宫游戏代码_C 语言

本文实例讲述了基于C语言实现迷宫游戏的方法,代码备有较为详尽的注释,便于读者理解.通过该游戏代码可以很好的复习C语言的递归算法与流程控制等知识,相信对于学习游戏开发的朋友有一定的借鉴价值. 完整的实例代码如下: #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #include <dos.h> #define N 20/*迷宫的大小,可改

java实现的简单猜数字游戏代码_java

本文实例讲述了java实现的简单猜数字游戏代码.分享给大家供大家参考. 具体代码如下: 复制代码 代码如下: import java.util.InputMismatchException; import java.util.Scanner; public class Main {         public static void main(String[] args) {                 // 产生一个随机数                 int number = (in