Java mini-game of the Dozen Aircraft (ii)

Source: Internet
Author: User
Tags explode getcolor

Java mini-game of the Dozen Aircraft (ii)

This article should have been written yesterday, but really intend to write the time, CSDN Blog maintenance, leading to drag to today:

The basic architecture and requirements analysis of the game have been described in detail in the last article of the Java mini-game airplane (i), and write down the implementation of each class in detail today:

1) Planegameframe class----The main interface of the game and some specific aircraft action methods, collision detection, etc.
Code:
Package Plane;import Java.awt.color;import Java.awt.font;import java.awt.graphics;import java.awt.Image;import Java.awt.event.keyadapter;import Java.awt.event.keyevent;import Java.util.arraylist;import Java.util.Date;import Util. Gameutil;import util. myframe;/** * Aircraft Game Main Page * inherit to MyFrame class under Util package * @author long * */public class Planegameframe extends MyFrame {Image Bg=gameut Il.getimage ("images/bg.jpg"); Plane p=new Plane ("Images/plane.png", 50,50); int bulletnum = 10; ArrayList list = new arraylist<bullet> (); Explode e = Null;//explode e = new Explode (a);D ate starttime;date endTime; @Overridepublic void Paint (Graphics g) {G.D Rawimage (BG, 0, 0, NULL), if (p.islive) {P.draw (g);d Rawbullet (g), Endtime=new Date ();p rinttime (g);} Else{e.draw (g); Printinfo (Lever (), 180,200,50,color.yellow,g);p rintinfo ("Total Time:" +gettime () + "s", 180,240, 20, COLOR.YELLOW,G);}} public void Printtime (Graphics g) {Double t = getTime (); if (t>0) {Printinfo ("Time:" +t+ "S", 390,50,15,color.yellow,g);}} Public double GetTime () {Double tiMe;int t= (int) (Endtime.gettime ()-starttime.gettime ())/100; System.out.println ("Time:" +t); time = T/10.0;if (t<0.2) return 0;return time;} Public String Lever () {string msg= "", int lever = (int) getTime ()/10;switch (lever) {case 0:msg = "rookie"; Break;case 1:msg = "Bird "; Break;case 2:msg =" Big Bird "; break;case 3:msg =" Prince of birds "; break;default:msg =" Bird God "; break; return msg;} public void Drawbullet (Graphics g) {for (int i=0;i<bulletnum;i++) {Bullet b= (Bullet) list.get (i); B.draw (g); Boolean Peng = B.getrect (). intersects (P.getrect ()), if (peng) {p.islive = False;if (e==null) {e=new Explode (p.x, p.y);} E.draw (g); Printinfo ("GAME over", 150,300,50,color.yellow,g); public void Printinfo (String str,int x,int y,int size,color color,graphics g) {Color c = g.getcolor (); G.setcolor (color); Font f = new font ("italic", font.bold,size); G.setfont (f); g.drawstring (str, x, y); G.setcolor (c);} public void Launchframe () {super.launchframe (), This.addkeylistener (New Keymonitor ()); for (int i=0;i<bulletnum;i++ ) {Bullet b=new Bullet (); list.Add (b);} StartTime = new Date ();} Class Keymonitor extends keyadapter{@Overridepublic void keypressed (KeyEvent e) {//system.out.println ("##########"); /system.out.println (E.getkeycode ());p. Addmove (e); @Overridepublic void keyreleased (KeyEvent e) {p.relisemove (e);}} public static void Main (string[] args) {new Planegameframe (). Launchframe ();}}

2) MyFrame class----PlanegameframeClass of the parent class, mainly some of the basic properties of the interface and methods of encapsulation, easy to expand the game
Code:
Package Util;import javax.swing.jframe;import javax.swing.jpanel;/** * Game Panel Parent class * @author long * */public class MyFrame Ext Ends jpanel{/** * Method of loading frame */public void Launchframe () {JFrame frame = new JFrame ("Mygame"); Frame.add (this); Frame.setsize (constant.game_width,constant.game_height); Frame.setalwaysontop (true); Set its total at the top frame.setlocationrelativeto (null); Set the initial position of the form frame.setdefaultcloseoperation (jframe.exit_on_close); frame.setvisible (true); Setfocusable (true); new Paintthread (). Start ();}  /** * Defines a redraw window for the thread class, is an inner class * @author Dell * */class Paintthread extends thread {public void run () {while (true) {repaint (); try {Thread.Sleep (+);//1s = 1000ms} catch (Interruptedexception e) {e.printstacktrace ();}}}   } public static void Main (string[] args) {new MyFrame (). Launchframe ();}}

3) Constant class----constant class, mainly encapsulates the constants used in the project
Code:
Package Util;public class Constant {public static final int game_width = 500;public static final int game_height = 500;}

4) The Gameutil class----Game tool class, used to encapsulate the game common tool method, because the project is relatively small, here just encapsulates a method of loading the picture, subsequent can encapsulate more methods
Code:
Package Util;import Java.awt.image;import Java.awt.image.bufferedimage;import java.io.ioexception;import Java.net.url;import javax.imageio.imageio;/** * Tool class (load picture) * @author long * */public class Gameutil {private Gameutil () {}< The c0/>//tool class will typically construct a method private public static Image GetImage (String path) {URL u = GameUtil.class.getClassLoader (). GetResource (Path) ; BufferedImage img = null;try {img = imageio.read (u);} catch (IOException e) {e.printstacktrace ();} return img;}}

5) Gameobject class----Game object class, encapsulates the basic properties and methods of game objects, film, coordinates, image width height and other properties, there is a more important way public Rectangle getrect () This method is used for subsequent collision detection
Code:
Package Plane;import Java.awt.image;import java.awt.rectangle;/** * Game Object class * @author long * */public class Gameobject {Imag e img;  Picture double x, y; coordinate int speed;  speed int width;  width int height; Height public gameobject () {}public-Gameobject (Image img, double x, double y, int speed, int width,int height) {super (); this.i MG = Img;this.x = X;this.y = Y;this.speed = Speed;this.width = Width;this.height = height;} Public Rectangle GetRect () {Rectangle r = new Rectangle ((int) x, (int) y, width, height); return r;}}

6) Plane class----inherit toGameobjectClass that encapsulates the method of airplane movement (keyboard events)
Code:
Package Plane;import java.awt.graphics;import java.awt.image;import java.awt.event.keyevent;import util. Constant;import util. gameutil;/** * Aircraft class * * @author long * */public class Plane extends Gameobject {Boolean left, right, up, down;//Status of Move direction Boolean islive = True;public void Draw (Graphics g) {G.drawimage (img, (int) x, (int) y, null), move ();} /** * Move state while pressing the keyboard * @param e */public void Addmove (keyevent e) {switch (E.getkeycode ()) {Case KeyEvent.VK_LEFT:left = Tru E;break;case KeyEvent.VK_RIGHT:right = true;break;case KeyEvent.VK_UP:up = True;break;case KeyEvent.VK_DOWN:down = True ; break;default:break;}} /** * Move state changes when releasing the keyboard * * @param e */public void Relisemove (keyevent e) {switch (E.getkeycode ()) {case KeyEvent.VK_LEFT:le FT = false;break;case KeyEvent.VK_RIGHT:right = false;break;case KeyEvent.VK_UP:up = false;break;case Keyevent.vk_down: down = False;break;default:break;}} public void Move () {if (left) {x = speed;if (x < 0) {x = 0;}} if (right) {x + = speed;if (x > Constant.game_width-width) {x = Constant.game_width-width;}} if (up) {y-= speed;if (Y < 0) {y = 0;}} if (down) {y + = speed;if (Y > constant.game_height-height-30) {y = constant.game_height-height-30;}}} Public Plane () {}public Plane (Image img, double x, double y) {this.speed = 10;this.img = img;this.x = X;this.y = Y;this.wi DTH = Img.getwidth (null) -10;this.height = Img.getheight (null)-10;} Public Plane (String Imgpath, double x, double y) {This (Gameutil.getimage (Imgpath), x, y);}}

7) Bullet class----bullets, inherited to the Gameobject class, encapsulated the bullet's basic properties and methods, there is an important thing about the bullet hit the wall rebound implementation
Code:
Package Plane;import java.awt.color;import java.awt.graphics;import java.awt.image;import util. constant;/** * bullets * randomly generated movement angle * hit the wall will bounce back * @author long * */public class Bullet extends Gameobject {double degree;//Angle PU Blic void Draw (Graphics g) {Color c = g.getcolor (); G.setcolor (Color.yellow); G.filloval ((int) x, (int) y, width, height); G.setcolor (c); x + = Speed*math.cos (degree); y + = Speed*math.sin (degree); if (y>constant.game_height-height-40| | y<0) {degree =-degree;} if (x<0| | X>constant.game_width-width-width) {degree = Math.pi-degree;}} Public Bullet () {this.x = Constant.game_width/2;this.y = Constant.game_height/2;this.width = 10;this.height = 10; This.speed = 5;  Bullet Movement Speed degree = math.random () *math.pi*2; Randomly generated}}

8) Explode class----explosion class, mainly used for bullets hit the aircraft when the explosion effect of the implementation, that is, a series of exploded pictures loading and painting on the panel
Code:
Package Plane;import java.awt.graphics;import java.awt.image;import util. Gameutil;public class Explode {double x,y;static image[] imgs=new image[16];static {for (int i=0;i


----------------------------------------------------------------------------------

Since then, the source code and the general explanation of all the classes in the project have ended, and the following will be a detailed account of the important methods and the difficulties I have encountered:

1. Collision Detection-----Bullet and aircraft collision

Collision detection in the game is usually to detect the two objects in which the rectangle is intersected? If the intersection is colliding, otherwise, no

Let's start with a way to create a rectangle:
Public Rectangle GetRect () {
Rectangle r = new Rectangle ((int) x, (int) y, width, height);
return R;
}
This method is primarily used to return a rectangle, creating a rectangular object based on the coordinates and the length of the width

Then introduce a method for detecting the intersection of rectangles:

Boolean java.awt.Rectangle.intersects (Rectangle R)
Returns true if two rectangles intersect, otherwise false

2. How to get the bullet to bounce back against the wall:

if (y>constant.game_height-height-40| | y<0) {
degree =-degree;
}
if (x<0| | X>constant.game_width-width-width) {
degree = Math.pi-degree;
}

degree represents the angle of the bullet run, X, y represents the coordinates of the bullet, Constant.game_height represents the height of the game panel, the constant.game_width represents the width of the game panel, height indicates the height of the bullet, width of the bullet

3. Reasons why keyboard events are not responding:

Keyboard events in the Panel receive focus by default, while the focus in JPanel is false, which is set to true manually or not in response to keyboard events
Manually add Setfocusable (true) when newjframe; it's OK.


Since then, the whole game is over, welcome to learn together and correct!!!



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java mini-game of the Dozen Aircraft (ii)

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.