Example usage for com.badlogic.gdx.graphics.g2d TextureRegion TextureRegion

List of usage examples for com.badlogic.gdx.graphics.g2d TextureRegion TextureRegion

Introduction

In this page you can find the example usage for com.badlogic.gdx.graphics.g2d TextureRegion TextureRegion.

Prototype

public TextureRegion(TextureRegion region) 

Source Link

Document

Constructs a region with the same texture and coordinates of the specified region.

Usage

From source file:at.juggle.games.memory.AssetManager.java

License:Apache License

public AssetManager(GameOptions options) {
    this.options = options;
    Preferences preferences = Gdx.app.getPreferences("memory_free_hd.prefs");
    if (preferences.contains("soundOn")) {
        options.soundOn = preferences.getBoolean("soundOn");
    }/*from w w w.ja va  2s.  co m*/
    font = new BitmapFont(getFileHandle("berlin_64.fnt"), false);
    smallFont = new BitmapFont(getFileHandle("berlin_42.fnt"), false);
    card = new Texture(getFileHandle("card-front.png"));
    cardBack = new Texture(getFileHandle("card-back.png"));
    cardBackMark = new Texture(getFileHandle("card-back-mark.png"));
    check = new Texture(getFileHandle("Check_32x32.png"));
    positive = new Texture(getFileHandle("Positive_256x256.png"));
    grey = new Texture(getFileHandle("grey.png"));
    background = new Texture(getFileHandle("background.jpg"));
    gradientTop = new Texture(getFileHandle("gradient_oben.png"));
    gradientBottom = new Texture(getFileHandle("gradient_unten.png"));
    if (GameOptions.isFreeVersion) {
        logo = new Texture(getFileHandle("Logo.png"));
    } else {
        logo = new Texture(getFileHandle("Logo_donated.png"));
    }

    cardBack.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
    cardBackMark.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
    logo.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);

    Texture vehiclesTexture = new Texture(getFileHandle("vehicles.png"));
    vehiclesTexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
    TextureRegion[][] veh = TextureRegion.split(vehiclesTexture, 256, 256);

    icons = new TextureRegion[24];
    icons[0] = new TextureRegion(loadTexture("animals/Butterfly_128x128.png"));
    icons[1] = new TextureRegion(loadTexture("animals/Dolphin_128x128.png"));
    icons[2] = new TextureRegion(loadTexture("animals/Elephant_128x128.png"));
    icons[3] = new TextureRegion(loadTexture("animals/Hippopotamus_128x128.png"));
    icons[4] = new TextureRegion(loadTexture("animals/Panda_128x128.png"));
    icons[5] = new TextureRegion(loadTexture("animals/Turtle_128x128.png"));
    icons[6] = new TextureRegion(loadTexture("vacation/surfboard_256x256.png"));
    icons[7] = new TextureRegion(loadTexture("vacation/umbrella_256x256.png"));

    int count = 0;
    for (int i = 0; i < veh.length; i++) {
        TextureRegion[] textureRegions = veh[i];
        for (int j = 0; j < textureRegions.length; j++) {
            icons[8 + count] = textureRegions[j];
            count++;
        }
    }

    // Particle effects
    fireworks = new ParticleEffect();
    fireworks.load(getFileHandle("fireworks"), getFileHandle(""));

    // sounds
    sndFlipCard = Gdx.audio.newSound(getFileHandle("flipcard.ogg"));
    sndCheer = Gdx.audio.newSound(getFileHandle("drums.ogg"));
    sndDing = Gdx.audio.newSound(getFileHandle("ding.ogg"));
}

From source file:at.tugraz.ist.catroid.plugin.Drone.other.DroneVideoCostume.java

License:Open Source License

public void initializeTexture() {
    Pixmap pixmap = new Pixmap(320, 240, Format.RGB888);
    pixmap.setColor(Color.BLUE);// w  ww .  j  a va2 s.co  m
    pixmap.fill();
    Texture texture = new Texture(pixmap, false);
    texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    this.region = new TextureRegion(texture);
    this.width = this.region.getRegionWidth();
    this.height = this.region.getRegionHeight();
    this.x -= (this.width / 2f);
    this.y -= (this.height / 2f);
    this.originX = (this.width / 2f);
    this.originY = (this.height / 2f);
    pixmap.dispose();
    firstStart = false;
}

From source file:ateamproject.kezuino.com.github.network.rmi.Client.java

@Override
public void registerPackets() {
    packets.registerFunc(PacketKick.class, packet -> {
        if (packet.getSender() == null) {
            new Dialog("Kicked", ((BaseScreen) game.getScreen()).getSkin()) {
                {//  www.  j a  v a2 s.  com
                    text(packet.getReason());
                    button("Oke");

                    addListener(new ClickListener(0) {
                        @Override
                        public void clicked(InputEvent event, float x, float y) {
                            game.setScreen(new MainScreen(game));
                        }
                    });
                }
            }.show(((BaseScreen) game.getScreen()).getStage());
            return true;
        } else {
            try {
                if (packet.getReceivers().length > 0) {
                    for (UUID receiver : packet.getReceivers()) {
                        this.rmi.getServer().kickClient(packet.getSender(), receiver, packet.getReasonType(),
                                packet.getReason());
                    }
                } else {
                    this.rmi.getServer().kickClient(packet.getSender(), null, packet.getReasonType(),
                            packet.getReason());
                }
            } catch (RemoteException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
            return true;
        }
    });

    packets.registerFunc(PacketLoginAuthenticate.class, packet -> {
        PacketLoginAuthenticate.ReturnData data = null;
        try {
            data = getRmi().getServer().login(packet.getEmailAddress(), packet.getPassword(), getRmi());
        } catch (Exception e) {
            data = new PacketLoginAuthenticate.ReturnData(null, null, null, null, "Server is niet online.",
                    false);
        }

        if (data != null) {
            if (data.getPrivateId() == null) {
                this.setEmailaddress(null);
                this.setUsername(null);
                this.setId(null);
                this.setPublicId(null);
            } else {
                this.setEmailaddress(data.getEmailadress());
                this.setUsername(data.getUsername());
                this.setId(data.getPrivateId());
                this.setPublicId(data.getPublicId());
                System.out.printf("Logged in as: (Username: %s), (Email: %s), (Private: %s), (Public: %s)%n",
                        data.getUsername(), data.getEmailadress(), data.getPrivateId(), data.getPublicId());
            }
        }

        return data;
    });

    packets.registerAction(PacketLogout.class, packet -> {

        try {
            getRmi().getServer().logout(getId());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    });

    packets.registerFunc(PacketHighScore.class, (packet) -> {
        try {
            return getRmi().getServer().setScore(packet.getSender(), packet.getScore());
        } catch (RemoteException ex) {
            Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    });

    packets.registerFunc(PacketCreateLobby.class, (p) -> {

        try {
            return getRmi().getServer().createLobby(p.getSender(), p.getLobbyname(), p.getClanname());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
        return null;
    });

    packets.registerFunc(PacketGetLobbies.class, (p) -> {
        try {
            return getRmi().getServer().getLobbies(p.getSender(), p.isClanGame());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
        return null;
    });

    packets.registerAction(PacketScreenUpdate.class, packet -> {
        if (game.getScreen().getClass().equals(packet.getScreenClass())) {
            RefreshableScreen screen = (RefreshableScreen) game.getScreen();
            screen.refresh();
        }
    });

    packets.registerFunc(PacketGetClans.class, (p) -> {
        try {
            return getRmi().getServer().getClans(p.getSender());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return null;
    });

    packets.registerAction(PacketReloadClans.class, (p) -> {
        // run methode op de serverbase .getclans
        try {
            getRmi().getServer().setClans(p.getSender());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    });

    packets.registerFunc(PacketJoinLobby.class, (p) -> {
        try {
            return getRmi().getServer().joinLobby(p.getLobbyId(), p.getSender());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
        return null;
    });

    packets.registerFunc(PacketLoginCreateNewUser.class, (p) -> {
        try {
            return getRmi().getServer().loginCreateUser(p.getSender(), p.getUsername(), p.getEmail());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerFunc(PacketLoginUserExists.class, (p) -> {
        try {
            return getRmi().getServer().doesUserExists(p.getEmail());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerFunc(PacketGetKickInformation.class, (p) -> {
        try {
            return getRmi().getServer().getKickInformation(p.getSender());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerFunc(PacketCreateClan.class, (p) -> {
        try {
            return getRmi().getServer().createClan(p.getSender(), p.getClanName());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerFunc(PacketFillTable.class, (p) -> {
        try {
            return getRmi().getServer().clanFillTable(p.getEmailadres());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerFunc(PacketGetEmail.class, (p) -> {
        try {
            return getRmi().getServer().getEmail(p.getSender());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerFunc(PacketGetInvitation.class, (p) -> {
        try {
            return getRmi().getServer().clanGetInvitation(p.getSender(), p.getClanName());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerFunc(PacketGetManagement.class, (p) -> {
        try {
            return getRmi().getServer().getManagement(p.getSender(), p.getClanName());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerFunc(PacketGetPeople.class, (p) -> {
        try {
            return getRmi().getServer().getPeople(p.getClanName());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerFunc(PacketGetUsername.class, (p) -> {
        try {
            return getRmi().getServer().getUsername(p.getEmailadres());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerFunc(PacketHandleInvitation.class, (p) -> {
        try {
            return getRmi().getServer().handleInvitation(p.getInvite(), p.getClanName(), p.getEmailadres(),
                    p.getNameOfInvitee());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerFunc(PacketHandleManagement.class, (p) -> {
        try {
            return getRmi().getServer().handleManagement(p.getManage(), p.getClanName(), p.getEmailadres());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerFunc(PacketSetUsername.class, (p) -> {
        try {
            return getRmi().getServer().setUsername(p.getName(), p.getEmailaddress(), p.getSender());
        } catch (RemoteException ex) {
            Logger.getLogger(ateamproject.kezuino.com.github.network.rmi.Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

        return false;
    });

    packets.registerAction(PacketSetKickInformation.class, packet -> {
        try {
            getRmi().getServer().setKickInformation(packet.getSender(), packet.getPersonToVoteFor());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    });

    packets.registerAction(PacketClientJoined.class, p -> {
        if (game.getScreen() instanceof LobbyScreen) {
            LobbyScreen t = (LobbyScreen) game.getScreen();
            t.addMember(p.getJoinenId(), p.getUsername());
        }
    });

    packets.registerFunc(PacketLobbyMembers.class, packet -> {
        try {
            // return all current members in the lobby
            return getRmi().getServer().getLobbyMembers(packet.getLobbyId());

        } catch (RemoteException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    });

    packets.registerAction(PacketLaunchGame.class, p -> {
        if (p.getSender() != null) {
            // Request came from client..
            try {
                rmi.getServer().launchGame(p.getSender(), p.getLevel(), p.getScore());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            // Request came from server..
            if (p.isPaused()) {
                Gdx.app.postRunnable(() -> {
                    // Sync data of pactales already send to connected clients with host.
                    try {
                        List<PacketGetGameClients.Data> data = getRmi().getServer()
                                .getGameClients(Client.getInstance().getId());

                        for (PacketGetGameClients.Data d : data) {
                            Pactale player = BaseScreen.getSession().getPlayer(d.getIndex());

                            player.setId(d.getPublicId());
                            player.setColor(
                                    ateamproject.kezuino.com.github.network.Game.SELECTABLE_COLORS[player
                                            .getPlayerIndex()]);
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                    game.setScreen(new GameScreen(game));
                    ((GameScreen) game.getScreen()).start();
                });
            } else {
                // Request came from server.. resume game.
                Gdx.app.postRunnable(() -> BaseScreen.getSession().resume());
            }
        }
    });

    packets.registerAction(PacketCreateGameObject.class, p -> {
        GameSession session = BaseScreen.getSession();
        if (session == null) {
            System.out.printf("Tried to create object: '%s' but no GameSession was set.%n", p.getTypeName());
            return;
        }

        GameObject object = null;
        try {
            String className = GameObject.class.getName();
            className = className.substring(0, className.lastIndexOf('.'));
            object = (GameObject) Class.forName(className + '.' + p.getTypeName()).newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        if (object == null) {
            throw new IllegalStateException(
                    String.format("Cannot create GameObject of type: '%s'", p.getTypeName()));
        }
        object.setId(p.getId());
        object.setStartingPosition(p.getPosition());
        object.setDirection(p.getDirection());
        object.setExactPosition(p.getPosition());
        object.setMap(session.getMap());
        object.setMovementSpeed(p.getSpeed());

        Color color = Color.WHITE.cpy();
        Color.rgba8888ToColor(color, p.getColor());
        object.setColor(color);

        if (object instanceof Pactale) {
            Pactale pactale = (Pactale) object;
            pactale.setPlayerIndex(p.getIndex());
            final GameObject finalObject = object;
            Gdx.app.postRunnable(() -> finalObject.setAnimation(new Animation(true,
                    Assets.getTexture(finalObject.getClass().getSimpleName().toLowerCase() + ".png"))));
        } else if (object instanceof Enemy) {
            final Enemy enemy = (Enemy) object;

            // Only host should generate enemy paths. Clients will receive them from the host.
            enemy.setDisablePathfinding(!Client.getInstance().isHost());
            Gdx.app.postRunnable(() -> enemy.setAnimation(
                    new Animation(Assets.getTexture(enemy.getClass().getSimpleName().toLowerCase() + ".png"))));
        }

        session.getMap().addGameObject(object);
        session.setObjectsLoaded(session.getObjectsLoaded() + 1);

        System.out.printf("Loaded (%s): %d/%d%n", object.getClass().getSimpleName(), session.getObjectsLoaded(),
                session.getObjectsToLoad());

        if (session.getObjectsToLoad() == session.getObjectsLoaded()) {
            send(new PacketSetLoadStatus(PacketSetLoadStatus.LoadStatus.ObjectsLoaded, null));
        }
    });

    packets.registerAction(PacketCreateItem.class, packet -> {
        GameSession session = BaseScreen.getSession();
        if (session == null) {
            System.out.printf("Tried to create object: '%s' but no GameSession was set.%n", "item");
            return;
        }

        // Create item.
        Item item = new Item(packet.getType().toString(), packet.getPosition(), packet.getType());
        item.setId(packet.getObjId());
        item.setMap(session.getMap());

        Gdx.app.postRunnable(() -> item.setTexture(
                new TextureRegion(Assets.getTexture(item.getItemType().name().toLowerCase() + ".png"))));
        session.getMap().getNode(item.getExactPosition()).setItem(item);

        // Update load status.
        session.setObjectsLoaded(session.getObjectsLoaded() + 1);
        System.out.printf("Loaded (%s): %d/%d%n", item.getClass().getSimpleName(), session.getObjectsLoaded(),
                session.getObjectsToLoad());

        if (session.getObjectsToLoad() == session.getObjectsLoaded()) {
            send(new PacketSetLoadStatus(PacketSetLoadStatus.LoadStatus.ObjectsLoaded, null));
        }
    });

    packets.registerAction(PacketLobbySetDetails.class, p -> {
        try {
            rmi.getServer().setLobbyDetails(p.getSender(), p.getData());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    });

    packets.registerFunc(PacketLobbyGetDetails.class, p -> {
        PacketLobbySetDetails.Data data = p.getResult();

        // TODO: Update lobby screen with new information.
        if (data.getName() != null) {
            System.out.println("New lobby name: " + data.getName());
        }
        if (data.getMap() != null) {
            System.out.println("New lobby map: " + data.getMap());
        }

        return data;
    });

    packets.registerAction(PacketLoadGame.class, p -> {
        // Set this session as the new main session.
        GameSession session = new GameSession(p.getLevel(), p.getScore());
        BaseScreen.setSession(session);
        MapLoader loader = Map.getLoader(session, p.getMap(), p.getLevel());

        EnumSet<MapLoader.MapObjectTypes> excluded = null;
        if (p.isMaster()) {
            // Load everything and synchronize with server.
            excluded = EnumSet.noneOf(MapLoader.MapObjectTypes.class);
            loader.addConsumer(Enemy.class, obj -> {
                try {
                    getRmi().getServer().createObject(p.getSender(), Enemy.class.getSimpleName(),
                            obj.getExactPosition(), obj.getDirection(), obj.getMovementSpeed(), obj.getId(),
                            Color.argb8888(obj.getColor()), 0);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            });
            loader.addConsumer(Pactale.class, obj -> {
                if (obj.getPlayerIndex() == 0) {
                    obj.setId(getPublicId());
                }

                try {
                    getRmi().getServer().createObject(p.getSender(), Pactale.class.getSimpleName(),
                            obj.getExactPosition(), obj.getDirection(), obj.getMovementSpeed(), obj.getId(),
                            Color.argb8888(obj.getColor()), obj.getPlayerIndex());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            });
            loader.addConsumer(Item.class, obj -> {
                try {
                    getRmi().getServer().createItem(p.getSender(), obj.getId(), obj.getItemType(),
                            obj.getExactPosition());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            });
        } else {
            // Exclude everything that's network dependant.
            excluded = EnumSet.of(MapLoader.MapObjectTypes.ENEMY, MapLoader.MapObjectTypes.PACTALE,
                    MapLoader.MapObjectTypes.ITEM);
        }

        // Load map (on OpenGL thread).
        final EnumSet<MapLoader.MapObjectTypes> finalExcluded = excluded;
        Gdx.app.postRunnable(() -> {
            loader.getTypesToLoad().removeAll(finalExcluded);
            loader.setPlayerLimit(p.getPlayerLimit());
            loader.load();
            session.setMap(loader.getMap());

            // Tell the game that we are done loading.
            if (p.isMaster()) {
                send(new PacketSetLoadStatus(PacketSetLoadStatus.LoadStatus.ObjectsLoaded, null));
            } else {
                send(new PacketSetLoadStatus(PacketSetLoadStatus.LoadStatus.MapLoaded, null));
            }
        });
    });

    packets.registerAction(PacketSetLoadStatus.class, packet -> {
        try {
            getRmi().getServer().setLoadStatus(packet.getSender(), packet.getStatus());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    });

    packets.registerAction(PacketUpdateProgress.class, packet -> {
        switch (packet.getId()) {
        case "game_load_objects":
            if (BaseScreen.getSession() == null) {
                System.out.println(
                        "Warning: PacketUpdateProgress received but was not expected. GameSession is null.");
                return;
            }
            BaseScreen.getSession().setObjectsToLoad(packet.getProgress());
            break;
        }
    });

    packets.registerAction(PacketShootProjectile.class, packet -> {
        // If client sended it..send this private id to server.
        if (packet.getSender() != null && packet.getSender().equals(getId())) {
            try {
                getRmi().getServer().shootProjectile(packet.getExactPosition(), packet.getDirection(),
                        packet.getSender());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            if (BaseScreen.getSession().getPlayer(packet.getSender()) != null) {
                Gdx.app.postRunnable(() -> {
                    // Server sended this.
                    BaseScreen.getSession().getPlayer(packet.getSender())
                            .shootProjectile(packet.getExactPosition(), packet.getDirection());
                });
            }
        }
    });

    packets.registerAction(PacketObjectMove.class, packet -> {
        if (packet.getSender() != null && packet.getSender().equals(getId())) {
            try {
                getRmi().getServer().objectSetDirection(packet.getSender(), packet.getObject(),
                        packet.getFrom(), packet.getTo());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            // Server sent this.
            GameObject object = BaseScreen.getSession().findObject(packet.getObject());
            if (object != null) {
                object.setExactPosition(packet.getFrom());
                object.setDirection(Direction.getDirection((int) packet.getFrom().x, (int) packet.getFrom().y,
                        (int) packet.getTo().x, (int) packet.getTo().y));
            }
        }
    });

    packets.registerAction(PacketPlayerDied.class, packet -> {
        if (packet.getSender() != null && packet.getSender().equals(getId())) {
            try {
                getRmi().getServer().playerDied(packet.getSender());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            BaseScreen.getSession().getPlayer(packet.getSender()).setInactive();
        }
    });

    packets.registerAction(PacketBalloonMessage.class, packet -> {
        if (packet.getSender() != null && packet.getSender().equals(getId())) {
            try {
                getRmi().getServer().balloonMessage(packet.getSender(), packet.getTypeName(),
                        packet.getPosition(), packet.getFollowTarget());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            // Create balloon on OpenGL thread.
            Gdx.app.postRunnable(() -> {
                try {
                    BalloonMessage message = ((BalloonMessage) Class
                            .forName(BalloonMessage.class.getPackage().getName() + ".messages.Balloon"
                                    + packet.getTypeName())
                            .newInstance());
                    if (packet.getFollowTarget() != null) {
                        message.setFollowObject(BaseScreen.getSession().findObject(packet.getFollowTarget()));
                    } else {
                        message.setPosition(packet.getPosition());
                    }
                    message.addBalloonMessage();
                } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            });
        }
    });

    packets.registerAction(PacketRemoveItem.class, packet -> {
        if (packet.getSender() != null && packet.getSender().equals(getId())) {
            try {
                getRmi().getServer().removeItem(packet.getSender(), packet.getPlayer(), packet.getItemId(),
                        packet.getItemType());
            } catch (RemoteException ex) {
                ex.printStackTrace();
            }
        } else {
            Item foundItem;

            if ((foundItem = BaseScreen.getSession().findItem(packet.getItemId())) != null) {
                foundItem.activate(BaseScreen.getSession().getPlayer(packet.getPlayer()));
                foundItem.getNode().removeItem();
            }
        }
    });

    packets.registerAction(PacketScoreChanged.class, packet -> {
        if (packet.getSender() != null && packet.getSender().equals(getId())) {
            try {
                getRmi().getServer().changeScore(packet.getSender(), packet.getManipulationType(),
                        packet.getChange());
            } catch (RemoteException ex) {
                ex.printStackTrace();
            }
        } else {
            Score currentScore = BaseScreen.getSession().getScore();

            switch (packet.getManipulationType()) {
            case DECREASE:
                currentScore.decrease(packet.getChange());
                break;
            case INCREASE:
                currentScore.increase(packet.getChange());
                break;
            }
        }
    });

    packets.registerFunc(PacketGetHighscores.class, packet -> {
        java.util.Map<String, Integer> returnMap = new HashMap<>();
        try {
            returnMap = getRmi().getServer().getHighscores(packet.getSender());
        } catch (RemoteException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
        return returnMap;
    });
}

From source file:be.ac.ucl.lfsab1509.bouboule.game.body.Arena.java

License:Open Source License

/**
 * Constructor for a Arena object./*from   ww w  .j a v a  2  s.  c  om*/
 * @param radius       : radius of Arena for a shape like body
 * @param Bodytype       : Dynamic or Static 
 * @param density       : Mass in [kg] of Arena 
 * @param elasticity   : define the elastical property of Arena [0..1]f
 * @param px/py         : initial posistion
 * @param angle         : initil rotation
 * @param texRegionPath : Path to the image file
 * @param jsonFile      : Path to the jsonFile if needed ( "" else)
 * @param jsonName      : jsonName of the object ( must match the json file attribute )
 *
 * public Arena(float radius, BodyType bodyType,float density,
 *    float elasticity,float px,float py, float angle,String texRegionPath,
 *  String jsonFile, String jsonName)
 */
public Arena(final float radius, final float px, final float py, final float angle, final String texRegionPath,
        final String jsonFile, final String jsonName) {

    super();

    Vector2 pos = new Vector2(px, py);

    this.texture = new TextureRegion(new Texture(texRegionPath));

    this.sprite = new Sprite(texture);

    MakeBody(0, 0, radius, BodyType.StaticBody, 0, 0, true, pos, angle, jsonFile, jsonName,
            GraphicManager.convertToGame(texture.getRegionWidth()));

    this.entity = new Entity(Entity.SCENERY);
    body.setUserData(this.entity);
}

From source file:be.ac.ucl.lfsab1509.bouboule.game.body.Bonus.java

License:Open Source License

/**
 * Constructor for a Bonus object /*from   w w w.  j av a2  s .  c  o m*/
 * @param px/py         : initial position
 * @param angle         : initial rotation
 * @param texRegionPath : Path to the image file
 * @param jsonFile      : Path to the jsonFile if needed ( "" else)
 * @param jsonName      : jsonName of the object ( must match the json file attribute )
 *
 * public Bonus( final float px, final float py, 
 *      final float angle, final String texRegionPath, 
 *      final String jsonFile, final String jsonName, final short bonusType)
 */
public Bonus(final float angle, final String texRegionPath, final String jsonFile, final String jsonName,
        final Entity.BonusType bonusType) {

    super();

    int size = GlobalSettings.ARENAWAYPOINTALLOW.size();
    MapNode node = GlobalSettings.ARENAWAYPOINTALLOW.get(random.nextInt(size));

    Vector2 pos = new Vector2(node.xToPixel() - 32, node.yToPixel() - 32);
    Vector2 radius = new Vector2(node.weightToPixel() * random.nextFloat(), 0);
    radius.rotate(random.nextInt(359));
    pos.add(radius);

    this.texture = new TextureRegion(new Texture(texRegionPath));

    this.sprite = new Sprite(texture);

    MakeBody(0, 0, 0, BodyType.StaticBody, 0, 0, true, pos, angle, jsonFile, jsonName,
            GraphicManager.convertToGame(texture.getRegionWidth()));

    //Ensure that the object don't rotate.
    body.setFixedRotation(true);

    //Create the userData of type Bonus and bonusType
    this.entity = new Entity(Entity.BONUS, true, bonusType);

    body.setUserData(this.entity);

    //Ensure that the body image position is set on the origin defined by 
    //the jsonFile
    if (origin != null) {
        pos = positionVector.cpy();
        pos = pos.sub(origin);
        sprite.setPosition(pos.x, pos.y);
        sprite.setOrigin(origin.x, origin.y);
        sprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
    }

    // removed the bonus after a delay
    Timer.Task task = new Timer.Task() {
        @Override
        public void run() {
            entity.setAlive(false);
        }
    };
    Timer timer = new Timer();
    timer.scheduleTask(task, 10f);
}

From source file:be.ac.ucl.lfsab1509.bouboule.game.body.Bouboule.java

License:Open Source License

/**
 * Constructor for a Bouboule object /*w  w w .  ja  v  a 2 s  .c om*/
 * @param radius       : radius of Bouboule for a shape like body
 * @param Bodytype       : Dynamic or Static 
 * @param density       : Mass in [kg] of Bouboule 
 * @param elasticity    : define the elastical property of Bouboul [0..1]f
 * @param px/py         : initial posistion
 * @param angle         : initil rotation
 * @param texRegionPath : Path to the image file
 * @param jsonFile      : Path to the jsonFile if needed ( "" else)
 * @param jsonName      : jsonName of the object ( must match the json file attribute )
 *
 * public Bouboule(float radius, BodyType bodyType,float density,
 *    float elasticity,float px,float py, float angle,String texRegionPath,
 *  String jsonFile, String jsonName)
 */
public Bouboule(final float radius, final BodyType bodyType, final float density, final float elasticity,
        final float px, final float py, final float angle, final String texRegionPath, final String jsonFile,
        final String jsonName, final short type, final int AILevel) {

    super();

    this.AILevel = AILevel;
    Vector2 pos = new Vector2(px, py);

    this.texture = new TextureRegion(new Texture(texRegionPath));
    this.sprite = new Sprite(texture);

    MakeBody(0, 0, radius, bodyType, density, elasticity, false, pos, angle, jsonFile, jsonName,
            GraphicManager.convertToGame(texture.getRegionWidth()));

    // added sprite to the fixture (to modify it somewhere else
    body.getFixtureList().get(0).setUserData(sprite);

    //Ensure that the object don't rotate.
    body.setFixedRotation(GlobalSettings.FIXED_ROTATION);

    this.entity = new Entity(type, true);

    body.setUserData(this.entity);
}

From source file:be.ac.ucl.lfsab1509.bouboule.game.body.Obstacle.java

License:Open Source License

/**
 * Constructor for a Obstacle object ./* ww w.ja  v a  2  s  .  c o m*/
 * @param Bodytype    : Dynamic or Static 
 * @param density    : Mass in [kg] of the obstacle 
 * @param elasticity : define the elastical property of Bouboul [0..1]f
 * @param px/py      : initial position
 * @param angle      : initial rotation
 * @param texRegionPath : Path to the image file
 * @param jsonFile   : Path to the jsonFile if needed ( "" else)
 * @param jsonName   : jsonName of the object ( must match the json file attribute )
 *
 * public Obstacle( final BodyType bodyType, final float density,
 *    final float elasticity, final float px, final float py,
 *  final float angle, final String texRegionPath, 
 *  final String jsonFile, final String jsonName)
 */
public Obstacle(final BodyType bodyType, final float density, final float elasticity, final float px,
        final float py, final float angle, final String texRegionPath, final String jsonFile,
        final String jsonName, final float initAccX, final float initAccY) {

    super();

    this.initialPos = new Vector2(px, py);

    this.texture = new TextureRegion(new Texture(texRegionPath));

    this.sprite = new Sprite(texture);

    MakeBody(0, 0, 0, bodyType, density, elasticity, false, initialPos, angle, jsonFile, jsonName,
            GraphicManager.convertToGame(texture.getRegionWidth()));

    //Ensure that the object don't rotate.
    //body.setFixedRotation(true);

    //Add Initail Velocity

    body.applyForceToCenter(new Vector2(initAccX, initAccY), true);

    this.entity = new Entity(Entity.OBSTACLE, true);
    body.setUserData(this.entity);
}

From source file:be.ac.ucl.lfsab1509.bouboule.game.gameManager.GraphicManager.java

License:Open Source License

/**
 * Load the background/*ww  w .j  av a 2 s .  c  o  m*/
 * @pre: {@link #dispose(false)} should have been called before
 */
protected void loadBackground(final String arenaName) {

    background = new Texture(arenaName + "bg.jpg");

    if (GlobalSettings.SCALE != 1f)
        backgroundRegion = new TextureRegion(background);
}

From source file:be.ac.ucl.lfsab1509.bouboule.game.screen.AbstractScreen.java

License:Open Source License

/**
 * @return a TextureRegionDrawable (Drawable) which is disposable via:
 *           `getRegion().getTexture().dispose();`
 *          if bAutomaticallyDisposeTexture is false.
 *///ww  w. jav  a2 s . c  o  m
protected TextureRegionDrawable getDrawableFromFile(String path, boolean bAutomaticallyDisposeTexture) {
    Texture texture = new Texture(path);
    if (bAutomaticallyDisposeTexture)
        textureList.add(texture);
    return new TextureRegionDrawable(new TextureRegion(texture));
}

From source file:broken.shotgun.throwthemoon.actors.Moon.java

License:Open Source License

public Moon(final AssetManager manager) {
    manager.setLoader(Texture.class, new TextureLoader(new InternalFileHandleResolver()));
    manager.setLoader(Sound.class, new SoundLoader(new InternalFileHandleResolver()));
    manager.load(TEXTURE_FILENAME, Texture.class);
    manager.load(SFX_MOON_CRASH_FILENAME, Sound.class);
    manager.finishLoading();//  w  ww  .  j  a  va  2s  . c  om

    texture = manager.get(TEXTURE_FILENAME);
    crashSfx = manager.get(SFX_MOON_CRASH_FILENAME);

    currentFrame = new TextureRegion(texture);

    setWidth(currentFrame.getRegionWidth());
    setHeight(currentFrame.getRegionHeight());
    setOrigin(getWidth() / 2, getHeight() / 2);

    reset();
}