Gamelib/src/main/java/uulm/teamname/marvelous/gamelibrary/json/ingame/deserialize/EntityDeserializer.java

89 lines
3.6 KiB
Java

package uulm.teamname.marvelous.gamelibrary.json.ingame.deserialize;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.*;
import uulm.teamname.marvelous.gamelibrary.IntVector2;
import uulm.teamname.marvelous.gamelibrary.entities.*;
import uulm.teamname.marvelous.gamelibrary.entities.Character;
import uulm.teamname.marvelous.gamelibrary.config.CharacterConfig;
import uulm.teamname.marvelous.gamelibrary.config.CharacterProperties;
import uulm.teamname.marvelous.gamelibrary.json.ingame.SerializedEntityType;
import java.io.IOException;
public class EntityDeserializer extends JsonDeserializer<Entity> {
@Override
public Entity deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
var config = (CharacterConfig) ctxt
.findInjectableValue("CharacterConfig", null, null);
ObjectCodec codec = p.getCodec();
JsonNode node = codec.readTree(p);
Entity result = null;
SerializedEntityType type = SerializedEntityType.valueOf(node.get("entityType").asText());
switch (type) {
case Character -> {
EntityID id = new EntityID(
EntityType.valueOf("P" + node.get("PID").intValue()),
node.get("ID").intValue());
String characterName = node.get("name").asText();
CharacterProperties properties = config.getMap().get(characterName);
if (properties == null) throw new IOException("Non-existent Character in Event");
result = new Character(
id,
codec.treeToValue(node.get("position"), IntVector2.class),
characterName,
properties.HP,
properties.MP,
properties.AP,
node.get("HP").asInt(),
node.get("MP").asInt(),
node.get("AP").asInt(),
properties.attackRange,
properties.rangedDamage,
properties.meleeDamage
);
for (var i: codec.treeToValue(node.get("stones"), Integer[].class)) {
((Character) result).inventory.addStone(StoneType.valueOf(i));
}
}
case NPC -> {
result = new NPC(
new EntityID(EntityType.NPC, node.get("ID").asInt()),
codec.treeToValue(node.get("position"), IntVector2.class),
node.get("MP").asInt()
);
for (var i: codec.treeToValue(node.get("stones"), Integer[].class)) {
((NPC) result).inventory.addStone(StoneType.valueOf(i));
}
}
case InfinityStone -> result = new InfinityStone(
new EntityID(EntityType.InfinityStones, node.get("ID").asInt()),
codec.treeToValue(node.get("position"), IntVector2.class),
StoneType.valueOf(node.get("ID").asInt())
);
case Rock -> result = new Rock(
new EntityID(EntityType.Rocks, node.get("ID").asInt()),
codec.treeToValue(node.get("position"), IntVector2.class),
node.get("HP").asInt()
);
case Portal -> result = new Portal(
new EntityID(EntityType.Portals, node.get("ID").asInt()),
codec.treeToValue(node.get("position"), IntVector2.class)
);
}
return result;
}
}