Libgdx – Lập trình Game Zombie Wars.

A. Nội Dung

1. Khởi tạo Project Libgdx:

  • Tạo một project Libgdx mới: Libgdx_Zombie_Wars
  • Cài đặt các thông số như mục lưu trữ, package, JDK, Desktop, Box2D,…

2. Cấu trúc Package:

  • com.game.zombilewars

3. Cấu trúc thư mục:

  • android
  • core
  • desktop

4. Thư mục android:

  • AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.game.zombilewars">

    <uses-feature android:glEsVersion="0x00020000" android:required="true" />

    <application
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@drawable/ic_launcher"
        android:isGame="true"
        android:appCategory="game"
        android:label="@string/app_name"
        android:theme="@style/GdxTheme"
        tools:ignore="UnusedAttribute">
        <activity
            android:name="com.game.zombilewars.AndroidLauncher"
            android:label="@string/app_name" 
            android:screenOrientation="landscape"
            android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
  • AndroindLauncher
package com.game.zombilewars;

import android.os.Bundle;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;

public class AndroidLauncher extends AndroidApplication {
	@Override
	protected void onCreate (Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
		initialize(new MainZombieWars(), config);
	}
}

5. assets

  • Quản lý tài nguyên của trò chơi bao gồm ảnh, map, font chữ, âm thanh, ….

6. Thư mục core:

  • Game:

– GameScreen:

package com.game.zombilewars.game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Input.Peripheral;
import com.badlogic.gdx.math.MathUtils;
import com.game.zombilewars.Assets;
import com.game.zombilewars.MainZombieWars;
import com.game.zombilewars.Settings;
import com.game.zombilewars.screens.Screens;


public class GameScreen extends Screens {
    static final int STATE_RUNNING = 0;
    static final int STATE_GAME_OVER = 1;
    static final int STATE_NEXT_LEVEL = 2;
    static final int STATE_PAUSED = 3;
    int state;

    public WorldGame oWorld;
    WorldGameRenderer2 renderer;

    float accelCamX;

    public GameScreen(MainZombieWars game, int level) {
        super(game);

        oWorld = new WorldGame(0);
        renderer = new WorldGameRenderer2(batcher, oWorld);

    }

    @Override
    public void update(float delta) {

        switch (state) {
            case STATE_RUNNING:
                updateRunning(delta);
                break;
        }

    }

    private void updateRunning(float delta) {

        if (Gdx.input.isKeyPressed(Keys.A))
            accelCamX = -5;
        else if (Gdx.input.isKeyPressed(Keys.D))
            accelCamX = 5;
        else if (Gdx.input.isPeripheralAvailable(Peripheral.Accelerometer))
            accelCamX = Gdx.input.getAccelerometerY() * 1.5f;
        else
            accelCamX = 0;

        if (Gdx.input.isKeyPressed(Keys.Z)) {
            Settings.zoom += .025;
            if (Settings.zoom > 2.105f)
                Settings.zoom = 2.105f;
        } else if (Gdx.input.isKeyPressed(Keys.X)) {
            Settings.zoom -= .025;
            if (Settings.zoom < 1)
                Settings.zoom = 1;
        }

        oWorld.update(delta, accelCamX);

    }

    @Override
    public void draw(float delta) {
        renderer.render(delta);
        oCam.update();
        batcher.setProjectionMatrix(oCam.combined);

        batcher.begin();
        Assets.fontGrande.draw(batcher, "FPS: " + Gdx.graphics.getFramesPerSecond() + "\nNew hero: E\nZoom: X,Z", 10, 400);
        batcher.end();
    }

    @Override
    public boolean keyDown(int keycode) {
        if (keycode == Keys.ESCAPE)
            Gdx.app.exit();
        else if (keycode == Keys.C)
            oWorld.atackaLL();
        else if (keycode == Keys.V)
            oWorld.dieALl();
        else if (keycode == Keys.E)
            if (MathUtils.randomBoolean()) {
                oWorld.objectCreatorManager.creatHeroLumber();
            } else if (MathUtils.randomBoolean()) {
                oWorld.objectCreatorManager.creatHeroFarmer();
            } else {
                oWorld.objectCreatorManager.creatHeroForce();
            }
        return super.keyDown(keycode);
    }

}

– ObjectCreatorManagerBox2d:

package com.game.zombilewars.game;

import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.game.zombilewars.objetos.Bullet;
import com.game.zombilewars.objetos.HeroFarmer;
import com.game.zombilewars.objetos.HeroForce;
import com.game.zombilewars.objetos.HeroLumber;
import com.game.zombilewars.objetos.Personajes;
import com.game.zombilewars.objetos.ZombieCuasy;
import com.game.zombilewars.objetos.ZombieFrank;
import com.game.zombilewars.objetos.ZombieKid;
import com.game.zombilewars.objetos.ZombieMummy;
import com.game.zombilewars.objetos.ZombiePan;

public class ObjectCreatorManagerBox2d {

	WorldGame oWorld;
	World oWorldBox;

	public ObjectCreatorManagerBox2d(WorldGame oWorld) {
		this.oWorld = oWorld;
		oWorldBox = oWorld.oWorldBox;
	}

	public void createZombieKid() {
		crearZombieMalo(ZombieKid.class);
	}

	public void createZombieCuasy() {
		crearZombieMalo(ZombieCuasy.class);
	}

	public void createZombieMummy() {
		crearZombieMalo(ZombieMummy.class);
	}

	public void createZombiePan() {
		crearZombieMalo(ZombiePan.class);
	}

	public void createZombieFrank() {
		crearZombieMalo(ZombieFrank.class);
	}

	public void creatHeroForce() {
		crearHero(HeroForce.class);
	}

	public void creatHeroFarmer() {
		crearHero(HeroFarmer.class);
	}

	public void creatHeroLumber() {
		crearHero(HeroLumber.class);
	}

	private void crearZombieMalo(Class<?> tipoZombie) {
		Personajes obj = null;

		BodyDef bd = new BodyDef();
		bd.position.set(16, 1.6f);
		bd.type = BodyType.DynamicBody;

		Body oBody = oWorldBox.createBody(bd);

		if (tipoZombie == ZombieKid.class) {
			obj = new ZombieKid(oBody);
		}
		else if (tipoZombie == ZombieCuasy.class) {
			obj = new ZombieCuasy(oBody);
		}
		else if (tipoZombie == ZombieMummy.class) {
			obj = new ZombieMummy(oBody);
		}
		else if (tipoZombie == ZombiePan.class) {
			obj = new ZombiePan(oBody);
		}
		else if (tipoZombie == ZombieFrank.class) {
			obj = new ZombieFrank(oBody);
		}

		PolygonShape shape = new PolygonShape();
		shape.setAsBox(.17f, .32f);

		FixtureDef fixture = new FixtureDef();
		fixture.shape = shape;
		fixture.density = 8;
		fixture.friction = 0;
		fixture.filter.groupIndex = -1;
		oBody.createFixture(fixture);

		oBody.setFixedRotation(true);
		oBody.setUserData(obj);
		oWorld.arrFacingLeft.add(obj);

		shape.dispose();

	}

	private void crearHero(Class<?> tipoHero) {
		Personajes obj = null;

		BodyDef bd = new BodyDef();
		bd.position.set(1, 1.6f);
		bd.type = BodyType.DynamicBody;

		Body oBody = oWorldBox.createBody(bd);

		if (tipoHero == HeroForce.class) {
			obj = new HeroForce(oBody);
		}
		else if (tipoHero == HeroFarmer.class) {
			obj = new HeroFarmer(oBody);
		}
		else if (tipoHero == HeroLumber.class) {
			obj = new HeroLumber(oBody);
		}

		PolygonShape shape = new PolygonShape();
		shape.setAsBox(.17f, .32f);

		FixtureDef fixture = new FixtureDef();
		fixture.shape = shape;
		fixture.density = 8;
		fixture.friction = 0;
		fixture.filter.groupIndex = -1;
		oBody.createFixture(fixture);

		oBody.setFixedRotation(true);
		oBody.setUserData(obj);
		oWorld.arrFacingRight.add(obj);

		shape.dispose();

	}

	public void createBullet(Personajes oPerWhoFired) {
		Bullet obj;
		BodyDef bd = new BodyDef();

		if (oPerWhoFired.tipo == Personajes.TIPO_RANGO) {
			if (oPerWhoFired.isFacingLeft) {
				bd.position.set(oPerWhoFired.position.x - .42f, oPerWhoFired.position.y - .14f);
			}
			else {
				bd.position.set(oPerWhoFired.position.x + .42f, oPerWhoFired.position.y - .14f);
			}
		}
		else
			bd.position.set(oPerWhoFired.position.x, oPerWhoFired.position.y);

		bd.type = BodyType.DynamicBody;
		Body oBody = oWorldBox.createBody(bd);

		obj = new Bullet(oBody, oPerWhoFired);

		PolygonShape shape = new PolygonShape();
		shape.setAsBox(.1f, .1f);

		FixtureDef fixture = new FixtureDef();
		fixture.shape = shape;
		fixture.density = 1;
		fixture.isSensor = true;
		oBody.createFixture(fixture);

		oBody.setFixedRotation(true);
		oBody.setUserData(obj);
		oBody.setBullet(true);
		oBody.setGravityScale(0);
		oWorld.arrBullets.add(obj);

	}

}

– TiledMapManagerBox2d:

package com.game.zombilewars.game;

import java.util.Iterator;

import com.badlogic.gdx.maps.Map;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.MapObjects;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.objects.CircleMapObject;
import com.badlogic.gdx.maps.objects.PolygonMapObject;
import com.badlogic.gdx.maps.objects.PolylineMapObject;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.objects.TextureMapObject;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.ChainShape;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.Shape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Logger;

public class TiledMapManagerBox2d {

	private World oWorldBox;
	private float unitScale;
	private Logger logger;
	private FixtureDef defaultFixture;

	public TiledMapManagerBox2d(WorldGame oWorld, float unitScale) {
		oWorldBox = oWorld.oWorldBox;
		this.unitScale = unitScale;
		logger = new Logger("MapBodyManager", 1);

		defaultFixture = new FixtureDef();
		defaultFixture.density = 1.0f;
		defaultFixture.friction = .5f;
		defaultFixture.restitution = 0.0f;

	}

	public void createObjetosDesdeTiled(Map map) {
		crearFisicos(map, "fisicos");

	}

	private void crearFisicos(Map map, String layerName) {
		MapLayer layer = map.getLayers().get(layerName);

		if (layer == null) {
			logger.error("layer " + layerName + " no existe");
			return;
		}

		MapObjects objects = layer.getObjects();
		Iterator<MapObject> objectIt = objects.iterator();

		while (objectIt.hasNext()) {
			MapObject object = objectIt.next();

			if (object instanceof TextureMapObject) {
				continue;
			}

			MapProperties properties = object.getProperties();
			String tipo = (String) properties.get("type");
			if (tipo == null)
				continue;

			/**
			 * Normalmente si no ninguno es el piso
			 */
			Shape shape;
			if (object instanceof RectangleMapObject) {
				shape = getRectangle((RectangleMapObject) object);
			}
			else if (object instanceof PolygonMapObject) {
				shape = getPolygon((PolygonMapObject) object);
			}
			else if (object instanceof PolylineMapObject) {
				shape = getPolyline((PolylineMapObject) object);
			}
			else if (object instanceof CircleMapObject) {
				shape = getCircle((CircleMapObject) object);
			}
			else {
				logger.error("non suported shape " + object);
				continue;
			}

			defaultFixture.shape = shape;

			BodyDef bodyDef = new BodyDef();
			bodyDef.type = BodyDef.BodyType.StaticBody;

			Body body = oWorldBox.createBody(bodyDef);
			body.createFixture(defaultFixture);
			body.setUserData(tipo);

			defaultFixture.shape = null;
			defaultFixture.isSensor = false;
			defaultFixture.filter.groupIndex = 0;
			shape.dispose();

		}

	}

	private Shape getRectangle(RectangleMapObject rectangleObject) {
		Rectangle rectangle = rectangleObject.getRectangle();
		PolygonShape polygon = new PolygonShape();
		Vector2 size = new Vector2((rectangle.x + rectangle.width * 0.5f) * unitScale, (rectangle.y + rectangle.height * 0.5f) * unitScale);
		polygon.setAsBox(rectangle.getWidth() * 0.5f * unitScale, rectangle.height * 0.5f * unitScale, size, 0.0f);
		return polygon;
	}

	private Shape getCircle(CircleMapObject circleObject) {
		Circle circle = circleObject.getCircle();
		CircleShape circleShape = new CircleShape();
		circleShape.setRadius(circle.radius * unitScale);
		circleShape.setPosition(new Vector2(circle.x * unitScale, circle.y * unitScale));
		return circleShape;

	}

	private Shape getPolygon(PolygonMapObject polygonObject) {
		PolygonShape polygon = new PolygonShape();
		float[] vertices = polygonObject.getPolygon().getVertices();
		float[] worldVertices = new float[vertices.length];
		float yLost = polygonObject.getPolygon().getY() * unitScale;
		float xLost = polygonObject.getPolygon().getX() * unitScale;

		for (int i = 0; i < vertices.length; ++i) {
			if (i % 2 == 0)
				worldVertices[i] = vertices[i] * unitScale + xLost;
			else
				worldVertices[i] = vertices[i] * unitScale + yLost;
		}
		polygon.set(worldVertices);

		return polygon;
	}

	private Shape getPolyline(PolylineMapObject polylineObject) {
		float[] vertices = polylineObject.getPolyline().getVertices();

		Vector2[] worldVertices = new Vector2[vertices.length / 2];
		float yLost = polylineObject.getPolyline().getY() * unitScale;
		float xLost = polylineObject.getPolyline().getX() * unitScale;
		for (int i = 0; i < vertices.length / 2; ++i) {
			worldVertices[i] = new Vector2();
			worldVertices[i].x = vertices[i * 2] * unitScale + xLost;
			worldVertices[i].y = vertices[i * 2 + 1] * unitScale + yLost;
		}
		ChainShape chain = new ChainShape();
		chain.createChain(worldVertices);
		return chain;
	}

}

WorldGame:

package com.game.zombilewars.game;

import java.util.Iterator;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Array;
import com.game.zombilewars.Assets;
import com.game.zombilewars.Settings;
import com.game.zombilewars.objetos.Bullet;
import com.game.zombilewars.objetos.Personajes;
import com.game.zombilewars.screens.Screens;


public class WorldGame {
    final float WIDTH = Screens.WORLD_WIDTH;
    final float HEIGHT = Screens.WORLD_HEIGHT;

    static final int STATE_RUNNING = 0;
    static final int STATE_GAMEOVER = 1;
    static final int STATE_NEXT_LEVEL = 2;
    public int state;

    final float TIME_TO_SPAWN_ZOMBIE_FRANK;
    float timeToSpwanZombieFrank;

    final float TIME_TO_SPAWN_ZOMBIE_CUASY;
    float timeToSpwanZombieCuasy;

    final float TIME_TO_SPAWN_ZOMBIE_KID;
    float timeToSpwanZombieKid;

    final float TIME_TO_SPAWN_ZOMBIE_MUMMY;
    float timeToSpwanZombieMummy;

    final float TIME_TO_SPAWN_ZOMBIE_PAN;
    float timeToSpwanZombiePan;

    /**
     * Mis tiles son de 32px, asi que la unidad seria 1/32 con una camara ortograpicha de 10x15 para ver 10 tiles de ancho y 15 de alto. El probema es que mi camara es de 8x4.8f por eso tengo que
     * cambiar la escala, con 1/32 solo veria 8 tiles a lo ancho y de altura 4.8 por como esta configurada la camara.
     * <p>
     * con 1/96 veo 24 tiles a lo ancho
     */
    float unitScale = 1 / 76f;
    public int tiledWidth;
    public int tiledHeight;

    float xMin, xMax, yMin;

    public World oWorldBox;
    public ObjectCreatorManagerBox2d objectCreatorManager;

    public Vector2 posCamara;

    Array<Personajes> arrFacingRight;
    Array<Personajes> arrFacingLeft;
    Array<Bullet> arrBullets;
    Array<Body> arrBodies;

    public WorldGame(int nivel) {
        oWorldBox = new World(new Vector2(0, -9.8f), true);
        oWorldBox.setContactListener(new Colisiones());

        arrFacingRight = new Array<Personajes>();
        arrFacingLeft = new Array<Personajes>();
        arrBullets = new Array<Bullet>();
        arrBodies = new Array<Body>();

        objectCreatorManager = new ObjectCreatorManagerBox2d(this);
        new TiledMapManagerBox2d(this, unitScale).createObjetosDesdeTiled(Assets.map);
        tiledWidth = ((TiledMapTileLayer) Assets.map.getLayers().get("1")).getWidth();
        tiledHeight = ((TiledMapTileLayer) Assets.map.getLayers().get("1")).getHeight();

        if (tiledWidth * tiledHeight > 2500) {
            Gdx.app.log("Advertencia de rendimiento", "Hay mas de 2500 tiles " + tiledWidth + " x " + tiledHeight + " = "
                    + (tiledWidth * tiledHeight));
        }

        Gdx.app.log("Tile Width", tiledWidth + "");
        Gdx.app.log("Tile Height", tiledHeight + "");

        xMin = 4.0f;// Inicia en 4 porque la camara esta centrada no en el origen
        xMax = unitScale * tiledWidth * 32 - 4;// Menos 4 porque la camara esta centrada en el origen
        yMin = 2.4f;

        posCamara = new Vector2(xMin, yMin);
        state = STATE_RUNNING;

        switch (nivel) {
            case 0:
                TIME_TO_SPAWN_ZOMBIE_KID = 3f;
                TIME_TO_SPAWN_ZOMBIE_CUASY = 10f;
                TIME_TO_SPAWN_ZOMBIE_MUMMY = 15f;
                TIME_TO_SPAWN_ZOMBIE_PAN = 20f;
                TIME_TO_SPAWN_ZOMBIE_FRANK = 25f;
                break;

            default:
                TIME_TO_SPAWN_ZOMBIE_KID = 0f;
                TIME_TO_SPAWN_ZOMBIE_CUASY = 0f;
                TIME_TO_SPAWN_ZOMBIE_MUMMY = 0f;
                TIME_TO_SPAWN_ZOMBIE_PAN = 0f;
                TIME_TO_SPAWN_ZOMBIE_FRANK = 0f;
                break;

        }

    }

    public void update(float delta, float accelCamX) {
        oWorldBox.step(delta, 8, 4);
        updateCamara(delta, accelCamX);

        eliminarObjetos();

        spawnStuff(delta);

        oWorldBox.getBodies(arrBodies);
        Iterator<Body> i = arrBodies.iterator();

        while (i.hasNext()) {
            Body body = i.next();
            if (body.getUserData() instanceof Personajes) {
                Personajes obj = (Personajes) body.getUserData();
                if (obj.isFacingLeft)
                    updateFacingLeft(delta, obj);
                else
                    updateFacingRight(delta, obj);
            } else if (body.getUserData() instanceof Bullet) {
                updateBullet(delta, body);
            }
        }
    }

    public void atackaLL() {
        Iterator<Personajes> i = arrFacingLeft.iterator();

        while (i.hasNext()) {

            Personajes obj = i.next();
            if (obj.attack())

                objectCreatorManager.createBullet(obj);
        }
    }

    public void dieALl() {
        Iterator<Personajes> i = arrFacingLeft.iterator();

        while (i.hasNext()) {

            Personajes obj = i.next();
            obj.die();
        }
    }

    private void spawnStuff(float delta) {

        timeToSpwanZombieKid += delta;
        if (timeToSpwanZombieKid >= TIME_TO_SPAWN_ZOMBIE_KID) {
            timeToSpwanZombieKid -= TIME_TO_SPAWN_ZOMBIE_KID;
            objectCreatorManager.createZombieKid();
        }

        timeToSpwanZombieCuasy += delta;
        if (timeToSpwanZombieCuasy >= TIME_TO_SPAWN_ZOMBIE_CUASY) {
            timeToSpwanZombieCuasy -= TIME_TO_SPAWN_ZOMBIE_CUASY;
            objectCreatorManager.createZombieCuasy();
        }

        timeToSpwanZombieMummy += delta;
        if (timeToSpwanZombieMummy >= TIME_TO_SPAWN_ZOMBIE_MUMMY) {
            timeToSpwanZombieMummy -= TIME_TO_SPAWN_ZOMBIE_MUMMY;
            objectCreatorManager.createZombieMummy();
        }

        timeToSpwanZombiePan += delta;
        if (timeToSpwanZombiePan >= TIME_TO_SPAWN_ZOMBIE_PAN) {
            timeToSpwanZombiePan -= TIME_TO_SPAWN_ZOMBIE_PAN;
            objectCreatorManager.createZombiePan();
        }

        timeToSpwanZombieFrank += delta;
        if (timeToSpwanZombieFrank >= TIME_TO_SPAWN_ZOMBIE_FRANK) {
            timeToSpwanZombieFrank -= TIME_TO_SPAWN_ZOMBIE_FRANK;
            objectCreatorManager.createZombieFrank();
        }

    }

    private void updateCamara(float delta, float accelCamX) {

        if (accelCamX != 0)
            posCamara.x += (delta * accelCamX);

        if (posCamara.x < xMin * Settings.zoom) {
            posCamara.x = xMin * Settings.zoom;
        } else if (posCamara.x > (xMax - (xMin * (Settings.zoom - 1)))) {
            posCamara.x = xMax - (xMin * (Settings.zoom - 1));
        }

        posCamara.y = yMin * Settings.zoom;

    }

    private void updateFacingRight(float delta, Personajes obj) {
        obj.update(delta);

        int len = arrFacingLeft.size;
        for (int i = 0; i < len; i++) {
            Personajes objMalo = arrFacingLeft.get(i);

            if (obj.position.dst(objMalo.position.x, objMalo.position.y) <= obj.DISTANCE_ATTACK) {
                if (obj.attack())
                    objectCreatorManager.createBullet(obj);

            }
        }
    }

    private void updateFacingLeft(float delta, Personajes obj) {
        obj.update(delta);

        int len = arrFacingRight.size;
        for (int i = 0; i < len; i++) {
            Personajes objBueno = arrFacingRight.get(i);
            // if (obj.position.dst(objBueno.position.x, objBueno.position.y) <= obj.DISTANCE_ATTACK) {
            // obj.attack();
            //
            // if (obj.attack) {
            // objBueno.getHurt(obj.DAMAGE);
            // obj.didAttackEnemy();
            // }
            // }
            if (obj.position.dst(objBueno.position.x, objBueno.position.y) <= obj.DISTANCE_ATTACK) {
                if (obj.attack())
                    objectCreatorManager.createBullet(obj);

            }
        }
    }

    private void updateBullet(float delta, Body body) {
        Bullet obj = (Bullet) body.getUserData();
        obj.update(delta);

        if (obj.position.x > xMax + 3 || obj.position.x < xMin - 3)
            obj.state = Bullet.STATE_DESTROY;

    }

    private void eliminarObjetos() {
        oWorldBox.getBodies(arrBodies);
        Iterator<Body> i = arrBodies.iterator();

        while (i.hasNext()) {
            Body body = i.next();

            if (!oWorldBox.isLocked()) {
                if (body.getUserData() instanceof Personajes) {
                    Personajes obj = (Personajes) body.getUserData();
                    if (obj.state == Personajes.STATE_DEAD && obj.stateTime >= obj.DURATION_DEAD) {
                        if (obj.isFacingLeft)
                            arrFacingLeft.removeValue(obj, true);
                        else
                            arrFacingRight.removeValue(obj, true);

                        oWorldBox.destroyBody(body);
                        continue;
                    }
                } else if (body.getUserData() instanceof Bullet) {
                    Bullet obj = (Bullet) body.getUserData();
                    if (obj.state == Bullet.STATE_DESTROY) {
                        arrBullets.removeValue(obj, true);
                        oWorldBox.destroyBody(body);
                        continue;
                    }
                }

            }
        }
    }

    class Colisiones implements ContactListener {

        @Override
        public void beginContact(Contact contact) {
            Fixture a = contact.getFixtureA();
            Fixture b = contact.getFixtureB();
            if (a.getBody().getUserData() instanceof Bullet)
                beginContactBulletOtraCosa(a, b);
            else if (b.getBody().getUserData() instanceof Bullet)
                beginContactBulletOtraCosa(b, a);

        }

        private void beginContactBulletOtraCosa(Fixture fixBullet, Fixture otraCosa) {
            Object oOtraCosa = otraCosa.getBody().getUserData();
            Bullet oBullet = (Bullet) fixBullet.getBody().getUserData();

            if (oOtraCosa instanceof Personajes) {
                if (oBullet.state == Bullet.STATE_NORMAL || oBullet.state == Bullet.STATE_MUZZLE) {
                    Personajes obj = (Personajes) oOtraCosa;

                    if (obj.isFacingLeft == oBullet.isFacingLeft)// Si van hacia el mismo lado son amigos
                        return;

                    if (obj.state != Personajes.STATE_DEAD) {
                        // if (obj.state != Zombie.STATE_DEAD)
                        // Assets.zombieHit.play();

                        obj.getHurt(oBullet.DAMAGE);
                        oBullet.hit();

                    }
                }
            }

        }

        @Override
        public void endContact(Contact contact) {
            // TODO Auto-generated method stub

        }

        @Override
        public void preSolve(Contact contact, Manifold oldManifold) {
            // TODO Auto-generated method stub

        }

        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
            // TODO Auto-generated method stub

        }

    }

}

– WorldGameRenderer2:

package com.game.zombilewars.game;

import java.util.Iterator;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.game.zombilewars.AnimationSprite;
import com.game.zombilewars.Assets;
import com.game.zombilewars.Settings;
import com.game.zombilewars.objetos.Bullet;
import com.game.zombilewars.objetos.HeroFarmer;
import com.game.zombilewars.objetos.HeroForce;
import com.game.zombilewars.objetos.HeroLumber;
import com.game.zombilewars.objetos.Personajes;
import com.game.zombilewars.objetos.ZombieCuasy;
import com.game.zombilewars.objetos.ZombieFrank;
import com.game.zombilewars.objetos.ZombieKid;
import com.game.zombilewars.objetos.ZombieMummy;
import com.game.zombilewars.objetos.ZombiePan;
import com.game.zombilewars.screens.Screens;


public class WorldGameRenderer2 {

	final float WIDTH = Screens.WORLD_WIDTH;
	final float HEIGHT = Screens.WORLD_HEIGHT;

	SpriteBatch batcher;
	WorldGame oWorld;
	OrthographicCamera oCam;
	OrthogonalTiledMapRenderer tiledRender;

	Box2DDebugRenderer renderBox;

	TiledMapTileLayer map1;
	TiledMapTileLayer map2;
	TiledMapTileLayer map3;
	TiledMapTileLayer map4;

	TiledMapTileLayer mapInFront;

	public WorldGameRenderer2(SpriteBatch batcher, WorldGame oWorld) {

		this.oCam = new OrthographicCamera(WIDTH, HEIGHT);
		this.oCam.position.set(WIDTH / 2f, HEIGHT / 2f, 0);
		this.batcher = batcher;
		this.oWorld = oWorld;
		this.renderBox = new Box2DDebugRenderer();
		tiledRender = new OrthogonalTiledMapRenderer(Assets.map, oWorld.unitScale);

		/**
		 * Entre mas chico el numero se renderean primero.
		 */
		map1 = (TiledMapTileLayer) tiledRender.getMap().getLayers().get("1");
		map2 = (TiledMapTileLayer) tiledRender.getMap().getLayers().get("2");
		map3 = (TiledMapTileLayer) tiledRender.getMap().getLayers().get("3");
		map4 = (TiledMapTileLayer) tiledRender.getMap().getLayers().get("4");
		mapInFront = (TiledMapTileLayer) tiledRender.getMap().getLayers().get("inFront");

	}

	public void render(float delta) {
		oCam.zoom = Settings.zoom;
		oCam.position.x = oWorld.posCamara.x;
		oCam.position.y = oWorld.posCamara.y;

		oCam.update();

		drawTiled();

		batcher.setProjectionMatrix(oCam.combined);
		batcher.begin();
		batcher.enableBlending();
		drawFacingRight();
		drawMalos();
		drawBullets();
		batcher.end();

		drawTiledInfront();


	}

	private void drawTiledInfront() {

		tiledRender.setView(oCam);

		tiledRender.getBatch().begin();
		if (mapInFront != null)
			tiledRender.renderTileLayer(mapInFront);
		tiledRender.getBatch().end();

	}

	private void drawTiled() {
		tiledRender.setView(oCam);
		tiledRender.getBatch().begin();
		if (map1 != null)
			tiledRender.renderTileLayer(map1);
		if (map2 != null)
			tiledRender.renderTileLayer(map2);
		if (map3 != null)
			tiledRender.renderTileLayer(map3);
		if (map4 != null)
			tiledRender.renderTileLayer(map4);


		tiledRender.getBatch().end();

	}

	private void drawMalos() {
		Iterator<Personajes> i = oWorld.arrFacingLeft.iterator();

		while (i.hasNext()) {

			Personajes obj = i.next();
			AnimationSprite animWalk = null;
			AnimationSprite animAttack = null;
			AnimationSprite animDie = null;
			Sprite spriteHurt = null;

			float ajusteY = 0;
			float size = 0;

			if (obj instanceof ZombieKid) {
				animWalk = Assets.zombieKidWalk;
				animAttack = Assets.zombieKidAttack;
				animDie = Assets.zombieKidDie;
				spriteHurt = Assets.zombieKidHurt;
				ajusteY = -.033f;
				size = .8f;
			}
			else if (obj instanceof ZombieCuasy) {
				animWalk = Assets.zombieCuasyWalk;
				animAttack = Assets.zombieCuasyAttack;
				animDie = Assets.zombieCuasyDie;
				spriteHurt = Assets.zombieCuasyHurt;
				ajusteY = -.035f;
				size = .8f;
			}
			else if (obj instanceof ZombieMummy) {
				animWalk = Assets.zombieMummyWalk;
				animAttack = Assets.zombieMummyAttack;
				animDie = Assets.zombieMummyDie;
				spriteHurt = Assets.zombieMummyHurt;
				ajusteY = -.035f;
				size = .8f;
			}
			else if (obj instanceof ZombiePan) {
				animWalk = Assets.zombiePanWalk;
				animAttack = Assets.zombiePanAttack;
				animDie = Assets.zombiePanDie;
				spriteHurt = Assets.zombiePanHurt;
				ajusteY = -.038f;
				size = .8f;
			}
			else if (obj instanceof ZombieFrank) {
				animWalk = Assets.zombieFrankWalk;
				animAttack = Assets.zombieFrankAttack;
				animDie = Assets.zombieFrankDie;
				spriteHurt = Assets.zombieFrankHurt;
				ajusteY = -.033f;
				size = .8f;
			}
			else if (obj instanceof HeroForce) {
				animWalk = Assets.heroForceWalk;
				animAttack = Assets.heroForceShoot;
				animDie = Assets.heroForceDie;
				spriteHurt = Assets.heroForceHurt;
				size = .7f;
			}

			Sprite spriteFrame = null;

			if (obj.state == Personajes.STATE_NORMAL) {
				spriteFrame = animWalk.getKeyFrame(obj.stateTime, true);

			}
			else if (obj.state == Personajes.STATE_ATTACK) {
				spriteFrame = animAttack.getKeyFrame(obj.stateTime, false);
			}
			else if (obj.state == Personajes.STATE_DEAD) {
				spriteFrame = animDie.getKeyFrame(obj.stateTime, false);
			}
			else if (obj.state == Personajes.STATE_HURT) {
				spriteFrame = spriteHurt;
			}

			// facing left
			spriteFrame.setPosition(obj.position.x + .29f, obj.position.y - .34f + ajusteY);
			spriteFrame.setSize(-size, size);
			spriteFrame.draw(batcher);

		}
	}

	private void drawFacingRight() {
		Iterator<Personajes> i = oWorld.arrFacingRight.iterator();

		while (i.hasNext()) {

			Personajes obj = i.next();
			AnimationSprite animWalk = null;
			AnimationSprite animAttack = null;
			AnimationSprite animDie = null;
			Sprite spriteHurt = null;

			float ajusteY = 0, ajusteX = 0;
			float sizeX = 0, sizeY = 0;

			if (obj instanceof HeroForce) {
				animWalk = Assets.heroForceWalk;
				animAttack = Assets.heroForceShoot;
				animDie = Assets.heroForceDie;
				spriteHurt = Assets.heroForceHurt;
				sizeX = sizeY = .7f;
			}
			else if (obj instanceof HeroFarmer) {
				animWalk = Assets.heroFarmerWalk;
				animAttack = Assets.heroFarmerShoot;
				animDie = Assets.heroFarmerDie;
				spriteHurt = Assets.heroFarmerHurt;
				sizeX = sizeY = .7f;
			}
			else if (obj instanceof HeroLumber) {
				animWalk = Assets.heroLumberWalk;
				animAttack = Assets.heroLumberShoot;
				animDie = Assets.heroLumberDie;
				spriteHurt = Assets.heroLumberHurt;
				sizeX = 1f;
				sizeY = .85f;
				ajusteX = -.15f;
			}

			Sprite spriteFrame = null;

			if (obj.state == Personajes.STATE_NORMAL) {
				spriteFrame = animWalk.getKeyFrame(obj.stateTime, true);

			}
			else if (obj.state == Personajes.STATE_ATTACK) {
				spriteFrame = animAttack.getKeyFrame(obj.stateTime, false);
			}
			else if (obj.state == Personajes.STATE_DEAD) {
				spriteFrame = animDie.getKeyFrame(obj.stateTime, false);
			}
			else if (obj.state == Personajes.STATE_HURT) {
				spriteFrame = spriteHurt;
			}

			spriteFrame.setPosition(obj.position.x - .29f + ajusteX, obj.position.y - .34f + ajusteY);
			spriteFrame.setSize(sizeX, sizeY);
			spriteFrame.draw(batcher);

		}
	}

	private void drawBullets() {
		Iterator<Bullet> i = oWorld.arrBullets.iterator();
		while (i.hasNext()) {
			Bullet obj = i.next();

			if (!obj.isVisible)
				continue;

			AnimationSprite animBullet = Assets.bullet1;

			if (obj.state == Bullet.STATE_DESTROY)
				continue;

			// BALA
			{
				Sprite spriteFrame = animBullet.getKeyFrame(obj.stateTime, false);

				if (obj.isFacingLeft) {
					spriteFrame.setPosition(obj.position.x + .1f, obj.position.y - .1f);
					spriteFrame.setSize(-.2f, .2f);
					spriteFrame.draw(batcher);
				}
				else {
					spriteFrame.setPosition(obj.position.x - .1f, obj.position.y - .1f);
					spriteFrame.setSize(.2f, .2f);
					spriteFrame.draw(batcher);
				}

			}

			// MUZZLE FIRE
			if (obj.state == Bullet.STATE_MUZZLE) {
				Sprite spriteFrame = Assets.muzzle.getKeyFrame(obj.stateTime, false);
				if (obj.isFacingLeft) {
					spriteFrame.setPosition(obj.oPerWhoFired.position.x + .1f - .42f, obj.oPerWhoFired.position.y - .1f - .14f);
					spriteFrame.setSize(-.2f, .2f);
				}
				else {
					spriteFrame.setPosition(obj.oPerWhoFired.position.x - .1f + .42f, obj.oPerWhoFired.position.y - .1f - .14f);
					spriteFrame.setSize(.2f, .2f);
				}
				spriteFrame.draw(batcher);
			}

			// MUZZLE HIT
			if (obj.state == Bullet.STATE_HIT) {
				Sprite spriteFrame = Assets.muzzle.getKeyFrame(obj.stateTime, false);
				if (obj.isFacingLeft) { // Aqui es lo mismo que muzzle fire pero alreves
					spriteFrame.setPosition(obj.position.x - .1f, obj.position.y - .1f);
					spriteFrame.setSize(.2f, .2f);
				}
				else {
					spriteFrame.setPosition(obj.position.x + .1f, obj.position.y - .1f);
					spriteFrame.setSize(-.2f, .2f);
				}
				spriteFrame.draw(batcher);
			}

		}

	}
}
  • handlers

– GameServicesHandler:

package com.game.zombilewars.handlers;

public interface GameServicesHandler {

	/**
	 * Este metodo abstrae a GPGS o a AGC
	 * 
	 * @param tiempoLap
	 */
	public void submitScore(long score);

	/**
	 * Este metodo abstrae a GPGS o a AGC
	 * 
	 * @param score
	 */
	public void unlockAchievement(String achievementId);

	/**
	 * Este metodo abstrae a GPGS o a AGC
	 * 
	 * @param score
	 */
	public void getLeaderboard();

	/**
	 * Este metodo abstrae a GPGS o a AGC
	 * 
	 * @param score
	 */
	public void getAchievements();

	public boolean isSignedIn();

	public void signIn();

	public void signOut();

}

RequestHandler:

package com.game.zombilewars.handlers;

public interface RequestHandler {
	public void showRater();

	public void showInterstitial();

	public void showMoreGames();

	
	public void shareOnTwitter(final String mensaje);

	public void removeAds();

	public void showAdBanner();

	public void hideAdBanner();

	public void buy5milCoins();

	public void buy15milCoins();

	public void buy30milCoins();

	public void buy50milCoins();

}
  • objetos

 1) Bullet:

package com.game.zombilewars.objetos;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.game.zombilewars.Assets;


public class Bullet {
    public final static int STATE_MUZZLE = 0;
    public final static int STATE_NORMAL = 1;
    public final static int STATE_HIT = 2;
    public final static int STATE_DESTROY = 3;
    public int state;

    public static float VELOCIDAD = 5;

    public final static float DURATION_MUZZLE = Assets.muzzle.animationDuration;
    public final int DAMAGE;

    public Vector2 position;
    public float stateTime;

    public boolean isFacingLeft;
    public boolean isVisible;

    public final Personajes oPerWhoFired;// the one who fired the bullet
    final Body body;

    public Bullet(Body body, Personajes oPerWhoFired) {
        this.body = body;
        position = new Vector2(body.getPosition().x, body.getPosition().y);
        this.oPerWhoFired = oPerWhoFired;
        state = STATE_MUZZLE;

        this.isFacingLeft = oPerWhoFired.isFacingLeft;
        this.DAMAGE = oPerWhoFired.DAMAGE;

        if (isFacingLeft)
            body.setLinearVelocity(-VELOCIDAD, 0);
        else
            body.setLinearVelocity(VELOCIDAD, 0);

        if (oPerWhoFired.tipo == Personajes.TIPO_RANGO)
            isVisible = true;
        else
            isVisible = false;

    }

    public void update(float delta) {
        if (state == STATE_MUZZLE || state == STATE_NORMAL) {
            position.x = body.getPosition().x;
            position.y = body.getPosition().y;

            // Si es invisible no pueede avanzar mucho la bala si no hay nada enfente
            if (!isVisible) {
                if (oPerWhoFired.position.dst(position) > oPerWhoFired.DISTANCE_ATTACK + .025f)
                    hit();
            }
        }

        if (state == STATE_HIT)
            body.setLinearVelocity(0, 0);

        if (state == STATE_MUZZLE || state == STATE_HIT) {
            stateTime += delta;
            if (stateTime >= DURATION_MUZZLE) {
                if (state == STATE_MUZZLE)
                    state = STATE_NORMAL;
                else if (state == STATE_HIT)
                    state = STATE_DESTROY;
                stateTime = 0;
            }
            return;
        }

        stateTime += delta;
    }

    public void hit() {
        state = STATE_HIT;
        stateTime = 0;
    }

}

2) HeroFarmer:

package com.game.zombilewars.objetos;

import com.badlogic.gdx.physics.box2d.Body;
import com.game.zombilewars.Assets;


public class HeroFarmer extends Personajes {

    public HeroFarmer(Body body) {
        super(body);
        DURATION_ATTACK = Assets.heroForceShoot.animationDuration;
        DURATION_DEAD = Assets.heroForceDie.animationDuration + .2f;
        VELOCIDAD_WALK = 1;
        DAMAGE = 1;
        DISTANCE_ATTACK = 2;
        TIME_TO_ATTACK_AGAIN = 2;
        vidas = 5;
        isFacingLeft = false;
        tipo = TIPO_RANGO;
    }

}


 3) HeroLumber:

package com.game.zombilewars.objetos;

import com.badlogic.gdx.physics.box2d.Body;
import com.game.zombilewars.Assets;


public class HeroForce extends Personajes {

    public HeroForce(Body body) {
        super(body);
        DURATION_ATTACK = Assets.heroForceShoot.animationDuration;
        DURATION_DEAD = Assets.heroForceDie.animationDuration + .2f;
        VELOCIDAD_WALK = 1;
        DAMAGE = 1;
        DISTANCE_ATTACK = 2;
        TIME_TO_ATTACK_AGAIN = 2;
        vidas = 5;
        isFacingLeft = false;
        tipo = TIPO_RANGO;

    }

}

4) Personajes:

package com.game.zombilewars.objetos;

import com.badlogic.gdx.physics.box2d.Body;
import com.game.zombilewars.Assets;


public class HeroLumber extends Personajes {

    public HeroLumber(Body body) {
        super(body);
        DURATION_ATTACK = Assets.heroLumberShoot.animationDuration;
        DURATION_DEAD = Assets.heroForceDie.animationDuration + .2f;
        VELOCIDAD_WALK = 1;
        DAMAGE = 1;
        DISTANCE_ATTACK = .5f;
        TIME_TO_ATTACK_AGAIN = 0;
        vidas = 5;
        isFacingLeft = false;
        tipo = TIPO_NO_RANGO;
    }

}


5) Personajes 

package com.game.zombilewars.objetos;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;

public class Personajes {
    public final static int STATE_NORMAL = 0;
    public final static int STATE_HURT = 1;
    public final static int STATE_ATTACK = 2;
    public final static int STATE_DEAD = 3;
    public int state;

    public final static int TIPO_RANGO = 0;
    public final static int TIPO_NO_RANGO = 1;
    public int tipo;

    public final float DURATION_HURT = .3f;
    public float DURATION_ATTACK;
    public float DURATION_DEAD;

    protected float TIME_TO_ATTACK_AGAIN = 0;

    float VELOCIDAD_WALK;
    public int DAMAGE;
    public float DISTANCE_ATTACK;

    public Vector2 position;
    public float stateTime;

    public int vidas;
    public boolean attack;// solo puede herir una vez cada vez que atacca

    Body body;

    /**
     * Los buenos caminan a la derecha
     */
    public boolean isFacingLeft = false;

    public Personajes(Body body) {
        this.body = body;
        position = new Vector2(body.getPosition().x, body.getPosition().y);

        state = STATE_NORMAL;
        stateTime = 0;
    }

    public void update(float delta) {
        body.setAwake(true);
        position.x = body.getPosition().x;
        position.y = body.getPosition().y;
        Vector2 velocity = body.getLinearVelocity();

        if (state == STATE_DEAD) {
            stateTime += delta;
            body.setLinearVelocity(0, velocity.y);
            return;
        }
        else if (state == STATE_HURT) {
            stateTime += delta;
            if (stateTime >= DURATION_HURT) {
                state = STATE_NORMAL;
                stateTime = 0;
            }
            body.setLinearVelocity(0, velocity.y);
            return;
        }
        else if (state == STATE_ATTACK) {
            stateTime += delta;
            if (stateTime >= DURATION_ATTACK) {

                if ((stateTime - DURATION_ATTACK) >= TIME_TO_ATTACK_AGAIN) {
                    state = STATE_NORMAL;
                    stateTime = 0;
                }
            }
            body.setLinearVelocity(0, velocity.y);
            return;
        }
        if (isFacingLeft)
            velocity.x = -VELOCIDAD_WALK;
        else
            velocity.x = VELOCIDAD_WALK;
        body.setLinearVelocity(velocity);
        stateTime += delta;
    }

    public void getHurt(int damage) {
        if (state != STATE_DEAD) {
            vidas -= damage;
            if (vidas <= 0) {
                state = STATE_DEAD;
                stateTime = 0;
            }
            else {
                if (state != STATE_HURT) {
                    state = STATE_HURT;
                    stateTime = 0;
                }
            }
        }
    }

    public void die() {
        if (state != STATE_DEAD) {
            state = STATE_DEAD;
            stateTime = 0;
        }
    }

    /**
     * Regresa si si ataco
     * 
     * @return
     */
    public boolean attack() {
        if (state == STATE_NORMAL) {
            state = STATE_ATTACK;
            attack = true;
            stateTime = 0;
            return true;
        }
        return false;
    }

    public void didAttackEnemy() {
        attack = false;
    }

}



6) ZombieCuasy:

package com.game.zombilewars.objetos;

import com.badlogic.gdx.physics.box2d.Body;
import com.game.zombilewars.Assets;


public class ZombieCuasy extends Personajes {

    public ZombieCuasy(Body body) {
        super(body);
        DURATION_ATTACK = Assets.zombieCuasyAttack.animationDuration;
        DURATION_DEAD = Assets.zombieCuasyDie.animationDuration + .2f;
        VELOCIDAD_WALK = .15f;
        DISTANCE_ATTACK = .35f;
        DAMAGE = 1;
        vidas = 5;
        isFacingLeft = true;
        tipo = TIPO_NO_RANGO;
    }
}



7) ZombieFrank:

package com.game.zombilewars.objetos;

import com.badlogic.gdx.physics.box2d.Body;
import com.game.zombilewars.Assets;


public class ZombieFrank extends Personajes {

    public ZombieFrank(Body body) {
        super(body);
        DURATION_ATTACK = Assets.zombieFrankAttack.animationDuration;
        DURATION_DEAD = Assets.zombieFrankDie.animationDuration + .2f;
        VELOCIDAD_WALK = 1f;
        DISTANCE_ATTACK = .35f;
        DAMAGE = 5;
        vidas = 10;
        isFacingLeft = true;
        tipo = TIPO_NO_RANGO;
    }

}


8) ZombieKid:

package com.game.zombilewars.objetos;

import com.badlogic.gdx.physics.box2d.Body;
import com.game.zombilewars.Assets;


public class ZombieKid extends Personajes {

    public ZombieKid(Body body) {
        super(body);
        DURATION_ATTACK = Assets.zombieKidAttack.animationDuration;
        DURATION_DEAD = Assets.zombieKidDie.animationDuration + .2f;
        VELOCIDAD_WALK = .3f;
        DISTANCE_ATTACK = .35f;
        DAMAGE = 1;
        vidas = 5;
        isFacingLeft = true;
        tipo = TIPO_NO_RANGO;
    }

}



9) ZombieMummy:

package com.game.zombilewars.objetos;

import com.badlogic.gdx.physics.box2d.Body;
import com.game.zombilewars.Assets;


public class ZombieMummy extends Personajes {

    public ZombieMummy(Body body) {
       super(body);
       DURATION_ATTACK = Assets.zombieMummyAttack.animationDuration;
       DURATION_DEAD = Assets.zombieMummyDie.animationDuration + .2f;
       VELOCIDAD_WALK = .5f;
       DISTANCE_ATTACK = .35f;
       DAMAGE = 1;
       vidas = 3;
       isFacingLeft = true;
       tipo = TIPO_NO_RANGO;
    }

}


10) ZombiePan:

package com.game.zombilewars.objetos;

import com.badlogic.gdx.physics.box2d.Body;
import com.game.zombilewars.Assets;


public class ZombiePan extends Personajes {

    public ZombiePan(Body body) {
        super(body);
        DURATION_ATTACK = Assets.zombiePanAttack.animationDuration;
        DURATION_DEAD = Assets.zombiePanDie.animationDuration + .2f;
        VELOCIDAD_WALK = .75f;
        DISTANCE_ATTACK = .35f;
        DAMAGE = 1;
        vidas = 3;
        isFacingLeft = true;
        tipo = TIPO_NO_RANGO;
    }

}
  • scene2d

– AnimatedSpriteActor:

package com.game.zombilewars.scene2d;



import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.game.zombilewars.AnimationSprite;


public class AnimatedSpriteActor extends Actor {

	AnimationSprite animation;

	float stateTime;

	public AnimatedSpriteActor(AnimationSprite animation) {
		this.animation = animation;
		stateTime = 0;
	}

	@Override
	public void act(float delta) {
		stateTime += delta;
		super.act(delta);
	}

	@Override
	public void draw(Batch batch, float parentAlpha) {
		Sprite spriteframe = animation.getKeyFrame(stateTime, true);
		spriteframe.setPosition(getX(), getY());
		spriteframe.setSize(getWidth(), getHeight());
		spriteframe.draw(batch);
	}

}
  • screens

– MainMenuScreen:

package com.game.zombilewars.screens;



import com.game.zombilewars.MainZombieWars;
import com.game.zombilewars.game.GameScreen;


public class MainMenuScreen extends Screens {

	public MainMenuScreen(MainZombieWars game) {
		super(game);
		// TODO Auto-generated constructor stub
	}

	boolean asd = true;

	@Override
	public void update(float delta) {
		if (asd) {
			asd = false;
			changeScreenWithFadeOut(GameScreen.class, 0, game);
		}

	}

	@Override
	public void draw(float delta) {
		// TODO Auto-generated method stub

	}

}

– Screens:

package com.game.zombilewars.screens;



import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Actor;
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.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.game.zombilewars.Assets;
import com.game.zombilewars.MainZombieWars;
import com.game.zombilewars.Settings;
import com.game.zombilewars.game.GameScreen;
import com.game.zombilewars.scene2d.AnimatedSpriteActor;


public abstract class Screens extends InputAdapter implements Screen {
	public static final int SCREEN_WIDTH = 800;
	public static final int SCREEN_HEIGHT = 480;

	public static final float WORLD_WIDTH = 8;
	public static final float WORLD_HEIGHT = 4.8f;

	public MainZombieWars game;

	public OrthographicCamera oCam;
	public SpriteBatch batcher;
	public Stage stage;

	protected Music music;

	public Screens(MainZombieWars game) {
		this.stage = game.stage;
		this.stage.clear();
		this.batcher = game.batcher;
		this.game = game;

		oCam = new OrthographicCamera(SCREEN_WIDTH, SCREEN_HEIGHT);
		oCam.position.set(SCREEN_WIDTH / 2f, SCREEN_HEIGHT / 2f, 0);

		InputMultiplexer input = new InputMultiplexer(stage, this);
		Gdx.input.setInputProcessor(input);

	}

	@Override
	public void render(float delta) {
		if (delta > .1f)
			delta = .1f;

		update(delta);
		stage.act(delta);

		oCam.update();
		batcher.setProjectionMatrix(oCam.combined);

		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
		draw(delta);
		stage.draw();
	}

	public void addEfectoPress(final Actor actor) {
		actor.addListener(new InputListener() {
			@Override
			public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
				actor.setPosition(actor.getX(), actor.getY() - 5);
				event.stop();
				return true;
			}

			@Override
			public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
				actor.setPosition(actor.getX(), actor.getY() + 5);
			}
		});
	}

	Image blackFadeOut;

	public void changeScreenWithFadeOut(final Class<?> newScreen, final int level, final MainZombieWars game) {
		blackFadeOut = new Image(Assets.pixelNegro);
		blackFadeOut.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
		blackFadeOut.getColor().a = 0;
		blackFadeOut.addAction(Actions.sequence(Actions.fadeIn(.5f), Actions.run(new Runnable() {
			@Override
			public void run() {
				if (newScreen == GameScreen.class) {
					Assets.loadTiledMap(level);
					game.setScreen(new GameScreen(game, level));
				}
				// else if (newScreen == MainMenuScreen.class)
				// game.setScreen(new MainMenuScreen(game));
				// else if (newScreen == SettingsScreen.class)
				// game.setScreen(new SettingsScreen(game));

				// El blackFadeOut se remueve del stage cuando se le da new Screens(game) "Revisar el constructor de la clase Screens" por lo que no hay necesidad de hacer
				// blackFadeout.remove();
			}
		})));

		Label lbl = new Label("Loading..", Assets.labelStyleGrande);
		lbl.setPosition(SCREEN_WIDTH / 2f - lbl.getWidth() / 2f, SCREEN_HEIGHT / 2f - lbl.getHeight() / 2f);
		lbl.getColor().a = 0;
		lbl.addAction(Actions.fadeIn(.6f));

		AnimatedSpriteActor corriendo = new AnimatedSpriteActor(Assets.zombieKidWalk);
		corriendo.setSize(70, 70);
		corriendo.setPosition(SCREEN_WIDTH / 2f - corriendo.getWidth() / 2f, 250);

		stage.addActor(blackFadeOut);
		stage.addActor(corriendo);
		stage.addActor(lbl);

	}

	public void changeScreenWithFadeOut(final Class<?> newScreen, final MainZombieWars game) {
		changeScreenWithFadeOut(newScreen, -1, game);
	}

	public abstract void update(float delta);

	public abstract void draw(float delta);

	@Override
	public void resize(int width, int height) {
		stage.getViewport().update(width, height, true);
	}

	@Override
	public void show() {
	}

	@Override
	public void hide() {
		if (music != null) {
			music.stop();
			music.dispose();
			music = null;
		}

		Settings.save();
	}

	@Override
	public void pause() {
	}

	@Override
	public void resume() {

	}

	@Override
	public void dispose() {
		batcher.dispose();
	}

}
  • AnimationSprite:
package com.game.zombilewars;



import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;

public class AnimationSprite {

    /** Defines possible playback modes for an {@link Animation}. */
    public enum PlayMode {
        NORMAL, REVERSED, LOOP, LOOP_REVERSED, LOOP_PINGPONG, LOOP_RANDOM,
    }

    final Sprite[] spriteFrames;
    public final float frameDuration;
    public final float animationDuration;

    private PlayMode playMode = PlayMode.NORMAL;

    /**
     * Constructor, storing the frame duration and key frames.
     *
     * @param frameDuration
     *            the time between frames in seconds.
     * @param keyFrames
     *            the {@link TextureRegion}s representing the frames.
     */
    public AnimationSprite(float frameDuration,
                           Array<? extends Sprite> keyFrames) {
        this.frameDuration = frameDuration;
        this.animationDuration = keyFrames.size * frameDuration;
        this.spriteFrames = new Sprite[keyFrames.size];
        for (int i = 0, n = keyFrames.size; i < n; i++) {
            this.spriteFrames[i] = keyFrames.get(i);
        }

        this.playMode = PlayMode.NORMAL;
    }

    /**
     * Constructor, storing the frame duration, key frames and play type.
     *
     * @param frameDuration
     *            the time between frames in seconds.
     * @param keyFrames
     *            the {@link TextureRegion}s representing the frames.
     * @param playMode
     *            the animation playback mode.
     */
    public AnimationSprite(float frameDuration,
                           Array<? extends Sprite> keyFrames, PlayMode playMode) {

        this.frameDuration = frameDuration;
        this.animationDuration = keyFrames.size * frameDuration;
        this.spriteFrames = new Sprite[keyFrames.size];
        for (int i = 0, n = keyFrames.size; i < n; i++) {
            this.spriteFrames[i] = keyFrames.get(i);
        }

        this.playMode = playMode;
    }

    /**
     * Constructor, storing the frame duration and key frames.
     *
     * @param frameDuration
     *            the time between frames in seconds.
     * @param keyFrames
     *            the {@link TextureRegion}s representing the frames.
     */
    public AnimationSprite(float frameDuration, Sprite... keyFrames) {
        this.frameDuration = frameDuration;
        this.animationDuration = keyFrames.length * frameDuration;
        this.spriteFrames = keyFrames;
        this.playMode = PlayMode.NORMAL;
    }

    /**
     * Returns a {@link TextureRegion} based on the so called state time. This is the amount of seconds an object has spent in the state this Animation instance represents, e.g. running, jumping and
     * so on. The mode specifies whether the animation is looping or not.
     *
     * @param stateTime
     *            the time spent in the state represented by this animation.
     * @param looping
     *            whether the animation is looping or not.
     * @return the TextureRegion representing the frame of animation for the given state time.
     */
    public Sprite getKeyFrame(float stateTime, boolean looping) {
        // we set the play mode by overriding the previous mode based on looping
        // parameter value
        PlayMode oldPlayMode = playMode;
        if (looping
                && (playMode == PlayMode.NORMAL || playMode == PlayMode.REVERSED)) {
            if (playMode == PlayMode.NORMAL)
                playMode = PlayMode.LOOP;
            else
                playMode = PlayMode.LOOP_REVERSED;
        }
        else if (!looping
                && !(playMode == PlayMode.NORMAL || playMode == PlayMode.REVERSED)) {
            if (playMode == PlayMode.LOOP_REVERSED)
                playMode = PlayMode.REVERSED;
            else
                playMode = PlayMode.LOOP;
        }

        Sprite frame = getKeyFrame(stateTime);
        playMode = oldPlayMode;
        return frame;
    }

    /**
     * Returns a {@link TextureRegion} based on the so called state time. This is the amount of seconds an object has spent in the state this Animation instance represents, e.g. running, jumping and
     * so on using the mode specified by {@link #setPlayMode(PlayMode)} method.
     *
     * @param stateTime
     * @return the TextureRegion representing the frame of animation for the given state time.
     */
    public Sprite getKeyFrame(float stateTime) {
        int frameNumber = getKeyFrameIndex(stateTime);
        return spriteFrames[frameNumber];
    }

    /**
     * Returns the current frame number.
     *
     * @param stateTime
     * @return current frame number
     */
    public int getKeyFrameIndex(float stateTime) {
        if (spriteFrames.length == 1)
            return 0;

        int frameNumber = (int) (stateTime / frameDuration);
        switch (playMode) {
            case NORMAL:
                frameNumber = Math.min(spriteFrames.length - 1, frameNumber);
                break;
            case LOOP:
                frameNumber = frameNumber % spriteFrames.length;
                break;
            case LOOP_PINGPONG:
                frameNumber = frameNumber % ((spriteFrames.length * 2) - 2);
                if (frameNumber >= spriteFrames.length)
                    frameNumber = spriteFrames.length - 2
                            - (frameNumber - spriteFrames.length);
                break;
            case LOOP_RANDOM:
                frameNumber = MathUtils.random(spriteFrames.length - 1);
                break;
            case REVERSED:
                frameNumber = Math.max(spriteFrames.length - frameNumber - 1, 0);
                break;
            case LOOP_REVERSED:
                frameNumber = frameNumber % spriteFrames.length;
                frameNumber = spriteFrames.length - frameNumber - 1;
                break;
        }

        return frameNumber;
    }

    /**
     * Returns the keyFrames[] array where all the TextureRegions of the animation are stored.
     *
     * @return keyFrames[] field
     */
    public TextureRegion[] getKeyFrames() {
        return spriteFrames;
    }

    /** Returns the animation play mode. */
    public PlayMode getPlayMode() {
        return playMode;
    }

    /**
     * Sets the animation play mode.
     *
     * @param playMode
     *            The animation {@link PlayMode} to use.
     */
    public void setPlayMode(PlayMode playMode) {
        this.playMode = playMode;
    }

    /**
     * Whether the animation would be finished if played without looping (PlayMode#NORMAL), given the state time.
     *
     * @param stateTime
     * @return whether the animation is finished.
     */
    public boolean isAnimationFinished(float stateTime) {
        int frameNumber = (int) (stateTime / frameDuration);
        return spriteFrames.length - 1 < frameNumber;
    }

}

  • Assets:
package com.game.zombilewars;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable;
import com.badlogic.gdx.utils.Array;

public class Assets {

    public static BitmapFont fontChico;
    public static BitmapFont fontGrande;

    public static TiledMap map;

    /**
     * Hero
     */
    public static AnimationSprite heroFarmerDie;
    public static Sprite heroFarmerHurt;
    public static AnimationSprite heroFarmerShoot;
    public static AnimationSprite heroFarmerWalk;

    public static AnimationSprite heroLumberDie;
    public static Sprite heroLumberHurt;
    public static AnimationSprite heroLumberShoot;
    public static AnimationSprite heroLumberWalk;

    public static AnimationSprite heroForceDie;
    public static Sprite heroForceHurt;
    public static AnimationSprite heroForceShoot;
    public static AnimationSprite heroForceWalk;

    public static AnimationSprite heroRamboDie;
    public static Sprite heroRamboHurt;
    public static AnimationSprite heroRamboShoot;
    public static AnimationSprite heroRamboWalk;

    public static AnimationSprite heroSoldierDie;
    public static Sprite heroSoldierHurt;
    public static AnimationSprite heroSoldierShoot;
    public static AnimationSprite heroSoldierWalk;

    public static AnimationSprite heroSwatDie;
    public static Sprite heroSwatHurt;
    public static AnimationSprite heroSwatShoot;
    public static AnimationSprite heroSwatWalk;

    public static AnimationSprite heroVaderDie;
    public static Sprite heroVaderHurt;
    public static AnimationSprite heroVaderShoot;
    public static AnimationSprite heroVaderWalk;

    /**
     * Bullet
     */
    public static AnimationSprite bullet1;
    public static AnimationSprite bullet2;
    public static AnimationSprite bullet3;
    public static AnimationSprite bullet4;
    public static AnimationSprite bullet5;
    public static AnimationSprite muzzle;

    /**
     * Zombies
     */
    public static AnimationSprite zombieKidWalk;
    public static AnimationSprite zombieKidAttack;
    public static AnimationSprite zombieKidDie;
    public static Sprite zombieKidHurt;

    public static AnimationSprite zombiePanWalk;
    public static AnimationSprite zombiePanAttack;
    public static AnimationSprite zombiePanDie;
    public static Sprite zombiePanHurt;

    public static AnimationSprite zombieCuasyWalk;
    public static AnimationSprite zombieCuasyAttack;
    public static AnimationSprite zombieCuasyDie;
    public static Sprite zombieCuasyHurt;

    public static AnimationSprite zombieFrankWalk;
    public static AnimationSprite zombieFrankAttack;
    public static AnimationSprite zombieFrankDie;
    public static Sprite zombieFrankHurt;

    public static AnimationSprite zombieMummyWalk;
    public static AnimationSprite zombieMummyAttack;
    public static AnimationSprite zombieMummyDie;
    public static Sprite zombieMummyHurt;

    public static LabelStyle labelStyleChico;
    public static LabelStyle labelStyleGrande;

    public static NinePatchDrawable pixelNegro;

    public static Sound shoot1;
    public static Sound zombiePan;
    public static Sound zombieKid;
    public static Sound zombieCuasy;
    public static Sound zombieMummy;
    public static Sound zombieFrank;

    public static Sound hurt1;
    public static Sound hurt2;
    public static Sound hurt3;
    public static Sound gem;
    public static Sound skull;
    public static Sound jump;
    public static Sound shield;
    public static Sound hearth;

    public static void loadStyles(TextureAtlas atlas) {
        // Label Style
        labelStyleChico = new LabelStyle(fontChico, Color.WHITE);
        labelStyleGrande = new LabelStyle(fontGrande, Color.WHITE);

        pixelNegro = new NinePatchDrawable(new NinePatch(atlas.findRegion("UI/pixelNegro"), 1, 1, 0, 0));
    }

    public static void load() {
        TextureAtlas atlas = new TextureAtlas(Gdx.files.internal("data/atlasMap.txt"));

        fontChico = new BitmapFont(Gdx.files.internal("data/fontChico.fnt"), atlas.findRegion("fontChico"));
        fontGrande = new BitmapFont(Gdx.files.internal("data/fontGrande.fnt"), atlas.findRegion("fontGrande"));

        loadStyles(atlas);

        /**
         * Bullets
         */
        bullet1 = loadAnimationBullet(atlas, "Bullet/bullet1");
        bullet2 = loadAnimationBullet(atlas, "Bullet/bullet2");
        bullet3 = loadAnimationBullet(atlas, "Bullet/bullet3");
        bullet4 = loadAnimationBullet(atlas, "Bullet/bullet4");
        bullet5 = loadAnimationBullet(atlas, "Bullet/bullet5");
        muzzle = loadAnimationMuzzle(atlas, "Bullet/");
        /**
         * Items
         */

        /**
         * HeroFarmer
         */
        heroFarmerDie = loadAnimationDie(atlas, "HeroFarmer/");
        heroFarmerHurt = atlas.createSprite("HeroFarmer/hurt");
        heroFarmerShoot = loadAnimationShoot(atlas, "HeroFarmer/");
        heroFarmerWalk = loadAnimationWalk(atlas, "HeroFarmer/");

        /**
         * HeroLumber
         */
        heroLumberDie = loadAnimationDie(atlas, "HeroLumber/");
        heroLumberHurt = atlas.createSprite("HeroLumber/hurt");
        heroLumberShoot = loadAnimationAttack(atlas, "HeroLumber/");
        heroLumberWalk = loadAnimationWalk(atlas, "HeroLumber/");

        /**
         * HeroForce
         */
        heroForceDie = loadAnimationDie(atlas, "HeroForce/");
        heroForceHurt = atlas.createSprite("HeroForce/hurt");
        heroForceShoot = loadAnimationShoot(atlas, "HeroForce/");
        heroForceWalk = loadAnimationWalk(atlas, "HeroForce/");

        /**
         * HeroRambo
         */
        heroRamboDie = loadAnimationDie(atlas, "HeroRambo/");
        heroRamboHurt = atlas.createSprite("HeroRambo/hurt");
        heroRamboShoot = loadAnimationShoot(atlas, "HeroRambo/");
        heroRamboWalk = loadAnimationWalk(atlas, "HeroRambo/");

        /**
         * HeroSoldier
         */
        heroSoldierDie = loadAnimationDie(atlas, "HeroSoldier/");
        heroSoldierHurt = atlas.createSprite("HeroSoldier/hurt");
        heroSoldierShoot = loadAnimationShoot(atlas, "HeroSoldier/");
        heroSoldierWalk = loadAnimationWalk(atlas, "HeroSoldier/");

        /**
         * HeroSwat
         */
        heroSwatDie = loadAnimationDie(atlas, "HeroSwat/");
        heroSwatHurt = atlas.createSprite("HeroSwat/hurt");
        heroSwatShoot = loadAnimationShoot(atlas, "HeroSwat/");
        heroSwatWalk = loadAnimationWalk(atlas, "HeroSwat/");

        /**
         * HeroVader
         */
        heroVaderDie = loadAnimationDie(atlas, "HeroVader/");
        heroVaderHurt = atlas.createSprite("HeroVader/hurt");
        heroVaderShoot = loadAnimationShoot(atlas, "HeroVader/");
        heroVaderWalk = loadAnimationWalk(atlas, "HeroVader/");

        /**
         * Zombie kid
         */
        zombieKidWalk = loadAnimationWalk(atlas, "ZombieKid/");
        zombieKidAttack = loadAnimationAttack(atlas, "ZombieKid/");
        zombieKidDie = loadAnimationDie(atlas, "ZombieKid/");
        zombieKidHurt = atlas.createSprite("ZombieKid/die1");

        /**
         * Zombie pan
         */
        zombiePanWalk = loadAnimationWalk(atlas, "ZombiePan/");
        zombiePanAttack = loadAnimationAttack(atlas, "ZombiePan/");
        zombiePanDie = loadAnimationDie(atlas, "ZombiePan/");
        zombiePanHurt = atlas.createSprite("ZombiePan/die1");

        /**
         * Zombie Cuasy
         */
        zombieCuasyWalk = loadAnimationWalk(atlas, "ZombieCuasy/");
        zombieCuasyAttack = loadAnimationAttack(atlas, "ZombieCuasy/");
        zombieCuasyDie = loadAnimationDie(atlas, "ZombieCuasy/");
        zombieCuasyHurt = atlas.createSprite("ZombieCuasy/die1");

        /**
         * Zombie Frank
         */
        zombieFrankWalk = loadAnimationWalk(atlas, "ZombieFrank/");
        zombieFrankAttack = loadAnimationAttack(atlas, "ZombieFrank/");
        zombieFrankDie = loadAnimationDie(atlas, "ZombieFrank/");
        zombieFrankHurt = atlas.createSprite("ZombieFrank/die1");

        /**
         * Zombie mummy
         */
        zombieMummyWalk = loadAnimationWalk(atlas, "ZombieMummy/");
        zombieMummyAttack = loadAnimationAttack(atlas, "ZombieMummy/");
        zombieMummyDie = loadAnimationDie(atlas, "ZombieMummy/");
        zombieMummyHurt = atlas.createSprite("ZombieMummy/die1");

        Settings.load();

        // shoot1 = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/shoot2.mp3"));
        // zombiePan = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/zombiePan.mp3"));
        // zombieKid = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/zombieKid.mp3"));
        // zombieCuasy = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/zombieCuasy.mp3"));
        // zombieMummy = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/zombieMummy.mp3"));
        // zombieFrank = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/zombieFrank.mp3"));
        //
        // hurt1 = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/hurt.mp3"));
        // hurt2 = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/hurt2.mp3"));
        // hurt3 = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/hurt3.mp3"));
        //
        // gem = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/gem.mp3"));
        // skull = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/skull.mp3"));
        // jump = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/jump.mp3"));
        // shield = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/pick.mp3"));
        // hearth = Gdx.audio.newSound(Gdx.files.internal("data/Sounds/hearth.mp3"));

        // 2

    }

    private static AnimationSprite loadAnimationWalk(TextureAtlas atlas, String ruta) {
        Array<Sprite> arrSprites = new Array<Sprite>();

        int i = 1;
        Sprite obj = null;
        do {
            obj = atlas.createSprite(ruta + "walk" + i);
            i++;
            if (obj != null)
                arrSprites.add(obj);
        } while (obj != null);

        float time = .009f * arrSprites.size;
        return new AnimationSprite(time, arrSprites);
    }

    private static AnimationSprite loadAnimationAttack(TextureAtlas atlas, String ruta) {
        Array<Sprite> arrSprites = new Array<Sprite>();

        int i = 1;
        Sprite obj = null;
        do {
            obj = atlas.createSprite(ruta + "attack" + i);
            i++;
            if (obj != null)
                arrSprites.add(obj);
        } while (obj != null);

        float time = .01875f * arrSprites.size;
        return new AnimationSprite(time, arrSprites);
    }

    private static AnimationSprite loadAnimationDie(TextureAtlas atlas, String ruta) {
        Array<Sprite> arrSprites = new Array<Sprite>();

        int i = 1;
        Sprite obj = null;
        do {
            obj = atlas.createSprite(ruta + "die" + i);
            i++;
            if (obj != null)
                arrSprites.add(obj);
        } while (obj != null);

        float time = .03f * arrSprites.size;
        return new AnimationSprite(time, arrSprites);
    }

    private static AnimationSprite loadAnimationShoot(TextureAtlas atlas, String ruta) {
        Array<Sprite> arrSprites = new Array<Sprite>();

        int i = 1;
        Sprite obj = null;
        do {
            obj = atlas.createSprite(ruta + "shoot" + i);
            i++;
            if (obj != null)
                arrSprites.add(obj);
        } while (obj != null);

        float time = .0095f * arrSprites.size;
        return new AnimationSprite(time, arrSprites);
    }

    private static AnimationSprite loadAnimationMuzzle(TextureAtlas atlas, String ruta) {
        Array<Sprite> arrSprites = new Array<Sprite>();

        int i = 1;
        Sprite obj = null;
        do {
            obj = atlas.createSprite(ruta + "muzzle" + i);
            i++;
            if (obj != null)
                arrSprites.add(obj);
        } while (obj != null);

        float time = .009f * arrSprites.size;
        return new AnimationSprite(time, arrSprites);
    }

    private static AnimationSprite loadAnimationBullet(TextureAtlas atlas, String ruta) {
        Array<Sprite> arrSprites = new Array<Sprite>();

        int i = 1;
        Sprite obj = null;
        do {
            obj = atlas.createSprite(ruta + i);
            i++;
            if (obj != null)
                arrSprites.add(obj);
        } while (obj != null);

        float time = .03f * arrSprites.size;
        return new AnimationSprite(time, arrSprites);
    }

    public static void loadTiledMap(int numMap) {
        if (map != null) {
            map.dispose();
            map = null;
        }

        if (Settings.isTest) {
            map = new TmxMapLoader().load("data/MapsTest/suelo.tmx");
        }
        else {
            map = new AtlasTmxMapLoader().load("data/Maps/suelo.tmx");
        }
    }

    public static void playSound(Sound sonido, float volume) {
        if (Settings.isSoundOn) {
            sonido.play(volume);
        }
    }

}

  • MainZombieWars:
package com.game.zombilewars;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.I18NBundle;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.game.zombilewars.handlers.FacebookHandler;
import com.game.zombilewars.handlers.GameServicesHandler;
import com.game.zombilewars.handlers.RequestHandler;
import com.game.zombilewars.screens.MainMenuScreen;
import com.game.zombilewars.screens.Screens;


public class MainZombieWars extends Game {
	public final GameServicesHandler gameServiceHandler;
	public final RequestHandler reqHandler;
	public final FacebookHandler facebookHandler;

	public I18NBundle idiomas;

	public MainZombieWars(RequestHandler reqHandler, GameServicesHandler gameServiceHandler, FacebookHandler facebookHandler) {
		this.reqHandler = reqHandler;
		this.gameServiceHandler = gameServiceHandler;
		this.facebookHandler = facebookHandler;
	}

	public Stage stage;
	public SpriteBatch batcher;

	@Override
	public void create() {
		// idiomas = I18NBundle.createBundle(Gdx.files.internal("strings/strings"));
		stage = new Stage(new StretchViewport(Screens.SCREEN_WIDTH, Screens.SCREEN_HEIGHT));

		batcher = new SpriteBatch();
		Assets.load();
		// Achievements.init(this);

		setScreen(new MainMenuScreen(this));
	}

}
  • Settings:
package com.game.zombilewars;

public class Settings {

    public static float zoom = 1;// Zoom de la camara.
    public static boolean isSoundOn;
    public static boolean isTest = true;

    public static void load() {
        // TODO Auto-generated method stub

    }

    public static void save() {
        // TODO Auto-generated method stub

    }

}

5. Thư mục desktop.

– DesktopLauncher:

package com.game.zombilewars;



import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration;
import com.game.zombilewars.handlers.FacebookHandler;
import com.game.zombilewars.handlers.GoogleGameServicesHandler;
import com.game.zombilewars.handlers.RequestHandler;


public class DesktopLauncher {
	public static void main(String[] arg) {
		Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration();
		config.setWindowedMode(800, 480); // Sử dụng phương thức setWindowedMode
		new Lwjgl3Application(new MainZombieWars(handler, gameHandler, faceHandler), config);
	}

	static RequestHandler handler = new RequestHandler() {

		@Override
		public void showRater() {
			// TODO Auto-generated method stub

		}

		@Override
		public void showMoreGames() {
			// TODO Auto-generated method stub

		}

		@Override
		public void showInterstitial() {
			// TODO Auto-generated method stub

		}

		@Override
		public void showAdBanner() {
			// TODO Auto-generated method stub

		}

		@Override
		public void shareOnTwitter(String mensaje) {
			// TODO Auto-generated method stub

		}

		@Override
		public void removeAds() {
			// TODO Auto-generated method stub

		}

		@Override
		public void hideAdBanner() {
			// TODO Auto-generated method stub

		}

		@Override
		public void buy5milCoins() {
			// TODO Auto-generated method stub

		}

		@Override
		public void buy50milCoins() {
			// TODO Auto-generated method stub

		}

		@Override
		public void buy30milCoins() {
			// TODO Auto-generated method stub

		}

		@Override
		public void buy15milCoins() {
			// TODO Auto-generated method stub

		}
	};

	static GoogleGameServicesHandler gameHandler = new GoogleGameServicesHandler() {

		@Override
		public void unlockAchievement(String achievementId) {
			// TODO Auto-generated method stub

		}

		@Override
		public void submitScore(long score) {
			// TODO Auto-generated method stub

		}

		@Override
		public void signOut() {
			// TODO Auto-generated method stub

		}

		@Override
		public void signIn() {
			// TODO Auto-generated method stub

		}

		@Override
		public boolean isSignedIn() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void getLeaderboard() {
			// TODO Auto-generated method stub

		}

		@Override
		public void getAchievements() {
			// TODO Auto-generated method stub

		}
	};
	static FacebookHandler faceHandler = new FacebookHandler() {

		@Override
		public void showFacebook() {
			// TODO Auto-generated method stub

		}

		@Override
		public void facebookSignOut() {
			// TODO Auto-generated method stub

		}

		@Override
		public void facebookSignIn() {
			// TODO Auto-generated method stub

		}

		@Override
		public void facebookShareFeed(String message) {
			// TODO Auto-generated method stub

		}

		@Override
		public boolean facebookIsSignedIn() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void facebookInviteFriends(String message) {
			// TODO Auto-generated method stub

		}
	};

}

B. Thành Viên và Link Github.

Link GitHub: https://github.com/NGUYENDANG19/Libdgx_Zombie_Wars.git

Nhóm : Đặng Hoàng Bảo Nguyên

Lớp : 22CDTH11