Java applet Ball Ball big battle (based on Java thread implementation) __ static function

Source: Internet
Author: User
Tags thread class


Java applet ball Big Battle (based on Java thread implementation)


first, the basic functions of the game:

1, their own small ball can be moved with the mouse to change the coordinates;

2, the enemy ball constantly moving in the interface

3. When the enemy ball is detected colliding with each other, the ball will bounce off

4, when our small ball collision with the enemy, we will judge the radius of the two sides, if our diameter is large, then eat the ball, score accumulation

If the enemy ball is bigger than ours, game interface, toggle panel, show game score


second, the game Operation interface:




third, the game to achieve the approximate idea


1. Create a form

2, create our small ball, and realize the mouse mobile monitoring

3. Create an enemy ball (Inherit thread class, each ball will keep moving)

4, to achieve collision detection (calculate the distance between the center of the small Ball and center)

5, the game is over, switch panel


Difficulties:

1. Multiple ball implementations (list package)

Implementation mechanism: If it involves a lot of small ball movement, then we need a container for unified management

Container: ArrayList

1 Create a ball through a loop: The code can be defined in the current class's construction method

2 drawing a small ball, by traversing the container object, to draw

3 coordinates, the ball diameter can be defined in a small ball, through the properties of the ball packaging

4 Paint method is only used to draw graphics,

5 How to calculate the center distance

1> first calculates the center coordinates of each ball: X+WIDTH/2 Y+WIDTH/2

2> the transverse distance and the longitudinal distance.

3> Calculate hypotenuse length

2. Double buffering to solve the flash screen problem

A) Principle:

I. By buffering the picture, draw all the things that need to be drawn first on the buffer picture

Ii. draw the buffered picture onto the form/panel

b) Implementation steps: Pant Method transformation

1. Create a buffered picture

2. Get a brush on a picture

3. Draw all the graphics through the picture brush

4. Draw the buffer picture onto the form

3. Keyboard listener Control oneself ball movement: KeyListener

A you need to define a class to implement the Listener interface

b) w:87 s:83 a:65 d:68

On: 38 Next: 40 Left: 37 Right: 39

4. Mouse listener control Their small ball movement: Mousemotionlistener Mouse Mobile monitoring

5. Music Add

A) Copy the Music.jar package to the engineering directory

b Right-click Music.jar, select Build Path, select Add to build Path option


Four, panel switch function code: every 2 seconds to switch pages

Package com.bluesky.movingball;
Import Java.awt.Color;

Import Java.awt.Graphics;
Import Javax.swing.ImageIcon;
Import Javax.swing.JFrame;

Import Javax.swing.JPanel;
	public class Gameframe extends jframe{public boolean flag=true;
	Public JPanel Panel,panel2;
	
	Public Graphics G;
	
	Public ImageIcon bgimg= New ImageIcon ("img/bg1.jpg");
		public void Initframe () {this.settitle ("moving Ball");
		This.setsize (800, 600);
		This.setdefaultcloseoperation (3);
		This.setlocationrelativeto (NULL);
		panel = new JPanel ();
		Panel.setbackground (color.red);
		Panel2 = new JPanel ();
		Panel2.setbackground (Color.green);
		Changepanel (this);
		This.add (panel);
		This.setvisible (TRUE);
		G=panel.getgraphics ();
	System.out.println ("this:" +g);
						public void Changepanel (Gameframe f) {new Thread () {public void run () {while (true) {if (!flag) {
						F.remove (panel);
						F.add (PANEL2);
						F.repaint ();
					F.setvisible (TRUE);
						} if (flag) {f.remove (PANEL2); F.adD (Panel);
						F.repaint ();
					F.setvisible (TRUE);
						try {sleep (2000);
					Flag=!flag;
					catch (Interruptedexception e) {e.printstacktrace ();
	}}}.start ();
 }

}


Package com.bluesky.movingball;

public class Test {public
	static void Main (string[] args) {
		Gameframe GF = new Gameframe ();
		Gf.initframe ();

	}


Five, Ball ball big Combat source code:

Main interface class:

Package Com.huaxin.zhou;
Import Java.awt.BasicStroke;
Import Java.awt.Color;
Import Java.awt.Graphics;
Import Java.awt.Graphics2D;
Import Java.awt.Image;
Import Java.awt.Stroke;
Import java.util.ArrayList;

Import Java.util.Random;
Import Javax.swing.ImageIcon;
Import Javax.swing.JFrame;

Import Javax.swing.JPanel; public class Moveballgame extends jframe{//hostile Pellets container class public static arraylist<movethread>list =new Arraylist<mo
	Vethread> ();
	
	With machine public Random r = new Random ();
	
	Public Myball Myball;
	
	public Ballmouselistener BL;
	
	Public JPanel Panel,overpanel;
	
	Public Moveballgame JF;
	
	public int score=0;
	
	Detect the end of the game flag public Boolean overflag=false;
	
	Detects whether the thread that adds the ball ends the public boolean over=false;
		Public Moveballgame () {myball = new Myball (0, 500, 1, 60);
		BL = new Ballmouselistener (Myball);
	Add background music com.huaxin.music.Util.startMusic ("Music/bg1.wav");
		}//form initialization public void Initframe () {jf=this;
		This.setsize (800,600); This.setdefaultcloSeoperation (3);
		This.setresizable (FALSE);
		This.settitle ("Ball ball big fight");
		This.setlocationrelativeto (NULL);
		Panel= new JPanel ();
		Overpanel= new JPanel ();
		
		This.add (panel);
		
		This.setvisible (TRUE);
		Get the brush of the form Graphics G =panel.getgraphics ();
		Add mouse to the form mobile monitor Ballkeylistener KL = new Ballkeylistener (Myball);
		Panel.addkeylistener (KL);
		
		Panel.addmousemotionlistener (BL);
		
	Checkballcount (); //paint method to draw small balls (enemy ball and our small ball), the soldier uses double buffering to solve the splash screen problem public void paint (Graphics g) {//Create a picture image buffimage = This.createimag
		E (800,600);
		
		Get this picture of the brush Graphics buffg=buffimage.getgraphics ();
		ImageIcon bgimg = new ImageIcon ("img/bg1.jpg");
		Draw Background Buffg.drawimage (Bgimg.getimage (), 0,0, null) for the picture;
			The loop draws the ball out of the container for (int i = 0; i < list.size (); i++) {Movethread MT = list.get (i);
			Buffg.setcolor (Mt.color);
		Buffg.filloval (Mt.x, Mt.y, Mt.width, mt.width);
		
		//Set the brush color draw our ball buffg.setcolor (color.orange); Buffg.filloval (myball.x, Myball.y, Myball.width, MYball.width);
	Use the brush of the form to draw the entire picture into the form g.drawimage (buffimage, 0, 0, NULL);
					public void Checkballcount () {//Detect whether the ball is finished thread, then recreate six balls after eating. New Thread () {public void run () {while (!over) {  while (!overflag) {//If there is no enemy ball on the screen, repaint 6 enemy balls if (MoveBallGame.list.size () = = 0) {for (int j = 0; J < 6;
								J + +) {movethread MT = new Movethread (JF);
								Mt.x + * J;
								Mt.y + * J;
								Mt.xspeed = 5;
								Mt.yspeed = 5;
								Mt.width = Jf.r.nextint (20) + 50;
								Mt.color = new Color (Jf.r.nextint (10000));
								MoveBallGame.list.add (MT);
							Mt.start ();
						} try {thread.sleep (100);
						catch (Interruptedexception e) {e.printstacktrace ();
						} if (Overflag) {jf.remove (panel);
						Jf.add (Overpanel);
						Jf.repaint ();
Jf.setvisible (TRUE);
						SYSTEM.OUT.PRINTLN ("panel switch");
						Graphics G=overpanel.getgraphics ();
	Graphics2D g1= (graphics2d) G;					ImageIcon overimg= New ImageIcon ("img/bg.jpg");
						G1.drawimage (Overimg.getimage (), 0, 0, NULL);
						G1.setcolor (color.red);
						G1.setstroke (New Basicstroke (5));
						G1.drawstring ("Game Over", 300,200);
						g.DrawString ("Score:" +score, 350, 200);
					Over=true;
					try {thread.sleep (100);
					catch (Interruptedexception e) {e.printstacktrace ();
				} try {thread.sleep (100);
				catch (Interruptedexception e) {e.printstacktrace ();
	}}.start ();
 }
	
	
}


Enemy Ball class: Each of the enemy's balls is a separate thread

Package Com.huaxin.zhou;

Import Java.awt.Color;

Import Javax.swing.JOptionPane;
	public class Movethread extends Thread {public moveballgame MB;
	public int x = m, y = 100;
	public int xspeed = 5;
	public int yspeed = 5;
	public int width;
	
	public color color;
public Boolean isbegin = true;
	
	public boolean over =false;
	Public Movethread (moveballgame MB) {this.mb = MB;
				//control each ball run thread public void run (!mb.overflag) {while (Isbegin) {//control the enemy ball movement x + = XSpeed;
				Y + + yspeed;
				Determine if the enemy ball is out of bounds if (This.x < | | this.x > 800-this.width-10) {xspeed =-xspeed;
				} if (This.y < | | this.y > 600-this.width-10) {yspeed =-yspeed;
				//Judge whether our ball is out of bounds if (Mb.myball.x < 4) {mb.myball.x = 4;
				} if (Mb.myball.y <28) {mb.myball.y = 28;
				} if (Mb.myball.x > 800-mb.myball.width-4) {mb.myball.x = 800-mb.myball.width-4; } if (Mb.myball.y > 600-MB. myball.width-4) {mb.myball.y = 600-mb.myball.width-4;

				//Collision Detection ishit ();
				Mb.repaint ();
				Thread Hibernate try {thread.sleep (50);
				catch (Interruptedexception e) {e.printstacktrace ();
			//thread Hibernate try {thread.sleep (50);
			catch (Interruptedexception e) {e.printstacktrace (); }//if (over) {//Joptionpane.showmessagedialog (NULL, "Game Over");//Mb.overflag=true//}//Check if the car is colliding
				The function of the public void Ishit () {//Determine whether the enemy ball and our ball are colliding with int x = ((this.x + this.width)-(mb.myball.x + mb.myball.width))
		* ((this.x + this.width)-(mb.myball.x + mb.myball.width)); int y = ((This.y + this.width)-(mb.myball.y + mb.myball.width)) * (This.y + this.width)-(mb.myball.y + mb.myball).
		width));

		int r = (int) math.sqrt (x + y);
			To determine the radius of the two sides of the large if (R <= (THIS.WIDTH/2 + mb.myball.width/2)) {//enemy diameter larger than me, then we are eaten, the game is over. if (This.width > Mb.myball.width) {//mb.overflag=true;//thIs.setdaemon (TRUE);
Isbegin = false;
				
				MoveBallGame.list.remove (this);
					for (int i = 0; I <moveballgame.list.size (); i++) {//MoveBallGame.list.get (i) Setdaemon (true);
				MoveBallGame.list.get (i). Isbegin=false; Joptionpane.showmessagedialog (NULL, "You are eaten by a big ball.")
				");
				Mb.overflag=true;
			Return
				///If our diameter is large, let us add 2 pixels in diameter and remove the small ball if (this.width <= mb.myball.width) {mb.myball.width = 2) from the container;

Mb.score=+this.width;
				This.setdaemon (TRUE);
				This.isbegin = false;
				
				MoveBallGame.list.remove (this);
					Our diameter is 500, we win if (Mb.myball.width >=) {//mb.overflag=true;
					Isbegin = false;
					MoveBallGame.list.remove (this); for (int i = 0; I <moveballgame.list.size (); i++) {MoveBallGame.list.get (i) isbegin=false;//Moveballgame.
					List.get (i). Setdaemon (True); Joptionpane.showmessagedialog (NULL, "Congratulations on winning.")
");
					Over=true;
				Mb.overflag=true; ()}}//Take from containerA small ball for (int i = 0; i < MoveBallGame.list.size (); i++) {Movethread MTB = MoveBallGame.list.get (i);
			If you are running a small ball, then take another small ball if (MTB = = this) {continue; else {//judge whether the enemy ball is colliding int x1 = ((mtb.x + mtb.width)-(this.x + this.width)) * (mtb.x + mtb.width)-(this.x +
				This.width));
				int y1 = ((Mtb.y + mtb.width)-(This.y + this.width)) * (Mtb.y + mtb.width)-(This.y + this.width));

				int r1 = (int) math.sqrt (x1 + y1);
					if (R1 <= (MTB.WIDTH/2 + this.width/2)) {mtb.xspeed =-mtb.xspeed;
					Mtb.yspeed =-mtb.yspeed;
					This.xspeed =-this.xspeed;
				This.yspeed =-this.yspeed;
 }
			}
		}

	}
}


Our small ball class:

Package Com.huaxin.zhou;

Import Java.awt.Color;

public class Myball {
	
	//our own ball

	//Our ball properties public
	int x,y;
	public int Speed;
	public int width;
	
	We are seeking the construction method of ball games public
	myball (int x, int y, int speed, int width) {
		this.x = x;
		This.y = y;
		This. Speed = Speed;
		This.width = width;
	}
	
	
}


Our small ball mouse mobile listening class:

Package Com.huaxin.zhou;

Import java.awt.event.MouseEvent;
Import Java.awt.event.MouseMotionListener;

Import Javax.swing.JOptionPane;

public class Ballmouselistener implements mousemotionlistener{
	
	//Our ball Mouse Mobile listener public
	
	Myball ball;
	
	Constructor public
	Ballmouselistener (Myball ball) {
		this.ball=ball;
	}
	
	When implementing mouse movement, the small ball coordinates change public
	void mousemoved (MouseEvent e) {
		int x=e.getx ();
		int y=e.gety ();
		
		BALL.X=X-BALL.WIDTH/2;
		ball.y=y;/*-ball.width/2;*/
		
	} public
	void mousedragged (MouseEvent e) {
		
	}
}



Our small ball keyboard mobile listening class:

Package Com.huaxin.zhou;

Import java.awt.event.KeyEvent;
Import Java.awt.event.KeyListener;

Import Javafx.scene.input.KeyCode;

public class Ballkeylistener implements keylistener{public
	
	myball ball;
	
	Public Ballkeylistener (Myball ball) {
		this.ball=ball;
	}

	public void keypressed (KeyEvent e) {
		
		int key=e.getkeycode ();
		
		
		if (key==37)
		ball.x-=3;
		if (key==38)
			ball.y-=3;
		if (key==39)
			ball.x+=5;
		if (key==40)
		  ball.y+=5;
		
	}

	public void keyreleased (KeyEvent e) {
		
	} public

	void keytyped (KeyEvent e) {
		
	}

}


Main function: Program entry

Package Com.huaxin.zhou;

Import Java.awt.Color;

public class MainFrame {public
	
	static void Main (string[] args) {
		//Program entry
		moveballgame MBG = new Moveballgam E ();
		Mbg.initframe ();
	}



Vi. Summary

Through this small project, learned a lot of knowledge, such as thread application, collision detection, double buffering principle and application, how to switch panels, music add, etc. encountered many problems in this project, such as memory leaks, because after the end of the game, use a double loop, because try is not the correct location, Causing memory leaks, that is, trapped in a dead loop;

It took several days to complete this little project, or, with the teacher's guidance, this design to a lot of knowledge of the details, the principle is not difficult to understand how much, mainly how to translate into code, as well as the understanding of the thread, how to end a thread; Collision detection is mainly used to calculate the center distance between circle and circle. Here we see the application of mathematics in computers, sure enough, mathematics is very important, of course, is not so important, you want to go to high places, you must learn enough knowledge; The individual feel that the panel switch is still cool, I do not know why, perhaps because finally can not be confined to the same panel. The double buffering principle turns out to be different from what it used to be, also used to update methods, the new version of the JDK simplifies this process, but also become better understanding; music switching needs to use a rack package, call inside a method can be achieved, well, or look forward to one day to be able to encapsulate their music package.

All right, let's just share it here. Share.




Related Article

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.