OOP object-oriented programming Java play airplane game

Source: Internet
Author: User
Tags gety

#写在前面

Following an OOP object-oriented programming of the Russian Block project implementation process, OOP object-oriented programming of the Java game, in fact, writing is very simple, it is easy to understand, and the comments are written very clearly, there are problems, their own private to make up for the learning (by the way 50 deep squat, hey, usually why go), see the Picture:

#完整代码

Enemy aircraft

Package Com.tarena.fly;import java.util.random;/** * Enemy aircraft: Flying objects, enemies */public class airplane extends Flyingobject implemen TS Enemy {private int speed = 3;  Move step/** Initialize Data */public airplane () {this.image = Shootgame.airplane;width = Image.getwidth (); height = image.getheight () ; y =-height;          Random rand = new Random (); x = Rand.nextint (shootgame.width-width);} /** Gets the score */@Overridepublic int getscore () {  return 5;} /**//cross-border processing */@Overridepublic Boolean outofbounds () {   return y>shootgame.height;} /** Mobile */@Overridepublic void step () {   y + = Speed;}}

Reward

<span style= "FONT-SIZE:24PX;" >package com.tarena.fly;/** * Reward */public Interface Award {int double_fire = 0;  Double firepower int life = 1;   1 Life/** Get the reward type (above 0 or 1) */int getType ();} </span>


Bees

<span style= "FONT-SIZE:24PX;" >package Com.tarena.fly;import java.util.random;/** Bee */public class Bee extends Flyingobject implements award{ private int xspeed = 1;   X-coordinate movement speed private int yspeed = 2;   Y-coordinate movement speed private int awardtype;    Reward type/** initialization data */public Bee () {this.image = Shootgame.bee;width = Image.getwidth (); height = image.getheight (); y =-height ; Random rand = new Random (); x = Rand.nextint (shootgame.width-width); awardtype = Rand.nextint (2)   ; Give reward}/** when initializing to receive the reward type */public int GetType () {return awardtype;} /** Cross-border processing */@Overridepublic Boolean outofbounds () {return y>shootgame.height;} /** Mobile, can fly diagonally */@Overridepublic void step () {      x + = Xspeed;y + yspeed;if (x > Shootgame.width-width) {  xspeed =-1; }if (x < 0) {xspeed = 1;}}} </span>


Bullet type: Flying Object

<span style= "FONT-SIZE:24PX;" >package com.tarena.fly;/** * Bullets: Is flier */public class Bullet extends Flyingobject {private int speed = 3;  Moving speed/** Initialize data */public Bullet (int x,int y) {this.x = X;this.y = Y;this.image = Shootgame.bullet;} /** Mobile */@Overridepublic void step () {   y-=speed;} /** Cross-border processing */@Overridepublic Boolean outofbounds () {return y<-height;}} </span>


The enemy's score

<span style= "FONT-SIZE:24PX;" >package com.tarena.fly;/** * Enemy, can have score */public interface Enemy {/** enemy score  */int Getscore ();} </span>

Flying objects (enemy aircraft, bees, bullets, hero machines)
Flying objects (enemy aircraft, bees, bullets, Heroes) Bullets: Flying Objects

Package Com.tarena.fly;import java.awt.image.bufferedimage;/** * Flying objects (enemy aircraft, bees, bullets, hero machines) */public abstract class    flyingobject {protected int x;    x-coordinate protected int y;    Y-coordinate protected int width;   width protected int height;   High protected bufferedimage image; Picture public int GetX () {return x;} public void SetX (int x) {this.x = x;} public int GetY () {return y;} public void sety (int y) {this.y = y;} public int getwidth () {return width;} public void setwidth (int width) {this.width = width;} public int getheight () {return height;} public void setheight (int height) {this.height = height;} Public BufferedImage GetImage () {return image;} public void SetImage (bufferedimage image) {this.image = image;}  /** * Check if out of bounds * @return true out of bounds */public abstract Boolean outofbounds ();/** * Flier Move one step */public abstract void step ();/** * Check if the current flying object is being shot (x, y) (shoot) * @param Bullet Bullet Object * @return true means hit */public boolean shootby (Bullet Bullet) {int x = Bul  Let.x;  Bullet axis int y = BULLET.Y; Bullet ordinate return this.x<x &&Amp X<this.x+width && this.y<y && y<this.y+height;}}


Game Launcher Main Class

Package Com.tarena.fly;import Java.awt.font;import Java.awt.color;import java.awt.graphics;import Java.awt.event.mouseadapter;import Java.awt.event.mouseevent;import Java.util.arrays;import java.util.Random; Import Java.util.timer;import java.util.timertask;import Java.awt.image.bufferedimage;import Javax.imageio.ImageIO ; Import Javax.swing.imageicon;import Javax.swing.jframe;import javax.swing.jpanel;public class ShootGame extends JPanel {public static final int width = 400;//Panel wide public static final int height = 654;//Panel height/** The current status of the game: START RUNNING  PAUSE game_over */private int state;private static final int START = 0;private static final int RUNNING = 1;private static Final int PAUSE = 2;private static final int game_over = 3;private int score = 0; Scoring private timer timer; Timer private int intervel = 1000/100; Interval (milliseconds) public static bufferedimage background;public static bufferedimage start;public static BufferedImage airplane ;p ublic static bufferedimage bee;public static BuffeRedimage bullet;public static bufferedimage hero0;public static bufferedimage hero1;public static bufferedimage pause; public static BufferedImage gameover;private flyingobject[] flyings = {}; Enemy array private bullet[] bullets = {}; Bullet array Private Hero Hero = new Hero (); Hero machine Static {//static code block, initialize picture resource try {background = Imageio.read (ShootGame.class.getResource ("background.png")); start = Imageio.read (ShootGame.class.getResource ("start.png")); airplane = Imageio.read (ShootGame.class.getResource (" Airplane.png ") Bee = Imageio.read (ShootGame.class.getResource (" bee.png ")); bullet = Imageio.read ( ShootGame.class.getResource ("Bullet.png")), Hero0 = Imageio.read (ShootGame.class.getResource ("hero0.png")); Hero1 = Imageio.read (ShootGame.class.getResource ("Hero1.png"));p ause = Imageio.read (ShootGame.class.getResource (" Pause.png ")); Gameover = Imageio.read (ShootGame.class.getResource (" gameover.png "));} catch (Exception e) {e.printstacktrace ();}} /** painting */@Overridepublic void Paint (Graphics g) {G.drawimage (BACKground, 0, 0, NULL); Drawing background Painthero (g); Draw Hero Machine Paintbullets (g); Draw Bullets paintflyingobjects (g); Painting flier Paintscore (g); Draw score Paintstate (g); Draw game state}/** draw hero Machine */public void Painthero (Graphics g) {G.drawimage (Hero.getimage (), Hero.getx (), hero.gety (), null);} /** Draw Bullets */public void Paintbullets (Graphics g) {for (int i = 0; i < bullets.length; i++) {Bullet b = Bullets[i];g.drawi Mage (B.getimage (), B.getx ()-B.getwidth ()/2, b.gety (), null);}} /** painting flier */public void Paintflyingobjects (Graphics g) {for (int i = 0; i < flyings.length; i++) {Flyingobject F = flyin Gs[i];g.drawimage (F.getimage (), F.getx (), f.gety (), null);}} /** Draw fraction */public void Paintscore (Graphics g) {int x = ten;//x-coordinate int y =;//y-coordinate font font = new Font (FONT.SANS_SERIF, Fo Nt. BOLD, 22); Font G.setcolor (new Color (0xFF0000)); G.setfont (font); Set the font g.drawstring ("Score:" + score, x, y); Draw score y=y+20; Y-coordinate increment 20g.drawstring ("Life:" + hero.getlife (), x, y); Life}/** painting game status */public void Paintstate (Graphics g) {switch (state) {CASE Start://Start State g.drawimage (start, 0, 0, null); Break;case pause://Pause State g.drawimage (pause, 0, 0, null); Break;case game_o VER://game termination status G.drawimage (Gameover, 0, 0, null); break;}} public static void Main (string[] args) {JFrame frame = new JFrame ("Fly"); Shootgame game = new Shootgame (); Panel Object Frame.add (game); Add a panel to the JFrame frame.setsize (WIDTH, HEIGHT); Set size Frame.setalwaysontop (TRUE); Set its total at the top frame.setdefaultcloseoperation (jframe.exit_on_close); The default shutdown operation Frame.seticonimage (new ImageIcon ("Images/icon.jpg"). GetImage ()); Sets the icon for the form frame.setlocationrelativeto (null); Sets the initial position of the form frame.setvisible (true); Call Paintgame.action () as soon as possible; Start execution}/** start execution code */public void action () {///mouse listener event Mouseadapter L = new Mouseadapter () {@Overridepublic void mousemoved (M Ouseevent e) {//mouse move if (state = = RUNNING) {//Move the hero machine in the run status--with the mouse position int x = E.GETX (); int y = E.gety (); Hero.moveto (x, y);}} @Overridepublic void mouseentered (MouseEvent e) {//Mouse entry to if (state = = pause) {//suspend status Run as = RUNNING;}} @Overridepublicvoid mouseexited (MouseEvent e) {//Mouse exit if (state = = RUNNING) {//The game does not end, set it to pause state = pause;}} @Overridepublic void mouseclicked (MouseEvent e) {//mouse click Switch (state) {Case start:state = RUNNING;//Run in startup State Break;case Game_over://Game over, cleanup site flyings = new Flyingobject[0]; Emptying the flier bullets = new Bullet[0]; Empty bullets Hero = new Hero (); Re-create hero machine score = 0; Clears the result state = START; The status is set to start break;}}; This.addmouselistener (l); Handle mouse click Operation This.addmousemotionlistener (L); Handling mouse Slide Operation timer = new timer (); Master Process Control Timer.schedule (new TimerTask () {@Overridepublic void run () {if (state = = RUNNING) {//Run status enteraction ();//Flier entry Stepaction (); Take one step shootaction (); Hero Machine Shooting bangaction (); Bullets hit flier outofboundsaction (); Removal of transboundary fliers and Bullets Checkgameoveraction (); Check Game over}repaint (); Redraw, call Paint () method}}, Intervel, intervel);} int flyenteredindex = 0; Flier Admission Count/** flier Admission */public void Enteraction () {flyenteredindex++;if (flyenteredindex% 40 = = 0) {//400 MS generates a flier--10*40 Flyingobject obj = Nextone (); Randomly generates a flier flyings= Arrays.copyof (flyings, flyings.length + 1); flyings[flyings.length-1] = obj;}} /** Take one step */public void Stepaction () {for (int i = 0; i < flyings.length; i++) {//Flier go one step flyingobject f = flyings[i];f.s Tep ();} for (int i = 0; i < bullets.length; i++) {//Bullets go one step bullet B = bullets[i];b.step ();} Hero.step (); Hero Machine Take one step}/** flying things take one step */public void Flyingstepaction () {for (int i = 0; i < flyings.length; i++) {Flyingobject F = flyin Gs[i];f.step ();}} int shootindex = 0;  Shot Count/** shot */public void Shootaction () {shootindex++;if (shootindex% 30 = = 0) {//300 milliseconds send a bullet[] bs = Hero.shoot (); Hero Shot bullets = arrays.copyof (bullets, bullets.length + bs.length); Expansion System.arraycopy (BS, 0, Bullets, bullets.length-bs.length,bs.length); Append array}}/** bullet collision detection with flier */public void Bangaction () {for (int i = 0; i < bullets.length; i++) {//traverse all bullets bullet B = Bull Ets[i];bang (b); Collision check between bullets and fliers}}/** Delete out-of-bounds fliers and bullets */public void Outofboundsaction () {int index = 0;//index flyingobject[] flyinglives = new F LYingobject[flyings.length]; Living flier for (int i = 0; i < flyings.length; i++) {Flyingobject f = flyings[i];if (!f.outofbounds ()) {Flyinglives[index + +] = f; Keep}}flyings = arrays.copyof (flyinglives, index) without crossing the border; Keep the flying objects that don't cross the border. Index = 0; Index reset to 0bullet[] bulletlives = new Bullet[bullets.length];for (int i = 0; i < bullets.length; i++) {Bullet b = bullets [I];if (!b.outofbounds ()) {bulletlives[index++] = b;}} Bullets = arrays.copyof (bulletlives, index); Keep the bullets out of bounds}/** check the game over */public void Checkgameoveraction () {if (Isgameover () ==true) {state = Game_over;//Change status}}/** check game Whether to end */public Boolean isgameover () {for (int i = 0; i < flyings.length; i++) {int index =-1; Flyingobject obj = flyings[i];if (hero.hit (obj)) {//check if the Hero machine collides with the flier hero.subtractlife ();//Life-loss hero.setdoublefire (0);//Double Fire Lift index = i; Record the Flying object hit index}if (Index! =-1) {Flyingobject T = flyings[index];flyings[index] = Flyings[flyings.length-1];flyings[flyin Gs.length-1] = t; Met with the last flier exchange Flyings = arrays.copyof (flyIngs, flyings.length-1); Remove the Flying Objects}}return Hero.getlife () <= 0;} Collision check between/** bullets and fliers */public void Bang (Bullet Bullet) {int index =-1;///Hit flier index for (int i = 0; i < flyings.length; i++ {Flyingobject obj = flyings[i];if (Obj.shootby (bullet)) {//Determines whether to hit index = i;//record the index of the hit flier break;}} if (Index! =-1) {//have hit the flier flyingobject one = Flyings[index];//Record The Flying object that was hit flyingobject temp = Flyings[index];//The Flying object hit With the last flier exchange Flyings[index] = flyings[flyings.length-1];flyings[flyings.length-1] = Temp;flyings = Arrays.copyOf ( Flyings, flyings.length-1); Delete the last flier (i.e. hit)//check the type of one (enemy bonus points, reward gets) if (one instanceof Enemy) {//Check type, is enemy, then add points Enemy e = (Enemy) A;//force type conversion score + = E.getscore (); Bonus points} else {//If reward, set Bonus award a = (award) One;int type = A.gettype ();//Get award Type switch (type) {case Award.DOUBLE_FIRE:her O.adddoublefire (); Set double firepower break;case Award.LIFE:hero.addLife (); Set the Kill break;}}} /** * Randomly generated flier * * @return Flier object */public static Flyingobject Nextone () {Random random = new RAndom (); int type = Random.nextint (20); [0,20) if (type < 4) {return new Bee ();} else {return new airplane ();}}}


#写在最后

The picture is not uploaded, need the source of the image please contact me privately, contact the way blog left!

Well, that's it, sleep!

OOP object-oriented programming Java play airplane game

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.