Add: Card Loading From Json

This commit is contained in:
rubenpirreram
2026-03-20 15:35:58 +01:00
parent 652b2a6516
commit fb63874607
2 changed files with 112 additions and 0 deletions
@@ -0,0 +1,76 @@
package it.polimi.ingsw.gc14.Model;
import com.google.gson.*;
import it.polimi.ingsw.gc14.Model.Cards.TribeCards.Characters.*;
import it.polimi.ingsw.gc14.Model.Cards.TribeCard;
import java.io.*;
import java.lang.reflect.Type;
import java.util.*;
public class DecksCreator {
public static List<TribeCard> loadDeck(String resourcePath) {
Gson gson = new Gson();
Type listType = new com.google.gson.reflect.TypeToken<List<CardDefinition>>(){}.getType();
try (InputStream is = DecksCreator.class.getResourceAsStream(resourcePath);
Reader reader = new InputStreamReader(is)) {
List<CardDefinition> definitions = gson.fromJson(reader, listType);
List<TribeCard> cards = new ArrayList<>();
for (CardDefinition def : definitions) {
cards.add(createCard(def));
}
return cards;
} catch (IOException e) {
throw new RuntimeException("Errore caricamento mazzo: " + resourcePath, e);
}
}
private static TribeCard createCard(CardDefinition def) {
int era = def.era;
int[] p = def.params.stream().mapToInt(d -> (int) Math.round((Float) d)).toArray();
return switch (def.type) {
case "Hunter" -> p.length == 0
? new Hunter(era, def.armed)
: new Hunter(era, def.armed, p[0]);
case "Builder" -> switch (p.length) {
case 2 -> new Builder(era, p[0], p[1]);
case 3 -> new Builder(era, p[0], p[1], p[2]);
default -> throw new IllegalArgumentException("Builder: parametri non validi");
};
case "Gatherers" -> switch (p.length) {
case 0 -> new Gatherers(era);
case 1 -> new Gatherers(era, p[0]);
default -> throw new IllegalArgumentException("Gatherers: parametri non validi");
};
case "Artist" -> switch (p.length) {
case 0 -> new Artist(era);
case 1 -> new Artist(era, p[0]);
default -> throw new IllegalArgumentException("Artist: parametri non validi");
};
case "Inventor" -> switch (p.length) {
case 1 -> new Inventor(era, p[0]);
case 2 -> new Inventor(era, p[0], p[1]);
default -> throw new IllegalArgumentException("Inventor: parametri non validi");
};
case "Shaman" -> switch (p.length) {
case 1 -> new Shaman(era, p[0]);
case 2 -> new Shaman(era, p[0], p[1]);
default -> throw new IllegalArgumentException("Shaman: parametri non validi");
};
default -> throw new IllegalArgumentException("Tipo sconosciuto: " + def.type);
};
}
private static class CardDefinition {
String type;
int era;
boolean armed;
List<Object> params; // Object per gestire boolean e int misti
}
}