The example in this article describes the hunting and shooting game code implemented in Java based on Swing. Share it with everyone for your reference.
The specific implementation code is as follows:
Copy the code code 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;// 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();
// picture height
int height = getHeight();
// draw the picture
g.drawImage(image, 0, 0, width, height, this);
}
super.paintComponent(g);
}
}
Copy the code code as follows:
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 generate the sleep time of the thread, that is, control the moving speed of the bird
private int sleepTime = (int) (Math.random() * 300) + 5;
private int y = 100;
private Thread thread; // Use thread as a member variable
private Container parent;
private int score = 15;//The score corresponding to this type of role
/**
*Construction method
*/
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 thread object
}
/**
* Control event listener of the control
*/
private final class ComponentAction extends ComponentAdapter {
public void componentResized(final ComponentEvent e) {
thread.start();//Thread start
}
}
/**
* Control's 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(); // Consume bullets
appScore(); // Bonus points
destroy(); // Destroy this component
}
}
public void run() {
parent = null;
int width = 0;
try {
while (width <= 0 || parent == null) {
if (parent == null) {
parent = getParent(); // Get the parent container
} else {
width = parent.getWidth(); // Get the width of the parent container
}
Thread.sleep(10);
}
for (int i = width; i > 0 && parent != null; i -= 8) {
setLocation(i, y);//Move the position of this component from right to left
Thread.sleep(sleepTime);//Sleep for a while
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if (parent != null) {
MainFrame.appScore(-score * 10); // Natural destruction will deduct points
}
destroy();// After the move is completed, destroy this component
}
/**
* Method to remove this component from the container
*/
public void destruction() {
if (parent == null)
return;
parent.remove(this);//Remove this file from the parent container
parent.repaint();
parent = null; // Terminate the thread loop through this statement
}
/**
* Ways to add points
*/
private void appScore() {
System.out.println("The bird was hit");
MainFrame.appScore(15);
}
}
Copy the code code as follows:
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 generate sleep time, which is the moving speed of the wild boar
private int sleepTime = (int) (Math.random() * 300) + 30;
private int y = 260;//Vertical coordinates of the control
private int score = 10;//The score corresponding to this character
private Thread thread; // built-in thread object
private Container parent;//The parent container object of the control
/**
*Construction method
*/
public PigLabel() {
super();
ImageIcon icon = new ImageIcon(getClass().getResource("pig.gif"));//Load wild boar pictures
setIcon(icon);//Set the icon of this component
//Add mouse event adapter
addMouseListener(new MouseAdapter() {
// How to handle mouse button presses
public void mousePressed(final MouseEvent e) {
if (!MainFrame.readyAmmo())
return;
MainFrame.useAmmo(); // Consume bullets
appScore(); // Add points to the game
destroy(); // Destroy this component
}
});
//Add component event adapter
addComponentListener(new ComponentAdapter() {
//When resizing the component
public void componentResized(final ComponentEvent e) {
thread.start();//Start the thread
}
});
//Initialize the thread object
thread = new Thread(this);
}
public void run() {
parent = null;
int width = 0;
while (width <= 0 || parent == null) {//Get the width of the parent container
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 for a while
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (parent != null) {
MainFrame.appScore(-score * 10); // Natural destruction will deduct points
}
destroy();
}
/**
* Method to remove this component from the container
*/
public void destruction() {
if (parent == null)
return;
parent.remove(this);
parent.repaint();
parent = null; // Terminate the thread loop through this statement
}
/**
* Ways to add points
*/
private void appScore() {
System.out.println("The wild boar was hit");
MainFrame.appScore(10);
}
}
Copy the code code as follows:
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
private static Integer ammoNum = 5;//Number of bullets
private static JLabel scoreLabel;// score
private BackgroundPanel backgroundPanel;
private static JLabel ammoLabel;
private static JPanel infoPane;
/**
*Construction method
*/
public MainFrame() {
super();
setResizable(false);//Adjust the size of the form
setTitle("Hunting Game");
infoPane = (JPanel) getGlassPane(); // Get the glass panel
JLabel label = new JLabel("Load bullets...");//Create prompt label component
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setFont(new Font("楷体", Font.BOLD, 32));
label.setForeground(Color.RED);
infoPane.setLayout(new BorderLayout());
infoPane.add(label);//Add prompt label component to the glass panel
setAlwaysOnTop(true);//The form remains at the top level
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 mouse event adapter
addMouseListener(new FrameMouseListener());
scoreLabel = new JLabel(); // Label component that displays scores
scoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
scoreLabel.setForeground(Color.ORANGE);
scoreLabel.setText("Score:");
scoreLabel.setBounds(25, 15, 120, 18);
backgroundPanel.add(scoreLabel);
ammoLabel = new JLabel(); // Display 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);
}
/**
* Extra 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--;// Decrease the number of bullets
ammoLabel.setText("Number of bullets: " + ammoNum);
if (ammoNum <= 0) {// Determine whether the bullet is less than 0
new Thread(new Runnable() {
public void run() {
//Display prompt information panel
infoPane.setVisible(true);
try {
// 1 second to load bullets
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ammoNum = 5;//Restore the number of bullets
// Modify the text of the bullet quantity label
ammoLabel.setText("Number of bullets: " + ammoNum);
infoPane.setVisible(false);//Hide the prompt information panel
}
}).start();
}
}
}
/**
* Determine whether the bullets are enough
*
*/
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 the 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 you click on the panel, bullets will also be deducted
MainFrame.useAmmo(); // Consume bullets
}
/*
* if (at instanceof BirdLabel) {//If you click on the birdMainFrame.appScore(32);//
* Bonus points} if (at instanceof PigLabel) {// If the wild boar is clicked
* MainFrame.appScore(11);//Extra points}
*/
}
}
/**
* Thread that generates pig characters
*
*/
class PigThread extends Thread {
@Override
public void run() {
while (true) {
//Create a label control representing the wild boar
PigLabel pig = new PigLabel();
pig.setSize(120, 80);//Set the initial size of the control
backgroundPanel.add(pig);//Add controls to the background panel
try {
//The thread randomly sleeps 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) {
//Create a label control representing the bird
BirdLabel bird = new BirdLabel();
bird.setSize(50, 50);//Set the initial size of the control
backgroundPanel.add(bird);//Add controls to the background panel
try {
//The thread randomly sleeps for a period of time
sleep((long) (Math.random() * 3000) + 500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
I hope this article will be helpful to everyone’s Java programming.