Eliminat TOT el online i merdes

This commit is contained in:
2025-02-20 12:07:28 +01:00
parent 9cb57e2ff2
commit e23f6b5ed9
20 changed files with 30 additions and 1235 deletions

View File

@@ -60,7 +60,7 @@ target_link_libraries(${PROJECT_NAME} ${LIBS})
# Configuración específica para cada plataforma # Configuración específica para cada plataforma
if(WIN32) if(WIN32)
target_compile_definitions(${PROJECT_NAME} PRIVATE WINDOWS_BUILD) target_compile_definitions(${PROJECT_NAME} PRIVATE WINDOWS_BUILD)
target_link_libraries(${PROJECT_NAME} mingw32 opengl32 gdi32 winmm imm32 ole32 version) target_link_libraries(${PROJECT_NAME} mingw32 opengl32 ws2_32)
elseif(APPLE) elseif(APPLE)
set(LIBS ${LIBS} "-framework OpenGL") set(LIBS ${LIBS} "-framework OpenGL")
target_compile_definitions(${PROJECT_NAME} PRIVATE MACOS_BUILD) target_compile_definitions(${PROJECT_NAME} PRIVATE MACOS_BUILD)

View File

@@ -12,12 +12,12 @@ linuxRelease = $(executable)-$(version)-linux.tar.gz
windows: windows:
@echo off @echo off
g++ $(source) -std=c++11 -Wall -Os -lmingw32 -lws2_32 -lSDL2main -lSDL2 -ffunction-sections -fdata-sections -Wl,--gc-sections -static-libstdc++ -Wl,-subsystem,windows -o "$(executable).exe" g++ $(source) -std=c++11 -Wall -Os -lmingw32 -lws2_32 -lSDL2main -lSDL2 -lopengl32 -ffunction-sections -fdata-sections -Wl,--gc-sections -static-libstdc++ -Wl,-subsystem,windows -o "$(executable).exe"
strip -s -R .comment -R .gnu.version "$(executable).exe" --strip-unneeded strip -s -R .comment -R .gnu.version "$(executable).exe" --strip-unneeded
windows_debug: windows_debug:
@echo off @echo off
g++ $(source) -D DEBUG -std=c++11 -Wall -Os -lmingw32 -lws2_32 -lSDL2main -lSDL2 -ffunction-sections -fdata-sections -Wl,--gc-sections -static-libstdc++ -Wl,-subsystem,windows -o "$(executable)_debug.exe" g++ $(source) -D DEBUG -std=c++11 -Wall -Os -lmingw32 -lws2_32 -lSDL2main -lSDL2 -lopengl32 -ffunction-sections -fdata-sections -Wl,--gc-sections -static-libstdc++ -Wl,-subsystem,windows -o "$(executable)_debug.exe"
strip -s -R .comment -R .gnu.version "$(executable)_debug.exe" --strip-unneeded strip -s -R .comment -R .gnu.version "$(executable)_debug.exe" --strip-unneeded
windows_release: windows_release:
@@ -38,7 +38,7 @@ windows_release:
powershell Copy-Item "release\*.dll" -Destination "$(releaseFolder)" powershell Copy-Item "release\*.dll" -Destination "$(releaseFolder)"
# Build # Build
g++ $(source) -std=c++11 -Wall -Os -lmingw32 -lws2_32 -lSDL2main -lSDL2 -ffunction-sections -fdata-sections -Wl,--gc-sections -static-libstdc++ -Wl,-subsystem,windows -o "$(releaseFolder)/$(executable).exe" g++ $(source) -std=c++11 -Wall -Os -lmingw32 -lws2_32 -lSDL2main -lSDL2 -lopengl32 -ffunction-sections -fdata-sections -Wl,--gc-sections -static-libstdc++ -Wl,-subsystem,windows -o "$(releaseFolder)/$(executable).exe"
strip -s -R .comment -R .gnu.version "$(releaseFolder)/$(executable).exe" --strip-unneeded strip -s -R .comment -R .gnu.version "$(releaseFolder)/$(executable).exe" --strip-unneeded
# Create ZIP # Create ZIP

View File

@@ -2,13 +2,12 @@
#include <iostream> #include <iostream>
// Constructor // Constructor
Cheevos::Cheevos(Screen *screen, options_t *options, std::string file, Online *online) Cheevos::Cheevos(Screen *screen, options_t *options, std::string file)
{ {
// 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;
// Inicializa los logros // Inicializa los logros
init(); init();
@@ -164,28 +163,16 @@ void Cheevos::enable(bool value)
// Carga el estado de los logros // Carga el estado de los logros
void Cheevos::load() void Cheevos::load()
{ {
if (options->online.enabled) // Carga el estado de los logros desde un fichero
{ // Carga el estado de los logros desde el servidor online
loadFromServer();
}
else
{ // Carga el estado de los logros desde un fichero
loadFromFile(); loadFromFile();
} }
}
// Guarda el estado de los logros // Guarda el estado de los logros
void Cheevos::save() void Cheevos::save()
{ {
if (options->online.enabled) // Guarda el estado de los logros en un fichero
{ // Guarda el estado de los logros en el servidor online
saveToServer();
}
else
{ // Guarda el estado de los logros en un fichero
saveToFile(); saveToFile();
} }
}
// Carga el estado de los logros desde un fichero // Carga el estado de los logros desde un fichero
void Cheevos::loadFromFile() void Cheevos::loadFromFile()
@@ -295,43 +282,6 @@ int Cheevos::count()
return cheevos.size(); return cheevos.size();
} }
// Carga el estado de los logros desde el servidor online
void Cheevos::loadFromServer()
{
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)
{
// Pone todos los logros en incompleto
init();
return;
}
// Asigna los valores leídos desde el servidor
for (int i = 0; i < (int)cheevosData.length(); ++i)
{
bool value = cheevosData.at(i) == '1' ? true : false;
cheevos.at(i).completed = value;
}
}
// Guarda el estado de los logros en el servidor online
void Cheevos::saveToServer()
{
std::string cheevosData = "";
// cheevos[2].completed = true;
for (auto cheevo : cheevos)
{
std::string data = cheevo.completed ? "1" : "0";
cheevosData.append(data);
}
online->setCheevos(cheevosData);
}
// Vuelve a cargar los logros desde el origen // Vuelve a cargar los logros desde el origen
void Cheevos::reload() void Cheevos::reload()
{ {

View File

@@ -2,7 +2,6 @@
#include <SDL2/SDL.h> #include <SDL2/SDL.h>
#include "jail_engine/screen.h" #include "jail_engine/screen.h"
#include "jail_engine/utils.h" #include "jail_engine/utils.h"
#include "online.h"
#include <string> #include <string>
#include <vector> #include <vector>
@@ -25,7 +24,6 @@ private:
// Punteros y objetos // Punteros y objetos
Screen *screen; // Objeto encargado de dibujar en pantalla Screen *screen; // Objeto encargado de dibujar en pantalla
options_t *options; // Puntero a las opciones del juego options_t *options; // Puntero a las opciones del juego
Online *online; // Objeto para gestionar la lectura y escritura de datos en el servidor remoto
// Variables // Variables
std::vector<cheevos_t> cheevos; // Listado de logros std::vector<cheevos_t> cheevos; // Listado de logros
@@ -50,15 +48,9 @@ private:
// Guarda el estado de los logros en un fichero // Guarda el estado de los logros en un fichero
void saveToFile(); void saveToFile();
// Carga el estado de los logros desde el servidor online
void loadFromServer();
// Guarda el estado de los logros en el servidor online
void saveToServer();
public: public:
// Constructor // Constructor
Cheevos(Screen *screen, options_t *options, std::string file, Online *online); Cheevos(Screen *screen, options_t *options, std::string file);
// Destructor // Destructor
~Cheevos(); ~Cheevos();

View File

@@ -1,4 +1,3 @@
#include "jail_engine/jscore.h"
#include "jail_engine/utils.h" #include "jail_engine/utils.h"
#include "director.h" #include "director.h"
#include <errno.h> #include <errno.h>
@@ -63,10 +62,6 @@ Director::Director(int argc, char *argv[])
screen->setBorderColor(borderColor); screen->setBorderColor(borderColor);
debug = new Debug(renderer, screen, asset); debug = new Debug(renderer, screen, asset);
music = JA_LoadMusic(asset->get("title.ogg").c_str()); music = JA_LoadMusic(asset->get("title.ogg").c_str());
online = new Online(options);
// Inicializa los servicios online
initOnline();
} }
Director::~Director() Director::~Director()
@@ -82,7 +77,6 @@ Director::~Director()
delete screen; delete screen;
delete debug; delete debug;
delete resource; delete resource;
delete online;
JA_DeleteMusic(music); JA_DeleteMusic(music);
SDL_DestroyRenderer(renderer); SDL_DestroyRenderer(renderer);
@@ -90,29 +84,6 @@ Director::~Director()
SDL_Quit(); SDL_Quit();
} }
// Inicializa los servicios online
void Director::initOnline()
{
if (options->online.jailerID == "")
{ // Jailer ID no definido
options->online.enabled = false;
}
else
{ // Jailer ID iniciado
if (options->online.enabled)
{ // Establece el servidor y el puerto
jscore::init(options->online.server, options->online.port);
options->online.sessionEnabled = true;
const std::string caption = options->online.jailerID + " IS LOGGED IN";
screen->showNotification(caption);
if (options->console)
{
std::cout << caption << std::endl;
}
}
}
}
// Crea e inicializa las opciones del programa // Crea e inicializa las opciones del programa
void Director::initOptions() void Director::initOptions()
{ {
@@ -156,18 +127,6 @@ void Director::initOptions()
options->stats.rooms = 0; options->stats.rooms = 0;
options->stats.items = 0; options->stats.items = 0;
// Opciones online
options->online.enabled = false;
options->online.sessionEnabled = false;
options->online.server = "jaildoctor.duckdns.org";
options->online.port = 9911;
#ifdef DEBUG
options->online.gameID = "jaildoctors_dilemma_debug";
#else
options->online.gameID = "jaildoctors_dilemma";
#endif
options->online.jailerID = "";
// Opciones de las notificaciones // Opciones de las notificaciones
options->notifications.posV = pos_top; options->notifications.posV = pos_top;
options->notifications.posH = pos_left; options->notifications.posH = pos_left;
@@ -383,12 +342,6 @@ bool Director::saveConfig()
file << "borderHeight=" + std::to_string(options->borderHeight) + "\n"; file << "borderHeight=" + std::to_string(options->borderHeight) + "\n";
file << "palette=" + std::to_string(options->palette) + "\n"; file << "palette=" + std::to_string(options->palette) + "\n";
file << "\n## ONLINE OPTIONS\n";
file << "enabled=" + boolToString(options->online.enabled) + "\n";
file << "server=" + options->online.server + "\n";
file << "port=" + std::to_string(options->online.port) + "\n";
file << "jailerID=" + options->online.jailerID + "\n";
file << "\n## NOTIFICATION OPTIONS\n"; file << "\n## NOTIFICATION OPTIONS\n";
file << "## notifications.posV = pos_top | pos_bottom\n"; file << "## notifications.posV = pos_top | pos_bottom\n";
if (options->notifications.posV == pos_top) if (options->notifications.posV == pos_top)
@@ -1158,30 +1111,6 @@ bool Director::setOptions(options_t *options, std::string var, std::string value
} }
} }
else if (var == "enabled")
{
options->online.enabled = stringToBool(value);
}
else if (var == "server")
{
options->online.server = value;
}
else if (var == "port")
{
if (value == "")
{
value = "0";
}
options->online.port = std::stoi(value);
}
else if (var == "jailerID")
{
options->online.jailerID = value;
}
else if (var == "notifications.posH") else if (var == "notifications.posH")
{ {
if (value == "pos_left") if (value == "pos_left")
@@ -1793,7 +1722,7 @@ void Director::runTitle()
JA_PlayMusic(music); JA_PlayMusic(music);
} }
loadResources(section); loadResources(section);
title = new Title(renderer, screen, resource, asset, input, online, options, section); title = new Title(renderer, screen, resource, asset, input, options, section);
title->run(); title->run();
delete title; delete title;
resource->free(); resource->free();
@@ -1878,7 +1807,7 @@ void Director::runGame()
} }
JA_StopMusic(); JA_StopMusic();
loadResources(section); loadResources(section);
game = new Game(renderer, screen, resource, asset, online, options, input, section, debug); game = new Game(renderer, screen, resource, asset, options, input, section, debug);
game->run(); game->run();
delete game; delete game;
resource->free(); resource->free();

View File

@@ -14,12 +14,10 @@
#include "gamestate_demo.h" #include "gamestate_demo.h"
#include "gamestate_ending.h" #include "gamestate_ending.h"
#include "gamestate_ending2.h" #include "gamestate_ending2.h"
#include "enter_id.h"
#include "gamestate_game_over.h" #include "gamestate_game_over.h"
#include "gamestate_game.h" #include "gamestate_game.h"
#include "gamestate_loading_screen.h" #include "gamestate_loading_screen.h"
#include "gamestate_logo.h" #include "gamestate_logo.h"
#include "online.h"
#include "gamestate_title.h" #include "gamestate_title.h"
#ifndef DIRECTOR_H #ifndef DIRECTOR_H
@@ -45,7 +43,6 @@ private:
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;
@@ -57,9 +54,6 @@ private:
// Crea e inicializa las opciones del programa // Crea e inicializa las opciones del programa
void initOptions(); void initOptions();
// Inicializa los servicios online
void initOnline();
// Comprueba los parametros del programa // Comprueba los parametros del programa
void checkProgramArguments(int argc, char *argv[]); void checkProgramArguments(int argc, char *argv[]);

View File

@@ -1,326 +0,0 @@
#include "jail_engine/jail_audio.h"
#include "jail_engine/jscore.h"
#include "const.h"
#include "enter_id.h"
#include <iostream>
// Constructor
EnterID::EnterID(SDL_Renderer *renderer, Screen *screen, Asset *asset, options_t *options, section_t *section)
{
// Copia la dirección de los objetos
this->renderer = renderer;
this->screen = screen;
this->asset = asset;
this->options = options;
this->section = section;
// Reserva memoria para los punteros
eventHandler = new SDL_Event();
texture = new Texture(renderer, asset->get("smb2.png"));
text = new Text(asset->get("smb2.txt"), texture, renderer);
// Crea la textura para el texto que se escribe en pantalla
textTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
if (textTexture == nullptr)
{
if (options->console)
{
std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
}
}
SDL_SetTextureBlendMode(textTexture, SDL_BLENDMODE_BLEND);
// Inicializa variables
oldJailerID = options->online.jailerID;
loopRunning = true;
counter = 0;
ticks = 0;
ticksSpeed = 15;
jailerIDPos = 0;
initName();
// Escribe el texto en la textura
fillTexture();
}
// Destructor
EnterID::~EnterID()
{
delete eventHandler;
delete text;
delete texture;
SDL_DestroyTexture(textTexture);
}
// Bucle para el logo del juego
void EnterID::run()
{
while (loopRunning)
{
update();
checkEvents();
render();
}
}
// Comprueba el manejador de eventos
void EnterID::checkEvents()
{
// Comprueba los eventos que hay en la cola
while (SDL_PollEvent(eventHandler) != 0)
{
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
{
section->name = SECTION_QUIT;
loopRunning = false;
break;
}
// Comprueba las teclas que se han pulsado
if ((eventHandler->type == SDL_KEYDOWN && eventHandler->key.repeat == 0) || (eventHandler->type == SDL_JOYBUTTONDOWN))
{
if (eventHandler->key.keysym.scancode == SDL_SCANCODE_RETURN)
{
options->online.jailerID = toLower((std::string)name);
endSection();
break;
}
if (eventHandler->key.keysym.scancode >= SDL_SCANCODE_A && eventHandler->key.keysym.scancode <= SDL_SCANCODE_Z)
{ // Si pulsa una letra
if (pos < maxLenght)
{
name[pos++] = eventHandler->key.keysym.scancode + 61;
name[pos] = 0;
}
}
else if (eventHandler->key.keysym.scancode >= SDL_SCANCODE_1 && eventHandler->key.keysym.scancode <= SDL_SCANCODE_9)
{ // Si pulsa un número
if (pos < maxLenght)
{ // En ascii el '0' va antes del '1', pero en scancode el '0' va despues de '9'
name[pos++] = eventHandler->key.keysym.scancode + 19;
name[pos] = 0;
}
}
else if (eventHandler->key.keysym.scancode == SDL_SCANCODE_0)
{
if (pos < maxLenght)
{
name[pos++] = 48;
name[pos] = 0;
}
}
else if (eventHandler->key.keysym.scancode == SDL_SCANCODE_BACKSPACE)
{
if (pos > 0)
{
name[--pos] = 0;
}
}
else if (eventHandler->key.keysym.scancode == SDL_SCANCODE_ESCAPE)
{
section->name = SECTION_QUIT;
loopRunning = false;
break;
}
else if (eventHandler->key.keysym.scancode == SDL_SCANCODE_F1)
{
screen->setWindowSize(1);
break;
}
else if (eventHandler->key.keysym.scancode == SDL_SCANCODE_F2)
{
screen->setWindowSize(2);
break;
}
else if (eventHandler->key.keysym.scancode == SDL_SCANCODE_F3)
{
screen->setWindowSize(3);
break;
}
else if (eventHandler->key.keysym.scancode == SDL_SCANCODE_F4)
{
screen->setWindowSize(4);
break;
}
else if (eventHandler->key.keysym.scancode == SDL_SCANCODE_F5)
{
switchPalette();
break;
}
}
}
}
// Actualiza las variables
void EnterID::update()
{
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
if (SDL_GetTicks() - ticks > ticksSpeed)
{
// Actualiza el contador de ticks
ticks = SDL_GetTicks();
// Actualiza el contador
counter++;
// Actualiza el cursor
cursor = (counter % 20 >= 10) ? " " : "_";
// Actualiza las notificaciones
screen->updateNotifier();
}
}
// Dibuja en pantalla
void EnterID::render()
{
// Prepara para empezar a dibujar en la textura de juego
screen->start();
// Dibuja la textura con el texto en pantalla
SDL_RenderCopy(renderer, textTexture, nullptr, nullptr);
// Escribe el jailerID
const std::string jailerID = (std::string)name + cursor;
const color_t color = stringToColor(options->palette, "white");
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, jailerIDPos, jailerID, 1, color);
// Vuelca el contenido del renderizador en pantalla
screen->render();
}
// Inicializa los textos
void EnterID::iniTexts()
{
texts.clear();
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"ONLINE CONFIGURATION:", stringToColor(options->palette, "green")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"PLEASE ENTER AN ID OR", stringToColor(options->palette, "white")});
texts.push_back({"LEAVE BLANK FOR OFFLINE MODE", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"", stringToColor(options->palette, "white")});
texts.push_back({"JAILER_ID:", stringToColor(options->palette, "green")});
jailerIDPos = ((int)texts.size() + 1) * text->getCharacterSize();
}
// Escribe el texto en la textura
void EnterID::fillTexture()
{
// Inicializa los textos
iniTexts();
// Rellena la textura de texto
SDL_SetRenderTarget(renderer, textTexture);
color_t c = stringToColor(options->palette, "black");
SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF);
SDL_RenderClear(renderer);
// Escribe el texto en la textura
const int size = text->getCharacterSize();
int i = 0;
for (auto t : texts)
{
text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, i * size, t.label, 1, t.color);
i++;
}
SDL_SetRenderTarget(renderer, nullptr);
}
// Inicializa los servicios online
void EnterID::initOnline()
{
// Si ya ha iniciado la sesión y no ha cambiado el jailerID, que no continue
if (options->online.sessionEnabled)
{
if (oldJailerID == options->online.jailerID)
{
return;
}
}
if (options->online.jailerID == "")
{ // Jailer ID no definido
options->online.enabled = false;
options->online.sessionEnabled = false;
}
else
{ // Jailer ID iniciado
options->online.enabled = options->online.sessionEnabled = true;
// Establece el servidor y el puerto
jscore::init(options->online.server, options->online.port);
#ifdef DEBUG
const std::string caption = "IS LOGGED IN (DEBUG)";
#else
const std::string caption = "IS LOGGED IN";
#endif
screen->showNotification(options->online.jailerID, caption, 12);
if (options->console)
{
std::cout << caption << std::endl;
}
}
}
// Termina la sección
void EnterID::endSection()
{
loopRunning = false;
initOnline();
}
// Inicializa el vector utilizado para almacenar el texto que se escribe en pantalla
void EnterID::initName()
{
// Calcula el tamaño del vector
name[0] = 0;
maxLenght = sizeof(name) / sizeof(name[pos]);
// Inicializa el vector con ceros
for (int i = 0; i < maxLenght; ++i)
{
name[i] = 0;
}
// Si no hay definido ningun JailerID, coloca el cursor en primera posición
if (options->online.jailerID == "")
{
pos = 0;
}
else
{ // En caso contrario, copia el texto al vector y coloca el cursor en posición
const int len = std::min((int)options->online.jailerID.size(), maxLenght);
for (int i = 0; i < len; ++i)
{
name[i] = (char)options->online.jailerID[i];
}
pos = len;
}
}
// Cambia la paleta
void EnterID::switchPalette()
{
options->palette = options->palette == p_zxspectrum ? p_zxarne : p_zxspectrum;
fillTexture();
}

View File

@@ -1,86 +0,0 @@
#pragma once
#include <SDL2/SDL.h>
#include "jail_engine/asset.h"
#include "jail_engine/screen.h"
#include "jail_engine/utils.h"
#include "jail_engine/text.h"
#include "jail_engine/texture.h"
#include <string>
#include <vector>
#ifndef ENTER_ID_H
#define ENTER_ID_H
class EnterID
{
private:
struct captions_t
{
std::string label; // Texto a escribir
color_t color; // Color del texto
};
// Punteros y objetos
Asset *asset; // Objeto con los ficheros de recursos
options_t *options; // Puntero a las opciones del juego
Screen *screen; // Objeto encargado de dibujar en pantalla
SDL_Event *eventHandler; // Manejador de eventos
SDL_Renderer *renderer; // El renderizador de la ventana
SDL_Texture *textTexture; // Textura para dibujar el texto
Text *text; // Objeto para escribir texto en pantalla
Texture *texture; // Textura para la fuente para el texto
section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables
bool loopRunning; // Indica si ha de terminar el bucle principal
int counter; // Contador
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
std::vector<captions_t> texts; // Vector con los textos
std::string cursor; // Contiene el caracter que se muestra como cursor
char name[15]; // Aqui se guardan los caracteres de las teclas que se van pulsando
int pos; // Posición actual en el vector name
int maxLenght; // Tamaño máximo del jailerID
std::string oldJailerID; // Almacena el valor de jailerID al inicio para ver si se ha modificado
int jailerIDPos; // Posición en el eje Y donde ser va a escribir el texto
// Actualiza las variables
void update();
// Dibuja en pantalla
void render();
// Comprueba el manejador de eventos
void checkEvents();
// Inicializa los textos
void iniTexts();
// Escribe el texto en la textura
void fillTexture();
// Inicializa los servicios online
void initOnline();
// Termina la sección
void endSection();
// Inicializa el vector utilizado para almacenar el texto que se escribe en pantalla
void initName();
// Cambia la paleta
void switchPalette();
public:
// Constructor
EnterID(SDL_Renderer *renderer, Screen *screen, Asset *asset, options_t *options, section_t *section);
// Destructor
~EnterID();
// Bucle principal
void run();
};
#endif

View File

@@ -2,13 +2,12 @@
#include <iostream> #include <iostream>
// Constructor // Constructor
Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Online *online, options_t *options, Input *input, section_t *section, Debug *debug) Game::Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, 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;
@@ -31,7 +30,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"), online); cheevos = new Cheevos(screen, options, asset->get("cheevos.bin"));
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();
@@ -44,7 +43,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, online); stats = new Stats(asset->get("stats.csv"), asset->get("stats_buffer.csv"), options);
// 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,7 +19,6 @@
#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
@@ -38,7 +37,6 @@ 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
@@ -153,7 +151,7 @@ private:
public: public:
// Constructor // Constructor
Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Online *online, options_t *options, Input *input, section_t *section, Debug *debug); Game(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, options_t *options, Input *input, section_t *section, Debug *debug);
// Destructor // Destructor
~Game(); ~Game();

View File

@@ -1,7 +1,7 @@
#include "gamestate_title.h" #include "gamestate_title.h"
// Constructor // Constructor
Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, Online *online, options_t *options, section_t *section) Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, 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,13 +9,12 @@ 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"), online); cheevos = new Cheevos(screen, options, asset->get("cheevos.bin"));
if (options->palette == p_zxspectrum) if (options->palette == p_zxspectrum)
{ {
texture = resource->getTexture("title_logo.png"); texture = resource->getTexture("title_logo.png");
@@ -125,14 +124,6 @@ void Title::checkEvents()
showCheevos = true; showCheevos = true;
break; break;
case SDL_SCANCODE_3:
runEnterID();
counter = 0;
cheevos->reload();
fillTexture();
createCheevosTexture();
break;
default: default:
break; break;
} }
@@ -257,8 +248,6 @@ void Title::renderMarquee()
// Dibuja la linea de información inferior // Dibuja la linea de información inferior
void Title::renderInfo() void Title::renderInfo()
{ {
const std::string loginText = options->online.enabled ? "OnLine: " + options->online.jailerID : "OnLine: OFF";
infoText->write(1, 1, loginText);
const std::string version = "v.1.09"; const std::string version = "v.1.09";
const int x = GAMECANVAS_WIDTH - infoText->lenght(version) - 1; const int x = GAMECANVAS_WIDTH - infoText->lenght(version) - 1;
infoText->write(x, 1, version); infoText->write(x, 1, version);
@@ -375,12 +364,10 @@ void Title::reLoadTextures()
// Carga la textura adecuada // Carga la textura adecuada
if (options->palette == p_zxspectrum) if (options->palette == p_zxspectrum)
{ {
// texture->loadFromFile(asset->get("loading_screen_color.png"), renderer);
texture = resource->getTexture("loading_screen_color.png"); texture = resource->getTexture("loading_screen_color.png");
} }
else if (options->palette == p_zxarne) else if (options->palette == p_zxarne)
{ {
// texture->loadFromFile(asset->get("loading_screen_color_zxarne.png"), renderer);
texture = resource->getTexture("loading_screen_color_zxarne.png"); texture = resource->getTexture("loading_screen_color_zxarne.png");
} }
@@ -413,19 +400,15 @@ void Title::moveCheevosList(int direction)
const int bottom = cheevosTexture->getHeight() - cheevosTextureView.h; const int bottom = cheevosTexture->getHeight() - cheevosTextureView.h;
if (cheevosTextureView.y < 0) if (cheevosTextureView.y < 0)
{
cheevosTextureView.y = 0; cheevosTextureView.y = 0;
}
else if (cheevosTextureView.y > bottom) else if (cheevosTextureView.y > bottom)
{
cheevosTextureView.y = bottom; cheevosTextureView.y = bottom;
cheevosSprite->setSpriteClip(cheevosTextureView);
} }
// Ejecuta la seccion en la que se solicita al usuario su ID online cheevosSprite->setSpriteClip(cheevosTextureView);
void Title::runEnterID()
{
enterID = new EnterID(renderer, screen, asset, options, section);
enterID->run();
delete enterID;
} }
// Rellena la textura de fondo con todos los gráficos // Rellena la textura de fondo con todos los gráficos
@@ -442,20 +425,12 @@ void Title::fillTexture()
// Pinta el gráfico del titulo a partir del sprite // Pinta el gráfico del titulo a partir del sprite
sprite->render(); sprite->render();
// Borra la firma
// const color_t coverColor = stringToColor(options->palette, "black");
// SDL_SetRenderDrawColor(renderer, coverColor.r, coverColor.g, coverColor.b, 0xFF);
// SDL_Rect coverRect = {28, 11, 21, 5};
// SDL_RenderFillRect(renderer, &coverRect);
// Escribe el texto en la textura // Escribe el texto en la textura
const color_t textColor = stringToColor(options->palette, "green"); const color_t textColor = stringToColor(options->palette, "green");
const int textSize = text->getCharacterSize(); const int textSize = text->getCharacterSize();
const std::string onlineText = options->online.jailerID == "" ? "(OFF)" : "(" + options->online.jailerID + ")";
text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 11 * textSize, "1.PLAY", 1, textColor); text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 11 * textSize, "1.PLAY", 1, textColor);
text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 13 * textSize, "2.ACHIEVEMENTS", 1, textColor); text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 13 * textSize, "2.ACHIEVEMENTS", 1, textColor);
text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 15 * textSize, "3.ONLINE MODE", 1, textColor); text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 15 * textSize, "3.REDEFINE KEYS", 1, textColor);
text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 16 * textSize + 1, onlineText, 1, textColor);
text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 20 * textSize, "ESC.EXIT GAME", 1, textColor); text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, 20 * textSize, "ESC.EXIT GAME", 1, textColor);
// Devuelve el puntero del renderizador a su sitio // Devuelve el puntero del renderizador a su sitio
@@ -467,7 +442,6 @@ void Title::createCheevosTexture()
{ {
// Crea la textura con el listado de logros // Crea la textura con el listado de logros
const std::vector<cheevos_t> cheevosList = cheevos->list(); const std::vector<cheevos_t> cheevosList = cheevos->list();
// const int iconSize = 16; // Altura del icono que representa a cada logro
const int cheevosTextureWidth = 200; const int cheevosTextureWidth = 200;
const int cheevosTextureViewHeight = 110; const int cheevosTextureViewHeight = 110;
const int cheevosTexturePosY = 73; const int cheevosTexturePosY = 73;
@@ -485,7 +459,7 @@ void Title::createCheevosTexture()
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
// Escribe la lista de logros en la textura // Escribe la lista de logros en la textura
const std::string cheevosOwner = options->online.jailerID == "" ? "LOCAL ACHIEVEMENTS" : "ACHIEVEMENTS FOR " + toUpper(options->online.jailerID); const std::string cheevosOwner = "LOCAL ACHIEVEMENTS";
const std::string cheevosListCaption = cheevosOwner + " (" + std::to_string(cheevos->unlocked()) + " / " + std::to_string(cheevos->count()) + ")"; const std::string cheevosListCaption = cheevosOwner + " (" + std::to_string(cheevos->unlocked()) + " / " + std::to_string(cheevos->count()) + ")";
int pos = 2; int pos = 2;
infoText->writeDX(TXT_CENTER | TXT_COLOR, cheevosTexture->getWidth() / 2, pos, cheevosListCaption, 1, stringToColor(options->palette, "bright_green")); infoText->writeDX(TXT_CENTER | TXT_COLOR, cheevosTexture->getWidth() / 2, pos, cheevosListCaption, 1, stringToColor(options->palette, "bright_green"));
@@ -497,31 +471,19 @@ void Title::createCheevosTexture()
const int lineX1 = (cheevosTextureWidth / 7) * 3; const int lineX1 = (cheevosTextureWidth / 7) * 3;
const int lineX2 = lineX1 + ((cheevosTextureWidth / 7) * 1); const int lineX2 = lineX1 + ((cheevosTextureWidth / 7) * 1);
// Texture *iconTexture = new Texture(renderer, asset->get("notify.png"));
// Sprite *sp = new Sprite({0, 0, iconSize, iconSize}, iconTexture, renderer);
for (auto cheevo : cheevosList) for (auto cheevo : cheevosList)
{ {
cheevoColor = cheevo.completed ? cheevoUnlockedColor : cheevoLockedColor; cheevoColor = cheevo.completed ? cheevoUnlockedColor : cheevoLockedColor;
// sp->setPos({2, pos, iconSize, iconSize});
// sp->setSpriteClip({iconSize * 2, 0, iconSize, iconSize});
// sp->getTexture()->setColor(cheevoColor.r, cheevoColor.g, cheevoColor.b);
// sp->render();
pos += cheevosPadding; pos += cheevosPadding;
int half = cheevosPadding / 2; int half = cheevosPadding / 2;
SDL_RenderDrawLine(renderer, lineX1, pos - half - 1, lineX2, pos - half - 1); SDL_RenderDrawLine(renderer, lineX1, pos - half - 1, lineX2, pos - half - 1);
// infoText->writeColored(2 + iconSize + 2, pos, cheevo.caption, cheevoColor);
infoText->writeDX(TXT_CENTER | TXT_COLOR, cheevosTextureWidth / 2, pos, cheevo.caption, 1, cheevoColor); infoText->writeDX(TXT_CENTER | TXT_COLOR, cheevosTextureWidth / 2, pos, cheevo.caption, 1, cheevoColor);
pos += infoText->getCharacterSize() + 1; pos += infoText->getCharacterSize() + 1;
// infoText->writeColored(2 + iconSize + 2, pos, cheevo.description, cheevoColor);
infoText->writeDX(TXT_CENTER | TXT_COLOR, cheevosTextureWidth / 2, pos, cheevo.description, 1, cheevoColor); infoText->writeDX(TXT_CENTER | TXT_COLOR, cheevosTextureWidth / 2, pos, cheevo.description, 1, cheevoColor);
// pos += cheevosPadding;
pos += infoText->getCharacterSize(); pos += infoText->getCharacterSize();
} }
// delete sp;
// delete iconTexture;
// Crea el sprite para el listado de logros // Crea el sprite para el listado de logros
// cheevosSprite = new Sprite((GAMECANVAS_WIDTH - cheevosTexture->getWidth()) / 2, (GAMECANVAS_HEIGHT - cheevosTextureViewHeight) / 2, cheevosTexture->getWidth(), cheevosTexture->getHeight(), cheevosTexture, renderer);
cheevosSprite = new Sprite((GAMECANVAS_WIDTH - cheevosTexture->getWidth()) / 2, cheevosTexturePosY, cheevosTexture->getWidth(), cheevosTexture->getHeight(), cheevosTexture, renderer); cheevosSprite = new Sprite((GAMECANVAS_WIDTH - cheevosTexture->getWidth()) / 2, cheevosTexturePosY, cheevosTexture->getWidth(), cheevosTexture->getHeight(), cheevosTexture, renderer);
cheevosTextureView = {0, 0, cheevosTexture->getWidth(), cheevosTextureViewHeight}; cheevosTextureView = {0, 0, cheevosTexture->getWidth(), cheevosTextureViewHeight};
cheevosSprite->setSpriteClip(cheevosTextureView); cheevosSprite->setSpriteClip(cheevosTextureView);

View File

@@ -2,7 +2,6 @@
#include <SDL2/SDL.h> #include <SDL2/SDL.h>
#include "cheevos.h" #include "cheevos.h"
#include "enter_id.h"
#include "jail_engine/asset.h" #include "jail_engine/asset.h"
#include "jail_engine/input.h" #include "jail_engine/input.h"
#include "jail_engine/jail_audio.h" #include "jail_engine/jail_audio.h"
@@ -12,7 +11,6 @@
#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>
@@ -42,7 +40,6 @@ 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
@@ -53,7 +50,6 @@ private:
Texture *cheevosTexture; // Textura con lo lista de logros Texture *cheevosTexture; // Textura con lo lista de logros
Sprite *cheevosSprite; // Sprite para manejar la textura con la lista de logros Sprite *cheevosSprite; // Sprite para manejar la textura con la lista de logros
Cheevos *cheevos; // Objeto encargado de gestionar los logros del juego Cheevos *cheevos; // Objeto encargado de gestionar los logros del juego
EnterID *enterID; // Objeto para recoger el JailerID desde el teclado
section_t *section; // Estado del bucle principal para saber si continua o se sale section_t *section; // Estado del bucle principal para saber si continua o se sale
// Variables // Variables
@@ -101,9 +97,6 @@ private:
// Desplaza la lista de logros // Desplaza la lista de logros
void moveCheevosList(int direction); void moveCheevosList(int direction);
// Ejecuta la seccion en la que se solicita al usuario su ID online
void runEnterID();
// Rellena la textura de fondo con todos los gráficos // Rellena la textura de fondo con todos los gráficos
void fillTexture(); void fillTexture();
@@ -115,7 +108,7 @@ private:
public: public:
// Constructor // Constructor
Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, Online *online, options_t *options, section_t *section); Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section);
// Destructor // Destructor
~Title(); ~Title();

View File

@@ -1,101 +0,0 @@
#ifdef JA_USESDLMIXER
#include "jail_audio.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include <stdio.h>
struct JA_Sound_t {}; // Dummy structs
struct JA_Music_t {};
int JA_freq {48000};
SDL_AudioFormat JA_format {AUDIO_S16};
Uint8 JA_channels {2};
void JA_Init(const int freq, const SDL_AudioFormat format, const int channels) {
JA_freq = freq;
JA_format = format;
JA_channels = channels;
Mix_OpenAudio(JA_freq, JA_format, JA_channels, 1024);
}
void JA_Quit() {
Mix_CloseAudio();
}
JA_Music_t *JA_LoadMusic(const char* filename) {
return (JA_Music_t*)Mix_LoadMUS(filename);
}
void JA_PlayMusic(JA_Music_t *music, const int loop) {
Mix_PlayMusic((Mix_Music*)music, loop);
}
void JA_PauseMusic() {
Mix_PauseMusic();
}
void JA_ResumeMusic() {
Mix_ResumeMusic();
}
void JA_StopMusic() {
Mix_HaltMusic();
}
JA_Music_state JA_GetMusicState() {
if (Mix_PausedMusic()) {
return JA_MUSIC_PAUSED;
} else if (Mix_PlayingMusic()) {
return JA_MUSIC_PLAYING;
} else {
return JA_MUSIC_STOPPED;
}
}
void JA_DeleteMusic(JA_Music_t *music) {
Mix_FreeMusic((Mix_Music*)music);
}
JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length) {
return NULL;
}
JA_Sound_t *JA_LoadSound(const char* filename) {
JA_Sound_t *sound = (JA_Sound_t*)Mix_LoadWAV(filename);
return sound;
}
int JA_PlaySound(JA_Sound_t *sound, const int loop) {
return Mix_PlayChannel(-1, (Mix_Chunk*)sound, loop);
}
void JA_DeleteSound(JA_Sound_t *sound) {
Mix_FreeChunk((Mix_Chunk*)sound);
}
void JA_PauseChannel(const int channel) {
Mix_Pause(channel);
}
void JA_ResumeChannel(const int channel) {
Mix_Resume(channel);
}
void JA_StopChannel(const int channel) {
Mix_HaltChannel(channel);
}
JA_Channel_state JA_GetChannelState(const int channel) {
if (Mix_Paused(channel)) {
return JA_CHANNEL_PAUSED;
} else if (Mix_Playing(channel)) {
return JA_CHANNEL_PLAYING;
} else {
return JA_CHANNEL_FREE;
}
}
int JA_SetVolume(int volume) {
return Mix_Volume(-1, volume);
}
#endif

View File

@@ -1,154 +0,0 @@
#include "jscore.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#ifdef _WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#endif
#include <unistd.h>
#include <string>
#include <vector>
namespace jscore {
using namespace std;
struct user {
string name;
int points;
};
vector<user> score;
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
int sock;
struct sockaddr_in client;
int PORT = 9911;
string HOST = "jaildoctor.duckdns.org";
#ifdef WIN32
WSADATA WsaData;
#endif
bool jscore_error = false;
string error_message;
void init(std::string host, const int port) {
PORT = port;
HOST = host;
}
void setErrorMessage(string message) {
jscore_error = true;
error_message = message;
}
string sendRequest(const string request) {
#ifdef WIN32
int ret = WSAStartup(0x101,&WsaData);
if (ret != 0) return 0;
#endif
struct hostent * host = gethostbyname(HOST.c_str());
if ( (host == NULL) || (host->h_addr == NULL) ) {
setErrorMessage("Error retrieving DNS information.\n");
return "";
}
bzero(&client, sizeof(client));
client.sin_family = AF_INET;
client.sin_port = htons( PORT );
memcpy(&client.sin_addr, host->h_addr, host->h_length);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
setErrorMessage("Error creating socket.\n");
return "";
}
if ( connect(sock, (struct sockaddr *)&client, sizeof(client)) < 0 ) {
close(sock);
setErrorMessage("Could not connect\n");
return "";
}
string r = request + " HTTP/1.1\r\nHost: "+HOST+"\r\nConnection: close\r\n\r\n\r\n";
if (send(sock, r.c_str(), r.length(), 0) != (int)r.length()) {
setErrorMessage("Error sending request.\n");
return "";
}
char cur;
char start[5]="\r\n\r\n";
int pos = 0;
while ( recv(sock, &cur, 1,0) > 0 ) {
if (cur==start[pos]) { pos++; if (pos == 4) break; } else { pos = 0; }
}
char buffer[1024]; buffer[0]=0; pos=0;
while ( recv(sock, &cur, 1,0) > 0 ) {
buffer[pos] = cur;
pos++;
}
#ifdef WIN32
WSACleanup();
#endif
buffer[pos]=0;
return buffer;
}
const bool initOnlineScore(string game) {
string strbuff = sendRequest("GET /score-list.php?game=" + game);
if (jscore_error) return not jscore_error;
user u;
char buffer[1024];
strcpy(buffer, strbuff.c_str());
char *str = buffer;
char *p = str;
score.clear();
while (*p!=0) {
while (*p!=',') {p++;}
*p=0; u.name = str; p++; str=p;
while (*p!='\n') {p++;}
*p=0; u.points = atoi(str); p++; str=p;
score.push_back(u);
}
return not jscore_error;
}
const int getNumUsers() {
return score.size();
}
string getUserName(const int index) {
return score[index].name;
}
const int getPoints(const int index) {
return score[index].points;
}
const bool updateUserPoints(string game, string user, const int points) {
string strbuff = sendRequest("GET /score-update.php?game=" + game + "&user=" + user + "&points=" + to_string(points));
initOnlineScore(game);
return not jscore_error;
}
const int getUserPoints(string game, std::string user) {
return atoi(sendRequest("GET /getuserpoints.php?game=" + game + "&user=" + user).c_str());
}
string getUserData(string game, string user) {
return sendRequest("GET /getuserdata.php?game=" + game + "&user=" + user);
}
void setUserData(string game, string user, string data) {
sendRequest("GET /setuserdata.php?game=" + game + "&user=" + user + "&data=" + data);
}
};

View File

@@ -1,16 +0,0 @@
#pragma once
#include <string>
namespace jscore {
void init(std::string host, const int port);
const bool initOnlineScore(std::string game);
const int getNumUsers();
std::string getUserName(const int index);
const int getPoints(const int index);
const int getUserPoints(std::string game, std::string user);
const bool updateUserPoints(std::string game, std::string user, const int points);
std::string getUserData(std::string game, std::string user);
void setUserData(std::string game, std::string user, std::string data);
};

View File

@@ -97,18 +97,6 @@ struct cheat_t
bool altSkin; // Indicxa si se usa una skin diferente para el jugador bool altSkin; // Indicxa si se usa una skin diferente para el jugador
}; };
// Estructura para el servicio online
struct online_t
{
bool enabled; // Indica si se quiere usar el modo online o no
bool sessionEnabled; // Indica ya se ha hecho login
std::string server; // Servidor para los servicios online
int port; // Puerto del servidor
std::string gameID; // Identificador del juego para los servicios online
std::string jailerID; // Identificador del jugador para los servicios online
int score; // Puntuación almacenada online
};
// Estructura para almacenar estadísticas // Estructura para almacenar estadísticas
struct op_stats_t struct op_stats_t
{ {
@@ -144,7 +132,6 @@ struct options_t
bool console; // Indica si ha de mostrar información por la consola de texto bool console; // Indica si ha de mostrar información por la consola de texto
cheat_t cheat; // Contiene trucos y ventajas para el juego cheat_t cheat; // Contiene trucos y ventajas para el juego
op_stats_t stats; // Datos con las estadisticas de juego op_stats_t stats; // Datos con las estadisticas de juego
online_t online; // Datos del servicio online
op_notification_t notifications; // Opciones relativas a las notificaciones; op_notification_t notifications; // Opciones relativas a las notificaciones;
op_screen_t screen; // Opciones relativas a la clase screen op_screen_t screen; // Opciones relativas a la clase screen
ctrl_schem_e keys; // Teclas usadas para jugar ctrl_schem_e keys; // Teclas usadas para jugar

View File

@@ -1,169 +0,0 @@
#include "jail_engine/jscore.h"
#include "online.h"
#include <fstream>
#include <iostream>
#include <sstream>
// Constructor
Online::Online(options_t *options)
{
this->options = options;
if (options->console)
{
std::cout << "ONLINE object created\n"
<< std::endl;
}
allData = "";
statsData = "";
cheevosData = "";
STATS_FLAG_INI = ";STATS_FLAG_INI;";
STATS_FLAG_END = ";STATS_FLAG_END;";
CHEEVOS_FLAG_INI = ";CHEEVOS_FLAG_INI;";
CHEEVOS_FLAG_END = ";CHEEVOS_FLAG_END;";
dataCached = false;
dataSaved = "";
getData();
}
// Destructor
Online::~Online()
{
sendData();
}
// Obtiene todos los datos y los coloca en sus respectivas variables
void Online::getData()
{
// 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)
{
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 (options->console)
{
std::cout << "NO DATA\n"
<< std::endl;
}
return;
}
// Obtiene el inicio y el fin de la cadena con las estadisticas
const size_t statsIni = allData.find(STATS_FLAG_INI) + STATS_FLAG_INI.length();
const size_t statsEnd = allData.find(STATS_FLAG_END);
const size_t statsDataLenght = statsEnd - statsIni;
// Obtiene la cadena con las estadisticas
if (statsIni != std::string::npos && statsEnd != std::string::npos)
statsData = allData.substr(statsIni, statsDataLenght);
// Obtiene el inicio y el fin de la cadena con los logros
const size_t cheevosIni = allData.find(CHEEVOS_FLAG_INI) + CHEEVOS_FLAG_INI.length();
const size_t cheevosEnd = allData.find(CHEEVOS_FLAG_END);
const size_t cheevosDataLenght = cheevosEnd - cheevosIni;
// Obtiene la cadena con los logros
if (cheevosIni != std::string::npos && cheevosEnd != std::string::npos)
cheevosData = allData.substr(cheevosIni, cheevosDataLenght);
dataCached = true;
printData("LOADING");
}
// Coloca todos los datos desde las variables en la cadena allData
void Online::sendData()
{
allData = STATS_FLAG_INI + statsData + STATS_FLAG_END + CHEEVOS_FLAG_INI + cheevosData + CHEEVOS_FLAG_END;
const bool newData = allData.compare(dataSaved) == 0 ? false : true;
if (options->online.enabled && newData)
{
jscore::setUserData(options->online.gameID, options->online.jailerID, allData);
dataSaved = allData;
printData("SAVING");
}
}
// Obtiene las estadísticas guardadas en el servidor
std::string Online::getStats()
{
getData();
return statsData;
}
// Guarda las estadísticas en el servidor
void Online::setStats(std::string data)
{
// getData();
statsData = data;
// setAllData();
}
// Obtiene los logros guardadas en el servidor
std::string Online::getCheevos()
{
getData();
return cheevosData;
}
// Guarda los logros en el servidor
void Online::setCheevos(std::string data)
{
getData();
cheevosData = data;
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

@@ -1,66 +0,0 @@
#pragma once
#include <SDL2/SDL.h>
#include "jail_engine/utils.h"
#include <string>
#include <vector>
#ifndef ONLINE_H
#define ONLINE_H
class Online
{
private:
// Punteros y objetos
options_t *options;
// Variables
std::string allData; // La cadena entera de datos
std::string statsData; // La cadena con los datos de las estadísticas
std::string cheevosData; // La cadena con los datos de los logros
std::string STATS_FLAG_INI; // Marca para establecer el inicio de las estadísticas
std::string STATS_FLAG_END; // Marca para establecer el final de las estadísticas
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
bool dataCached; // Indica si se han obtenido los datos del servidor
std::string dataSaved; // Contiene los datos que se han salvado en el servidor
std::string jailerID; // ID del usuario cuyos datos estan cacheados
// 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:
// Constructor
Online(options_t *options);
// Destructor
~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
std::string getStats();
// Guarda las estadísticas en el servidor
void setStats(std::string data);
// Obtiene los logros guardadas en el servidor
std::string getCheevos();
// Guarda los logros en el servidor
void setCheevos(std::string data);
};
#endif

View File

@@ -1,4 +1,3 @@
#include "jail_engine/jscore.h"
#include "stats.h" #include "stats.h"
#include <algorithm> #include <algorithm>
#include <fstream> #include <fstream>
@@ -6,10 +5,9 @@
#include <sstream> #include <sstream>
// Constructor // Constructor
Stats::Stats(std::string file, std::string buffer, options_t *options, Online *online) Stats::Stats(std::string file, std::string buffer, options_t *options)
{ {
this->options = options; this->options = options;
this->online = online;
bufferPath = buffer; bufferPath = buffer;
filePath = file; filePath = file;
bufferList.clear(); bufferList.clear();
@@ -27,7 +25,6 @@ Stats::~Stats()
checkWorstNightmare(); checkWorstNightmare();
// Guarda las estadísticas // Guarda las estadísticas
saveToServer();
saveToFile(bufferPath, bufferList); saveToFile(bufferPath, bufferList);
saveToFile(filePath, list); saveToFile(filePath, list);
@@ -37,15 +34,11 @@ Stats::~Stats()
} }
// Inicializador // Inicializador
// Se debe llamar a este procedimiento una vez se haya creado el diccionario numero-nombre
void Stats::init() void Stats::init()
// Se debe llamar a este procedimiento una vez se haya creado el diccionario numero-nombre
{ {
loadFromFile(bufferPath, bufferList); loadFromFile(bufferPath, bufferList);
loadFromFile(filePath, list); loadFromFile(filePath, list);
if (options->online.enabled)
{
loadFromServer();
}
// Vuelca los datos del buffer en la lista de estadisticas // Vuelca los datos del buffer en la lista de estadisticas
updateListFromBuffer(); updateListFromBuffer();
@@ -54,9 +47,6 @@ void Stats::init()
// Añade una muerte a las estadisticas // Añade una muerte a las estadisticas
void Stats::addDeath(std::string name) void Stats::addDeath(std::string name)
{ {
// Normaliza el nombre
// std::replace(name.begin(), name.end(), ' ', '_');
// Primero busca si ya hay una entrada con ese nombre // Primero busca si ya hay una entrada con ese nombre
const int index = findByName(name, bufferList); const int index = findByName(name, bufferList);
if (index != -1) if (index != -1)
@@ -78,9 +68,6 @@ void Stats::addDeath(std::string name)
// Añade una visita a las estadisticas // Añade una visita a las estadisticas
void Stats::addVisit(std::string name) void Stats::addVisit(std::string name)
{ {
// Normaliza el nombre
// std::replace(name.begin(), name.end(), ' ', '_');
// Primero busca si ya hay una entrada con ese nombre // Primero busca si ya hay una entrada con ese nombre
const int index = findByName(name, bufferList); const int index = findByName(name, bufferList);
if (index != -1) if (index != -1)
@@ -163,62 +150,14 @@ bool Stats::loadFromFile(std::string filePath, std::vector<stats_t> &list)
// El fichero no existe // El fichero no existe
else else
{ // Crea el fichero con los valores por defecto {
// Crea el fichero con los valores por defecto
saveToFile(filePath, list); saveToFile(filePath, list);
} }
return success; return success;
} }
// Carga las estadisticas desde un servidor
void Stats::loadFromServer()
{
// Limpia los datos del servidor
// eraseServerData();
list.clear();
std::string data;
if (options->online.enabled)
{
//data = jscore::getUserData(options->online.gameID, options->online.jailerID);
data = online->getStats();
}
std::stringstream ss(data);
std::string tmp;
int count = 0;
for (int i = 0; i < (int)data.size(); ++i)
{
if (data[i] == ';')
{
count++;
}
}
while (count > 0)
{
stats_t stat;
// Obtiene el nombre
getline(ss, tmp, ';');
stat.name = numberToName(tmp);
// Obtiene las visitas
getline(ss, tmp, ';');
stat.visited = std::stoi(tmp);
// Obtiene las muertes
getline(ss, tmp, ';');
stat.died = std::stoi(tmp);
list.push_back(stat);
count = count - 3;
}
}
// Guarda las estadisticas en un fichero // Guarda las estadisticas en un fichero
void Stats::saveToFile(std::string filePath, std::vector<stats_t> &list) void Stats::saveToFile(std::string filePath, std::vector<stats_t> &list)
{ {
@@ -236,21 +175,6 @@ void Stats::saveToFile(std::string filePath, std::vector<stats_t> &list)
file.close(); file.close();
} }
// Guarda las estadisticas en un servidor
void Stats::saveToServer()
{
std::string data = "";
if (options->online.enabled)
{
for (auto item : list)
{
data = data + nameToNumber(item.name) + ";" + std::to_string(item.visited) + ";" + std::to_string(item.died) + ";";
}
//jscore::setUserData(options->online.gameID, options->online.jailerID, data);
online->setStats(data);
}
}
// Calcula cual es la habitación con más muertes // Calcula cual es la habitación con más muertes
void Stats::checkWorstNightmare() void Stats::checkWorstNightmare()
{ {
@@ -320,13 +244,6 @@ void Stats::updateListFromBuffer()
} }
} }
// Sube los datos al servidor
if (options->online.enabled)
{
saveToServer();
bufferList.clear();
}
saveToFile(bufferPath, bufferList); saveToFile(bufferPath, bufferList);
saveToFile(filePath, list); saveToFile(filePath, list);
} }

View File

@@ -1,7 +1,6 @@
#pragma once #pragma once
#include <SDL2/SDL.h> #include <SDL2/SDL.h>
#include "jail_engine/utils.h" #include "jail_engine/utils.h"
#include "online.h"
#include <string> #include <string>
#include <vector> #include <vector>
@@ -26,7 +25,6 @@ private:
// Punteros y objetos // Punteros y objetos
options_t *options; // Puntero a la variable con todas las opciones del programa options_t *options; // Puntero a la variable con todas las opciones del programa
Online *online; // Objeto para gestionar la lectura y escritura de datos en el servidor remoto
// Variables // Variables
std::vector<stats_dictionary_t> dictionary; // Lista con la equivalencia nombre-numero de habitacion std::vector<stats_dictionary_t> dictionary; // Lista con la equivalencia nombre-numero de habitacion
@@ -41,15 +39,9 @@ private:
// Carga las estadisticas desde un fichero // Carga las estadisticas desde un fichero
bool loadFromFile(std::string filePath, std::vector<stats_t> &list); bool loadFromFile(std::string filePath, std::vector<stats_t> &list);
// Carga las estadisticas desde un servidor
void loadFromServer();
// Guarda las estadisticas en un fichero // Guarda las estadisticas en un fichero
void saveToFile(std::string filePath, std::vector<stats_t> &list); void saveToFile(std::string filePath, std::vector<stats_t> &list);
// Guarda las estadisticas en un servidor
void saveToServer();
// Calcula cual es la habitación con más muertes // Calcula cual es la habitación con más muertes
void checkWorstNightmare(); void checkWorstNightmare();
@@ -64,7 +56,7 @@ private:
public: public:
// Constructor // Constructor
Stats(std::string file, std::string buffer, options_t *options, Online *online); Stats(std::string file, std::string buffer, options_t *options);
// Destructor // Destructor
~Stats(); ~Stats();