Example usage for com.badlogic.gdx.utils Json toJson

List of usage examples for com.badlogic.gdx.utils Json toJson

Introduction

In this page you can find the example usage for com.badlogic.gdx.utils Json toJson.

Prototype

public void toJson(Object object, Writer writer) 

Source Link

Usage

From source file:com.ahsgaming.valleyofbones.network.MPGameClient.java

License:Apache License

/**
 * /*  w  w w  .  j  a v a  2 s.  c om*/
 */
public MPGameClient(VOBGame g, final GameSetupConfig cfg) {
    this.game = g;
    gameConfig = cfg;

    client = new Client();
    client.start();

    KryoCommon.register(client);

    client.addListener(new Listener() {

        public void connected(Connection c) {
            RegisterPlayer rp = new RegisterPlayer();
            rp.name = cfg.playerName;
            rp.spectator = cfg.isSpectator;
            rp.race = cfg.playerRace;
            rp.key = cfg.playerKey;
            client.sendTCP(rp);
        }

        public void received(Connection c, Object obj) {

            if (isConnecting) {
                if (obj instanceof KryoCommon.VersionError) {
                    Gdx.app.log(LOG, "VersionError");
                    error = (KryoCommon.VersionError) obj;
                    c.close();
                }

                if (obj instanceof KryoCommon.GameFullError) {
                    Gdx.app.log(LOG, "GameFullError");
                    error = (KryoCommon.GameFullError) obj;
                    c.close();
                }

                if (obj instanceof RegisteredPlayer) {
                    RegisteredPlayer reg = (RegisteredPlayer) obj;
                    playerId = reg.id;
                    gameConfig.isHost = reg.host;
                    Gdx.app.log(LOG, String.format("RegisteredPlayer rec'd (id: %d)", playerId));
                    recdRegisterPlayer = true;
                    gameConfig.isSpectator = reg.spectator;
                }
                isConnecting = false;
                return;
            }

            if (obj instanceof KryoCommon.ChatMessage) {
                Gdx.app.log(LOG, "ChatMessage rec'd");
                KryoCommon.ChatMessage chatMessage = (KryoCommon.ChatMessage) obj;
                chatLog.add(chatMessage.name + ": " + chatMessage.message);
            }

            if (obj instanceof Command[]) {
                Gdx.app.log(LOG, "Game history rec'd: " + ((Command[]) obj).length);
                commandQueue.addAll((Command[]) obj);
            }

            if (obj instanceof KryoCommon.GameUpdate) {
                Gdx.app.log(LOG, "Game update rec'd");
                gameUpdate = (KryoCommon.GameUpdate) obj;
            }

            if (controller == null) {
                if (obj instanceof RegisteredPlayer[]) {
                    Gdx.app.log(LOG, "Playerlist rec'd");
                    RegisteredPlayer[] plist = (RegisteredPlayer[]) obj;
                    players.clear();
                    spectators.clear();
                    for (int p = 0; p < plist.length; p++) {
                        if (plist[p].spectator) {
                            spectators.put(plist[p].id, plist[p].name);
                        } else {
                            Player pl = new Player(plist[p].id, plist[p].name,
                                    Player.AUTOCOLORS[plist[p].color], plist[p].race);
                            if (plist[p].isAI) {
                                pl.setReady(true);
                                pl.setAI(true);
                            } else {
                                pl.setReady(plist[p].ready);
                            }
                            players.add(pl);
                            if (pl.getPlayerId() == playerId) {
                                player = pl;
                                gameConfig.isHost = plist[p].host;
                            }

                            Gdx.app.log(LOG, "Player ready: " + plist[p].ready);
                        }
                    }
                }

                if (obj instanceof KryoCommon.GameDetails) {
                    Gdx.app.log(LOG, "GameDetails rec'd");
                    KryoCommon.GameDetails details = (KryoCommon.GameDetails) obj;
                    gameConfig.setDetails(details);

                    Json json = new Json();
                    System.out.println(json.toJson(details, KryoCommon.GameDetails.class));

                }

                if (obj instanceof StartGame) {
                    // we want to start the game, but we need to load our objects on the other thread, where we have an OpenGL context
                    Gdx.app.log(LOG, "StartGame rec'd");
                    game.setLoadGame();
                    firstTurnPid = ((StartGame) obj).currentPlayer;
                    gameConfig.spawnType = ((StartGame) obj).spawnType;
                }
                return;
            }

            if (obj instanceof Command) {
                Command cmd = (Command) obj;
                if (cmd instanceof Unpause)
                    System.out.println("Unpause " + Integer.toString(cmd.turn));
                if (cmd instanceof Pause)
                    System.out.println("Pause " + Integer.toString(cmd.turn));
                //                    if (cmd instanceof Move) System.out.println("Move recd");
                if (!(obj instanceof StartTurn || obj instanceof EndTurn)) {
                    if (commandQueue.size > 0) {
                        //                            System.out.println("cmd to commandQueue");
                        commandQueue.add(cmd);
                    } else {
                        controller.queueCommand(cmd);
                        //                            System.out.println("cmd to controller");
                    }
                }
            }

            if (obj instanceof GameResult) {
                Gdx.app.log(LOG, "GameResult rec'd");
                gameResult = (GameResult) obj;
            }

            if (obj instanceof StartTurn) {
                Gdx.app.log(LOG, "StartTurn");
            }

            if (obj instanceof EndTurn) {
                Gdx.app.log(LOG, "EndTurn");
                if (controller != null) {
                    controller.setCommandQueue(((EndTurn) obj).commands);
                    Gdx.app.log(LOG,
                            String.format("EndTurn.commands.length = %d", ((EndTurn) obj).commands.length));

                    sentEndTurn = false;
                    recdEndTurn = true;
                }
            }

        }

        public void disconnected(Connection c) {
            Gdx.app.log(LOG, "Disconnected!");
            if (gameResult == null && controller != null) {
                Gdx.app.log(LOG, "Reconnect");
                isReconnect = true;
                Pause p = new Pause();
                p.isAuto = true;
                p.owner = -1;
                p.turn = controller.getGameTurn();
                controller.queueCommand(p);
            }
        }
    });
    connect();
}

From source file:com.algodal.gdxscreen.utils.GdxSave.java

License:Apache License

/**
 * Saves all objects in the list to the file you specify.  The file is overwritten or created.
 * The save format possess additional information such as time of save and number of objects.
 * @return String version of the saved data.
 *///from  w ww. j ava 2 s. co m
public String save() {
    StringWriter stringWriter = new StringWriter();
    XmlWriter xmlWriter = new XmlWriter(stringWriter);
    Json json = new Json();

    debug.assertNoException("No exception during save", new Operation<Void>() {
        @Override
        public Void resultOf() throws Exception {
            xmlWriter.element(ROOT_ELEMENT).attribute(ROOT_NAME, dataName).attribute(ROOT_TIME, flashTime())
                    .attribute(ROOT_COUNT, Integer.toString(plainOldJavaObjects.size));
            for (int i = 0; i < plainOldJavaObjects.size; i++) {
                debug.assertContructorEmpty("object has null constructor class",
                        plainOldJavaObjects.get(i).getClass());
                xmlWriter.element(CHILD_ELEMENT).attribute(CHILD_ID, Integer.toString(i));
                xmlWriter.text(json.toJson(plainOldJavaObjects.get(i), Object.class));
                xmlWriter.pop();
            }
            xmlWriter.pop();
            xmlWriter.close();
            return null;
        }
    });

    String xmlJsonString = stringWriter.toString();
    handle.writeString(xmlJsonString, false);
    return xmlJsonString;
}

From source file:com.intrepid.studio.animation.GenerateAnimationPackInfo.java

private void createAnimationOutput(Json json) {
    for (String groupTagName : mapGroupTagResource.keySet()) {
        GroupTag groupTag = mapGroupTagResource.get(groupTagName);

        String outputApInfo = API_INFO_OUTPUT + groupTag.getName() + "." + API_EXTENSION;
        String outputTexture = TEXTURE_OUTPUT + groupTag.getName() + "." + TEXTURE_EXTENSION;
        groupTag.setTextureOutput(outputTexture);

        // Write Animation Pack Info
        AnimationPackInfo api = groupTag.createAnimationPackInfo();
        String toWrite = (PRETTY_PRINT ? json.prettyPrint(api) : json.toJson(api, AnimationPackInfo.class));
        if (ENCODED)
            toWrite = new String(Base64.getEncoder().encode(toWrite.getBytes()));
        getFileHandle(outputApInfo).writeString(toWrite, false);

        // Write Texture file
        PixmapIO.writePNG(files.local(outputTexture), groupTag.getPixmap());

        System.out.println("GROUP TAG: " + groupTagName);
        System.out.println("  " + outputApInfo);
        System.out.println("  " + outputTexture);
    }/*  w  w w. j  a va2s.  c  om*/
}

From source file:com.kotcrab.vis.editor.module.editor.DonateReminderModule.java

License:Apache License

@Override
public void init() {
    FileHandle storage = fileAccess.getMetadataFolder();
    FileHandle storageFile = storage.child("donateReminder.json");

    Json json = new Json();
    json.setIgnoreUnknownFields(true);/*  w w  w . java 2  s  . c  om*/
    json.addClassTag("EditorRunCounter", EditorRunCounter.class);

    EditorRunCounter runCounter;
    try {
        if (storageFile.exists()) {
            runCounter = json.fromJson(EditorRunCounter.class, storageFile);
        } else
            runCounter = new EditorRunCounter();
    } catch (SerializationException ignored) {
        runCounter = new EditorRunCounter();
    }

    runCounter.counter++;

    if (runCounter.counter % 50 == 0) {
        VisTable table = new VisTable(true);

        table.add("If you like VisEditor please consider").spaceRight(3);
        table.add(new LinkLabel("donating.", DONATE_URL));
        LinkLabel hide = new LinkLabel("Hide");
        table.add(hide);
        menuBar.setUpdateInfoTableContent(table);

        hide.setListener(labelUrl -> menuBar.setUpdateInfoTableContent(null));
    }

    json.toJson(runCounter, storageFile);
}

From source file:com.kotcrab.vis.editor.module.project.ProjectVersionModule.java

License:Apache License

@Override
public void init() {
    Json json = getNewJson();
    FileHandle versionFile = fileAccess.getModuleFolder().child("version.json");

    if (versionFile.exists()) {
        ProjectVersionDescriptor descriptor = json.fromJson(ProjectVersionDescriptor.class, versionFile);
        if (descriptor.versionCode > App.VERSION_CODE)
            return; //prevent downgrading version saved in version.json
    }/*from   w w w  .j  a  v  a2s .  c  o  m*/

    json.toJson(new ProjectVersionDescriptor(App.VERSION_CODE, App.VERSION), versionFile);
}

From source file:com.kotcrab.vis.editor.ui.dialog.SpriterImportDialog.java

License:Apache License

private void importAnimation() {
    SteppedAsyncTask importTask = new SteppedAsyncTask("SpriterImporter") {
        @Override/*from  w  ww.j  a v a2 s.c o  m*/
        public void execute() throws IOException {
            FileHandle[] files = animFolder.list();
            setTotalSteps(files.length * 2);

            float scaleFactor = Float.valueOf(scaleField.getText());

            visAnimFolder.mkdirs();
            visAnimFolder.child("update").mkdirs();

            FileHandle target = visAnimFolder.child("original");
            target.mkdirs();

            for (FileHandle file : files) {
                setMessage("Copying " + file.name());
                file.copyTo(target);
                nextStep();
            }

            for (FileHandle file : files) {
                if (file.extension().equals("png") == false)
                    continue;

                setMessage("Converting " + file.name());
                BufferedImage image = ImageIO.read(file.file());
                BufferedImage scaledImage = Scalr.resize(image, MathUtils.round(image.getWidth() * scaleFactor),
                        MathUtils.round(image.getHeight() * scaleFactor));
                ImageIO.write(scaledImage, "png", file.file());
                nextStep();
            }

            setMessage("Saving data");

            Json json = SpriterDataIOModule.getNewJson();
            SpriterAssetData assetData = new SpriterAssetData(scaleFactor);
            json.toJson(assetData, visAnimFolder.child("data.json"));
        }
    };
    getStage().addActor(new AsyncTaskProgressDialog("Importing animation", importTask));
}

From source file:com.kotcrab.vis.plugin.spriter.ui.SpriterImportDialog.java

License:Apache License

private void importAnimation() {
    SteppedAsyncTask importTask = new SteppedAsyncTask("SpriterImporter") {
        @Override/*from   w ww .j av  a2s  .com*/
        public void doInBackground() throws IOException {
            FileHandle[] files = animFolder.list();
            setTotalSteps(files.length * 2);

            float scaleFactor = Float.valueOf(scaleField.getText());

            visAnimFolder.mkdirs();
            visAnimFolder.child("update").mkdirs();

            FileHandle target = visAnimFolder.child("original");
            target.mkdirs();

            for (FileHandle file : files) {
                setMessage("Copying " + file.name());
                file.copyTo(target);
                nextStep();
            }

            for (FileHandle file : files) {
                if (file.extension().equals("png") == false)
                    continue;

                setMessage("Converting " + file.name());
                BufferedImage image = ImageIO.read(file.file());
                BufferedImage scaledImage = Scalr.resize(image, MathUtils.round(image.getWidth() * scaleFactor),
                        MathUtils.round(image.getHeight() * scaleFactor));
                ImageIO.write(scaledImage, "png", file.file());
                nextStep();
            }

            setMessage("Saving data");

            Json json = SpriterDataIOModule.getNewJson();
            SpriterAssetData assetData = new SpriterAssetData(scaleFactor);
            json.toJson(assetData, visAnimFolder.child("data.json"));
        }
    };
    Async.startTask(getStage(), "Importing animation", importTask);
}

From source file:es.danirod.rectball.android.AndroidLauncher.java

License:Open Source License

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // Save the game state if the game is running.
    if (game.getState().isPlaying()) {
        Json json = new Json();
        json.setOutputType(JsonWriter.OutputType.json);
        String jsonBoard = json.toJson(game.getState(), GameState.class);
        outState.putString("state", jsonBoard);
        Gdx.app.debug("Rectball", "Saving State: " + jsonBoard);
    } else {// w  w w.  j a  v a  2s .  co  m
        Gdx.app.debug("Rectball", "Not playing, no need to save state.");
    }
}

From source file:eu.rubenrosado.inmisericordia.LSGame.java

License:Open Source License

/**
 * Save the game in JSon//from ww  w. ja  va2s .  co m
 */
public void saveGame() {
    Json json = new Json();
    String hero = json.toJson(PlayGame.hero, Hero.class);
    String monsters = json.toJson(PlayGame.monsters, Monster.class);

    FileHandle file = Gdx.files.local("hero.sav");
    file.writeString(hero, false);
    file = Gdx.files.local("monsters.sav");
    file.writeString(monsters, false);

    Preferences pref = Gdx.app.getPreferences(".sav");
    if (!pref.getBoolean("savedgame", false)) {
        pref.putBoolean("savedgame", true);
    }
    pref.flush();
}

From source file:headmade.arttag.ArtTag.java

License:Apache License

private void saveGame() {
    final Json json = new Json();
    final FileHandle saveFile = Gdx.files.local(SAVE_FILE);
    json.toJson(gameState, saveFile);
}