Java based on the Swing to achieve the hunting shooting game code

  • 2020-04-01 03:35:05
  • OfStack

This article describes the Java based on the Swing implementation of the hunting shooting game code. Share with you for your reference.

The specific implementation code is as follows:


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;//The background image         public BackgroundPanel() {
                setOpaque(false);
                setLayout(null);
        }         public void setImage(Image image) {
                this.image = image;
        }         /**
         * Draw the background
         */
        protected void paintComponent(Graphics g) {
                if (image != null) {
                        //Image width
                        int width = getWidth();
                        //Image height
                        int height = getHeight();
                        //Draw the picture
                        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;
        //Randomly generated thread sleep time, that is, control the bird movement speed
        private int sleepTime = (int) (Math.random() * 300) + 5;
        private int y = 100;
        private Thread thread;//Thread as a member variable
        private Container parent;
        private int score = 15;//The score for this class of roles         /**
         * A constructor
         */
        public BirdLabel() {
                super();
                //Create a bird icon object
                ImageIcon icon = new ImageIcon(getClass().getResource("bird.gif"));
                setIcon(icon);//Set the control icon
                addMouseListener(new MouseAction());//Add mouse event listener
                //Add control event listener
                addComponentListener(new ComponentAction());
                thread = new Thread(this);//Create a thread object
        }         /**
         * Control event listener for the control
         */
        private final class ComponentAction extends ComponentAdapter {
                public void componentResized(final ComponentEvent e) {
                        thread.start();//Thread startup
                }
        }         /**
         * Control for the mouse event listener
         */
        private final class MouseAction extends MouseAdapter {
                public void mousePressed(final MouseEvent e) {
                        if (!MainFrame.readyAmmo())//If the bullet is not ready
                                return;//Do nothing
                        MainFrame.useAmmo();//Spent bullets
                        appScore();//Plus < br / >                         destory();//Destroy this component
                }
        }         public void run() {
                parent = null;
                int width = 0;
                try {
                        while (width <= 0 || parent == null) {
                                if (parent == null) {
                                        parent = getParent();//Gets the parent container
                                } else {
                                        width = parent.getWidth();//Gets the width of the parent container
                                }
                                Thread.sleep(10);
                        }
                        for (int i = width; i > 0 && parent != null; i -= 8) {
                                setLocation(i, y);//Move the component position from right to left
                                Thread.sleep(sleepTime);//Sleep time
                        }
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }
                if (parent != null) {
                        MainFrame.appScore(-score * 10); //Points will be deducted for natural destruction                 }
                destory();//After moving, destroy the component
        }         /**
         * Method to remove this component from the container
         */
        public void destory() {
                if (parent == null)
                        return;
                parent.remove(this);//Remove this step from the parent container
                parent.repaint();
                parent = null; //This statement terminates the thread loop
        }         /**
         * Ways to score points
         */
        private void appScore() {
                System.out.println(" The bird was hit ");
                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;
        //Randomly generated dormancy time, that is, the boar moving speed
        private int sleepTime = (int) (Math.random() * 300) + 30;
        private int y = 260;//Control
        private int score = 10;//The score for this role is
        private Thread thread;//Built-in thread object
        private Container parent;//The parent container object of the control         /**
         * A constructor
         */
        public PigLabel() {
                super();
                ImageIcon icon = new ImageIcon(getClass().getResource("pig.gif"));//Load picture of wild boar
                setIcon(icon);//Sets the icon of this component
                //Add the mouse event adapter
                addMouseListener(new MouseAdapter() {
                        //
                        public void mousePressed(final MouseEvent e) {
                                if (!MainFrame.readyAmmo())
                                        return;
                                MainFrame.useAmmo();//Spent bullets
                                appScore();//Bonus points for games
                                destory();//Destroy this component
                        }
                });
                //Add component event adapter
                addComponentListener(new ComponentAdapter() {
                        //Adjust component size
                        public void componentResized(final ComponentEvent e) {
                                thread.start();//Start thread
                        }
                });
                //Initializes the thread object
                thread = new Thread(this);
        }         public void run() {
                parent = null;
                int width = 0;
                while (width <= 0 || parent == null) {//Gets the parent container width
                        if (parent == null)
                                parent = getParent();
                        else
                                width = parent.getWidth();
                }
                //Move this component from left to right
                for (int i = 0; i < width && parent != null; i += 8) {
                        setLocation(i, y);
                        try {
                                Thread.sleep(sleepTime);//Sleep time
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                }
                if (parent != null) {
                        MainFrame.appScore(-score * 10); //Points will be deducted for natural destruction                 }
                destory();
        }         /**
         * Method to remove this component from the container
         */
        public void destory() {
                if (parent == null)
                        return;
                parent.remove(this);
                parent.repaint();
                parent = null; //This statement terminates the thread loop
        }         /**
         * Ways to score points
         */
        private void appScore() {
                System.out.println(" The boar was shot ");
                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;//Score < br / >         private static Integer ammoNum = 5;//Number of bullets
        private static JLabel scoreLabel;//Score < br / >         private BackgroundPanel backgroundPanel;
        private static JLabel ammoLabel;
        private static JPanel infoPane;         /**
         * A constructor
         */
        public MainFrame() {
                super();
                setResizable(false);//Base resizing form
                setTitle(" Hunting game ");
                infoPane = (JPanel) getGlassPane();//Gets the glass panel
                JLabel label = new JLabel(" Loaded with bullets... ");//Create a prompt label component
                label.setHorizontalAlignment(SwingConstants.CENTER);
                label.setFont(new Font(" Regular script ", Font.BOLD, 32));
                label.setForeground(Color.RED);
                infoPane.setLayout(new BorderLayout());
                infoPane.add(label);//Add prompt label component to glass panel                 setAlwaysOnTop(true);//


                setBounds(100, 100, 573, 411);
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                backgroundPanel = new BackgroundPanel();//Create a panel
with a background                 backgroundPanel.setImage(new ImageIcon(getClass().getResource(
                                "background.jpg")).getImage());//Set the background image
                getContentPane().add(backgroundPanel, BorderLayout.CENTER);
                //Add the mouse event adapter
                addMouseListener(new FrameMouseListener());
                scoreLabel = new JLabel();//The label component that displays the score is
                scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
                scoreLabel.setForeground(Color.ORANGE);
                scoreLabel.setText(" Score: ");
                scoreLabel.setBounds(25, 15, 120, 18);
                backgroundPanel.add(scoreLabel);
                ammoLabel = new JLabel();//Displays the automatic number of label components
                ammoLabel.setForeground(Color.ORANGE);
                ammoLabel.setHorizontalAlignment(SwingConstants.RIGHT);
                ammoLabel.setText(" Number of bullets: " + ammoNum);
                ammoLabel.setBounds(422, 15, 93, 18);
                backgroundPanel.add(ammoLabel);
        }         /**
         * Points method
         */
        public synchronized static void appScore(int num) {
                score += num;
                scoreLabel.setText(" Score: " + score);
        }         /**
         * How to consume bullets
         */
        public synchronized static void useAmmo() {
                synchronized (ammoNum) {
                        ammoNum--;//Bullets decrease
                        ammoLabel.setText(" Number of bullets: " + ammoNum);
                        if (ammoNum <= 0) {//Determine if the bullet is less than 0
                                new Thread(new Runnable() {
                                        public void run() {
                                                //Display prompt information panel
                                                infoPane.setVisible(true);
                                                try {
                                                        //Load time of 1 second
                                                        Thread.sleep(1000);
                                                } catch (InterruptedException e) {
                                                        e.printStackTrace();
                                                }
                                                ammoNum = 5;//Number of recovered bullets
                                                //Modify the text of the bullet count tag
                                                ammoLabel.setText(" Number of bullets: " + ammoNum);
                                                infoPane.setVisible(false);//Hide prompt message panel
                                        }
                                }).start();
                        }
                }
        }         /**
         * Determine if there are enough bullets
         *
         */
        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();
                                }
                        }
                });
        }         /**
         * How to start a game
         */
        public void start() {
                new PigThread().start();
                new BirdThread().start();
        }         /**
         * Mouse event listener for the form
         *
         */
        private final class FrameMouseListener extends MouseAdapter {
                public void mousePressed(final MouseEvent e) {
                        Component at = backgroundPanel.getComponentAt(e.getPoint());
                        if (at instanceof BackgroundPanel) {//If the point to the panel also subtracted bullets
                                MainFrame.useAmmo();//Spent bullets
                        }
                        /*
                         * if (at instanceof BirdLabel) {// If I hit bird MainFrame.appScore(32);//
                         * Bonus points } if (at instanceof PigLabel) {//If I go to boar
                         * MainFrame.appScore(11);//Plus} < br / >                          */
                }
        }         /**
         * The thread that generates the pig character
         *
         */
        class PigThread extends Thread {
                @Override
                public void run() {
                        while (true) {
                                //Creates a label control that represents a wild boar
                                PigLabel pig = new PigLabel();
                                pig.setSize(120, 80);//Sets the initial size of the control
                                backgroundPanel.add(pig);//Add control to background panel
                                try {
                                        //
the thread sleeps at random for a period of time                                         sleep((long) (random() * 3000) + 500);
                                } catch (InterruptedException e) {
                                        e.printStackTrace();
                                }
                        }
                }
        }         /**
         * The thread that generates the bird character
         *
         */
        class BirdThread extends Thread {
                @Override
                public void run() {
                        while (true) {
                                //Creates a tag control that represents a bird
                                BirdLabel bird = new BirdLabel();
                                bird.setSize(50, 50);//Sets the initial size of the control
                                backgroundPanel.add(bird);//Add control to background panel
                                try {
                                        //
the thread sleeps at random for a period of time                                         sleep((long) (Math.random() * 3000) + 500);
                                } catch (InterruptedException e) {
                                        e.printStackTrace();
                                }
                        }
                }
        }
}

I hope this article has been helpful to your Java programming.


Related articles: