Android Combat Aircraft Game Monster (Enemy) class implementation (4) _android

Source: Internet
Author: User

First look at the effect chart:

Analysis: distinguish the motion logic of enemy aircraft according to the type of enemy aircraft and draw

/** * @author liuml * @time 2016-5-31 PM 4:14:59/public class Enemy {//the type of enemy aircraft identifies public int type;
  Fly public static final int type_fly = 1;
  Ducks (moving from left to right) public static final int type_duckl = 2;
  Ducks (moving from right to left) public static final int type_duckr = 3;
  Enemy image Resources public Bitmap bmpenemy;
  Enemy aircraft coordinates public int x, y;
  Enemy aircraft each frame of the wide high public int framew, Frameh;
  Enemy aircraft current frame subscript private int frameindex;
  The moving speed of enemy aircraft is private int speed;;

  Judge whether the enemy aircraft has been out of the screen public boolean isdead;
    The constructor of the enemy aircraft is Public Enemy (Bitmap bmpenemy, int enemytype, int x, int y) {this.bmpenemy = Bmpenemy;
    Framew = Bmpenemy.getwidth ()/10;
    Frameh = Bmpenemy.getheight ();
    This.type = Enemytype;
    this.x = x;
    This.y = y;
      Different types of enemy blood volume different switch (type) {//Fly case type_fly:speed = 25;
    Break
      Duck Case type_duckl:speed = 3;
    Break
      Case type_duckr:speed = 3;
    Break }///enemy drawing function public void Draw (Canvas Canvas, Paint Paint) {canvas.save ();
    Canvas.cliprect (x, y, x + framew, y + Frameh);
    Canvas.drawbitmap (Bmpenemy, X-frameindex * Framew, y, paint);
  Canvas.restore ();
    }//Enemy plane logic ai public void logic () {///continuous loop play frame to form animation frameindex++;
    if (FrameIndex >=) {frameindex = 0;
        ///Different kinds of enemy aircraft have different AI logical switch (type) {case Type_fly:if (Isdead = = False) {//deceleration appears, accelerate return
        Speed-= 1;
        Y + + speed;
        if (y <= -200) {isdead = true;
    }} break;
        Case Type_duckl:if (Isdead = = False) {//Oblique right lower corner movement x + = SPEED/2;
        Y + + speed;
        if (x > Mysurfaceview.screenw) {isdead = true;
    }} break;
        Case Type_duckr:if (Isdead = = False) {//Oblique left corner movement X-= SPEED/2;
        Y + + speed;
        if (x < -50) {Isdead = true;
    }} break;

 }
  }

}

Generate enemy aircraft in Mysurfaceview

public class Mysurfaceview extends Surfaceview implements Callback, Runnable {private Surfaceholder sfh;
  Private Paint Paint;
  private Thread th;
  Private Boolean flag;

  Private Canvas Canvas;  1 Definition game state constant public static final int game_menu = 0;//Game menu public static final int gameing = 1;//game public static Final int game_win = 2;//game wins public static final int game_lost = 3;//game failure public static final int game_pause =-1;
  Game Menu//Current game status (Default initial in Game menu interface) public static int gamestate = Game_menu;
  Declare a resources instance to facilitate loading pictures private resources res = this.getresources (); Declare the game needs to use the picture resources (picture statement) Private Bitmap bmpbackground;//game background private Bitmap bmpboom;//explosion effect Private Bitmap Bmpboosboo m;//boos explosion effect private Bitmap bmpbutton;//game start button Private Bitmap bmpbuttonpress;//game Start button is clicked Private Bitmap bmpenemyd uck;//Monster Duck private Bitmap bmpenemyfly;//monster fly private Bitmap bmpenemyboos;//monster pig head boos private Bitmap bmpgamewin;// Game victory background Private Bitmap Bmpgamelost;//Game Background Private Bitmap bmpplayer;//game lead airplane private Bitmap bmpplayerhp;//lead airplane blood volume private Bitmap bmpmenu;//menu background public static Bitmap bmpbullet;//bullets public static Bitmap bmpenemybullet;//enemy bullets public static Bitmap Bmpbossbullet;
  Boss Bullets public static int screenw;

  public static int screenh;
  Declare an enemy aircraft container private vector<enemy> vcenemy;
  Time of each generation of enemy aircraft (milliseconds) private int createenemytime = 50;  private int count;//counter//enemy array: 1 and 2 indicate the type of enemy aircraft,-1 indicates that each dimension of the Boss//two-dimensional array is a set of monsters private int enemyarray[][] = {1, 2}, {1,  1}, {1, 3, 1, 2}, {1, 2}, {2, 3}, {3, 1, 3}, {2, 2}, {1, 2}, {2, 2}, {1, 3, 1, 1}, {2, 1},
  {1, 3}, {2, 1}, {-1}};
  The subscript private int enemyarrayindex of the one-dimensional array is currently removed;
  Whether the presence of the boss identification bit private Boolean isboss;

  Random library, for the creation of the enemy aircraft given immediately coordinates private Random Random;
  Private Gamemenu Gamemenu;

  Private GAMEBG GAMEBG;

  Private player player;
 /** * Surfaceview initialization function/public Mysurfaceview (context context) {   Super (context);
    SFH = This.getholder ();
    Sfh.addcallback (this);
    Paint = new paint ();
    Paint.setcolor (Color.White);
    Paint.setantialias (TRUE);
  Setfocusable (TRUE); /** * Surfaceview View creation, response to this function/@Override public void surfacecreated (Surfaceholder holder) {screenw = t
    His.getwidth ();
    Screenh = This.getheight ();
    Initgame ();
    Flag = true;
    instance thread th = new thread (this);
  Start thread Th.start (); /** * Load game resource/private void Initgame () {//load game resource Bmpbackground = bitmapfactory. Decodereso
    Urce (res, r.drawable.background);
    Bmpboom = Bitmapfactory.decoderesource (res, r.drawable.boom);
    Bmpboosboom = Bitmapfactory.decoderesource (res, r.drawable.boos_boom);
    Bmpbutton = Bitmapfactory.decoderesource (res, R.drawable.button);
    bmpbuttonpress = Bitmapfactory.decoderesource (res, r.drawable.button_press);
    Bmpenemyduck = Bitmapfactory.decoderesource (res, r.drawable.enemy_duck); BmpEnemyfly = Bitmapfactory.decoderesource (res, r.drawable.enemy_fly);
    Bmpenemyboos = Bitmapfactory.decoderesource (res, r.drawable.enemy_pig);
    Bmpgamewin = Bitmapfactory.decoderesource (res, r.drawable.gamewin);
    Bmpgamelost = Bitmapfactory.decoderesource (res, r.drawable.gamelost);
    Bmpplayer = Bitmapfactory.decoderesource (res, r.drawable.player);
    BMPPLAYERHP = Bitmapfactory.decoderesource (res, R.DRAWABLE.HP);
    Bmpmenu = Bitmapfactory.decoderesource (res, r.drawable.menu);
    Bmpbullet = Bitmapfactory.decoderesource (res, r.drawable.bullet);
    Bmpenemybullet = Bitmapfactory.decoderesource (res, r.drawable.bullet_enemy);

    Bmpbossbullet = bitmapfactory. Decoderesource (res, r.drawable.boosbullet);
    Menu class Instantiation Gamemenu = new Gamemenu (Bmpmenu, Bmpbutton, bmpbuttonpress);
    Instance Game Background GAMEBG = new GAMEBG (bmpbackground);

    Instance lead player = new player (Bmpplayer, BMPPLAYERHP);
    Instance enemy Vessel Vcenemy = new vector<enemy> (); InstanceRandom library random = new Random ();
      /** * Game drawing/public void Mydraw () {try {canvas = Sfh.lockcanvas ();
        if (canvas!= null) {Canvas.drawcolor (color.white);
          Drawing functions vary according to game state to draw switch (gamestate) {case GAME_MENU:gameMenu.draw (canvas, paint);
        Break
          Case GAMEING:gameBg.draw (canvas, paint);
          Player.draw (canvas, paint); if (Isboss = = False) {//enemy draw for (int i = 0; i < vcenemy.size (); i++) {Vcenemy
            . ElementAt (i) Draw (canvas, paint);

        } else {//boss draw} break;
        Case Game_win:break;
        Case Game_lost:break;
        Case Game_pause:break;
        Default:break; (Exception e) {//Todo:handle Exception} finally {if (canvas!= null) s Fh.unlockcanvasandpost (Canvas);
    /** * Touchscreen Event Monitor/@Override public boolean ontouchevent (Motionevent event) {switch (gamestate) {
      Case GAME_MENU:gameMenu.onTouchEvent (event);
    Break

    Case Gameing:break;
    Case Game_win:break;
    Case Game_lost:break;
    Case Game_pause:break;
  return true;
    /** * Key Event Monitor/@Override public boolean onKeyDown (int keycode, keyevent event) {switch (gamestate) {
    Case Game_menu:break;
      Case GAMEING:player.onKeyDown (KeyCode, event);

    Break
    Case Game_win:break;
    Case Game_lost:break;
    Case Game_pause:break;
  Return Super.onkeydown (KeyCode, event);

      @Override public boolean onKeyUp (int keycode, keyevent event) {switch (gamestate) {case Game_menu:
    Break
      Case GAMEING:player.onKeyUp (KeyCode, event);

    Break
    Case Game_win:break;

   Case Game_lost:   Break
    Case Game_pause:break;
  Return Super.onkeyup (KeyCode, event);
    /** * Game logic/private void logic () {switch (gamestate) {case game_menu:break;
      Case GAMEING:gameBg.logic ();
      Player.logic ();  Enemy aircraft logic if (Isboss = False) {//Enemy aircraft logic for (int i = 0; i < vcenemy.size (); i++) {Enemy
          En = Vcenemy.elementat (i); Because the container is constantly adding enemy aircraft, then the enemy isdead determine,//If the death then removed from the container, the container played an optimal role; if (En.isdead) {Vcenemy.remov
          Eelementat (i);
          else {en.logic ();
        }//Generate enemy count++;
            if (count% Createenemytime = 0) {for (int i = 0; i < enemyarray[enemyarrayindex].length; i++) {
              Fly if (enemyarray[enemyarrayindex][i] = = 1) {int x = Random.nextint (screenW-100) + 50;
              Vcenemy.addelement (New Enemy (Bmpenemyfly, 1, X,-50));Duck left} else if (enemyarray[enemyarrayindex][i] = = 2) {int y = Random.nextint (20);
              Vcenemy.addelement (New Enemy (Bmpenemyduck, 2, -50, y));
              Duck Right} else if (enemyarray[enemyarrayindex][i] = = 3) {int y = Random.nextint (20);
            Vcenemy.addelement (New Enemy (Bmpenemyduck, 3, Screenw + y)); }//Here to determine if the next group is the last group (Boss) if (Enemyarrayindex = = enemyarray.length-1) {Isbo
          SS = true;
          else {enemyarrayindex++;

    }} break;
    Case Game_win:break;
    Case Game_lost:break;
    Case Game_pause:break;
      @Override public void Run () {a while (flag) {Long start = System.currenttimemillis ();
      Mydraw ();
      Logic ();
      Long end = System.currenttimemillis ();
    try {if (End-start < 50) {      Thread.Sleep (End-start);
      } catch (Interruptedexception e) {e.printstacktrace ();  /** * Surfaceview view state changed in response to this function */@Override public void surfacechanged (surfaceholder holder, int format, int width, int height) {}/** * Surfaceview View dies, respond to this function/@Override public void Surfacedest
  Royed (Surfaceholder holder) {flag = false;

 }
}

Collision Detection
Modify player class

Package COM.GSF;
Import Android.graphics.Bitmap;
Import Android.graphics.Canvas;
Import Android.graphics.Paint;

Import android.view.KeyEvent;

  public class Player {private int playerhp = 3;
  Private Bitmap BMPPLAYERHP;
  Lead coordinates and bitmap private int x, y;
  Private Bitmap Bmpplayer;
  Lead moving speed private int speed = 5;

  Protagonist Mobile Logo Private Boolean isUp, Isdown, Isleft, isright;
    The constructor of the protagonist is public Player (Bitmap Bmpplayer, Bitmap bmpplayerhp) {this.bmpplayer = Bmpplayer;
    THIS.BMPPLAYERHP = BMPPLAYERHP;
    Aircraft initial position x = MYSURFACEVIEW.SCREENW/2-Bmpplayer.getwidth ()/2;
  y = Mysurfaceview.screenh-bmpplayer.getheight (); //Lead game rendering method public void Draw (Canvas Canvas, Paint Paint) {//Draw lead Canvas.drawbitmap (Bmpplayer, x, Y, pain
    T);
          Draw the blood volume for (int i = 0; i < PLAYERHP i++) {canvas.drawbitmap (BMPPLAYERHP, I * bmpplayerhp.getwidth (),
    Mysurfaceview.screenh-bmpplayerhp.getheight (), paint); }/** * Key thingpiece monitor/public void OnKeyDown (int keycode, keyevent event) {if (keycode = = keyevent.keycode_dpad_up) {isUp
    = true;
    } if (keycode = = Keyevent.keycode_dpad_down) {Isdown = true;
    } if (keycode = = keyevent.keycode_dpad_left) {Isleft = true;
    } if (keycode = = keyevent.keycode_dpad_right) {isright = true; } public void OnKeyUp (int keycode, keyevent event) {if (keycode = = keyevent.keycode_dpad_up) {isUp = FA
    Lse
    } if (keycode = = Keyevent.keycode_dpad_down) {Isdown = false;
    } if (keycode = = keyevent.keycode_dpad_left) {isleft = false;
    } if (keycode = = keyevent.keycode_dpad_right) {isright = false;
    }/** * Game logic */public void logic () {if (isUp) {y-= speed;
    } if (Isdown) {y + = speed;
    } if (isleft) {x = speed;
    } if (Isright) {x + = speed; //Judge screen x boundary if (x + bmpplayer.getwidth (); = Mysurfaceview.screenw) {x = Mysurfaceview.screenw-bmpplayer.getwidth ();
    else if (x <= 0) {x = 0; }//Judge screen y boundary if (y + bmpplayer.getheight () >= mysurfaceview.screenh) {y = Mysurfaceview.screenh-bmppla
    Yer.getheight ();
    else if (y <= 0) {y = 0;
  }//Set lead blood volume public void setplayerhp (int hp) {THIS.PLAYERHP = HP;
  //Get the lead blood volume public int getplayerhp () {return PLAYERHP;
      //Judge collision (enemy plane with lead bullet collision) Public boolean iscollsionwith (enemy bullet) {int x2 = bullet.x;
      int y2 = BULLET.Y;
      int w2 = Bullet.framew;
      int h2 = Bullet.frameh;
      if (x >= x2 && x >= x2 + W2) {return false;
      else if (x <= x2 && x + bmpplayer.getwidth () <= x2) {return false;
      else if (y >= y2 && y >= y2 + H2) {return false;
      else if (y <= y2 && y + bmpplayer.getheight () <= y2) {return false; }
      Collision, let its death//isdead = true;
    return true;

 }


}

Add collision logic to mysurface

  /** * Game logic */private void logic () {switch (gamestate) {case game_menu:break;
      Case GAMEING:gameBg.logic ();
      Player.logic ();  Enemy aircraft logic if (Isboss = False) {//Enemy aircraft logic for (int i = 0; i < vcenemy.size (); i++) {Enemy
          En = Vcenemy.elementat (i); Because the container is constantly adding enemy aircraft, then the enemy isdead determine,//If the death then removed from the container, the container played an optimal role; if (En.isdead) {Vcenemy.remov
          Eelementat (i);
          else {en.logic ();
        }//Generate enemy count++;
            if (count% Createenemytime = 0) {for (int i = 0; i < enemyarray[enemyarrayindex].length; i++) {
              Fly if (enemyarray[enemyarrayindex][i] = = 1) {int x = Random.nextint (screenW-100) + 50;
              Vcenemy.addelement (New Enemy (Bmpenemyfly, 1, X,-50)); Duck left} else if (enemyarray[enemyarrayindex][i] = = 2) {int y = RandoM.nextint (20);
              Vcenemy.addelement (New Enemy (Bmpenemyduck, 2, -50, y));
              Duck Right} else if (enemyarray[enemyarrayindex][i] = = 3) {int y = Random.nextint (20);
            Vcenemy.addelement (New Enemy (Bmpenemyduck, 3, Screenw + y)); }//Here to determine if the next group is the last group (Boss) if (Enemyarrayindex = = enemyarray.length-1) {Isbo
          SS = true;
          else {enemyarrayindex++; }///Handling collision for enemy and protagonist for (int i = 0; i < vcenemy.size (); i++) {if (Player.iscollsionwith) (Vcenemy.elementat (i)))
            {//Collision, lead blood volume-1 PLAYER.SETPLAYERHP (PLAYER.GETPLAYERHP ()-1);
            When the protagonist's blood volume is less than 0, determine the game failure if (PLAYER.GETPLAYERHP () <=-1) {gamestate = Game_lost;

 Break in}}};

Timer
  private int nocollisioncount = 0;
  Because invincible time
  private int nocollisiontime =;
  Whether the collision of the identity bit
  private Boolean iscollision;

Judge the collision (lead and enemy) public
  boolean iscollsionwith (enemy en) {
    //is in invincible time if
    (iscollision = = false) {
      int x2 = en.x;
      int y2 = EN.Y;
      int w2 = En.framew;
      int h2 = En.frameh;
      if (x >= x2 && x >= x2 + w2) {return
        false;
      } else if (x <= x2 && x + bmpplayer.getwid Th () <= x2) {return
        false;
      } else if (y >= y2 && y >= y2 + H2) {return
        false;
      } els e if (y <= y2 && y + bmpplayer.getheight () <= y2) {return
        false;
      }
      Collision is to enter invincible state
      iscollision = true;
      return true;
      In an invincible state, ignoring collisions
    } else {return
      false
    ;
  }}

Modifying logical methods

  /**
   * Game Logic
   *
  /public void logic () {
    if (isUp) {
      y-= speed;
    }
    if (isdown) {
      y = = speed;
    }
    if (isleft) {
      x = speed;
    }
    if (isright) {
      x + = speed;
    }
    To determine the screen x boundary
    if (x + bmpplayer.getwidth () >= mysurfaceview.screenw) {
      x = mysurfaceview.screenw-bmpplayer.ge Twidth ();
    } else if (x <= 0) {
      x = 0;
    }
    To determine the screen y boundary
    if (y + bmpplayer.getheight () >= mysurfaceview.screenh) {
      y = mysurfaceview.screenh-bmpplayer.g Etheight ();
    } else if (y <= 0) {
      y = 0;
    }

    Handle the Invincible status
    if (iscollision) {
      //Timer starts timing
      nocollisioncount++;
      if (Nocollisioncount >= nocollisiontime) {
        //invincible time, contact Invincible State and initialization counter
        iscollision = false;
        Nocollisioncount = 0;
      }
    }

  

To modify the drawing of a lead
Player class

Lead game rendering method public
  void Draw (Canvas Canvas, Paint Paint) {

    //Draw protagonist
    //When in invincible time, let the protagonist Blink
    if (iscollision) {
   //every 2 game loops, draw a lead
      if (nocollisioncount% 2 = 0) {
        canvas.drawbitmap (bmpplayer, x, y, paint);
      }
    Else {
      Canvas.drawbitmap (bmpplayer, x, y, paint);
    }
    Draw the blood volume

    for (int i = 0; i < PLAYERHP i++) {
      Canvas.drawbitmap (BMPPLAYERHP, I * bmpplayerhp.getwidth (),
          Mysurfaceview.screenh-bmpplayerhp.getheight (), paint);
    }

  

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.