Java Hunting shooting game code _java based on swing implementation

Source: Internet
Author: User
Tags event listener set background

This article illustrates the Java hunting shooting game code based on swing implementation. Share to everyone for your reference.

The specific implementation code is as follows:

Copy 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 picture

Public Backgroundpanel () {
Setopaque (FALSE);
SetLayout (NULL);
}

public void setimage (image image) {
This.image = image;
}

/**


* Draw a background


*/


protected void Paintcomponent (Graphics g) {


if (image!= null) {


Picture width


int width = getwidth ();


Picture height


int height = getheight ();


Draw a picture


G.drawimage (image, 0, 0, width, height, this);


}


Super.paintcomponent (g);


}


}


Copy 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;
Random generation of the thread's sleep time, that is, control the bird moving speed
private int sleeptime = (int) (Math.random () * 300) + 5;
private int y = 100;
Private thread thread;//The 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 Control icons


Addmouselistener (New MouseAction ());//Add mouse event listener


Adding control event listeners


Addcomponentlistener (New Componentaction ());


thread = new threads (this);//Create threading Object


}

/**
* Control event listener for controls
*/
Private Final class Componentaction extends Componentadapter {
public void componentresized (final componentevent e) {
Thread.Start ();//thread Start
}
}

/**


* Mouse event listener for the control


*/


Private Final class MouseAction extends Mouseadapter {


public void mousepressed (final mouseevent e) {


if (! Mainframe.readyammo ())//If the bullets are not ready.


return;//don't do anything.


Mainframe.useammo ()//consumption of bullets


Appscore ()//bonus points


Destory ()//Destroy This component


}


}

public void Run () {


parent = NULL;


int width = 0;


try {


while (width <= 0 | | | parent = NULL) {


if (parent = null) {


Parent = GetParent ();


} else {


width = parent.getwidth ();//Get the breadth of the parent container


}


Thread.Sleep (10);


}


for (int i = width; i > 0 && parent!= null; I-= 8) {


SetLocation (i, y);//move this component position from right to left


Thread.Sleep (sleeptime);/dormant for a moment


}


catch (Interruptedexception e) {


E.printstacktrace ();


}


if (parent!= null) {


Mainframe.appscore (-score * 10); Natural destruction will deduct points


}


Destory ()//move complete, destroy this component


}

       /**
         * Methods for removing this component from the container
         */
         public void Destory () {
                 if (parent = null)
                         return;
                Parent.remove ( this);//remove this gradually from the parent container
                 Parent.repaint ();
                parent = null;// Terminate thread looping
       }

with this statement

/**
* Method of adding points
*/
private void Appscore () {
System.out.println ("The bird is hit");
Mainframe.appscore (15);
}
}

Copy 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;
Random generation of dormant time, that is, wild boar moving speed
private int sleeptime = (int) (Math.random () * 300) + 30;
private int y = 260;//control's vertical coordinates
private int score = 10;//The score corresponding to the role
Private thread thread;//Built-in thread object
Private Container parent;//control's parent container object

/**


* Construction Method


*/


Public Piglabel () {


Super ();


ImageIcon icon = new ImageIcon (GetClass (). GetResource ("Pig.gif"))//load wild boar pictures


SetIcon (icon)//Set icons for this component


Add Mouse Event Adapter


Addmouselistener (New Mouseadapter () {


How to handle the mouse button


public void mousepressed (final mouseevent e) {


if (! Mainframe.readyammo ())


Return


Mainframe.useammo ()//consumption of bullets


Appscore ()//Add points to the game


Destory ()//Destroy This component


}


});


Adding component Event Adapters


Addcomponentlistener (New Componentadapter () {


Resize component Large hours


public void componentresized (final componentevent e) {


Thread.Start ()//Start thread


}


});


Initializing a Thread object


thread = new thread (this);


}

public void Run () {


parent = NULL;


int width = 0;


while (width <= 0 | | | parent = NULL) {//Get 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);/dormant for a moment


catch (Interruptedexception e) {


E.printstacktrace ();


}


}


if (parent!= null) {


Mainframe.appscore (-score * 10); Natural destruction will deduct points


}


Destory ();


}

       /**
         * Methods for removing this component from the container
         */
         public void Destory () {
                 if (parent = null)
                         return;
                Parent.remove ( this);
                Parent.repaint () ;
                parent = null;// Terminate thread looping
       }

with this statement

/**
* Method of adding points
*/
private void Appscore () {
System.out.println ("Wild boar is hit");
Mainframe.appscore (10);
}
}

Copy 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;//fraction
private static Integer Ammonum = number of 5;//bullets
private static JLabel scorelabel;//fractions
Private Backgroundpanel Backgroundpanel;
private static JLabel Ammolabel;
private static JPanel InfoPane;

/**


* Construction Method


*/


Public MainFrame () {


Super ();


Setresizable (false);//Feed Resize form


Settitle ("Hunting Game");


InfoPane = (JPanel) Getglasspane ()//Get glass panel


JLabel label = new JLabel ("Load bullets ...");//Create a hint label component


Label.sethorizontalalignment (Swingconstants.center);


Label.setfont (New Font ("italics", Font.Bold, 32));


Label.setforeground (color.red);


Infopane.setlayout (New BorderLayout ());


Infopane.add (label);//Add hint label component to Glass panel

Setalwaysontop (TRUE);//is the form remains at the top level


SetBounds (100, 100, 573, 411);


Setdefaultcloseoperation (Jframe.exit_on_close);


Backgroundpanel = new Backgroundpanel ();//Create a panel with background


Backgroundpanel.setimage (New ImageIcon (GetClass (). GetResource (


"Background.jpg")). GetImage ())//Set background picture


Getcontentpane (). Add (Backgroundpanel, borderlayout.center);


Add Mouse Event Adapter


Addmouselistener (New Framemouselistener ());


Scorelabel = new JLabel ();//Label component showing score


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);


}

/**
* Method of adding points
*/
Public synchronized static void Appscore (int num) {
Score + = num;
Scorelabel.settext ("Score:" + score);
}

/**


* Method of consuming bullets


*/


Public synchronized static void Useammo () {


Synchronized (ammonum) {


The number of ammonum--;//bullets decreased


Ammolabel.settext ("Number of bullets:" + ammonum);


if (ammonum <= 0) {//judge whether the bullet is less than 0


New Thread (New Runnable () {


public void Run () {


Display the Hint Info panel


Infopane.setvisible (TRUE);


try {


1 seconds to load the bullets.


Thread.Sleep (1000);


catch (Interruptedexception e) {


E.printstacktrace ();


}


Ammonum = 5;//Recovery Bullet number


Revise the Bullet Quantity label text


Ammolabel.settext ("Number of bullets:" + ammonum);


Infopane.setvisible (false);//Hide Hint Info panel


}


). Start ();


}


}


}

/**
* To determine whether a bullet is adequate
*
*/
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 dot to panel also deduct bullets


Mainframe.useammo ()//consumption of bullets


}


/*


* IF (at instanceof Birdlabel) {//If point to birdie Mainframe.appscore (32);


* Plus cent} if (at instanceof Piglabel) {//if the boar


* Mainframe.appscore (11);//Bonus points}


*/


}


}

/**


* thread to generate pig role


*


*/


Class Pigthread extends Thread {


@Override


public void Run () {


while (true) {


Create a Label control that represents a wild boar


Piglabel pig = new Piglabel ();


Pig.setsize (120, 80);//Set the initial size of the control


Backgroundpanel.add (pig);//Add control to Background panel


try {


Threads sleep randomly for a period of time


Sleep (Long) (random () * 3000) + 500);


catch (Interruptedexception e) {


E.printstacktrace ();


}


}


}


}

/**


* Threads that generate bird characters


*


*/


Class Birdthread extends Thread {


@Override


public void Run () {


while (true) {


Create a Label control that represents a bird


Birdlabel bird = new Birdlabel ();


Bird.setsize (50, 50);//Set the initial size of the control


Backgroundpanel.add (bird);//Add control to Background panel


try {


Threads sleep randomly for a period of time


Sleep (Long) (Math.random () * 3000) + 500);


catch (Interruptedexception e) {


E.printstacktrace ();


}


}


}


}


}


I hope this article will help you with your Java programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.