libgdx 仿微信打飞机完成版本(终结版)

来源:互联网 发布:仓鼠翻译软件 编辑:程序博客网 时间:2024/05/20 15:40
  libgdx 仿微信打飞机完成版本:


 源码下载位置:

https://github.com/luxiaoming/Air-plane

 下载地址:

  点击打开链接

  bullet.java  子弹类

package com.example.gamedemo;import java.util.Random;import android.util.Log;import com.badlogic.gdx.graphics.Color;import com.badlogic.gdx.graphics.g2d.Sprite;import com.badlogic.gdx.graphics.g2d.SpriteBatch;import com.badlogic.gdx.graphics.g2d.TextureAtlas;import com.badlogic.gdx.math.Rectangle;import com.badlogic.gdx.utils.Array;import com.badlogic.gdx.utils.Pools;public class bullet {Random r = new Random(1000);private Array<Rectangle> bulletArray = new Array<Rectangle>();private Sprite bullet1Texture;private Sprite bullet2Texture;private TextureAtlas atlas;private int bullet1W;private int bullet1H;private int bullet2W;private int bullet2H;private float stateTime = 0f;private int Type = TypeBullet1;public static final int TypeBullet2 = 1;public static final int TypeBullet1 = 0;private int hreoW;private float stateTimeforbullet2 = 0f;private float stateTimedf = 10f; // 持续5s的增强攻击// private boolean isTrpublic bullet(TextureAtlas atlas) {// TODO Auto-generated constructor stubthis.atlas = atlas;bullet1Texture = new Sprite(atlas.findRegion("bullet1"));bullet2Texture = new Sprite(atlas.findRegion("bullet2"));bullet1W = bullet1Texture.getRegionWidth();bullet1H = bullet1Texture.getRegionHeight();bullet2W = bullet2Texture.getRegionWidth();bullet2H = bullet2Texture.getRegionHeight();}public void creatbullet(int x, int y, int W) {// 构造一个子弹,需要增加参数,判断是否为普通还是增强模式hreoW = W;if (Type == TypeBullet1) {Rectangle tmp = Pools.obtain(Rectangle.class);tmp.set(x - bullet1W / 2, y, bullet1W, bullet1H);bulletArray.add(tmp);} else {Rectangle tmp = Pools.obtain(Rectangle.class);tmp.set(x - bullet1W / 2 - W / 4, y, bullet1W, bullet1H);bulletArray.add(tmp);Rectangle tmp2 = Pools.obtain(Rectangle.class);tmp2.set(x - bullet1W / 2 + W / 4, y, bullet1W, bullet1H);bulletArray.add(tmp2);}}public void setType(int Type) {this.Type = Type;stateTimeforbullet2 = 0;}public void act(float delta, int x, int y) {// 依据时间戳,移动子弹stateTime += delta;stateTimeforbullet2 += delta;if (Type == TypeBullet2 && stateTimeforbullet2 > stateTimedf) {Type = TypeBullet1;stateTimeforbullet2 = 0f;}if (stateTime > time_df) {stateTime = 0;creatbullet(x, y, hreoW);}int index = 0;for (index = bulletArray.size - 1; index >= 0; index--) {bulletArray.get(index).y += pix_df * delta;if (bulletArray.get(index).y >= 854) {bulletArray.removeIndex(index);}}}public void draw(SpriteBatch batch) {// 刷新数据for (Rectangle bullet : bulletArray) {if (Type == TypeBullet1) {bullet1Texture.setX(bullet.getX());bullet1Texture.setY(bullet.getY());bullet1Texture.draw(batch);} else {bullet2Texture.setX(bullet.getX());bullet2Texture.setY(bullet.getY());bullet2Texture.draw(batch);}}}public Array<Rectangle> getbulletArray() {//return bulletArray;}static final float time_df = 0.16f;static final int pix_df = 1800;}


  Enemy.java   敌机类

package com.example.gamedemo;import java.util.Random;import android.util.Log;import com.badlogic.gdx.graphics.g2d.Animation;import com.badlogic.gdx.graphics.g2d.SpriteBatch;import com.badlogic.gdx.graphics.g2d.TextureAtlas;import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;import com.badlogic.gdx.graphics.g2d.TextureRegion;import com.badlogic.gdx.math.Rectangle;import com.badlogic.gdx.utils.Array;import com.badlogic.gdx.utils.Pools;public class Enemy {Random r = new Random(1000);// 创建一个随机数private Array<EnemyParameter> EnemyArray = new Array<EnemyParameter>();private float stateTime = 0f;private float stateTimeforDraw = 0f;private AtlasRegion Enemy1Texture;float Enemy1Width;float Enemy1Height;private Animation Enemy1Anima;private AtlasRegion Enemy2Texture;private AtlasRegion Enemy2HitTexture;float Enemy2Width;float Enemy2Height;private Animation Enemy2Anima;private Animation Enemy3TextureAnima;float Enemy3Width;float Enemy3Height;private Animation Enemy3Anima;private AtlasRegion Enemy3HitTexture;// 敌人类别 ,0--3 从弱到强static final int EnemyType1 = 0;static final int EnemyType2 = 1;static final int EnemyType3 = 2;static final int EnemyType4 = 3;// AttackValue 当前无效,敌人当前不发子弹。public Enemy(TextureAtlas atlas) {// TODO Auto-generated constructor stubEnemy1Texture = atlas.findRegion("enemy1");Enemy1Width = Enemy1Texture.getRegionWidth();Enemy1Height = Enemy1Texture.getRegionHeight();Array<TextureRegion> Texturelist = new Array<TextureRegion>();Texturelist.add(atlas.findRegion("enemy1_down1"));Texturelist.add(atlas.findRegion("enemy1_down2"));Texturelist.add(atlas.findRegion("enemy1_down3"));Texturelist.add(atlas.findRegion("enemy1_down4"));Enemy1Anima = new Animation(0.16f, Texturelist);Texturelist.clear();Enemy2HitTexture = atlas.findRegion("enemy2_hit");Enemy2Texture = atlas.findRegion("enemy2");Enemy2Width = Enemy2Texture.getRegionWidth();Enemy2Height = Enemy2Texture.getRegionHeight();Texturelist.add(atlas.findRegion("enemy2_down1"));Texturelist.add(atlas.findRegion("enemy2_down2"));Texturelist.add(atlas.findRegion("enemy2_down3"));Texturelist.add(atlas.findRegion("enemy2_down4"));Enemy2Anima = new Animation(0.16f, Texturelist);Texturelist.clear();Enemy3HitTexture = atlas.findRegion("enemy3_hit");AtlasRegion Enemy3Texture = atlas.findRegion("enemy3_n1");Enemy3Width = Enemy3Texture.getRegionWidth();Enemy3Height = Enemy3Texture.getRegionHeight();Texturelist.add(atlas.findRegion("enemy3_n1"));Texturelist.add(atlas.findRegion("enemy3_n2"));Enemy3TextureAnima = new Animation(1.2f, Texturelist, Animation.LOOP) {};Texturelist.clear();Texturelist.add(atlas.findRegion("enemy3_down1"));Texturelist.add(atlas.findRegion("enemy2_down2"));Texturelist.add(atlas.findRegion("enemy3_down3"));Texturelist.add(atlas.findRegion("enemy3_down4"));Texturelist.add(atlas.findRegion("enemy3_down5"));Texturelist.add(atlas.findRegion("enemy3_down6"));Enemy3Anima = new Animation(0.16f, Texturelist);}// 构造一个敌人,需要增加参数,判断是否为普通还是增强模式public void creatEnemy(int Type) {switch (Type) {case EnemyType1:EnemyParameter tmp = Pools.obtain(EnemyParameter.class);tmp.set(r.nextInt((int) (480 - Enemy1Width)), 854,(int) Enemy1Width, (int) Enemy1Height, EnemyType1, 5, 1);EnemyArray.add(tmp);break;case EnemyType2:EnemyParameter tmp2 = Pools.obtain(EnemyParameter.class);tmp2.set(r.nextInt((int) (480 - Enemy2Width)), 854,(int) Enemy2Width, (int) Enemy2Height, EnemyType2, 5, 4);EnemyArray.add(tmp2);break;case EnemyType3:EnemyParameter tmp3 = Pools.obtain(EnemyParameter.class);tmp3.set(r.nextInt((int) (480 - Enemy3Width)), 854,(int) Enemy3Width, (int) Enemy3Height, EnemyType3, 5, 10);EnemyArray.add(tmp3);break;default:break;}}public void act(float delta) {// 依据时间戳,移动敌人// stateTime += delta;// if (stateTime > time_df) {// Log.i("Enemy draw", "" + delta);// float Rate = stateTime / time_df;stateTime = 0;int index = 0;EnemyParameter Tmp;for (index = EnemyArray.size - 1; index >= 0; index--) {Tmp = EnemyArray.get(index);Tmp.df = (System.nanoTime() - Tmp.OverTime) / 1000000000.0f;if (Tmp.rectangle.y + Tmp.rectangle.height <= 0) {EnemyArray.removeIndex(index);continue;}switch (Tmp.Type) {case EnemyType1:if (Tmp.isover) {if (Enemy1Anima.isAnimationFinished(Tmp.df)) {EnemyArray.removeIndex(index);}continue;} else {Tmp.rectangle.y -= pix_df_type1 * delta;// Log.i("Enemy draw", "" + delta+"--"+Tmp.rectangle.y);}break;case EnemyType2:if (Tmp.isover) {if (Enemy2Anima.isAnimationFinished(Tmp.df)) {EnemyArray.removeIndex(index);}continue;} else {Tmp.rectangle.y -= pix_df_type2 * delta;}break;case EnemyType3:if (Tmp.isover) {if (Enemy3Anima.isAnimationFinished(Tmp.df)) {EnemyArray.removeIndex(index);}continue;} else {Tmp.rectangle.y -= pix_df_type3 * delta;}break;default:break;}}}public void draw(SpriteBatch batch, float delta) {// 刷新数据stateTimeforDraw += delta;for (EnemyParameter Enemy : EnemyArray) {switch (Enemy.Type) {case EnemyType1:if (Enemy.isover) {batch.draw(Enemy1Anima.getKeyFrame(Enemy.df),Enemy.rectangle.x, Enemy.rectangle.y);} else {batch.draw(Enemy1Texture, Enemy.rectangle.x,Enemy.rectangle.y);}break;case EnemyType2:if (Enemy.isover) {batch.draw(Enemy2Anima.getKeyFrame(Enemy.df),Enemy.rectangle.x, Enemy.rectangle.y);} else if (Enemy.isHit) {batch.draw(Enemy2HitTexture, Enemy.rectangle.x,Enemy.rectangle.y);Enemy.isHit = false;} else {batch.draw(Enemy2Texture, Enemy.rectangle.x,Enemy.rectangle.y);}break;case EnemyType3:if (Enemy.isover) {batch.draw(Enemy3Anima.getKeyFrame(Enemy.df),Enemy.rectangle.x, Enemy.rectangle.y);} else if (Enemy.isHit) {batch.draw(Enemy3HitTexture, Enemy.rectangle.x,Enemy.rectangle.y);Enemy.isHit = false;} else {batch.draw(Enemy3TextureAnima.getKeyFrame(stateTimeforDraw),Enemy.rectangle.x, Enemy.rectangle.y);}break;default:break;}}}public void bomb(GameScore Gs) {for (int index2 = EnemyArray.size - 1; index2 >= 0; index2--) {EnemyParameter Enemy = EnemyArray.get(index2);Enemy.isover = true;Enemy.OverTime = System.nanoTime();Enemy.Health = 0;}}public void cleanall() {if (EnemyArray != null) {EnemyArray.clear();}}//public boolean checkbulletAndPlay(Array<Rectangle> bulletArray,Rectangle Play, GameScore Gs) {// 检测 是否打中,返回是否游戏结束for (int index = bulletArray.size - 1; index >= 0; index--) {Rectangle Re = bulletArray.get(index);for (int index2 = EnemyArray.size - 1; index2 >= 0; index2--) {EnemyParameter Enemy = EnemyArray.get(index2);if (Enemy.rectangle.overlaps(Play)) {return true;}if ((!Enemy.isover) && Enemy.rectangle.overlaps(Re)) {Enemy.Health -= 1;if (Enemy.Health <= 0) {Enemy.isover = true;Enemy.OverTime = System.nanoTime();switch (Enemy.Type) {case EnemyType1:GameScreen.Enemy1.play();Gs.addScore(1);break;case EnemyType2:GameScreen.Enemy2.play();Gs.addScore(5);break;case EnemyType3:GameScreen.Enemy3.play();Gs.addScore(10);break;default:break;}} else {Enemy.isHit = true;}bulletArray.removeIndex(index);break;}}}return false;}static final int pix_df_type1 = 250;static final int pix_df_type2 = 200;static final int pix_df_type3 = 100;}


  EnemyParameter.java  敌机参数类

package com.example.gamedemo;import com.badlogic.gdx.math.Rectangle;public class EnemyParameter {Rectangle rectangle = new Rectangle();boolean isover; // 是否已经挂掉int Type; // 敌人类别int AttackValue; // 攻击值int Health;// 生命值float df; // 挂掉之后流失时间float OverTime; // 挂掉时间boolean isHit=false; // 是否被打中public EnemyParameter() {// TODO Auto-generated constructor stub}public void set(int x, int y, int W, int H, int Type, int AttackValue,int Health) {// TODO Auto-generated constructor stubrectangle.x = x;rectangle.y = y;rectangle.width = W;rectangle.height = H;this.Type = Type;this.AttackValue = AttackValue;this.Health = Health;}}


  FirstGame.java   启动game

package com.example.gamedemo;import cn.waps.AppConnect;import android.app.Activity;import android.util.Log;public class FirstGame extends Game {MainActivity Main;public FirstGame(MainActivity Main) {// TODO Auto-generated constructor stubthis.Main = Main;}@Overridepublic void create() {// this.setScreen(new InfoScreen(this));this.setScreen(new InfoScreen(this));}public void EndGame() {Main.finish();}public void ShowOff() {Main.showAdStatic(0);}}


  Game.java   base game 类

package com.example.gamedemo;/******************************************************************************* * Copyright 2011 See AUTHORS file. *  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *  *   http://www.apache.org/licenses/LICENSE-2.0 *  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/import android.util.Log;import com.badlogic.gdx.ApplicationListener;import com.badlogic.gdx.Gdx;import com.badlogic.gdx.Screen;/** * <p> * An {@link ApplicationListener} that delegates to a {@link Screen}. This * allows an application to easily have multiple screens. * </p> * <p> * Screens are not disposed automatically. You must handle whether you want to * keep screens around or dispose of them when another screen is set. * </p> */public abstract class Game implements ApplicationListener {private Screen screen;@Overridepublic void dispose() {if (screen != null)screen.hide();}@Overridepublic void pause() {if (screen != null)screen.pause();}@Overridepublic void resume() {if (screen != null)screen.resume();}@Overridepublic void render() {if (screen != null)screen.render(Gdx.graphics.getDeltaTime());}@Overridepublic void resize(int width, int height) {if (screen != null)screen.resize(width, height);}/** * Sets the current screen. {@link Screen#hide()} is called on any old * screen, and {@link Screen#show()} is called on the new screen, if any. *  * @param screen *            may be {@code null} */public void setScreen(Screen screen) {if (this.screen != null)this.screen.hide();this.screen = screen;if (this.screen != null) {this.screen.show();this.screen.resize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());}}/** @return the currently active {@link Screen}. */public Screen getScreen() {return screen;}}


  GameScore.java  得分类

package com.example.gamedemo;import com.badlogic.gdx.Gdx;import com.badlogic.gdx.graphics.g2d.BitmapFont;import com.badlogic.gdx.graphics.g2d.SpriteBatch;import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;public class GameScore {private int Score = 0;private BitmapFont font;private float x = 0;public GameScore(ImageButton pause) {// TODO Auto-generated constructor stubfont = new BitmapFont(Gdx.files.internal("ui/font.fnt"), false);x = pause.getX() + pause.getWidth();}public void addScore(int Score) {this.Score += Score;}public void cleanScore() {this.Score = 0;}public void draw(SpriteBatch batch) {// TODO Auto-generated method stubfont.draw(batch, Score + "000", x, Gdx.graphics.getHeight() - 5);}}


  GameScreen.java  游戏主界面,在后面


  Hero.java   英雄类

package com.example.gamedemo;


import android.util.Log;


import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Pools;


public class Hero extends Actor {


Animation hreo;
float stateTime = 0f;
TextureRegion Draw;
private int status = eIsRuning;
static final public int eIsOvering = 1;
static final public int eIsPause = 2;
static final public int eIsRuning = 3;
static final public int eIsOver = 4;
Animation hreoOver;


public Hero(float df, Array<TextureRegion> Texturelist,
Array<TextureRegion> TextureOverlist) {
// TODO Auto-generated constructor stub
super();
hreo = new Animation(df, Texturelist);
hreoOver = new Animation(0.16f, TextureOverlist);
}


@Override
public void act(float delta) {
// TODO Auto-generated method stub
super.act(delta);
stateTime += delta;
if (status == eIsRuning) {
Draw = hreo.getKeyFrame(stateTime, true);
} else if (status == eIsOvering) {
Draw = hreoOver.getKeyFrame(stateTime, false);
Log.i("isGameOver", stateTime + "--" + hreoOver.isAnimationFinished(stateTime));
if (hreoOver.isAnimationFinished(stateTime)) {
status = eIsOver;
}
}


}


public void setStatus(int Status) {
status = Status;
if (status == eIsOvering) {
stateTime = 0; // 清除,开始计算over动画
}
}


public boolean isOver() {
return status == eIsOver;
}


@Override
public void draw(SpriteBatch batch, float parentAlpha) {
// TODO Auto-generated method stub
super.draw(batch, parentAlpha);
batch.draw(Draw, getX(), getY());
}


public Rectangle getrectangle() {
Rectangle Tmp = Pools.obtain(Rectangle.class);
Tmp.set(getX() + 28, getY() + 28, 38, 92 - 8);// 去掉周边因素
return Tmp;


}


}

  InfoScreen.java  启动介绍类

package com.example.gamedemo;import android.util.Log;import com.badlogic.gdx.Gdx;import com.badlogic.gdx.ScreenAdapter;import com.badlogic.gdx.graphics.g2d.Animation;import com.badlogic.gdx.graphics.g2d.Sprite;import com.badlogic.gdx.graphics.g2d.SpriteBatch;import com.badlogic.gdx.graphics.g2d.TextureAtlas;import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;import com.badlogic.gdx.graphics.g2d.TextureRegion;import com.badlogic.gdx.scenes.scene2d.InputEvent;import com.badlogic.gdx.scenes.scene2d.Stage;import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle;import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;import com.badlogic.gdx.utils.Array;import com.badlogic.gdx.utils.Timer;import com.badlogic.gdx.utils.Timer.Task;public class InfoScreen extends ScreenAdapter {Stage Ui;SpriteBatch Batch;private TextureAtlas atlas;private Sprite sprite;private Sprite Title;FirstGame Gm;Animation flyMove;Array<TextureRegion> keyFramesArray = new Array<TextureRegion>();float stateTime = 0f;float x, y;int regionWidth, regionHeight;AtlasRegion Region;float flyMovex;ImageButton Back;public InfoScreen(FirstGame tGm) {// TODO Auto-generated constructor stubthis.Gm = tGm;Batch = new SpriteBatch();Ui = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());atlas = new TextureAtlas(Gdx.files.internal("shoot_background.pack"));sprite = atlas.createSprite("background");sprite.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());Title = atlas.createSprite("shoot_copyright");Region = atlas.findRegion("game_loading3");flyMovex = (Gdx.graphics.getWidth() - Region.getRegionWidth()) / 2;keyFramesArray.add(atlas.findRegion("game_loading1"));keyFramesArray.add(atlas.findRegion("game_loading2"));keyFramesArray.add(atlas.findRegion("game_loading3"));keyFramesArray.add(atlas.findRegion("game_loading4"));flyMove = new Animation(0.3f, keyFramesArray);x = (Gdx.graphics.getWidth() - Title.getWidth()) / 2;y = (Gdx.graphics.getHeight() - (Title.getHeight() + 150));regionWidth = Title.getRegionWidth();regionHeight = Title.getRegionHeight();Title.setPosition(x, y);ImageButtonStyle style = new ImageButtonStyle();style.imageUp = new TextureRegionDrawable(atlas.findRegion("btn_finish"));style.imageDown = new TextureRegionDrawable(atlas.findRegion("btn_finish"));Back = new ImageButton(style);Back.addListener(new ClickListener() {public void clicked(InputEvent event, float x, float y) {Gm.EndGame();}});Back.setX(Gdx.graphics.getWidth() - Back.getWidth() - 2);Back.setY(10);Ui.addActor(Back);Gdx.input.setInputProcessor(Ui);new Timer().scheduleTask(new Task() {@Overridepublic void run() {// TODO Auto-generated method stubLog.i("lxmlxm", "timer ok!");Gm.setScreen(new GameScreen(Gm));}}, 3);}@Overridepublic void render(float delta) {// TODO Auto-generated method stubsuper.render(delta);Batch.begin();sprite.draw(Batch);Title.draw(Batch);stateTime += delta;TextureRegion frame = flyMove.getKeyFrame(stateTime, true);Batch.draw(frame, flyMovex, y - 80 - Region.getRegionHeight());Batch.end();Ui.draw();}@Overridepublic void resume() {// TODO Auto-generated method stubsuper.resume();Gdx.input.setInputProcessor(Ui);}@Overridepublic void pause() {// TODO Auto-generated method stubsuper.pause();Gdx.input.setInputProcessor(null);}@Overridepublic void hide() {// TODO Auto-generated method stubsuper.hide();}@Overridepublic void dispose() {// TODO Auto-generated method stubsuper.dispose();Batch.dispose();Ui.dispose();atlas.dispose();}}


  MainActivity.java  主activity

package com.example.gamedemo;import android.content.Context;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.WindowManager;import cn.waps.AppConnect;import com.badlogic.gdx.backends.android.AndroidApplication;public class MainActivity extends AndroidApplication {Game Gm;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);AppConnect.getInstance("dca242344a805d9afae7b59c263148f6", "default",this);AppConnect.getInstance(this).initPopAd(this);Gm = new FirstGame(MainActivity.this);// setLogLevel(LOG_DEBUG);initialize(Gm, false);//AppConnect.getInstance(this).showOffers(this);mContext = this;}private static Handler handler = handler = new Handler() {@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubswitch (msg.what) {case 0:AppConnect.getInstance(mContext).showOffers(mContext);break;}}};private static Context mContext;public static void showAdStatic(int adTag) {Message msg = handler.obtainMessage();msg.what = adTag; // 私有静态的整型变量,开发者请自行定义值handler.sendMessage(msg);}}


  MyImageButton.java  自定义button

package com.example.gamedemo;import com.badlogic.gdx.graphics.g2d.SpriteBatch;import com.badlogic.gdx.scenes.scene2d.Actor;import com.badlogic.gdx.scenes.scene2d.ui.Label;import com.badlogic.gdx.scenes.scene2d.utils.Align;import com.badlogic.gdx.scenes.scene2d.utils.Drawable;public class MyImageButton extends Actor {private Drawable imageUp;private Label Lab;public MyImageButton(Drawable imageUp) {// TODO Auto-generated constructor stubthis.imageUp = imageUp;}@Overridepublic void act(float delta) {// TODO Auto-generated method stubsuper.act(delta);}public void setLabel(Label Lab) {Lab.setPosition(getX(), getY());Lab.setSize(getWidth(), getHeight());Lab.setAlignment(Align.center | Align.top);this.Lab = Lab;}@Overridepublic void draw(SpriteBatch batch, float parentAlpha) {// TODO Auto-generated method stubsuper.draw(batch, parentAlpha);if (imageUp != null) {imageUp.draw(batch, getX(), getY(), getWidth(), getHeight());}Lab.draw(batch, parentAlpha);}}


  PauseScreen.java  暂停界面

package com.example.gamedemo;import com.badlogic.gdx.Gdx;import com.badlogic.gdx.Screen;import com.badlogic.gdx.graphics.g2d.BitmapFont;import com.badlogic.gdx.graphics.g2d.NinePatch;import com.badlogic.gdx.graphics.g2d.SpriteBatch;import com.badlogic.gdx.graphics.g2d.TextureAtlas;import com.badlogic.gdx.scenes.scene2d.InputEvent;import com.badlogic.gdx.scenes.scene2d.Stage;import com.badlogic.gdx.scenes.scene2d.ui.Label;import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable;public class PauseScreen implements Screen {private GameScreen gameScreen;private Stage stage;private MyImageButton back;private NinePatch NineTexture;private TextureAtlas atlas;private SpriteBatch Batch;private BitmapFont font;private MyImageButton Exit;public PauseScreen(GameScreen tgameScreen, boolean isover) {this.gameScreen = tgameScreen;stage = new Stage(480, 854, true);Batch = new SpriteBatch();atlas = new TextureAtlas(Gdx.files.internal("menu/Pause.pack"));font = new BitmapFont(Gdx.files.internal("ui/font1.fnt"), false);NineTexture = new NinePatch(atlas.findRegion("game_burst_aircraft_button_bule_small_normal"),16, 16, 5, 5);// 继续按钮back = new MyImageButton(new NinePatchDrawable(NineTexture));back.setPosition(80, 854 - 854 / 3);back.setSize(480 - 160, 50);if (isover) {back.setLabel(new Label("重新开始", new LabelStyle(font, null)));} else {back.setLabel(new Label("继续", new LabelStyle(font, null)));}back.addListener(new ClickListener() {public void clicked(InputEvent event, float x, float y) {gameScreen.getGame().getScreen().dispose();gameScreen.getGame().setScreen(gameScreen);}});Exit = new MyImageButton(new NinePatchDrawable(NineTexture));Exit.setPosition(80, back.getY() - back.getHeight() - 50);Exit.setSize(480 - 160, 50);Exit.setLabel(new Label("退出游戏", new LabelStyle(font, null)));Exit.addListener(new ClickListener() {public void clicked(InputEvent event, float x, float y) {gameScreen.getGame().EndGame();}});stage.addActor(back);stage.addActor(Exit);Gdx.input.setCatchBackKey(true);Gdx.input.setInputProcessor(stage);}@Overridepublic void render(float delta) {gameScreen.draw(delta);stage.act(delta);stage.draw();Batch.begin();Batch.end();// if (back.isPressed()) {// gameScreen.dispose();// gameScreen.getGame().getScreen().dispose();// }// if (restart.isPressed()) {// gameScreen.getGame().getScreen().dispose();// gameScreen.getGame().setScreen(gameScreen);// }}@Overridepublic void resize(int width, int height) {// TODO Auto-generated method stub}@Overridepublic void show() {// TODO Auto-generated method stub}@Overridepublic void hide() {// TODO Auto-generated method stub}@Overridepublic void pause() {// TODO Auto-generated method stub}@Overridepublic void resume() {// TODO Auto-generated method stub}@Overridepublic void dispose() {stage.dispose();}}


  UiStage.java  舞台
package com.example.gamedemo;import android.util.Log;import com.badlogic.gdx.Gdx;import com.badlogic.gdx.graphics.g2d.SpriteBatch;import com.badlogic.gdx.math.Vector2;import com.badlogic.gdx.scenes.scene2d.Actor;import com.badlogic.gdx.scenes.scene2d.InputEvent;import com.badlogic.gdx.scenes.scene2d.Stage;import com.badlogic.gdx.scenes.scene2d.InputEvent.Type;import com.badlogic.gdx.utils.Pools;public class UiStage extends Stage {public UiStage() {this(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false, null);}/** * Creates a stage with the specified * {@link #setViewport(float, float, boolean) viewport} that doesn't keep * the aspect ratio. The stage will use its own {@link SpriteBatch}, which * will be disposed when the stage is disposed. */public UiStage(float width, float height) {this(width, height, false, null);}/** * Creates a stage with the specified * {@link #setViewport(float, float, boolean) viewport}. The stage will use * its own {@link SpriteBatch}, which will be disposed when the stage is * disposed. */public UiStage(float width, float height, boolean keepAspectRatio) {this(width, height, keepAspectRatio, null);}/** * Creates a stage with the specified * {@link #setViewport(float, float, boolean) viewport} and * {@link SpriteBatch}. This can be used to avoid creating a new SpriteBatch * (which can be somewhat slow) if multiple stages are used during an * applications life time. *  * @param batch *            Will not be disposed if {@link #dispose()} is called. Handle *            disposal yourself. */public UiStage(float width, float height, boolean keepAspectRatio,SpriteBatch batch) {super(width, height, keepAspectRatio, batch);}}



  之前放出过一些界面接口,这讲放出主游戏界面的java源码。


  UiStage.java  舞台


package com.example.gamedemo;import java.util.Random;import android.util.Log;import cn.waps.AppConnect;import com.badlogic.gdx.Gdx;import com.badlogic.gdx.Input;import com.badlogic.gdx.Preferences;import com.badlogic.gdx.ScreenAdapter;import com.badlogic.gdx.audio.Music;import com.badlogic.gdx.audio.Sound;import com.badlogic.gdx.graphics.GL10;import com.badlogic.gdx.graphics.g2d.Animation;import com.badlogic.gdx.graphics.g2d.BitmapFont;import com.badlogic.gdx.graphics.g2d.Sprite;import com.badlogic.gdx.graphics.g2d.SpriteBatch;import com.badlogic.gdx.graphics.g2d.TextureAtlas;import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion;import com.badlogic.gdx.graphics.g2d.TextureRegion;import com.badlogic.gdx.math.Interpolation;import com.badlogic.gdx.math.Rectangle;import com.badlogic.gdx.scenes.scene2d.Event;import com.badlogic.gdx.scenes.scene2d.InputEvent;import com.badlogic.gdx.scenes.scene2d.InputListener;import com.badlogic.gdx.scenes.scene2d.Stage;import com.badlogic.gdx.scenes.scene2d.actions.Actions;import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction;import com.badlogic.gdx.scenes.scene2d.ui.Image;import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;import com.badlogic.gdx.utils.Array;import com.badlogic.gdx.utils.TimeUtils;public class GameScreen extends ScreenAdapter {Random r = new Random(1000);// 创建一个随机数Stage Ui;SpriteBatch Batch;private TextureAtlas atlas;private TextureAtlas shoot_background;private Hero hero;private Sprite background;FirstGame Gm;Animation flyMove;Array<TextureRegion> keyFramesArray = new Array<TextureRegion>();float stateTime = 0f;float stateTimeforEnemy1 = 0f;float stateTimeforEnemy2 = 0f;float stateTimeforEnemy3 = 0f;float stateTimeforUfo = 0f;float stateTimedfforEnemy1 = 0.5f;float stateTimedfforEnemy2 = 1.5f;float stateTimedfforEnemy3 = 5f;float x, y;int regionWidth, regionHeight;AtlasRegion Region;float flyMovex;ImageButton Back;private Music music;private Sound bulletSound;static public Sound Enemy1;static public Sound Enemy2;static public Sound Enemy3;float touchdownx, touchdowny;private bullet bulletGroup;private Enemy EnemyGroup;float df_y = 0;boolean isGameOver;GameScore Score;private BitmapFont font;private ImageButton pause;static public float Screen_W;static public float Screen_H;private Image Ufo1;private Image Ufo2;boolean isUfo1;private ImageButton baoxiang;private ImageButton bomb; // 炸弹private int bombnum;public FirstGame getGame() {return Gm;}// 初始化Ufo1private void initUfo1() {int x = r.nextInt((int) (Screen_W - Ufo1.getWidth()));Ufo1.setPosition(x, Screen_H * 4 / 5);MoveToAction move3 = Actions.moveTo(x, 0 - Ufo1.getHeight() - 10, 2f);move3.setInterpolation(Interpolation.circleOut);Ufo1.addAction(Actions.sequence(move3));}// 初始化Ufo2private void initUfo2() {int x = r.nextInt((int) (Screen_W - Ufo2.getWidth()));Ufo2.setPosition(x, Screen_H * 4 / 5);MoveToAction move3 = Actions.moveTo(x, 0 - Ufo2.getHeight() - 10, 2f);move3.setInterpolation(Interpolation.circleOut);Ufo2.addAction(Actions.sequence(move3));}public GameScreen(FirstGame Gme) {// TODO Auto-generated constructor stubthis.Gm = Gme;Batch = new SpriteBatch();Screen_W = Gdx.graphics.getWidth();Screen_H = Gdx.graphics.getHeight();Ui = new UiStage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());// 场景构造font = new BitmapFont(Gdx.files.internal("ui/font.fnt"), false);shoot_background = new TextureAtlas(Gdx.files.internal("shoot_background.pack"));background = shoot_background.createSprite("background");background.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());atlas = new TextureAtlas(Gdx.files.internal("baohe.pack"));baoxiang = new ImageButton(new TextureRegionDrawable(atlas.findRegion("tools_time_box")), new TextureRegionDrawable(atlas.findRegion("tools_time_box")));baoxiang.addListener(new ClickListener() {public void clicked(InputEvent event, float x, float y) {Gm.ShowOff();Gm.getScreen().pause();}});atlas = new TextureAtlas(Gdx.files.internal("shoot.pack"));Ufo1 = new Image(atlas.findRegion("ufo1"));Ufo1.setPosition(0, 0 - Ufo1.getHeight() - 20);Ufo2 = new Image(atlas.findRegion("ufo2")); // 设置到不可见的位置,后面使用Ufo2.setPosition(0, 0 - Ufo1.getHeight() - 20);pause = new ImageButton(new TextureRegionDrawable(atlas.findRegion("game_pause_nor")), new TextureRegionDrawable(atlas.findRegion("game_pause_pressed")));pause.setPosition(0,Gdx.graphics.getHeight()- atlas.findRegion("game_pause_nor").getRegionHeight());pause.addListener(new ClickListener() {public void clicked(InputEvent event, float x, float y) {Gm.setScreen(new PauseScreen(GameScreen.this, false));}});bomb = new ImageButton(new TextureRegionDrawable(atlas.findRegion("bomb")), new TextureRegionDrawable(atlas.findRegion("bomb")));bomb.addListener(new ClickListener() {public void clicked(InputEvent event, float x, float y) {bombnum = GetInt("Ufo2");Log.i("lxmlxm", bombnum + "");if (bombnum > 0) {PutInt("Ufo2", bombnum - 1);EnemyGroup.bomb(Score);// 炸掉所有敌机}}});baoxiang.setPosition(0, bomb.getHeight() + baoxiang.getWidth());baoxiang.getImage().setRotation(-90f);Score = new GameScore(pause);Array<TextureRegion> Texturelist = new Array<TextureRegion>();Array<TextureRegion> TextureOverlist = new Array<TextureRegion>();regionWidth = atlas.findRegion("hero1").getRegionWidth();regionHeight = atlas.findRegion("hero1").getRegionHeight();Texturelist.add(atlas.findRegion("hero1"));Texturelist.add(atlas.findRegion("hero2"));TextureOverlist.add(atlas.findRegion("hero_blowup_n1"));TextureOverlist.add(atlas.findRegion("hero_blowup_n2"));TextureOverlist.add(atlas.findRegion("hero_blowup_n3"));hero = new Hero(0.3f, Texturelist, TextureOverlist);// 创建主角x = (Gdx.graphics.getWidth() - regionWidth) / 2;y = 5;hero.setPosition(x, y);hero.setWidth(regionWidth);hero.setHeight(regionHeight);Log.i("lxm", "" + hero.getWidth() + " h=" + hero.getHeight());bulletGroup = new bullet(atlas); // 构造子弹EnemyGroup = new Enemy(atlas); // 构造敌人EnemyGroup.creatEnemy(Enemy.EnemyType1);Ui.addActor(baoxiang);Ui.addActor(pause);Ui.addActor(Ufo1);Ui.addActor(Ufo2);Ui.addListener(new InputListener() {/** * Called when a mouse button or a finger touch goes down on the * actor. If true is returned, this listener will receive all * touchDragged and touchUp events, even those not over this actor, * until touchUp is received. Also when true is returned, the event * is {@link Event#handle() handled}. *  * @see InputEvent */public boolean touchDown(InputEvent event, float x, float y,int pointer, int button) {Log.i("lxm touchDown", "x=" + x + " y=" + y);touchdownx = x;touchdowny = y;return true;}/** * Called when a mouse button or a finger touch goes up anywhere, * but only if touchDown previously returned true for the mouse * button or touch. The touchUp event is always * {@link Event#handle() handled}. *  * @see InputEvent */public void touchUp(InputEvent event, float x, float y,int pointer, int button) {}/** * Called when a mouse button or a finger touch is moved anywhere, * but only if touchDown previously returned true for the mouse * button or touch. The touchDragged event is always * {@link Event#handle() handled}. *  * @see InputEvent */public void touchDragged(InputEvent event, float x, float y,int pointer) {// Log.i("lxm touchDragged ",// "x=" + x + " y=" + y + "X=" + hero.getX() + "Y="// + hero.getY() + "ParentX=" + Ui.getWidth()// + "ParentH=" + Ui.getHeight());//// Log.i("lxm touchDragged ",// "y=" +(Y + regionHeight));float X = hero.getX() + x - touchdownx;float Y = hero.getY() + y - touchdowny;touchdownx = x;touchdowny = y;// Log.i("lxm touchDragged ", "y=" + (Y + regionHeight) + "h="// + hero.getHeight() + "Pos=" + (854 - regionHeight - 2));X = X <= 0 ? 0 : (X + regionWidth) >= Screen_W ? Screen_W- regionWidth : X;Y = Y <= 0 ? 0 : (Y + regionHeight) >= Screen_H ? Screen_H- regionHeight - 2 : Y;Log.i("lxm", X + "--" + Y);hero.setPosition(X, Y);}});bulletGroup.creatbullet((int) (hero.getX() + regionWidth / 2),(int) (hero.getY() + regionHeight), regionWidth);Gdx.input.setInputProcessor(Ui);Gdx.input.setCatchBackKey(true);music = Gdx.audio.newMusic(Gdx.files.internal("sound/game_music.mp3"));music.setLooping(true);music.play();bulletSound = Gdx.audio.newSound(Gdx.files.internal("sound/bullet.mp3"));// Gdx.audio.newSound(Gdx.files.getFileHandle("data/shotgun.ogg",Enemy1 = Gdx.audio.newSound(Gdx.files.internal("sound/enemy1_down.mp3"));Enemy2 = Gdx.audio.newSound(Gdx.files.internal("sound/enemy2_down.mp3"));Enemy3 = Gdx.audio.newSound(Gdx.files.internal("sound/enemy3_down.mp3"));waitForLoadCompleted(bulletSound); // FileType.Internal));//Gdx.audio.newSound(Gdx.files.internal("data/shotgun.ogg"));bulletSound.loop(1, 2f, 0);Ui.addActor(bomb);Ui.addActor(hero);}private long waitForLoadCompleted(Sound sound) {long id;while ((id = sound.play(0)) == -1) {long t = TimeUtils.nanoTime();while (TimeUtils.nanoTime() - t < 100000000);}return id;}@Overridepublic void render(float delta) {// TODO Auto-generated method stubstateTime += delta;stateTimeforEnemy1 += delta;stateTimeforEnemy2 += delta;stateTimeforEnemy3 += delta;stateTimeforUfo += delta;df_y--;if (stateTimeforEnemy3 > stateTimedfforEnemy3) {stateTimeforEnemy3 = 0;stateTimedfforEnemy3 = 10f + r.nextFloat() * 20f;EnemyGroup.creatEnemy(Enemy.EnemyType3);} else if (stateTimeforEnemy2 > stateTimedfforEnemy2) {stateTimeforEnemy2 = 0;stateTimedfforEnemy2 = 1.5f + r.nextFloat() * 3f;EnemyGroup.creatEnemy(Enemy.EnemyType2);} else if (stateTimeforEnemy1 > stateTimedfforEnemy1) {stateTimeforEnemy1 = 0;stateTimedfforEnemy1 = 0.25f + r.nextFloat() * 1f;EnemyGroup.creatEnemy(Enemy.EnemyType1);}// 28s 形成一个ufoif (stateTimeforUfo > 28f) {stateTimeforUfo = 0;if (isUfo1) {initUfo1();isUfo1 = false;} else {initUfo2();isUfo1 = true;}}Rectangle Ufo = new Rectangle(Ufo1.getX(), Ufo1.getY(),Ufo1.getWidth(), Ufo1.getHeight());if (Ufo.overlaps(hero.getrectangle())) {Ufo1.setPosition(0, 0 - Ufo1.getHeight() - 20);Ufo1.clearActions();bulletGroup.setType(bullet.TypeBullet2);// 开启增强模式了}Rectangle Ufot = new Rectangle(Ufo2.getX(), Ufo2.getY(),Ufo2.getWidth(), Ufo2.getHeight());if (Ufot.overlaps(hero.getrectangle())) {Log.i("Remove", "ufo2");Ufo2.setPosition(0, 0 - Ufo2.getHeight() - 20);Ufo2.clearActions();bombnum = GetInt("Ufo2") + 1;PutInt("Ufo2", bombnum);// 得到一个炸弹}if (!isGameOver) {// 在非结束状态下,判断是否overisGameOver = EnemyGroup.checkbulletAndPlay(bulletGroup.getbulletArray(), hero.getrectangle(), Score);if (isGameOver) {hero.setStatus(Hero.eIsOvering);Gdx.input.setInputProcessor(null);}}bulletGroup.act(delta, (int) (hero.getX() + regionWidth / 2),(int) (hero.getY() + regionHeight));EnemyGroup.act(delta);draw(delta);boolean isBackPressed = Gdx.input.isKeyPressed(Input.Keys.BACK);if (isBackPressed) {Gm.setScreen(new PauseScreen(this, false));} else if ((isGameOver && hero.isOver())) {Gm.setScreen(new PauseScreen(this, true));}}public void draw(float delta) {Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);Batch.begin();Batch.disableBlending();background.setY(df_y % Gdx.graphics.getHeight());background.draw(Batch);background.setY(Gdx.graphics.getHeight() + df_y% Gdx.graphics.getHeight());background.draw(Batch);Batch.enableBlending();Batch.end();Ui.act();Ui.draw();Batch.begin();bulletGroup.draw(Batch);EnemyGroup.draw(Batch, stateTime);Score.draw(Batch);font.draw(Batch, bombnum + "", Ufo2.getWidth() + 10,Ufo2.getHeight() / 2);Batch.end();}@Overridepublic void resume() {// TODO Auto-generated method stubsuper.resume();Gdx.input.setInputProcessor(Ui);bulletSound.loop();isGameOver = false;hero.setStatus(Hero.eIsRuning);}@Overridepublic void pause() {// TODO Auto-generated method stubsuper.pause();bulletSound.pause();hero.setStatus(Hero.eIsPause);Gdx.input.setInputProcessor(null);Gm.setScreen(new PauseScreen(this, false));}@Overridepublic void show() {// TODO Auto-generated method stubsuper.show();Gdx.input.setInputProcessor(Ui);bulletSound.loop();if (isGameOver) {x = (Gdx.graphics.getWidth() - regionWidth) / 2;y = 5;hero.setPosition(x, y);EnemyGroup.cleanall();Score.cleanScore();}isGameOver = false;hero.setStatus(Hero.eIsRuning);}@Overridepublic void hide() {// TODO Auto-generated method stubsuper.hide();bulletSound.pause();hero.setStatus(Hero.eIsPause);}@Overridepublic void dispose() {// TODO Auto-generated method stubsuper.dispose();Batch.dispose();Ui.dispose();atlas.dispose();music.dispose();}public void PutInt(String name, int value) {Preferences Ps = Gdx.app.getPreferences("cfg");Ps.putInteger(name, value);Ps.flush();}public int GetInt(String name) {Preferences Ps = Gdx.app.getPreferences("cfg");return (int) Ps.getInteger(name, 0);}}


1 0
原创粉丝点击