Post by AlexP on Apr 6, 2018 12:50:17 GMT
If anyone is interested in an ugly but fast way to populate the Pokemon database I have made a script for that. The data I used are from the Game Master link given at the tutorial.
All the data in the json file will suffice for populating the database, except for the maxCP column in the SpeciesStats table which I decided to populate as the sum of Defense, Attack and Stamina.
You need 2 things the make the code work.
1. Import SimpleJSON for the json parsing.
2. Store the json data in the resources folder and change the name accordingly in the code so that it would load it.
Depending whether the the tables have been already created on your database or not some changes must be made on the two methods DatabaseDidLoad and CreateTables, just read the comments.
Any feedback or suggestions for improvement would be appreciated.
All the data in the json file will suffice for populating the database, except for the maxCP column in the SpeciesStats table which I decided to populate as the sum of Defense, Attack and Stamina.
You need 2 things the make the code work.
1. Import SimpleJSON for the json parsing.
2. Store the json data in the resources folder and change the name accordingly in the code so that it would load it.
Depending whether the the tables have been already created on your database or not some changes must be made on the two methods DatabaseDidLoad and CreateTables, just read the comments.
Any feedback or suggestions for improvement would be appreciated.
using UnityEngine;
using System.Collections;
using SimpleJSON;
using SQLite4Unity3d;
using System.Collections.Generic;
using ECS;
using System;
public class PokemonParser : MonoBehaviour
{
DatabaseController databaseController;
Dictionary<int, int> movesDictionary = new Dictionary<int, int>();
Dictionary<string, int> typesDictionary = new Dictionary<string, int>();
string jsonFileName = "pokemonStoredData";
// Use this for initialization
void Start()
{
databaseController = new DatabaseController("Pokemon.db");
var openFlags = SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite;
databaseController.Load(openFlags, DatabaseDidLoad);
}
void DatabaseDidLoad(DatabaseController sender)
{
TextAsset jsonData = Resources.Load<TextAsset>(jsonFileName);
var data = JSON.Parse(jsonData.ToString());
// Create the tables you can comment this line if you have already created the tables
CreateTables();
// Again if you have been following the tutorial the Component table will be populated
// you can uncomment this line if you have not already inserted the 4 rows for the Component table
//PopulateComponents();
// Store Pokemon to database
LoadPokemon(data);
// Store Pokemon types and multipliers to database
LoadTypes(data);
// Store all species stats
LoadSpeciesStats(data);
// Store all evolutions
LoadEvolutions(data);
// Store all encounter stats
LoadEncounterRate(data);
// Store all moves
LoadMoves(data);
LoadPokemonMoves(data);
databaseController.Save();
Debug.Log("Done");
}
void CreateTables()
{
// These three tables are already created on the example database if you are creating a database from scratch then you must create
// these too.
//databaseController.connection.CreateTable<Entity>();
//databaseController.connection.CreateTable<ECS.Component>();
//databaseController.connection.CreateTable<EntityComponent>();
databaseController.connection.CreateTable<Encounterable>();
databaseController.connection.CreateTable<Evolvable>();
databaseController.connection.CreateTable<Move>();
databaseController.connection.CreateTable<SpeciesStats>();
databaseController.connection.CreateTable<ECS.Type>();
databaseController.connection.CreateTable<TypeMultiplier>();
databaseController.Save();
}
void PopulateComponents()
{
ECS.Component speciesStats = new ECS.Component
{
name = "SpeciesStats",
description = "The base stats of the pokemon."
};
ECS.Component evolvable = new ECS.Component
{
name = "Evolvable",
description = "This component indicates what other Pokemon an entity can evolve into, " +
"after paying the candy cost. Not all Pokemon have this component."
};
ECS.Component encounterable = new ECS.Component
{
name = "Encounterable",
description = "This component indicates the chance that a given Pokemon can appear. " +
"Not all Pokemon will have this component either, such as Legendary pokemon like Mew."
};
ECS.Component move = new ECS.Component
{
name = "Move",
description = "This component holds the information of an attack such as its power or energy cost. "+
"By attaching one or more as a component to a Pokemon we can define its set of abilities."
};
databaseController.connection.GetMapping<ECS.Component>();
List<ECS.Component> components = new List<ECS.Component>();
components.Add(speciesStats);
components.Add(evolvable);
components.Add(encounterable);
components.Add(move);
databaseController.connection.InsertAll(components);
}
void LoadTypes(JSONNode data)
{
databaseController.connection.GetMapping<ECS.Type>();
List<ECS.Type> types = new List<ECS.Type>();
List<TypeMultiplier> typesMultiplier = new List<TypeMultiplier>();
Dictionary<string, int> typesIndices = new Dictionary<string, int>();
for (int i = 0; i < data["TypeScalarArray"].AsArray.Count; i++)
{
// Store here the types so it can be reused in other parts of the code
typesDictionary.Add(data["TypeScalarArray"][i], (i + 1));
string typeCodeName = data["TypeScalarArray"][i];
typesIndices.Add(typeCodeName, i + 1);
ECS.Type type = new ECS.Type
{
name = typeCodeName.Substring(13)
};
types.Add(type);
}
databaseController.connection.InsertAll(types);
databaseController.connection.GetMapping<TypeMultiplier>();
for (int i = 0; i < data["PokemonTypes"].AsArray.Count; i++)
{
JSONArray multipliers = data["PokemonTypes"][i]["TypeEffective"]["AttackScalar"].AsArray;
for (int j = 0; j < multipliers.Count; j++)
{
TypeMultiplier type = new TypeMultiplier
{
attack_type_id = typesIndices[data["PokemonTypes"][i]["TemplateId"]],
defend_type_id = (j + 1),
value = multipliers[j]
};
typesMultiplier.Add(type);
}
}
databaseController.connection.InsertAll(typesMultiplier);
}
void LoadPokemon(JSONNode data)
{
databaseController.connection.GetMapping<Entity>();
List<Entity> pokemons = new List<Entity>();
for (int i = 0; i < data["Pokemon"].AsArray.Count; i++)
{
string dataTemplate = data["Pokemon"][i]["TemplateId"].ToString();
string pokemonName = dataTemplate[15] +
dataTemplate.Substring(16, dataTemplate.Length - 17).ToLower();
pokemons.Add(new Entity { label = pokemonName });
}
databaseController.connection.InsertAll(pokemons);
}
void LoadEncounterRate(JSONNode data)
{
List<Encounterable> encounters = new List<Encounterable>();
List<EntityComponent> entityComponents = new List<EntityComponent>();
int componentDataId = 1;
for (int i = 0; i < data["Pokemon"].AsArray.Count; i++)
{
float encounterRate = data["Pokemon"][i]["Pokemon"]["Encounter"]["BaseCaptureRate"];
if (encounterRate > 0)
{
Encounterable encounter = new Encounterable
{
rate = Math.Round(encounterRate, 2)
};
EntityComponent entityComponent = new EntityComponent
{
entity_id = (i + 1),
component_id = Encounterable.ComponentID,
component_data_id = componentDataId
};
componentDataId++;
encounters.Add(encounter);
entityComponents.Add(entityComponent);
}
}
databaseController.connection.GetMapping<Encounterable>();
databaseController.connection.InsertAll(encounters);
databaseController.connection.GetMapping<EntityComponent>();
databaseController.connection.InsertAll(entityComponents);
}
void LoadSpeciesStats(JSONNode data)
{
List<SpeciesStats> speciesStats = new List<SpeciesStats>();
List<EntityComponent> entityComponents = new List<EntityComponent>();
for (int i = 0; i < data["Pokemon"].AsArray.Count; i++)
{
string dataTemplate = data["Pokemon"][i]["TemplateId"].ToString();
string name = dataTemplate[15] +
dataTemplate.Substring(16, dataTemplate.Length - 17).ToLower();
string typeA = data["Pokemon"][i]["Pokemon"]["Type1"];
string typeB = data["Pokemon"][i]["Pokemon"]["Type2"];
int stamina = data["Pokemon"][i]["Pokemon"]["Stats"]["BaseStamina"];
int attack = data["Pokemon"][i]["Pokemon"]["Stats"]["BaseAttack"];
int defense = data["Pokemon"][i]["Pokemon"]["Stats"]["BaseDefense"];
int maxCP = stamina + attack + defense;
SpeciesStats stats = new SpeciesStats
{
name = name,
typeA = typesDictionary[typeA],
attack = attack,
defense = defense,
stamina = stamina,
maxCP = maxCP
};
if (typeB != null)
{
stats.typeB = typesDictionary[typeB];
}
else
{
typeB = "-";
}
EntityComponent entityComponent = new EntityComponent
{
entity_id = (i + 1),
component_id = SpeciesStats.ComponentID,
component_data_id = (i + 1)
};
entityComponents.Add(entityComponent);
speciesStats.Add(stats);
}
databaseController.connection.GetMapping<SpeciesStats>();
databaseController.connection.InsertAll(speciesStats);
databaseController.connection.GetMapping<EntityComponent>();
databaseController.connection.InsertAll(entityComponents);
}
void LoadEvolutions(JSONNode data)
{
List<Evolvable> evolutions = new List<Evolvable>();
List<EntityComponent> entityComponents = new List<EntityComponent>();
int componentDataId = 1;
for (int i = 0; i < data["Pokemon"].AsArray.Count; i++)
{
if (data["Pokemon"][i]["Pokemon"]["Evolution"] != null)
{
if (data["Pokemon"][i]["Pokemon"]["Evolution"].AsArray.Count == 1)
{
Evolvable evolution = new Evolvable
{
entity_id = (i + 1),
cost = data["Pokemon"][i]["Pokemon"]["CandyToEvolve"]
};
EntityComponent entityComponent = new EntityComponent
{
entity_id = (i + 1),
component_id = Evolvable.ComponentID,
component_data_id = componentDataId
};
componentDataId++;
evolutions.Add(evolution);
entityComponents.Add(entityComponent);
}
}
}
databaseController.connection.GetMapping<Evolvable>();
databaseController.connection.InsertAll(evolutions);
databaseController.connection.GetMapping<EntityComponent>();
databaseController.connection.InsertAll(entityComponents);
}
void LoadMoves(JSONNode data)
{
List<Move> moves = new List<Move>();
for (int i = 0; i < data["Moves"].Count; i++)
{
string templateid = data["Moves"][i]["TemplateId"].ToString().Substring(2, 4);
movesDictionary.Add(Int32.Parse(templateid), i);
string[] moveCharacters = (data["Moves"][i]["TemplateId"].ToString().Split('_'));
string moveName = "";
for (int charIndex = 2; charIndex < moveCharacters.Length; charIndex++)
{
moveName += moveCharacters[charIndex][0] + moveCharacters[charIndex].Substring(1).ToLower() + " ";
}
moveName = moveName.Remove(moveName.Length - 2);
Move move = new Move
{
name = moveName,
power = data["Moves"][i]["Move"]["Power"],
duration = Math.Round((data["Moves"][i]["Move"]["DurationMs"].AsFloat * .001f), 2),
energy = data["Moves"][i]["Move"]["EnergyDelta"],
type = typesDictionary[data["Moves"][i]["Move"]["Type"]]
};
moves.Add(move);
}
databaseController.connection.GetMapping<Move>();
databaseController.connection.InsertAll(moves);
}
void LoadPokemonMoves(JSONNode data)
{
List<EntityComponent> entityComponents = new List<EntityComponent>();
for (int i = 0; i < data["Pokemon"].AsArray.Count; i++)
{
for (int moveIndex = 0; moveIndex < data["Pokemon"][i]["Pokemon"]["QuickMoves"].AsArray.Count; moveIndex++)
{
JSONArray quickMovesArray = data["Pokemon"][i]["Pokemon"]["QuickMoves"].AsArray;
int index = (int)quickMovesArray[moveIndex];
string[] moveCharacters = (data["Moves"][movesDictionary[index]]["TemplateId"].ToString().Split('_'));
string moveName = "";
for (int charIndex = 2; charIndex < moveCharacters.Length; charIndex++)
{
moveName += moveCharacters[charIndex][0] + moveCharacters[charIndex].Substring(1).ToLower() + " ";
}
moveName = moveName.Remove(moveName.Length - 2);
EntityComponent entityComponent = new EntityComponent
{
entity_id = (i + 1),
component_id = Move.ComponentID,
component_data_id = (movesDictionary[index] + 1)
};
entityComponents.Add(entityComponent);
}
for (int moveIndex = 0; moveIndex < data["Pokemon"][i]["Pokemon"]["CinematicMoves"].AsArray.Count; moveIndex++)
{
JSONArray cinematicMovesArray = data["Pokemon"][i]["Pokemon"]["CinematicMoves"].AsArray;
int index = (int)cinematicMovesArray[moveIndex];
EntityComponent entityComponent = new EntityComponent
{
entity_id = (i + 1),
component_id = Move.ComponentID,
component_data_id = (movesDictionary[index] + 1)
};
entityComponents.Add(entityComponent);
string[] moveCharacters = (data["Moves"][movesDictionary[index]]["TemplateId"].ToString().Split('_'));
string moveName = "";
for (int charIndex = 2; charIndex < moveCharacters.Length; charIndex++)
{
moveName += moveCharacters[charIndex][0] + moveCharacters[charIndex].Substring(1).ToLower() + " ";
}
moveName = moveName.Remove(moveName.Length - 2);
}
}
databaseController.connection.GetMapping<EntityComponent>();
databaseController.connection.InsertAll(entityComponents);
}
}