List of usage examples for com.badlogic.gdx.utils Json fromJson
public <T> T fromJson(Class<T> type, String 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); }/* ww w . j a va2s.c o m*/ 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.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//from w w w . jav a2 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.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;/*from w w w . jav a2 s . c o 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.pokeadot.HighScoreService.java
License:Open Source License
public static HighScore get() { FileHandle saveFile = Gdx.files.external(HIGHSCORE_EXTERNAL_PATH); if (saveFile.exists()) { String jsonString;/*w w w . j a v a 2s. c o 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 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.cyphercove.dayinspace.Story.java
License:Apache License
public Story(Assets assets) { Json json = new Json(); Board.Parameters[] params = json.fromJson(Board.Parameters[].class, Gdx.files.internal("boardParams.json")); for (int i = 0; i < params.length; i++) { Board.Parameters stageParams = params[i]; Board board = new Board(assets, stageParams); boards.add(board);/* w ww . j a v a 2 s . c o m*/ } movesPerTurn = 3; livesLeft = 3; heartsLeft = 3; stagesComplete = 0; stepsTaken = 0; enemiesDestroyed = 0; }
From source file:com.flaiker.reaktio.servcies.PreferencesManager.java
License:Open Source License
public ScoreEntry[] getScoreArray() { String string = getPreferences().getString(PREF_SCORE, null); if (string == null) return null; Json json = new Json(); return json.fromJson(ScoreArray.class, string).scores; }
From source file:com.flaiker.reaktio.servcies.PreferencesManager.java
License:Open Source License
public void addScoreEntry(ScoreEntry score) { Json json = new Json(); String string = getPreferences().getString(PREF_SCORE, null); ScoreArray scores;/* w w w. j a v a 2s. com*/ if (string == null) { scores = new ScoreArray(); scores.scores = new ScoreEntry[0]; } else scores = json.fromJson(ScoreArray.class, string); ArrayList<ScoreEntry> scoreList = new ArrayList<ScoreEntry>(Arrays.asList(scores.scores)); scoreList.add(score); scores.scores = scoreList.toArray(new ScoreEntry[scoreList.size()]); getPreferences().putString(PREF_SCORE, json.toJson(scores)); getPreferences().flush(); Gdx.app.log(LOG, "Added scoreentry"); }
From source file:com.github.fauu.helix.manager.AreaManager.java
License:Open Source License
public void loadFromFile(FileHandle file, String name) { Json json = new Json(); json.setIgnoreUnknownFields(true);//from ww w . j ava2s. co m AreaWrapper areaWrapper = json.fromJson(AreaWrapper.class, file); Tile[][] tiles = new Tile[areaWrapper.length][areaWrapper.width]; int i = 0; for (TileWrapper wrapper : areaWrapper.tiles) { Tile tile = new Tile(); tile.setPermissions(wrapper.permissions); if (wrapper.passage != null) { TileAreaPassage areaPassage = new TileAreaPassage(); areaPassage.setTargetAreaName(wrapper.passage.area); areaPassage.setTargetCoords(new IntVector2(wrapper.passage.position.x, wrapper.passage.position.y)); tile.setAreaPassage(areaPassage); } tiles[i / areaWrapper.width][i % areaWrapper.width] = tile; i++; } String modelPath = "model/" + name + ".g3db"; assetManager.load(modelPath, Model.class); assetManager.finishLoading(); Model model = assetManager.get(modelPath, Model.class); for (Material m : model.materials) { m.set(new FloatAttribute(FloatAttribute.AlphaTest, 0.1f)); } Entity area = world.createEntity().edit().add(new AreaTypeComponent(areaWrapper.type)) .add(new TilesComponent(tiles)) .add(new DimensionsComponent(new IntVector2(areaWrapper.width, areaWrapper.length))) .add(new NameComponent(name)).add(new DisplayableComponent(new AreaDisplayable(model))) .add(new VisibilityComponent()).getEntity(); world.getManager(TagManager.class).register("area", area); this.area = area; }
From source file:com.intrepid.studio.animation.TagResource.java
public void loadData(Json json) { if (!hasData()) return;// www . j a v a 2s .c om this.animationInfo = json.fromJson(AnimationInfo.class, this.sai); this.pixmap = new Pixmap(this.png); }
From source file:com.jupiter.europa.entity.component.AttributesComponent.java
License:Open Source License
@Override public void read(Json json, JsonValue jsonData) { if (jsonData.has(BASE_ATTRIBUTES_KEY)) { this.baseAttributes = json.fromJson(AttributeSet.class, jsonData.get(BASE_ATTRIBUTES_KEY).prettyPrint(EuropaGame.PRINT_SETTINGS)); }//from w w w . java 2 s. c o m if (jsonData.has(CURRENT_ATTRIBUTES_KEY)) { this.currentAttributes = json.fromJson(AttributeSet.class, jsonData.get(CURRENT_ATTRIBUTES_KEY).prettyPrint(EuropaGame.PRINT_SETTINGS)); } }