Godot 4 Final Fantasy 6 Data in LiteDB
Summary
TLDREl script proporciona una guía detallada sobre cómo utilizar la base de datos NoSQL LightDB para almacenar datos de Final Fantasy VI. Se discuten métodos para instalar LightDB y Newtonsoft.Json a través del Package Manager GUI o manualmente. Se destaca la importancia de definir clases C# que representen los campos en las colecciones de la base de datos, como habilidades, armas, armaduras y personajes, y cómo se utilizan para organizar y acceder a los datos. Además, se cubren técnicas para actualizar la base de datos y manejar colecciones, incluyendo la adición de personajes y habilidades, y se sugieren mejoras para la integridad de los datos y la eficiencia en la manipulación de la base de datos. El objetivo es crear una base sólida para el desarrollo de menús de batalla y la interfaz de usuario en futuras tutoriales.
Takeaways
- 📚 Utilizaremos Light DB para almacenar datos de Final Fantasy VI de manera más sencilla que en tutoriales anteriores.
- 📦 Necesitaremos instalar Light DB y Newtonsoft.Json, que son paquetes necesarios para la gestión de la base de datos y el manejo de JSON.
- 🗂 Crearemos variables para almacenar la base de datos y las colecciones, que son objetos para los cuales queremos mantener datos.
- 📝 Inicializaremos la base de datos y las colecciones con una ruta de archivo específica y una cadena de conexión segura.
- 🏢 Las clases C# definirán los campos en las colecciones de la base de datos, como ID, nombre y otros atributos específicos de Final Fantasy.
- 🔍 El uso de ID es crucial para la actualización de la base de datos, y se debe incluir en las clases para permitir consultas.
- 🔢 Utilizaremos enumeraciones (enums) para representar estados o características específicas, lo que mejora la integridad de los datos.
- 🛡️ Las armas y armaduras tendrán atributos específicos, como posibilidades de activación de habilidades o reducción de daño.
- 🧙 Los personajes tendrán una lista de habilidades y magias nativas, que se almacenarán en diccionarios para su fácil recuperación.
- 🎮 La gestión de la base de datos incluirá métodos para obtener y actualizar objetos, como personajes y habilidades, en la colección.
- 📈 Los métodos de manejo de la base de datos también se utilizarán para construir menús de batalla y UI en futuras tutoriales.
Q & A
¿Qué base de datos se utilizará para almacenar los datos de Final Fantasy VI?
-Se utilizará Light DB para almacenar los datos de Final Fantasy VI.
¿Qué paquete adicional se necesita además de Light DB?
-Además de Light DB, se necesita Newtonsoft.Json.
¿Cómo se instala un paquete en el proyecto?
-Se puede instalar un paquete utilizando la GUI del administrador de paquetes o agregando las referencias del paquete manualmente en el archivo del proyecto.
¿Qué es importante tener en cuenta al crear clases C# para la base de datos?
-Es importante incluir un campo de ID para Light DB, ya que se utiliza para consultar y actualizar la base de datos.
¿Cómo se definen las colecciones en la base de datos?
-Las colecciones se definen como cualquier tipo de objeto para el que se desee realizar un seguimiento de datos, y se inicializan creando una instancia de la base de datos y obteniendo la ruta de conexión.
¿Qué es una forma de representar las fortalezas y debilidades de los elementos en una clase?
-Se puede utilizar una enumeración (enum) para representar las fortalezas y debilidades de los elementos, lo que permite obtener el porcentaje de reducción o absorción de daño.
¿Cómo se obtiene un objeto de personaje de la base de datos?
-Se utiliza el método 'get character object', que toma el nombre del personaje, lo convierte en JSON, y luego lo deserializa en un objeto C# utilizando la biblioteca Newtonsoft.Json.
¿Cómo se actualiza un personaje en la base de datos?
-Se utiliza el método 'update character', que busca el personaje por su ID, y luego utiliza ese ID para actualizar los valores nuevos que se han pasado.
¿Cómo se obtiene el líder del grupo en la base de datos?
-Se utiliza una consulta que busca una propiedad donde 'is party leader' es verdadero, lo que debería devolver solo un resultado dado que solo hay un líder.
¿Cómo se obtiene la lista de habilidades mágicas de un personaje?
-Se utiliza el método 'get character magic', que toma el nombre del personaje y devuelve una lista de habilidades mágicas asociadas a ese personaje.
¿Cómo se agregan habilidades por defecto a la base de datos?
-Se utiliza un script que agrega objetos a la base de datos, asegurándose de que no existan registros duplicados y utilizando índices para garantizar la unicidad de los nombres de personajes.
Outlines
😀 Introducción a la base de datos LightDB y su uso en Final Fantasy VI
El primer párrafo introduce el uso de LightDB para almacenar datos de Final Fantasy VI. Se menciona que el tutorial será más sencillo que uno previo, ya que no implica la creación de objetos en una escena a través de C Sharp y GD Script. Se detalla el proceso de instalación del paquete LightDB y la necesidad de NewtonSoft.Json. Se habla de la inicialización de la base de datos y las colecciones, y cómo se definen las clases C Sharp para las colecciones de datos.
📚 Definición de clases y estructura de datos para objetos del juego
Este párrafo se enfoca en la definición de las clases C Sharp que representan los distintos elementos del juego, como habilidades, armas, armaduras y enemigos. Se discute la importancia del campo ID para la biblioteca LightDB y cómo se estructuran los datos para cada tipo de objeto, incluyendo habilidades especiales y estadísticas de personajes y enemigos.
🔍 Consultas y actualizaciones en la base de datos para el juego
El tercer párrafo cubre cómo realizar consultas y actualizaciones en la base de datos. Se describen métodos para obtener objetos de personaje, obtener estadísticas de personajes y habilidades, y cómo se usan las consultas de LightDB para encontrar y manipular datos específicos. Se destaca la importancia del ID para la actualización de registros en la base de datos.
🛠️ Procesos de inserción de datos y garantía de integridad en la base de datos
El último párrafo se centra en los procesos de inserción de datos en la base de datos, garantizando la integridad y la unicidad de los registros. Se detallan los métodos para agregar personajes, habilidades y otros objetos del juego a la base de datos, y cómo se utiliza el código para inicializar la base de datos con todos los objetos necesarios para el juego.
Mindmap
Keywords
💡Light DB
💡Final Fantasy VI
💡C#
💡Newtonsoft.Json
💡BSON
💡Clases de C#
💡Colecciones
💡Consultas
💡Serialización
💡Enums
💡Interfaces de usuario (UI)
Highlights
Utilización de Light DB para almacenar datos de Final Fantasy VI.
Instalación del paquete Light DB y Newtonsoft.Json a través del Package Manager GUI.
Creación de variables para la base de datos y las colecciones.
Inicialización de la base de datos y las colecciones con una ruta y una cadena de conexión segura.
Definición de clases C# para estructurar los campos en las colecciones de la base de datos.
Importancia del campo ID para la biblioteca Light DB y su uso en consultas y actualizaciones.
Creación de clases para habilidades, armas, armaduras y otros objetos del juego con diferentes campos relevantes.
Uso de enumeraciones (enums) para representar estados y elementos en lugar de texto para mejorar la eficiencia.
Implementación de diccionarios para almacenar probabilidades de habilidades y efectos.
Definición de la estructura de la zona de batalla y enemigos asociados.
Descripción de las propiedades y características de los personajes, incluyendo habilidades nativas y niveles.
Inclusión de métodos para recuperar objetos de personajes de la base de datos y convertirlos en objetos C#.
Actualización de objetos de personajes en la base de datos utilizando su ID único.
Consulta de información específica de personajes, como el líder del equipo o estadísticas de personajes.
Recuperación de la lista de habilidades mágicas de un personaje para su uso en menús de batalla.
Adición de habilidades y objetos predeterminados a la base de datos para cada personaje y colección.
Uso de diccionarios y enumeraciones para definir reducciones y absorciones de daño por elemento.
Preparación de la base de datos con todos los objetos necesarios para alimentar menús de batalla y UI en futuras tutoriales.
Transcripts
okay we're going to use light DB and
this time we're going to use it to store
Final Fantasy VI's data uh so I have a
other video on nosql and light DB using
that wiggado this one's going to be a
little bit simpler because we're not
going to pass from C sharp to GD script
and create objects uh in the scene that
hold the data we're just going to use
the database which is a little more
straightforward so we're going to need
light DB using light DB and again I have
that other nuget tutorial which we'll
show how to install a package so again
to install the package you can use the
package manager GUI put light DB we're
also going to need Newton's off Json
uh the alternative to that is in the Cs
project file you can put the new get
package references right in this item
group that's the manual way to add it
but the guis are easier so just make
sure you have the those things installed
because we're going to need them
so first we just need to have some
variables here that will store the
database and our collections the
database itself is just going to be a
single file you can pick the path for
that the collections are going to be any
type of object that we want to keep
track of data on we're just going to
create a collection for that
so here we're going to initialize the
database and initialize the collections
which right down here this is
essentially just getting the path and
then this connection string you have the
file name equal to the database path
that you choose where you're going to
write that file
I would put a password so no one can
edit your data with a text editor and
the connection type is just meant to
allow multiple things happening at once
I think but anyway just so this will
create the database new light database
in that connection string and if it's
already there it won't it won't bother
you know it's already done
initialize collections it's very much
the same thing we take that game
database that we just stored in there
you know again we have it in a variable
as well so that that object get
collection and the type of collection
which is going to be a c-sharp class
which I'll show you in a moment and then
the name of that collection that you
want anything you want
so first I want to talk about this the
c-sharp classes are going to define the
fields in the database collection so
we're going to look at one of those
first ability like we're starting with
here make sure you have this ID field
for light DB anyway this is important
so it's in that object ID comes from the
light DB library and name it this to
underscore ID because when you query
light DB it will return results but if
your class doesn't have this as a
property you won't be able to access it
and you do need that to update the
database
so we're going to go through some of
these uh classes just so I can show the
traits or fields that I'm storing on
each of them so if you're reproducing
this you know you get to see all the
abilities but I'm going to go kind of
quickly through them because a lot of
it's repetition and it gets kind of
boring so every one of these has its
name uh the ability class I made to kind
of be able to handle different types of
abilities meaning like a spell or some
of the monster special abilities or
whatever it may be so some of these
aren't going to get used for each
ability
but you know you got name power physical
some of these are called different
things in the different Final Fantasy uh
versions so if you if you need to pause
this just uh by all means
um I'm gonna explain a few of the ones
that might not be obvious but a lot of
this stuff is pretty obvious magic class
is just a string because I was lazy it's
just the black white or gray magic
that's going to come in handy for
organizing them the same way the
original game did and some of the you
know any time it has a random a chance
of happening like maybe your low energy
attacks you could store that in here
armors and weapons are gonna uh armor
and weapons are going to be pretty
straightforward too they just kind of
have the typical traits
um I figured we'd store the statuses
that it would induce or block in an enum
oh in a list excuse me the enums
actually enums are good for whenever
you're you have a set list of things
that that something can be basically if
you can avoid storing stuff as text than
any enum is a nice way to do that so
anytime you see that enums dot whatever
it's coming from this class that I
defined and I put in the statuses and uh
you know the Elementals just to fish
fish yummy fish all that stuff is there
um except the stuff I forgot so this
part here um
damage reduction and damage absorption a
lot of times I tried this method of
using an i dictionary where you put in
whatever the thing is and store it as an
uh integer or a float to give you a
number or percentage chance of that
thing happening or in this case maybe
percentage uh of damage reduction or
absorption that way when you're you know
if you're calling this in code you can
call the item by its name or by its enum
and it'll return the percentage so if
you're in you know you're doing a
calculation in the battle algorithm you
want to know like okay some jerk cast
fire on me check my equipment does my
equipment have fire you know et cetera
damage reduction so since we did armor
I'm just going to click on weapons next
because it's you know same idea I don't
think there's anything too different in
here name
the random Mobility cast like if you've
got aluminum and you and it casts Pearl
it'll you know any abilities that get
cast in there you can store here
Bushido capable is just uh science sword
Tech runic same you know you know same
deal for the most part same damage back
row like the locks weapons in the middle
of the game
battle area this needs to be more
complicated to be really be a true
representation but this will give us the
concept uh just the battle area name is
going to be like I'm going to name the
scene of the battle area and then this
is going to be a reference to the
enemies that should appear in that scene
really it might better be a list of
lists or something like that because
there are different sets of enemies but
I'm not going to go that deep at least
not yet so character that one's I'm
gonna have a few that are worth
explaining so like native magic
activation list same idea the dictionary
you put the magic spell name and what
level
it activates is going to get returned
from that dictionary you know hey does
that spell activate at such and such a
level
actually that one should probably be
turned around that one should be pass in
the level that I just got to and return
the spell that I learned yeah this also
needs to be turned around what it should
be is in string so you can pass in the
level and then hey seven learns Mantra
you know row position is going to be
integral obviously in battle strengths
and weaknesses down here
um I think that this doesn't necessarily
have to be a static value of course so
like if you're equipped you could
actually just store the characters
strengths and weaknesses as a result of
the equipment or you can store it on the
equipment but this is kind of what I was
thinking here
enemy is you would think a little
simpler but not really
um so a lot of this is the same so you
have the name level all of the typical
statistics no HP and we obviously need
the max depending on what level they're
at I don't know if you would need all
these for every enemy but actually I'm
sure you don't for every enemy but it's
here and you can always mess with it
later same thing here elements strong
and weak this one just to explain a
little bit this is more a correct way to
use string and then the float so like
sketch abilities so from uses sketch we
have a dictionary of the abilities uh
and then the percent chance that they're
going to happen what I was reading is
the control are the same abilities that
uh confuse does and so when you're in
control obviously you don't need the
percentage of that happening but in
confuse you would rage abilities of
course if GAO has the rage you know
which abilities same thing with lore
sometimes there are multiple items that
when you use Ragnarok on an enemy
that you can get and those also have a
percentage chance of turning into that
item and dropped installing you know
self-explanatory so a piece I want to
touch on here uh this is going to be uh
used in the next tutorial so in this
database Handler
um I'm going to touch on some of these
methods just to show how they work I do
want to go over some of these methods
these are going to come into play in the
next tutorial where we build out the
menu so I'm actually going to start with
this so get character objects so when
you query the database you're going to
get back that C sharp character object
when you query the character collection
of course so here we pass in the
character name and we need to convert
that to Json and lightdb has a built-in
way to convert it to Json which is what
this is doing here it's going to refer
to this this bson mapper Global to
document what I'm doing here is since
we're just taking the character name in
this is querying the character
collection for that character name and
then this light DB Json serializer that
converts it to Json that's kind of what
a light DB e offers is converting back
and forth to Json but I want the C sharp
object back so we can mess with the code
so that's what this does and obviously
this can be done to any of these this
character is just the one we're going to
use first so here we get the Json I just
split it out here to make it a little
easier to read and then this Json
convert
deserialize and then your class you know
that character class that's uh going to
use the Newton soft Json library and
then that's going to return the actual
c-sharp object so that way we can pass
in anything that we've stored in the
character collection we can pass in the
character's name and get back a C sharp
object where we can access any of these
properties update character I did cover
this in the other tutorial but really
quickly we're just going to query for
that make sure we have that ID again
that's why that that ID is important and
all those classes so you pass in that
modified character it's going to make
sure it's in the database and use that
ID property to update with the new
values that you passed in with that
object
so these we're going to use when we
start a battle so get party leader
um you know it's pretty straightforward
you're just querying where the property
which is one of those
um you know properties is is party lead
equals true there's only going to be one
hopefully this one uh get all the
characters in The Party
this dollar sign is just kind of the
light DB syntax like if you use light DB
Studio you'll see like it uses the
dollar sign to kind of Mark the object
and then dot property pretty much like
any language and equals true so get
character stat is string this is going
to pass in or take in rather a character
name and the name of a stat so like you
pass in lock you pass in HP then this
uses reflection to say get the property
info and then get the value of that
property and that way we can just simply
say give me this person's stat and now
we don't have to rewrite this every time
get character magic so one of the things
we're going to do in the next tutorial
is populate their a magic list and we're
going to use this to simplify that pass
in the character name and again the
um we're going to get a list back
because again the character magic list
the property is a list already
so all we have to do is get the Single
Character and get back that magic list
property and that will be a list of
abilities so first we're going to get
the character
and pay attention to this dollar sign
notation here so this might look a
little confusing if you're not familiar
with it this dollar sign is part of
light DB syntax that we were just
talking about this one outside the
quotes is a C sharp convention so that
within the quotes so you can pass in a
variable value
in the curly braces pay also close
attention to the single quotes on each
side of these because you're passing a
string into a database query you want to
have the single quotes around it
first to default is necessary here
because this method the find method
could return multiple so we have to
specify first or default because it
would break if you had multiple rows I
did have a little issue with the other
syntax here I'm not sure if that's a bug
or whatever but that's why I use this
way and it's going to come in handy
anyway so here we just initialize the
list make sure it's not null and set
that magic list that we're returning
equal to the result that character's
magic list and that's going to give us a
list of abilities now specifically
spells so to get the boring stuff out of
the way here last thing are these
database default abilities I'm going to
just look at the character ones because
they're basically all the same so first
here we have ADD character and you know
in other ones it'll be addability or
whatever it's just the same template
this query is the database to make sure
the character doesn't already exist if
it does just skips out of the method
insert the character and ensure index
make sure that the that it's Unique so
that you're you know you cannot have two
records in here with the same character
name that's what this is saying that
true is ensuring uniqueness as well as
being an index and then it just prints
out either way so what I'm doing with
these database default scripts is you
know basically code entering all of the
objects that I want to for one that's
just how light DB is mainly designed to
work it seems if I want to change
something I just delete the whole
database file when the game starts up
again it'll run through this as it is it
just you know this is what I get every
time everything's already in the
database so the ad characters I just
break them up into regions for each
character we just create an object as a
new character and it'll be whatever
c-sharp class that you made for that
collection so this would be ability
um weapon armor or whatever
and then open close the curly braces and
then you put all of the properties in
here
so this is mostly obvious so a couple
little things to note so the fine one is
actually kind of Overkill but it gives a
little database Integrity I guess
um so this actually finds the spell
in the database so you'd have to add the
abilities first which is important if
you're doing it this way but you don't
have to do that like you could just
create the ability and I'll show you an
example of that below one point of
Interest this native magic activation
list again the spell and what level
which I probably should turn around so
the other example here go I didn't add
all of his rage abilities as abilities
or enemies yet actually so if you're not
actually referencing the database you
know you create the object
right in the list here so you're
creating a new list create a new ability
and add it right into that unique
ability list that's going to be stored
you know as the character object's
unique ability list and so yeah that was
fun you can see all the different rages
that he has here and then you just to go
through the same process through each
character and for each object so that's
all these other ones do and like for
example I did a list of characters that
can equip each item this was kind of
tedious another kind of not terribly
often used cases Elemental damage
reductions so this uh what is this the
the Minerva so it does you know you can
store the Elementals as an enum which I
did here and then you uh just say for
each one of those the percentage of
damage reduction and again that's why
it's a dictionary because there's more
than one and you want to be able to get
the percentage when you're messing with
battle algorithms and also you can also
just see at the end of each of these
objects I I do add armor add character
whatever that's the method at the top it
just adds that variable that I just
created
you know this is the same process as the
you know
as this process except it's just
referencing the different collections so
we're not going to need all this
immediately but we're going to need some
of this in order to feed the battle
menus when we actually get into a battle
and then start making up the UI and
that's what will be next
Browse More Related Video
Curso de Android con Java: Almacenamiento mediante la base de datos SQLite
¿Como realizar una Base de Datos en Google Sheets? Base de datos en la nube Gratis
1. Conectar y Mostrar Datos con PHP y MySQL
Cómo CONECTAR un FORMULARIO con una BASE de DATOS en NOTION
Cómo crear tablas y relaciones en Microsoft Access
NO SQL: como se modelan las bases de datos no relacionales?
5.0 / 5 (0 votes)