Ya gestiona correctamente los datos online para diferentes usuarios

This commit is contained in:
2023-10-09 22:20:34 +02:00
parent 9b265c6cca
commit c835f943b5
12 changed files with 151 additions and 61 deletions

View File

@@ -2,15 +2,13 @@
#include <iostream> #include <iostream>
// Constructor // Constructor
Cheevos::Cheevos(Screen *screen, options_t *options, std::string file) Cheevos::Cheevos(Screen *screen, options_t *options, std::string file, Online *online)
{ {
// Copia la dirección de los objetos // Copia la dirección de los objetos
this->options = options; this->options = options;
this->screen = screen; this->screen = screen;
this->file = file; this->file = file;
this->online = online;
// Crea objetos
online = new Online(options);
// Inicializa los logros // Inicializa los logros
init(); init();
@@ -29,14 +27,13 @@ Cheevos::~Cheevos()
save(); save();
cheevos.clear(); cheevos.clear();
// Libera memoria
delete online;
} }
// Inicializa los logros // Inicializa los logros
void Cheevos::init() void Cheevos::init()
{ {
cheevos.clear();
cheevos_t c; cheevos_t c;
c.completed = false; c.completed = false;
c.valid = true; c.valid = true;
@@ -303,9 +300,19 @@ void Cheevos::loadFromServer()
{ {
std::string cheevosData = online->getCheevos(); std::string cheevosData = online->getCheevos();
// Gestiona los posibles errores
const bool noData = cheevosData == "" ? true : false;
const bool incompleteData = cheevosData.length() != cheevos.size() ? true : false;
if (noData || incompleteData)
{
init();
return;
}
// Asigna los valores leídos desde el servidor
for (int i = 0; i < (int)cheevosData.length(); ++i) for (int i = 0; i < (int)cheevosData.length(); ++i)
{ {
bool value = cheevosData.substr(i, 1) == "1" ? true : false; bool value = cheevosData.at(i) == '1' ? true : false;
cheevos.at(i).completed = value; cheevos.at(i).completed = value;
} }
} }
@@ -314,7 +321,7 @@ void Cheevos::loadFromServer()
void Cheevos::saveToServer() void Cheevos::saveToServer()
{ {
std::string cheevosData = ""; std::string cheevosData = "";
// cheevos[2].completed = true;
for (auto cheevo : cheevos) for (auto cheevo : cheevos)
{ {
std::string data = cheevo.completed ? "1" : "0"; std::string data = cheevo.completed ? "1" : "0";
@@ -322,4 +329,10 @@ void Cheevos::saveToServer()
} }
online->setCheevos(cheevosData); online->setCheevos(cheevosData);
}
// Vuelve a cargar los logros desde el origen
void Cheevos::reload()
{
load();
} }

View File

@@ -58,7 +58,7 @@ private:
public: public:
// Constructor // Constructor
Cheevos(Screen *screen, options_t *options, std::string file); Cheevos(Screen *screen, options_t *options, std::string file, Online *online);
// Destructor // Destructor
~Cheevos(); ~Cheevos();
@@ -80,6 +80,9 @@ public:
// Devuelve el número total de logros // Devuelve el número total de logros
int count(); int count();
// Vuelve a cargar los logros desde el origen
void reload();
}; };
#endif #endif

View File

@@ -62,8 +62,8 @@ Director::Director(int argc, char *argv[])
screen = new Screen(window, renderer, asset, options); screen = new Screen(window, renderer, asset, options);
screen->setBorderColor(borderColor); screen->setBorderColor(borderColor);
debug = new Debug(renderer, screen, asset); debug = new Debug(renderer, screen, asset);
online = new Online(options);
music = JA_LoadMusic(asset->get("title.ogg").c_str()); music = JA_LoadMusic(asset->get("title.ogg").c_str());
online = new Online(options);
} }
Director::~Director() Director::~Director()
@@ -1762,7 +1762,7 @@ void Director::runTitle()
JA_PlayMusic(music); JA_PlayMusic(music);
} }
loadResources(section); loadResources(section);
title = new Title(renderer, screen, resource, asset, input, options, section); title = new Title(renderer, screen, resource, asset, input, online, options, section);
title->run(); title->run();
delete title; delete title;
resource->free(); resource->free();
@@ -1847,7 +1847,7 @@ void Director::runGame()
} }
JA_StopMusic(); JA_StopMusic();
loadResources(section); loadResources(section);
game = new Game(renderer, screen, resource, asset, options, input, section, debug); game = new Game(renderer, screen, resource, asset, online, options, input, section, debug);
game->run(); game->run();
delete game; delete game;
resource->free(); resource->free();

View File

@@ -41,11 +41,11 @@ private:
Intro *intro; // Objeto para gestionar la introducción del juego Intro *intro; // Objeto para gestionar la introducción del juego
Credits *credits; // Objeto para gestionar los creditos del juego Credits *credits; // Objeto para gestionar los creditos del juego
Demo *demo; // Objeto para gestionar el modo demo, en el que se ven pantallas del juego Demo *demo; // Objeto para gestionar el modo demo, en el que se ven pantallas del juego
Online *online; // Objeto para gestionar la lectura y escritura de datos en el servidor remoto
Ending *ending; // Objeto para gestionar el final del juego Ending *ending; // Objeto para gestionar el final del juego
Ending2 *ending2; // Objeto para gestionar el final del juego Ending2 *ending2; // Objeto para gestionar el final del juego
GameOver *gameOver; // Objeto para gestionar el final de la partida GameOver *gameOver; // Objeto para gestionar el final de la partida
Debug *debug; // Objeto para getsionar la información de debug Debug *debug; // Objeto para getsionar la información de debug
Online *online; // Objeto para gestionar la lectura y escritura de datos en el servidor remoto
struct options_t *options; // Variable con todas las opciones del programa struct options_t *options; // Variable con todas las opciones del programa
section_t *section; // Sección y subsección actual del programa; section_t *section; // Sección y subsección actual del programa;

View File

@@ -2,12 +2,13 @@
#include <iostream> #include <iostream>
// Constructor // Constructor
Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options, Input *input, section_t *section, Debug *debug) Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Online *online, options_t *options, Input *input, section_t *section, Debug *debug)
{ {
// Copia los punteros // Copia los punteros
this->resource = resource; this->resource = resource;
this->renderer = renderer; this->renderer = renderer;
this->asset = asset; this->asset = asset;
this->online = online;
this->screen = screen; this->screen = screen;
this->input = input; this->input = input;
this->debug = debug; this->debug = debug;
@@ -30,7 +31,7 @@ Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as
#endif #endif
// Crea los objetos // Crea los objetos
cheevos = new Cheevos(screen, options, asset->get("cheevos.bin")); cheevos = new Cheevos(screen, options, asset->get("cheevos.bin"), online);
scoreboard = new ScoreBoard(renderer, resource, asset, options, &board); scoreboard = new ScoreBoard(renderer, resource, asset, options, &board);
itemTracker = new ItemTracker(); itemTracker = new ItemTracker();
roomTracker = new RoomTracker(); roomTracker = new RoomTracker();
@@ -43,7 +44,7 @@ Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *as
text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer);
music = JA_LoadMusic(asset->get("game.ogg").c_str()); music = JA_LoadMusic(asset->get("game.ogg").c_str());
deathSound = JA_LoadSound(asset->get("death.wav").c_str()); deathSound = JA_LoadSound(asset->get("death.wav").c_str());
stats = new Stats(asset->get("stats.csv"), asset->get("stats_buffer.csv"), options); stats = new Stats(asset->get("stats.csv"), asset->get("stats_buffer.csv"), options, online);
// Crea la textura para poner el nombre de la habitación // Crea la textura para poner el nombre de la habitación
roomNameTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, text->getCharacterSize() * 2); roomNameTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, text->getCharacterSize() * 2);

View File

@@ -19,6 +19,7 @@
#include "room.h" #include "room.h"
#include "scoreboard.h" #include "scoreboard.h"
#include "stats.h" #include "stats.h"
#include "online.h"
#ifndef GAME_H #ifndef GAME_H
#define GAME_H #define GAME_H
@@ -37,6 +38,7 @@ private:
Asset *asset; // Objeto con la ruta a todos los ficheros de recursos Asset *asset; // Objeto con la ruta a todos los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada Input *input; // Objeto pata gestionar la entrada
Text *text; // Objeto para los textos del juego Text *text; // Objeto para los textos del juego
Online *online; // Objeto para gestionar la lectura y escritura de datos en el servidor remoto
ScoreBoard *scoreboard; // Objeto encargado de gestionar el marcador ScoreBoard *scoreboard; // Objeto encargado de gestionar el marcador
Cheevos *cheevos; // Objeto encargado de gestionar los logros del juego Cheevos *cheevos; // Objeto encargado de gestionar los logros del juego
Resource *resource; // Objeto con los recursos Resource *resource; // Objeto con los recursos
@@ -151,7 +153,7 @@ private:
public: public:
// Constructor // Constructor
Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options, Input *input, section_t *section, Debug *debug); Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Online *online, options_t *options, Input *input, section_t *section, Debug *debug);
// Destructor // Destructor
~Game(); ~Game();

View File

@@ -9,36 +9,63 @@ Online::Online(options_t *options)
{ {
this->options = options; this->options = options;
if (options->console)
{
std::cout << "ONLINE object created\n"
<< std::endl;
}
allData = ""; allData = "";
statsData = ""; statsData = "";
cheevosData = ""; cheevosData = "";
STATS_FLAG_INI = "STATS_FLAG_INI"; STATS_FLAG_INI = ";STATS_FLAG_INI;";
STATS_FLAG_END = "STATS_FLAG_END"; STATS_FLAG_END = ";STATS_FLAG_END;";
CHEEVOS_FLAG_INI = "CHEEVOS_FLAG_INI"; CHEEVOS_FLAG_INI = ";CHEEVOS_FLAG_INI;";
CHEEVOS_FLAG_END = "CHEEVOS_FLAG_END"; CHEEVOS_FLAG_END = ";CHEEVOS_FLAG_END;";
getAllData(); dataCached = false;
std::cout << "allData: " << allData << std::endl; dataSaved = "";
std::cout << "statsData: " << statsData << std::endl; getData();
std::cout << "cheevosData: " << cheevosData << std::endl;
} }
// Destructor // Destructor
Online::~Online() Online::~Online()
{ {
sendData();
} }
// Obtiene todos los datos y los coloca en sus respectivas variables // Obtiene todos los datos y los coloca en sus respectivas variables
void Online::getAllData() void Online::getData()
{ {
if (!options->online.enabled) // Si el usuario es distinto del que hay cacheado, marca la cache como invalida y borra los datos
if (jailerID.compare(options->online.jailerID) != 0)
{ {
allData = jscore::getUserData(options->online.gameID, options->online.jailerID); dataCached = false;
clearData();
} }
// Si los datos ya estan cacheados, no hace nada
if (dataCached)
{
return;
}
// Si las opciones online estan activadas, obtiene los datos desde el servidor
if (options->online.enabled)
{
allData = jscore::getUserData(options->online.gameID, options->online.jailerID);
jailerID = options->online.jailerID;
}
// Si no ha podido obtener los datos del servidor, no hace nada
if (allData.length() == 0) if (allData.length() == 0)
{ {
if (options->console)
{
std::cout << "NO DATA\n"
<< std::endl;
}
return; return;
} }
@@ -59,44 +86,84 @@ void Online::getAllData()
// Obtiene la cadena con los logros // Obtiene la cadena con los logros
if (cheevosIni != std::string::npos && cheevosEnd != std::string::npos) if (cheevosIni != std::string::npos && cheevosEnd != std::string::npos)
cheevosData = allData.substr(cheevosIni, cheevosDataLenght); cheevosData = allData.substr(cheevosIni, cheevosDataLenght);
dataCached = true;
printData("LOADING");
} }
// Coloca todos los datos desde las variables en la cadena allData // Coloca todos los datos desde las variables en la cadena allData
void Online::setAllData() void Online::sendData()
{ {
allData = STATS_FLAG_INI + statsData + STATS_FLAG_END + CHEEVOS_FLAG_INI + cheevosData + CHEEVOS_FLAG_END; allData = STATS_FLAG_INI + statsData + STATS_FLAG_END + CHEEVOS_FLAG_INI + cheevosData + CHEEVOS_FLAG_END;
if (options->online.enabled) const bool newData = allData.compare(dataSaved) == 0 ? false : true;
if (options->online.enabled && newData)
{ {
jscore::setUserData(options->online.gameID, options->online.jailerID, allData); jscore::setUserData(options->online.gameID, options->online.jailerID, allData);
dataSaved = allData;
printData("SAVING");
} }
} }
// Obtiene las estadísticas guardadas en el servidor // Obtiene las estadísticas guardadas en el servidor
std::string Online::getStats() std::string Online::getStats()
{ {
getAllData(); getData();
return statsData; return statsData;
} }
// Guarda las estadísticas en el servidor // Guarda las estadísticas en el servidor
void Online::setStats(std::string data) void Online::setStats(std::string data)
{ {
getAllData(); // getData();
statsData = data; statsData = data;
setAllData(); // setAllData();
} }
// Obtiene los logros guardadas en el servidor // Obtiene los logros guardadas en el servidor
std::string Online::getCheevos() std::string Online::getCheevos()
{ {
getAllData(); getData();
return cheevosData; return cheevosData;
} }
// Guarda los logros en el servidor // Guarda los logros en el servidor
void Online::setCheevos(std::string data) void Online::setCheevos(std::string data)
{ {
getAllData(); getData();
cheevosData = data; cheevosData = data;
setAllData(); sendData();
}
// Imprime información de diagnóstico
void Online::printData(std::string text)
{
static int counter = 0;
if (options->console)
{
std::cout << "mode is: " << text << " (" << counter << ")" << std::endl;
std::cout << "allData: " << allData << std::endl;
std::cout << "statsData: " << statsData << std::endl;
std::cout << "cheevosData: " << cheevosData << std::endl;
std::cout << "options->online.jailerID: " << options->online.jailerID << std::endl;
std::cout << "options->online.enabled: " << options->online.enabled << std::endl;
std::cout << std::endl;
counter++;
}
}
// Elimina los datos del servidor
void Online::eraseServerData()
{
if (options->online.enabled)
{
jscore::setUserData(options->online.gameID, options->online.jailerID, "");
}
}
// Limpia los datos almacenados en la caché
void Online::clearData()
{
allData = "";
statsData = "";
cheevosData = "";
} }

View File

@@ -23,11 +23,19 @@ private:
std::string CHEEVOS_FLAG_INI; // Marca para establecer el inicio de los logros std::string CHEEVOS_FLAG_INI; // Marca para establecer el inicio de los logros
std::string CHEEVOS_FLAG_END; // Marca para establecer el final de los logros std::string CHEEVOS_FLAG_END; // Marca para establecer el final de los logros
// Obtiene todos los datos y los coloca en sus respectivas variables bool dataCached; // Indica si se han obtenido los datos del servidor
void getAllData(); std::string dataSaved; // Contiene los datos que se han salvado en el servidor
std::string jailerID; // ID del usuario cuyos datos estan cacheados
// Coloca todos los datos desde las variables en la cadena allData
void setAllData(); // Imprime información de diagnóstico
void printData(std::string text);
// Elimina los datos del servidor
void eraseServerData();
// Limpia los datos almacenados en la caché
void clearData();
public: public:
// Constructor // Constructor
@@ -36,6 +44,12 @@ public:
// Destructor // Destructor
~Online(); ~Online();
// Obtiene todos los datos y los coloca en sus respectivas variables
void getData();
// Coloca todos los datos desde las variables en la cadena allData
void sendData();
// Obtiene las estadísticas guardadas en el servidor // Obtiene las estadísticas guardadas en el servidor
std::string getStats(); std::string getStats();

View File

@@ -6,17 +6,15 @@
#include <sstream> #include <sstream>
// Constructor // Constructor
Stats::Stats(std::string file, std::string buffer, options_t *options) Stats::Stats(std::string file, std::string buffer, options_t *options, Online *online)
{ {
this->options = options; this->options = options;
this->online = online;
bufferPath = buffer; bufferPath = buffer;
filePath = file; filePath = file;
bufferList.clear(); bufferList.clear();
list.clear(); list.clear();
dictionary.clear(); dictionary.clear();
// Crea objetos
online = new Online(options);
} }
// Destructor // Destructor
@@ -36,9 +34,6 @@ Stats::~Stats()
bufferList.clear(); bufferList.clear();
list.clear(); list.clear();
dictionary.clear(); dictionary.clear();
// Libera memoria
delete options;
} }
// Inicializador // Inicializador
@@ -334,10 +329,4 @@ void Stats::updateListFromBuffer()
saveToFile(bufferPath, bufferList); saveToFile(bufferPath, bufferList);
saveToFile(filePath, list); saveToFile(filePath, list);
}
// Limpia los datos del servidor
void Stats::eraseServerData()
{
jscore::setUserData(options->online.gameID, options->online.jailerID, "");
} }

View File

@@ -62,12 +62,9 @@ private:
// Vuelca los datos del buffer en la lista de estadisticas // Vuelca los datos del buffer en la lista de estadisticas
void updateListFromBuffer(); void updateListFromBuffer();
// Limpia los datos del servidor
void eraseServerData();
public: public:
// Constructor // Constructor
Stats(std::string file, std::string buffer, options_t *options); Stats(std::string file, std::string buffer, options_t *options, Online *online);
// Destructor // Destructor
~Stats(); ~Stats();

View File

@@ -1,7 +1,7 @@
#include "title.h" #include "title.h"
// Constructor // Constructor
Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section) Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, Online *online, options_t *options, section_t *section)
{ {
// Copia la dirección de los objetos // Copia la dirección de los objetos
this->resource = resource; this->resource = resource;
@@ -9,12 +9,13 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *
this->screen = screen; this->screen = screen;
this->asset = asset; this->asset = asset;
this->input = input; this->input = input;
this->online = online;
this->options = options; this->options = options;
this->section = section; this->section = section;
// Reserva memoria para los punteros // Reserva memoria para los punteros
eventHandler = new SDL_Event(); eventHandler = new SDL_Event();
cheevos = new Cheevos(screen, options, asset->get("cheevos.bin")); cheevos = new Cheevos(screen, options, asset->get("cheevos.bin"), online);
if (options->palette == p_zxspectrum) if (options->palette == p_zxspectrum)
{ {
texture = resource->getTexture("loading_screen_color.png"); texture = resource->getTexture("loading_screen_color.png");
@@ -118,6 +119,7 @@ void Title::checkEvents()
case SDL_SCANCODE_3: case SDL_SCANCODE_3:
runEnterID(); runEnterID();
cheevos->reload();
fillTexture(); fillTexture();
createCheevosTexture(); createCheevosTexture();
break; break;

View File

@@ -11,6 +11,7 @@
#include "jail_engine/sprite.h" #include "jail_engine/sprite.h"
#include "jail_engine/text.h" #include "jail_engine/text.h"
#include "jail_engine/utils.h" #include "jail_engine/utils.h"
#include "online.h"
#include "const.h" #include "const.h"
#include <vector> #include <vector>
@@ -33,6 +34,7 @@ private:
Resource *resource; // Objeto con los recursos Resource *resource; // Objeto con los recursos
Asset *asset; // Objeto con los ficheros de recursos Asset *asset; // Objeto con los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada Input *input; // Objeto pata gestionar la entrada
Online *online; // Objeto para gestionar la lectura y escritura de datos en el servidor remoto
SDL_Event *eventHandler; // Manejador de eventos SDL_Event *eventHandler; // Manejador de eventos
Texture *texture; // Textura con los graficos Texture *texture; // Textura con los graficos
Sprite *sprite; // Sprite para manejar la textura Sprite *sprite; // Sprite para manejar la textura
@@ -103,7 +105,7 @@ private:
public: public:
// Constructor // Constructor
Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section); Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, Online *online, options_t *options, section_t *section);
// Destructor // Destructor
~Title(); ~Title();