Ya funcionan las puntuaciones online

This commit is contained in:
2022-11-15 19:21:03 +01:00
parent 452ef4c91d
commit 9708f4e7ff
12 changed files with 175 additions and 39 deletions

View File

@@ -8,7 +8,7 @@ windows:
@echo off @echo off
powershell if (Test-Path data\config\config.bin) {Remove-Item data\config\config.bin -Recurse -Force} powershell if (Test-Path data\config\config.bin) {Remove-Item data\config\config.bin -Recurse -Force}
powershell if (Test-Path data\config\score.bin) {Remove-Item data\config\score.bin -Recurse -Force} powershell if (Test-Path data\config\score.bin) {Remove-Item data\config\score.bin -Recurse -Force}
g++ $(source) -std=c++11 -Wall -Os -lmingw32 -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 -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_release: windows_release:
@@ -29,7 +29,7 @@ windows_release:
powershell Copy-Item "release/SDL2.dll" -Destination "$(releaseFolder)" powershell Copy-Item "release/SDL2.dll" -Destination "$(releaseFolder)"
# Build # Build
g++ $(source) -D RELEASE -std=c++11 -Wall -Os -lmingw32 -lSDL2main -lSDL2 -ffunction-sections -fdata-sections -Wl,--gc-sections -static-libstdc++ -Wl,-subsystem,windows -o "$(releaseFolder)/$(executable).exe" g++ $(source) -D RELEASE -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"
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

@@ -0,0 +1 @@
JailDesigner

View File

@@ -1,38 +1,55 @@
#include "jscore.h" #include "jscore.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> #include <sys/types.h>
#include <winsock2.h> #ifdef WIN32
//#include <sys/socket.h> #include <winsock2.h>
//#include <netdb.h> #else
//#include <netinet/in.h> #include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#endif
#include <unistd.h> #include <unistd.h>
#include <string> #include <string>
#include <vector> #include <vector>
namespace jscore { namespace jscore {
using namespace std;
struct user { struct user {
std::string name; string name;
int points; int points;
}; };
std::vector<user> score; vector<user> score;
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0) #define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
using namespace std;
int sock; int sock;
struct sockaddr_in client; struct sockaddr_in client;
int PORT = 9911; int PORT = 9911;
const char *HOST = "jaildoctor.duckdns.org"; const char *HOST = "jaildoctor.duckdns.org";
WSADATA WsaData;
std::string sendRequest(const std::string request) { #ifdef WIN32
WSADATA WsaData;
#endif
bool jscore_error = false;
string error_message;
void setErrorMessage(string message) {
jscore_error = true;
error_message = message;
}
string sendRequest(const string request) {
#ifdef WIN32
int ret = WSAStartup(0x101,&WsaData); int ret = WSAStartup(0x101,&WsaData);
if (ret != 0) return 0; if (ret != 0) return 0;
#endif
struct hostent * host = gethostbyname(HOST); struct hostent * host = gethostbyname(HOST);
if ( (host == NULL) || (host->h_addr == NULL) ) { if ( (host == NULL) || (host->h_addr == NULL) ) {
printf("Error retrieving DNS information.\n"); setErrorMessage("Error retrieving DNS information.\n");
return ""; return "";
} }
@@ -44,19 +61,19 @@ namespace jscore {
sock = socket(AF_INET, SOCK_STREAM, 0); sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) { if (sock < 0) {
printf("Error creating socket.\n"); setErrorMessage("Error creating socket.\n");
return ""; return "";
} }
if ( connect(sock, (struct sockaddr *)&client, sizeof(client)) < 0 ) { if ( connect(sock, (struct sockaddr *)&client, sizeof(client)) < 0 ) {
close(sock); close(sock);
printf("Could not connect\n"); setErrorMessage("Could not connect\n");
return ""; return "";
} }
std::string r = request + " HTTP/1.1\r\nHost: "+HOST+"\r\nConnection: close\r\n\r\n\r\n"; 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()) { if (send(sock, r.c_str(), r.length(), 0) != (int)r.length()) {
printf("Error sending request.\n"); setErrorMessage("Error sending request.\n");
return ""; return "";
} }
@@ -72,14 +89,17 @@ namespace jscore {
buffer[pos] = cur; buffer[pos] = cur;
pos++; pos++;
} }
#ifdef WIN32
WSACleanup(); WSACleanup();
#endif
buffer[pos]=0; buffer[pos]=0;
return buffer; return buffer;
} }
const bool initOnlineScore(std::string game) { const bool initOnlineScore(string game) {
std::string strbuff = sendRequest("GET /score-list.php?game=" + game); string strbuff = sendRequest("GET /score-list.php?game=" + game);
if (jscore_error) return not jscore_error;
user u; user u;
char buffer[1024]; char buffer[1024];
strcpy(buffer, strbuff.c_str()); strcpy(buffer, strbuff.c_str());
@@ -93,29 +113,34 @@ namespace jscore {
*p=0; u.points = atoi(str); p++; str=p; *p=0; u.points = atoi(str); p++; str=p;
score.push_back(u); score.push_back(u);
} }
return not jscore_error;
} }
const int getNumUsers() { const int getNumUsers() {
return score.size(); return score.size();
} }
std::string getUserName(const int index) { string getUserName(const int index) {
return score[index].name; return score[index].name;
} }
const int getPoints(const int index) { const int getPoints(const int index) {
return score[index].points; return score[index].points;
} }
const bool updateUserPoints(std::string game, std::string user, const int points) { const bool updateUserPoints(string game, string user, const int points) {
char dst[255]; string strbuff = sendRequest("GET /score-update.php?game=" + game + "&user=" + user + "&points=" + to_string(points));
std::string strbuff = sendRequest("GET /score-update.php?game=" + game + "&user=" + user + "&points=" + itoa(points, dst, 10));
initOnlineScore(game); initOnlineScore(game);
return not jscore_error;
} }
std::string getUserData(std::string game, std::string user) { 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); return sendRequest("GET /getuserdata.php?game=" + game + "&user=" + user);
} }
void setUserData(std::string game, std::string user, std::string data) { void setUserData(string game, string user, string data) {
sendRequest("GET /setuserdata.php?game=" + game + "&user=" + user + "&data=" + data); sendRequest("GET /setuserdata.php?game=" + game + "&user=" + user + "&data=" + data);
} }

View File

@@ -6,6 +6,7 @@ namespace jscore {
const int getNumUsers(); const int getNumUsers();
std::string getUserName(const int index); std::string getUserName(const int index);
const int getPoints(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); const bool updateUserPoints(std::string game, std::string user, const int points);
std::string getUserData(std::string game, std::string user); std::string getUserData(std::string game, std::string user);

View File

@@ -43,19 +43,16 @@ void Notify::update()
{ {
notifications.at(i).counter++; notifications.at(i).counter++;
const int height = notifications.at(i).texture->getHeight();
const int halfDesp = text->getCharacterSize() / 2;
// Comprueba los estados // Comprueba los estados
if (notifications.at(i).state == ns_rising) if (notifications.at(i).state == ns_rising)
{ {
const float step = ((float)notifications.at(i).counter / (height + halfDesp)); const float step = ((float)notifications.at(i).counter / notifications.at(i).travelDist);
const int alpha = 255 * step; const int alpha = 255 * step;
notifications.at(i).rect.y++; notifications.at(i).rect.y++;
notifications.at(i).texture->setAlpha(alpha); notifications.at(i).texture->setAlpha(alpha);
if (notifications.at(i).rect.y == 0 + halfDesp) if (notifications.at(i).rect.y == notifications.at(i).y)
{ {
notifications.at(i).state = ns_stay; notifications.at(i).state = ns_stay;
notifications.at(i).texture->setAlpha(255); notifications.at(i).texture->setAlpha(255);
@@ -74,13 +71,13 @@ void Notify::update()
else if (notifications.at(i).state == ns_vanishing) else if (notifications.at(i).state == ns_vanishing)
{ {
const float step = (notifications.at(i).counter / (float)height); const float step = (notifications.at(i).counter / (float)notifications.at(i).travelDist);
const int alpha = 255 * (1 - step); const int alpha = 255 * (1 - step);
notifications.at(i).rect.y--; notifications.at(i).rect.y--;
notifications.at(i).texture->setAlpha(alpha); notifications.at(i).texture->setAlpha(alpha);
if (notifications.at(i).rect.y == -height) if (notifications.at(i).rect.y == notifications.at(i).y - notifications.at(i).travelDist)
{ {
notifications.at(i).state = ns_finished; notifications.at(i).state = ns_finished;
} }
@@ -112,17 +109,21 @@ void Notify::showText(std::string text)
// Crea constantes // Crea constantes
const int width = this->text->lenght(text) + (this->text->getCharacterSize() * 2); const int width = this->text->lenght(text) + (this->text->getCharacterSize() * 2);
const int height = this->text->getCharacterSize() * 2; const int height = this->text->getCharacterSize() * 2;
const int desp = this->text->getCharacterSize(); const int despH = this->text->getCharacterSize() / 2;
const int halfDesp = desp / 2; const int despV = despH;
const int travelDist = height + despV;
const int offset = (int)notifications.size() * (travelDist) + despV;
// Crea la notificacion // Crea la notificacion
notification_t n; notification_t n;
// inicializa variables // inicializa variables
n.y = offset;
n.travelDist = travelDist;
n.counter = 0; n.counter = 0;
n.state = ns_rising; n.state = ns_rising;
n.text = text; n.text = text;
n.rect = {halfDesp, -height, width, height}; n.rect = {despH, offset - travelDist, width, height};
// Crea la textura // Crea la textura
n.texture = new Texture(renderer); n.texture = new Texture(renderer);
@@ -131,7 +132,7 @@ void Notify::showText(std::string text)
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255); SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
n.texture->setBlendMode(SDL_BLENDMODE_BLEND); n.texture->setBlendMode(SDL_BLENDMODE_BLEND);
this->text->writeDX(TXT_CENTER | TXT_STROKE, width / 2, halfDesp, text, 1, {255, 255, 255}, 1, {0, 0, 0}); this->text->writeDX(TXT_CENTER | TXT_STROKE, width / 2, despV, text, 1, {255, 255, 255}, 1, {0, 0, 0});
// Crea el sprite // Crea el sprite
n.sprite = new Sprite(n.rect, n.texture, renderer); n.sprite = new Sprite(n.rect, n.texture, renderer);

View File

@@ -42,6 +42,8 @@ private:
Texture *texture; Texture *texture;
Sprite *sprite; Sprite *sprite;
SDL_Rect rect; SDL_Rect rect;
int y;
int travelDist;
}; };
// Objetos y punteros // Objetos y punteros

View File

@@ -83,6 +83,14 @@ struct input_t
Uint8 deviceType; // Tipo de dispositivo (teclado o mando) Uint8 deviceType; // Tipo de dispositivo (teclado o mando)
}; };
// Estructura para el servicio online
struct online_t
{
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 con todas las opciones de configuración del programa // Estructura con todas las opciones de configuración del programa
struct options_t struct options_t
{ {
@@ -100,6 +108,7 @@ struct options_t
bool keepAspect; // Indica si se ha de mantener la relación de aspecto al poner el modo a pantalla completa bool keepAspect; // Indica si se ha de mantener la relación de aspecto al poner el modo a pantalla completa
bool borderEnabled; // Indica si ha de mostrar el borde en el modo de ventana bool borderEnabled; // Indica si ha de mostrar el borde en el modo de ventana
float borderSize; // Porcentaje de borde que se añade a lo ventana float borderSize; // Porcentaje de borde que se añade a lo ventana
online_t online; // Datos del servicio online
}; };
// Calcula el cuadrado de la distancia entre dos puntos // Calcula el cuadrado de la distancia entre dos puntos

View File

@@ -1,7 +1,9 @@
#include "common/jscore.h"
#include "common/utils.h"
#include "const.h" #include "const.h"
#include "director.h" #include "director.h"
#include "common/utils.h"
#include <iostream> #include <iostream>
#include <fstream>
#include <string> #include <string>
// Constructor // Constructor
@@ -37,6 +39,9 @@ Director::Director(std::string path)
initInput(); initInput();
screen = new Screen(window, renderer, asset, options, GAME_WIDTH, GAME_HEIGHT); screen = new Screen(window, renderer, asset, options, GAME_WIDTH, GAME_HEIGHT);
// Inicializa los servicios online
initOnline();
} }
Director::~Director() Director::~Director()
@@ -170,6 +175,7 @@ bool Director::setFileList()
asset->add(prefix + "/data/config/score.bin", t_data, false); asset->add(prefix + "/data/config/score.bin", t_data, false);
asset->add(prefix + "/data/config/demo.bin", t_data); asset->add(prefix + "/data/config/demo.bin", t_data);
asset->add(prefix + "/data/config/config.bin", t_data, false); asset->add(prefix + "/data/config/config.bin", t_data, false);
asset->add(prefix + "/data/config/jailer_id.txt", t_data, false);
asset->add(prefix + "/data/config/gamecontrollerdb.txt", t_data); asset->add(prefix + "/data/config/gamecontrollerdb.txt", t_data);
// Musicas // Musicas
@@ -316,6 +322,9 @@ bool Director::loadConfigFile()
options->keepAspect = true; options->keepAspect = true;
options->borderSize = 0.0f; options->borderSize = 0.0f;
options->borderEnabled = false; options->borderEnabled = false;
options->online.gameID = "coffee_crisis";
options->online.jailerID = "";
options->online.score = 0;
// Indicador de éxito en la carga // Indicador de éxito en la carga
bool success = true; bool success = true;
@@ -498,4 +507,56 @@ void Director::run()
break; break;
} }
} }
}
// Inicializa los servicios online
void Director::initOnline()
{
// Obtiene la información online
if (jscore::initOnlineScore(options->online.gameID))
{
screen->showText("Conectado a jaildoctor.duckdns.org");
std::cout << "Conectado a jaildoctor.duckdns.org" << std::endl;
}
else
{
screen->showText("Fallo al conectar a jaildoctor.duckdns.org");
std::cout << "Fallo al conectar a jaildoctor.duckdns.org" << std::endl;
}
// Obten el Jailer ID
std::fstream f;
f.open(asset->get("jailer_id.txt"), std::ios::in);
if (f.is_open())
{
std::string str;
if (getline(f, options->online.jailerID))
{
f.close();
}
}
f.close();
if (options->online.jailerID == "")
{
screen->showText("No ha especificado ningun Jailer ID");
std::cout << "No ha especificado ningun Jailer ID" << std::endl;
}
else
{
screen->showText(options->online.jailerID + " ha iniciado sesion");
std::cout << options->online.jailerID << " ha iniciado sesion" << std::endl;
}
// Obten la puntuación online
const int points = jscore::getUserPoints(options->online.gameID, options->online.jailerID);
if (points == 0)
{
screen->showText("No se ha podido obtener la puntuacion online");
std::cout << "No se ha podido obtener la puntuacion online" << std::endl;
}
else
{
options->online.score = points;
}
} }

View File

@@ -57,6 +57,9 @@ private:
// Inicializa el objeto input // Inicializa el objeto input
void initInput(); void initInput();
// Inicializa los servicios online
void initOnline();
// Crea el indice de ficheros // Crea el indice de ficheros
bool setFileList(); bool setFileList();

View File

@@ -1,4 +1,5 @@
#include "game.h" #include "game.h"
#include "common/jscore.h"
// Constructor // Constructor
Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang, Input *input, bool demo, options_t *options) Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang, Input *input, bool demo, options_t *options)
@@ -54,6 +55,7 @@ Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, Screen *scr
Game::~Game() Game::~Game()
{ {
saveScoreFile(); saveScoreFile();
sendOnlineScore();
saveDemoFile(); saveDemoFile();
// Restaura el metodo de control // Restaura el metodo de control
@@ -725,6 +727,28 @@ bool Game::saveScoreFile()
return success; return success;
} }
// Sube la puntuación online
bool Game::sendOnlineScore()
{
const int score = players.at(0)->getScore();
if (score <= options->online.score)
{
return true;
}
if (jscore::updateUserPoints("coffee_crisis", options->online.jailerID, score))
{
options->online.score = score;
screen->showText("PUNTUACION ENVIADA: " + std::to_string(score) + " PUNTOS");
return true;
}
else
{
screen->showText("NO SE HA PODIDO ENVIAR LA PUNTUACION");
return false;
}
}
// Guarda el fichero de datos para la demo // Guarda el fichero de datos para la demo
bool Game::saveDemoFile() bool Game::saveDemoFile()
{ {
@@ -1659,7 +1683,9 @@ void Game::renderScoreBoard()
// HI-SCORE // HI-SCORE
textScoreBoard->writeCentered(PLAY_AREA_CENTER_X, offset3, lang->getText(56)); textScoreBoard->writeCentered(PLAY_AREA_CENTER_X, offset3, lang->getText(56));
textScoreBoard->writeCentered(PLAY_AREA_CENTER_X, offset4, updateScoreText(hiScore)); // textScoreBoard->writeCentered(PLAY_AREA_CENTER_X, offset4, updateScoreText(hiScore));
const std::string txt = jscore::getUserName(0) + " - " + updateScoreText((Uint32)jscore::getPoints(0));
textScoreBoard->writeCentered(PLAY_AREA_CENTER_X, offset4, txt);
} }
// Actualiza las variables del jugador // Actualiza las variables del jugador
@@ -3581,6 +3607,9 @@ void Game::runGameOverScreen()
// Guarda los puntos // Guarda los puntos
saveScoreFile(); saveScoreFile();
// Sube la puntuación online
sendOnlineScore();
// Reinicia el menu // Reinicia el menu
gameOverMenu->reset(); gameOverMenu->reset();

View File

@@ -262,6 +262,9 @@ private:
// Guarda el fichero de puntos // Guarda el fichero de puntos
bool saveScoreFile(); bool saveScoreFile();
// Sube la puntuación online
bool sendOnlineScore();
// Guarda el fichero de datos para la demo // Guarda el fichero de datos para la demo
bool saveDemoFile(); bool saveDemoFile();

View File

@@ -1,4 +1,5 @@
#include "title.h" #include "title.h"
#include "common/jscore.h"
// Constructor // Constructor
Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset, options_t *options, Lang *lang, section_t section) Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset, options_t *options, Lang *lang, section_t section)