Hello Guys, im back from a long needed break from programming and I’m back with another question.
I’ve never had to approach json in java before and I had to get an external library to get everything working properly. So bear with me for a moment.
I’m trying to make the json file of the player basically a “database” for the player. Something I can reference from other classes using methods I have built. Etc. This is the code that I have currently WORKING, but something does not feel right. I feel like there is a terrible problem with the implementation of the code. Can someone tell me how they would do theirs? Maybe some advice? Thanks.
package com.rojarstudios.prisma.saveSystem;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
public class SaveSystem {
JSONObject obj = new JSONObject();
ReadData read = new ReadData();
File playerData = new File("assets/data/player.json");
private boolean levelUp = false;
public SaveSystem() {
}
public void Ding(){
levelUp = true;
}
public void DataManager(String file) throws IOException{
// Call all the needed methods that make changes to the json file.
PlayerDefaultFile();
changeLevel();
changePlayerHP();
// Then use the collected obj refrences to write to the file.
writePlayerData(file);
if (Gdx.input.isKeyPressed(Keys.SPACE)) {
Ding();
}
}
@SuppressWarnings("unchecked")
public void changeLevel() {
if (levelUp) {
obj.put("level", (read.readData("assets/data/player.json", "level") + 1));
levelUp = false;
}
}
@SuppressWarnings("unchecked")
public void changePlayerHP() {
if ((read.readData("assets/data/player.json", "player_hp")) > 0) {
obj.put("player_hp", read.readData("assets/data/player.json", "player_hp") - 30);
}
}
public void writePlayerData(String fileName) throws IOException{
try {
// Make sure the file gets written to the right dir.
FileWriter file = new FileWriter(fileName);
if(playerData.exists()) {
file.write(obj.toJSONString());
file.flush();
file.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void PlayerDefaultFile() throws IOException{
if (!playerData.exists()) {
obj.put("name", "ROJAR");
obj.put("level", 1);
obj.put("player_hp", 100);
obj.put("player_mana", 100);
obj.put("player_stamina", 100);
obj.put("player_x", 50);
obj.put("player_y", 50);
// We can store the current items of the player in a list.
// Use the item ID's.
JSONArray inventory = new JSONArray();
inventory.add("001");
inventory.add("069");
inventory.add("333");
obj.put("items", inventory);
} else {
// Do nothing. Player.json already created.
}
}
}
Oh, and basically all readData(); does is readData(file, property); just grabs the json property I want from the file I specified.