List of usage examples for com.badlogic.gdx.utils Json Json
public Json()
From source file:com.ahsgaming.valleyofbones.ai.AIPlayer.java
License:Apache License
@Override public void update(GameController controller, float delta) { super.update(controller, delta); if (genome == null) { Json json = new Json(); genome = json.fromJson(GenomicAI.class, Gdx.files.internal("ai/xjix3xuv").readString()); Gdx.app.log(LOG, "Loaded ai: " + genome.id); }// w w w .j a v a 2 s . c om if (controller.getCurrentPlayer().getPlayerId() == getPlayerId()) { timer -= delta; if (timer < 0) { timer = countdown; if (VOBGame.DEBUG_AI) Gdx.app.log(LOG, "start..."); // first, create the visibility matrix if (visibilityMatrix == null) { if (VOBGame.DEBUG_AI) Gdx.app.log(LOG, "...create visibility matrix"); visibilityMatrix = createVisibilityMatrix(controller.getMap(), controller.getUnitsByPlayerId(getPlayerId())); return; } // next, create the value matrix and threat matrix if (valueMatrix == null) { Array<AbstractUnit> visibleUnits = new Array<AbstractUnit>(); for (AbstractUnit unit : controller.getUnits()) { if (visibilityMatrix[(int) (unit.getView().getBoardPosition().y * controller.getMap().getWidth() + unit.getView().getBoardPosition().x)]) { visibleUnits.add(unit); } } if (VOBGame.DEBUG_AI) Gdx.app.log(LOG, "...create value/threat matrices"); valueMatrix = createUnitMatrix(controller.getMap(), visibleUnits, false); threatMatrix = createUnitMatrix(controller.getMap(), visibleUnits, true); return; } // create goalMatrix (based on knowledge of the map) if (goalMatrix == null) { if (VOBGame.DEBUG_AI) Gdx.app.log(LOG, "...create goal matrix"); goalMatrix = createGoalMatrix(controller.getMap(), controller.getUnits()); if (VOBGame.DEBUG_AI) { DecimalFormat formatter = new DecimalFormat("00.0"); for (int y = 0; y < controller.getMap().getHeight(); y++) { if (y % 2 == 1) { System.out.print(" "); } for (int x = 0; x < controller.getMap().getWidth(); x++) { int i = y * controller.getMap().getWidth() + x; float sum = (visibilityMatrix[i] ? goalMatrix[i] + valueMatrix[i] + threatMatrix[i] : 0); System.out.print((sum >= 0 ? " " : "") + formatter.format(sum) + " "); } System.out.println("\n"); } } return; } // move units for (AbstractUnit unit : controller.getUnitsByPlayerId(getPlayerId())) { if (unit.getData().getMovesLeft() < 1) continue; Vector2[] adjacent = HexMap.getAdjacent((int) unit.getView().getBoardPosition().x, (int) unit.getView().getBoardPosition().y); Vector2 finalPos = new Vector2(unit.getView().getBoardPosition()); float finalSum = goalMatrix[(int) finalPos.y * controller.getMap().getWidth() + (int) finalPos.x] + valueMatrix[(int) finalPos.y * controller.getMap().getWidth() + (int) finalPos.x] + threatMatrix[(int) finalPos.y * controller.getMap().getWidth() + (int) finalPos.x]; for (Vector2 v : adjacent) { if (v.x < 0 || v.x >= controller.getMap().getWidth() || v.y < 0 || v.y >= controller.getMap().getHeight()) continue; float curSum = goalMatrix[(int) v.y * controller.getMap().getWidth() + (int) v.x] + valueMatrix[(int) v.y * controller.getMap().getWidth() + (int) v.x] + threatMatrix[(int) v.y * controller.getMap().getWidth() + (int) v.x]; if (curSum > finalSum && controller.isBoardPosEmpty(v)) { finalPos.set(v); finalSum = curSum; } } if (finalPos.x != unit.getView().getBoardPosition().x || finalPos.y != unit.getView().getBoardPosition().y) { // move! Move mv = new Move(); mv.owner = getPlayerId(); mv.turn = controller.getGameTurn(); mv.unit = unit.getId(); mv.toLocation = finalPos; netController.sendAICommand(mv); valueMatrix = null; threatMatrix = null; return; } } // attack Array<AbstractUnit> visibleUnits = new Array<AbstractUnit>(); Array<AbstractUnit> friendlyUnits = controller.getUnitsByPlayerId(this.getPlayerId()); for (AbstractUnit unit : controller.getUnits()) { if (unit.getOwner() == this || unit.getOwner() == null) continue; if (visibilityMatrix[(int) (unit.getView().getBoardPosition().y * controller.getMap().getWidth() + unit.getView().getBoardPosition().x)] && !unit.getData().isInvisible() || controller.getMap().detectorCanSee(this, friendlyUnits, unit.getView().getBoardPosition())) { visibleUnits.add(unit); } } for (AbstractUnit unit : controller.getUnitsByPlayerId(getPlayerId())) { if (unit.getData().getAttacksLeft() < 1) continue; AbstractUnit toAttack = null; float toAttackThreat = 0; for (AbstractUnit o : visibleUnits) { float thisThreat = threatMatrix[controller.getMap().getWidth() * (int) o.getView().getBoardPosition().y + (int) o.getView().getBoardPosition().x]; if (controller.getUnitManager().canAttack(unit, o) && (toAttack == null || thisThreat > toAttackThreat)) { toAttack = o; toAttackThreat = thisThreat; } } if (toAttack != null) { // Gdx.app.log(LOG + "$attack", String.format("%s --> %s", unit.getProtoId(), toAttack.getProtoId())); Attack at = new Attack(); at.owner = getPlayerId(); at.turn = controller.getGameTurn(); at.unit = unit.getId(); at.target = toAttack.getId(); netController.sendAICommand(at); valueMatrix = null; threatMatrix = null; return; } } // build units // TODO build other than marines (ie: implement chromosome 11) int positionToBuild = -1; for (int i = 0; i < valueMatrix.length; i++) { if (visibilityMatrix[i]) { float sum = threatMatrix[i] + valueMatrix[i] + goalMatrix[i]; if ((positionToBuild == -1 || valueMatrix[positionToBuild] + valueMatrix[positionToBuild] + goalMatrix[positionToBuild] < sum)) { // Gdx.app.log(LOG, i + ":" + controller.isBoardPosEmpty( // i % controller.getMap().getWidth(), // i / controller.getMap().getWidth())); if (controller.isBoardPosEmpty(i % controller.getMap().getWidth(), i / controller.getMap().getWidth())) { positionToBuild = i; } } } } Prototypes.JsonProto unitToBuild = null; if (positionToBuild >= 0) { Vector2 buildPosition = new Vector2(positionToBuild % controller.getMap().getWidth(), positionToBuild / controller.getMap().getWidth()); Array<String> protoIds = new Array<String>(); HashMap<String, Float> buildScores = new HashMap<String, Float>(); for (Prototypes.JsonProto proto : Prototypes.getAll(getRace())) { protoIds.add(proto.id); if (proto.cost > 0) { buildScores.put(proto.id, 0f); } } for (AbstractUnit unit : controller.getUnits()) { if (unit.getOwner() == this || !visibilityMatrix[(int) (unit.getView().getBoardPosition().y * controller.getMap().getWidth() + unit.getView().getBoardPosition().x)]) continue; int unitIndex = protoIds.indexOf(unit.getProto().id, false); int unitDistance = controller.getMap().getMapDist(unit.getView().getBoardPosition(), buildPosition); for (String key : buildScores.keySet()) { buildScores.put(key, buildScores.get(key) + ((Array<Float>) genome.chromosomes.get(10).genes.get(key)).get(unitIndex) / unitDistance); } } String maxScore = null; float maxBuildScore = 0; while (unitToBuild == null && buildScores.keySet().size() > 0) { for (String id : buildScores.keySet()) { if (maxScore == null || buildScores.get(id) > buildScores.get(maxScore)) { maxScore = id; if (buildScores.get(id) > maxBuildScore) { maxBuildScore = buildScores.get(id); } } } if (!maxScore.equals("saboteur") && buildScores.get(maxScore) > 0 && buildScores.get(maxScore) >= maxBuildScore - (Float) genome.chromosomes.get(10).genes.get("wait") && getBankMoney() >= Prototypes.getProto(getRace(), maxScore).cost) { unitToBuild = Prototypes.getProto(getRace(), maxScore); } else { buildScores.remove(maxScore); maxScore = null; } } } if (unitToBuild != null) { Build build = new Build(); build.owner = getPlayerId(); build.turn = controller.getGameTurn(); build.building = unitToBuild.id; build.location = new Vector2(positionToBuild % controller.getMap().getWidth(), positionToBuild / controller.getMap().getWidth()); netController.sendAICommand(build); valueMatrix = null; return; } EndTurn et = new EndTurn(); et.owner = getPlayerId(); et.turn = controller.getGameTurn(); netController.sendAICommand(et); } } else { visibilityMatrix = null; valueMatrix = null; threatMatrix = null; goalMatrix = null; } }
From source file:com.ahsgaming.valleyofbones.network.MPGameClient.java
License:Apache License
/** * //from w ww. j av a 2 s . co m */ 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.GdxLoad.java
License:Apache License
public LoadData load() { XmlReader xmlReader = new XmlReader(); Json json = new Json(); return debug.assertNoException("No exception during loading", new Operation<LoadData>() { @Override//w w w. j a va 2 s .c o m public LoadData resultOf() throws Exception { Element element = xmlReader.parse(handle); final LoadData data = new LoadData(); data.setName(element.getAttribute(GdxSave.ROOT_NAME)); data.setTime(element.getAttribute(GdxSave.ROOT_TIME)); data.setCount(Integer.parseInt(element.getAttribute(GdxSave.ROOT_COUNT))); data.setPlainOldJavaObjects(new Array<Object>()); data.setRepresentation(element.toString()); debug.assertEqual("root element is " + GdxSave.ROOT_ELEMENT, element.getName(), GdxSave.ROOT_ELEMENT); for (int i = 0; i < element.getChildCount(); i++) { Element child = element.getChild(i); debug.assertEqual("child element is " + GdxSave.CHILD_ELEMENT, child.getName(), GdxSave.CHILD_ELEMENT); Object childObject = json.fromJson(Object.class, child.getText()); data.getPlainOldJavaObjects().add(childObject); } return data; } }); }
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. *///w ww . ja v a2 s.c om 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.andgate.ikou.io.ProgressDatabaseService.java
License:Open Source License
public static ProgressDatabase read() { FileHandle saveFile = Gdx.files.external(Constants.PROGRESS_DATABASE_EXTERNAL_PATH); if (saveFile.exists()) { String jsonString;// ww w .j ava 2 s. co m try { jsonString = Base64Coder.decodeString(saveFile.readString()); } catch (java.lang.IllegalArgumentException e) { // The highscore has been tampered with, // so now they get a new one. return new ProgressDatabase(); } Json json = new Json(); ProgressDatabase progressDatabase = json.fromJson(ProgressDatabase.class, jsonString); if (progressDatabase != null) { return progressDatabase; } } // Always return a fresh db, // if something is mucked up. // Only executes if something is wrong // with the return new ProgressDatabase(); }
From source file:com.andgate.ikou.io.ProgressDatabaseService.java
License:Open Source License
public static void write(ProgressDatabase progressDatabase) { Json json = new Json(); String jsonString = json.toJson(progressDatabase); String encodedString = Base64Coder.encodeString(jsonString); FileHandle saveFile = Gdx.files.external(Constants.PROGRESS_DATABASE_EXTERNAL_PATH); saveFile.writeString(encodedString, false); }
From source file:com.andgate.pokeadot.HighScoreService.java
License:Open Source License
public static HighScore get() { FileHandle saveFile = Gdx.files.external(HIGHSCORE_EXTERNAL_PATH); if (saveFile.exists()) { String jsonString;/* www . ja v a2s . com*/ try { jsonString = Base64Coder.decodeString(saveFile.readString()); } catch (java.lang.IllegalArgumentException e) { // The highscore has been tampered with, // so now they get a new one. return new HighScore(); } Json json = new Json(); /*json.setTypeName(null); json.setUsePrototypes(false); json.setIgnoreUnknownFields(true); json.setOutputType(JsonWriter.OutputType.json);*/ HighScore highScore = json.fromJson(HighScore.class, jsonString); if (highScore != null) { return highScore; } } return new HighScore(); }
From source file:com.andgate.pokeadot.HighScoreService.java
License:Open Source License
public static void set(HighScore newHighScore) { Json json = new Json(); String jsonString = json.toJson(newHighScore); String encodedString = Base64Coder.encodeString(jsonString); FileHandle saveFile = Gdx.files.external(HIGHSCORE_EXTERNAL_PATH); saveFile.writeString(encodedString, false); }
From source file:com.appham.dictson.Dictson.java
License:Apache License
/** * Returns a Dictson instance with the text values obtained from dictionary.json file * //from ww w . j a va2 s . c o m * @param aLocale * @return a Dictson instance with the requested Locale or English if not supported */ @SuppressWarnings("unchecked") public static Dictson getInstance(Locale aLocale) { INSTANCE.wordsMap = new Json().fromJson(OrderedMap.class, Gdx.files.internal("data/dictionary.json")); INSTANCE.setLocale(getSupportedLocale(aLocale)); return INSTANCE; }
From source file:com.bladecoder.engine.actions.DisableActionAction.java
License:Apache License
public void setAction(Action a) { action = a;//from ww w . j a v a 2 s .c o m Json json = new Json(); StringWriter buffer = new StringWriter(); json.setWriter(buffer); ActionUtils.writeJson(a, json); serializedAction = buffer.toString(); }