Arreglada la clase Screen. Había un lio de conceptos con varias variables

This commit is contained in:
2022-11-18 20:09:03 +01:00
parent 90bdad7d51
commit fdc8797d2b
20 changed files with 708 additions and 128 deletions

2
.gitignore vendored
View File

@@ -10,4 +10,4 @@ thumbs.db
*.tar.gz *.tar.gz
*.zip *.zip
*.app *.app
*_debug *_debug*

View File

@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleIdentifier</key>
<string>com.apple.xcode.dsym.jaildoctors_dilemma_debug</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>dSYM</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>

154
source/common/jscore.cpp Normal file
View File

@@ -0,0 +1,154 @@
#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);
}
};

16
source/common/jscore.h Normal file
View File

@@ -0,0 +1,16 @@
#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);
};

156
source/common/notify.cpp Normal file
View File

@@ -0,0 +1,156 @@
#include "notify.h"
#include <string>
#include <stdio.h>
// Constructor
Notify::Notify(SDL_Renderer *renderer, std::string bitmapFile, std::string textFile)
{
// Inicializa variables
this->renderer = renderer;
bgColor = {64, 64, 64};
waitTime = 300;
// Crea objetos
texture = new Texture(renderer, bitmapFile);
text = new Text(textFile, texture, renderer);
}
// Destructor
Notify::~Notify()
{
// Libera la memoria de los objetos
delete texture;
delete text;
for (auto notification : notifications)
{
delete notification.sprite;
delete notification.texture;
}
}
// Dibuja las notificaciones por pantalla
void Notify::render()
{
for (int i = (int)notifications.size() - 1; i >= 0; --i)
{
notifications.at(i).sprite->render();
}
}
// Actualiza el estado de las notificaiones
void Notify::update()
{
for (int i = 0; i < (int)notifications.size(); ++i)
{
notifications.at(i).counter++;
// Comprueba los estados
if (notifications.at(i).state == ns_rising)
{
const float step = ((float)notifications.at(i).counter / notifications.at(i).travelDist);
const int alpha = 255 * step;
notifications.at(i).rect.y++;
notifications.at(i).texture->setAlpha(alpha);
if (notifications.at(i).rect.y == notifications.at(i).y)
{
notifications.at(i).state = ns_stay;
notifications.at(i).texture->setAlpha(255);
notifications.at(i).counter = 0;
}
}
else if (notifications.at(i).state == ns_stay)
{
if (notifications.at(i).counter == waitTime)
{
notifications.at(i).state = ns_vanishing;
notifications.at(i).counter = 0;
}
}
else if (notifications.at(i).state == ns_vanishing)
{
const float step = (notifications.at(i).counter / (float)notifications.at(i).travelDist);
const int alpha = 255 * (1 - step);
notifications.at(i).rect.y--;
notifications.at(i).texture->setAlpha(alpha);
if (notifications.at(i).rect.y == notifications.at(i).y - notifications.at(i).travelDist)
{
notifications.at(i).state = ns_finished;
}
}
notifications.at(i).sprite->setRect(notifications.at(i).rect);
}
clearFinishedNotifications();
}
// Elimina las notificaciones finalizadas
void Notify::clearFinishedNotifications()
{
for (int i = (int)notifications.size() - 1; i >= 0; --i)
{
if (notifications.at(i).state == ns_finished)
{
delete notifications.at(i).sprite;
delete notifications.at(i).texture;
notifications.erase(notifications.begin() + i);
}
}
}
// Muestra una notificación de texto por pantalla;
void Notify::showText(std::string text)
{
// Crea constantes
const int width = this->text->lenght(text) + (this->text->getCharacterSize() * 2);
const int height = this->text->getCharacterSize() * 2;
const int despH = this->text->getCharacterSize() / 2;
const int despV = despH;
const int travelDist = height + despV;
// const int offset = (int)notifications.size() * (travelDist) + despV;
const int offset = (int)notifications.size() > 0 ? notifications.back().y + travelDist : despV;
// Crea la notificacion
notification_t n;
// inicializa variables
n.y = offset;
n.travelDist = travelDist;
n.counter = 0;
n.state = ns_rising;
n.text = text;
n.rect = {despH, offset - travelDist, width, height};
// Crea la textura
n.texture = new Texture(renderer);
n.texture->createBlank(renderer, width, height, SDL_TEXTUREACCESS_TARGET);
n.texture->setAsRenderTarget(renderer);
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_RenderClear(renderer);
n.texture->setBlendMode(SDL_BLENDMODE_BLEND);
this->text->writeDX(TXT_CENTER | TXT_STROKE, width / 2, despV, text, 1, {255, 255, 255}, 1, {0, 0, 0});
// Crea el sprite
n.sprite = new Sprite(n.rect, n.texture, renderer);
// Añade la notificación a la lista
notifications.push_back(n);
}
// Indica si hay notificaciones activas
bool Notify::active()
{
if ((int)notifications.size() > 0)
{
return true;
}
return false;
}

82
source/common/notify.h Normal file
View File

@@ -0,0 +1,82 @@
#pragma once
#include <SDL2/SDL.h>
#include "text.h"
#include "texture.h"
#include "sprite.h"
#include "utils.h"
#include <vector>
#ifndef NOTIFY_H
#define NOTIFY_H
class Notify
{
private:
enum notification_state_e
{
ns_rising,
ns_stay,
ns_vanishing,
ns_finished
};
enum notification_position_e
{
upperLeft,
upperCenter,
upperRight,
middleLeft,
middleRight,
bottomLeft,
bottomCenter,
bottomRight
};
struct notification_t
{
std::string text;
int counter;
notification_state_e state;
notification_position_e position;
Texture *texture;
Sprite *sprite;
SDL_Rect rect;
int y;
int travelDist;
};
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Texture *texture; // Textura para la fuente de las notificaciones
Text *text; // Objeto para dibujar texto
// Variables
color_t bgColor; // Color de fondo de las notificaciones
int waitTime; // Tiempo que se ve la notificación
std::vector<notification_t> notifications; // La lista de notificaciones activas
// Elimina las notificaciones finalizadas
void clearFinishedNotifications();
public:
// Dibuja las notificaciones por pantalla
void render();
// Actualiza el estado de las notificaiones
void update();
// Constructor
Notify(SDL_Renderer *renderer, std::string bitmapFile, std::string textFile);
// Destructor
~Notify();
// Muestra una notificación de texto por pantalla;
void showText(std::string text);
// Indica si hay notificaciones activas
bool active();
};
#endif

View File

@@ -3,15 +3,19 @@
#include <iostream> #include <iostream>
// Constructor // Constructor
Screen::Screen(SDL_Window *window, SDL_Renderer *renderer, options_t *options, int gameInternalResX, int gameInternalResY) Screen::Screen(SDL_Window *window, SDL_Renderer *renderer, Asset *asset, options_t *options)
{ {
// Inicializa variables // Inicializa variables
this->window = window; this->window = window;
this->renderer = renderer; this->renderer = renderer;
this->options = options; this->options = options;
this->asset = asset;
gameCanvasWidth = gameInternalResX; // Crea los objetos
gameCanvasHeight = gameInternalResY; notify = new Notify(renderer, asset->get("smb2.png"), asset->get("smb2.txt"));
gameCanvasWidth = options->gameWidth;
gameCanvasHeight = options->gameHeight;
iniFade(); iniFade();
iniSpectrumFade(); iniSpectrumFade();
@@ -27,15 +31,16 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer, options_t *options, i
} }
// Establece el modo de video // Establece el modo de video
setVideoMode(options->fullScreenMode); setVideoMode(options->videoMode);
// Calcula los anclajes // Inicializa variables
anchor.left = 0; notifyActive = false;
anchor.right = gameCanvasWidth; }
anchor.center = gameCanvasWidth / 2;
anchor.top = 0; // Destructor
anchor.bottom = gameCanvasHeight; Screen::~Screen()
anchor.middle = gameCanvasHeight / 2; {
delete notify;
} }
// Limpia la pantalla // Limpia la pantalla
@@ -64,42 +69,49 @@ void Screen::blit()
// Copia la textura de juego en el renderizador en la posición adecuada // Copia la textura de juego en el renderizador en la posición adecuada
SDL_RenderCopy(renderer, gameCanvas, nullptr, &dest); SDL_RenderCopy(renderer, gameCanvas, nullptr, &dest);
// Dibuja las notificaciones
// renderNotifications();
// Muestra por pantalla el renderizador // Muestra por pantalla el renderizador
SDL_RenderPresent(renderer); SDL_RenderPresent(renderer);
} }
// Establece el modo de video // Establece el modo de video
void Screen::setVideoMode(int fullScreenMode) void Screen::setVideoMode(int videoMode)
{ {
// Aplica el modo de video // Aplica el modo de video
SDL_SetWindowFullscreen(window, fullScreenMode); SDL_SetWindowFullscreen(window, videoMode);
// Si está activo el modo ventana quita el borde // Si está activo el modo ventana quita el borde
if (fullScreenMode == 0) if (videoMode == 0)
{ {
if (options->borderEnabled) if (options->borderEnabled)
{ {
const int incWidth = gameCanvasWidth * options->borderSize; const int incWidth = options->gameWidth * options->borderSize;
const int incHeight = gameCanvasHeight * options->borderSize; const int incHeight = options->gameHeight * options->borderSize;
screenWidth = gameCanvasWidth + incWidth; gameCanvasWidth = options->gameWidth + incWidth;
screenHeight = gameCanvasHeight + incHeight; gameCanvasHeight = options->gameHeight + incHeight;
dest = {0 + (incWidth / 2), 0 + (incHeight / 2), gameCanvasWidth, gameCanvasHeight}; screenWidth = gameCanvasWidth * options->windowSize;
screenHeight = gameCanvasHeight * options->windowSize;
dest = {0 + (incWidth / 2), 0 + (incHeight / 2), options->gameWidth, options->gameHeight};
} }
else else
{ {
screenWidth = gameCanvasWidth; gameCanvasWidth = options->gameWidth;
screenHeight = gameCanvasHeight; gameCanvasHeight = options->gameHeight;
screenWidth = gameCanvasWidth * options->windowSize;
screenHeight = gameCanvasHeight * options->windowSize;
dest = {0, 0, gameCanvasWidth, gameCanvasHeight}; dest = {0, 0, gameCanvasWidth, gameCanvasHeight};
} }
// Modifica el tamaño del renderizador y de la ventana // Modifica el tamaño del renderizador y de la ventana
SDL_RenderSetLogicalSize(renderer, screenWidth, screenHeight); SDL_RenderSetLogicalSize(renderer, gameCanvasWidth, gameCanvasHeight);
SDL_SetWindowSize(window, screenWidth * options->windowSize, screenHeight * options->windowSize); SDL_SetWindowSize(window, screenWidth, screenHeight);
} }
// Si está activo el modo de pantalla completa añade el borde // Si está activo el modo de pantalla completa añade el borde
else if (fullScreenMode == SDL_WINDOW_FULLSCREEN_DESKTOP) else if (videoMode == SDL_WINDOW_FULLSCREEN_DESKTOP)
{ {
// Obten el alto y el ancho de la ventana // Obten el alto y el ancho de la ventana
SDL_GetWindowSize(window, &screenWidth, &screenHeight); SDL_GetWindowSize(window, &screenWidth, &screenHeight);
@@ -149,22 +161,14 @@ void Screen::setVideoMode(int fullScreenMode)
} }
// Actualiza el valor de la variable // Actualiza el valor de la variable
options->fullScreenMode = fullScreenMode; options->videoMode = videoMode;
} }
// Camibia entre pantalla completa y ventana // Camibia entre pantalla completa y ventana
void Screen::switchVideoMode() void Screen::switchVideoMode()
{ {
if (options->fullScreenMode == 0) options->videoMode = (options->videoMode == 0) ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0;
{ setVideoMode(options->videoMode);
options->fullScreenMode = SDL_WINDOW_FULLSCREEN_DESKTOP;
}
else
{
options->fullScreenMode = 0;
}
setVideoMode(options->fullScreenMode);
} }
// Cambia el tamaño de la ventana // Cambia el tamaño de la ventana
@@ -338,4 +342,30 @@ void Screen::renderFX()
{ {
renderFade(); renderFade();
renderSpectrumFade(); renderSpectrumFade();
}
// Actualiza el notificador
void Screen::updateNotifier()
{
notify->update();
notifyActive = notify->active();
}
// Muestra una notificación de texto por pantalla;
void Screen::showText(std::string text)
{
notify->showText(text);
}
// Dibuja las notificaciones
void Screen::renderNotifications()
{
if (!notifyActive)
{
return;
}
SDL_RenderSetLogicalSize(renderer, screenWidth, screenHeight);
notify->render();
SDL_RenderSetLogicalSize(renderer, gameCanvasWidth, gameCanvasHeight);
} }

View File

@@ -1,6 +1,8 @@
#pragma once #pragma once
#include <SDL2/SDL.h> #include <SDL2/SDL.h>
#include "asset.h"
#include "notify.h"
#include "utils.h" #include "utils.h"
#include <vector> #include <vector>
@@ -10,42 +12,33 @@
#define FILTER_NEAREST 0 #define FILTER_NEAREST 0
#define FILTER_LINEAL 1 #define FILTER_LINEAL 1
struct anchor_t
{
int left; // Parte izquierda de la pantalla de juego
int right; // Parte drecha de la pantalla de juego
int center; // Parte central horizontal de la pantalla de juego
int top; // Parte superior de la pantalla de juego
int bottom; // Parte infoerior de la pantalla de juego
int middle; // Parte central vertical de la pantalla de juego
};
// Clase Screen
class Screen class Screen
{ {
private: private:
// Objetos y punteros // Objetos y punteros
SDL_Window *window; // Ventana de la aplicación SDL_Window *window; // Ventana de la aplicación
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer; // El renderizador de la ventana
Asset *asset; // Objeto con el listado de recursos
SDL_Texture *gameCanvas; // Textura para completar la ventana de juego hasta la pantalla completa SDL_Texture *gameCanvas; // Textura para completar la ventana de juego hasta la pantalla completa
options_t *options; // Variable con todas las opciones del programa options_t *options; // Variable con todas las opciones del programa
Notify *notify; // Dibuja notificaciones por pantalla
// Variables // Variables
int screenWidth; // Ancho de la pantalla o ventana int screenWidth; // Ancho de la pantalla o ventana
int screenHeight; // Alto de la pantalla o ventana int screenHeight; // Alto de la pantalla o ventana
int gameCanvasWidth; // Resolución interna del juego. Es el ancho de la textura donde se dibuja el juego int gameCanvasWidth; // Resolución interna del juego. Es el ancho de la textura donde se dibuja el juego
int gameCanvasHeight; // Resolución interna del juego. Es el alto de la textura donde se dibuja el juego int gameCanvasHeight; // Resolución interna del juego. Es el alto de la textura donde se dibuja el juego
anchor_t anchor; // Variable con los anclajes de la pantalla
SDL_Rect dest; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana SDL_Rect dest; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana
color_t borderColor; // Color del borde añadido a la textura de juego para rellenar la pantalla color_t borderColor; // Color del borde añadido a la textura de juego para rellenar la pantalla
bool notifyActive; // Indica si hay notificaciones activas
// Variables - Efectos // Variables - Efectos
bool fade; // Indica si esta activo el efecto de fade bool fade; // Indica si esta activo el efecto de fade
int fadeCounter; // Temporizador para el efecto de fade int fadeCounter; // Temporizador para el efecto de fade
int fadeLenght; // Duración del fade int fadeLenght; // Duración del fade
bool spectrumFade; // Indica si esta activo el efecto de fade spectrum bool spectrumFade; // Indica si esta activo el efecto de fade spectrum
int spectrumFadeCounter; // Temporizador para el efecto de fade spectrum int spectrumFadeCounter; // Temporizador para el efecto de fade spectrum
int spectrumFadeLenght; // Duración del fade spectrum int spectrumFadeLenght; // Duración del fade spectrum
std::vector<color_t> spectrumColor; // Colores para el fade spectrum std::vector<color_t> spectrumColor; // Colores para el fade spectrum
// Inicializa las variables para el fade // Inicializa las variables para el fade
@@ -66,9 +59,15 @@ private:
// Dibuja el spectrum fade // Dibuja el spectrum fade
void renderSpectrumFade(); void renderSpectrumFade();
// Dibuja las notificaciones
void renderNotifications();
public: public:
// Constructor // Constructor
Screen(SDL_Window *window, SDL_Renderer *renderer, options_t *options, int gameInternalResX, int gameInternalResY); Screen(SDL_Window *window, SDL_Renderer *renderer, Asset *asset, options_t *options);
// Destructor
~Screen();
// Limpia la pantalla // Limpia la pantalla
void clean(color_t color = {0x00, 0x00, 0x00}); void clean(color_t color = {0x00, 0x00, 0x00});
@@ -80,7 +79,7 @@ public:
void blit(); void blit();
// Establece el modo de video // Establece el modo de video
void setVideoMode(int fullScreenMode); void setVideoMode(int videoMode);
// Camibia entre pantalla completa y ventana // Camibia entre pantalla completa y ventana
void switchVideoMode(); void switchVideoMode();
@@ -120,6 +119,12 @@ public:
// Dibuja los efectos // Dibuja los efectos
void renderFX(); void renderFX();
// Actualiza el notificador
void updateNotifier();
// Muestra una notificación de texto por pantalla;
void showText(std::string text);
}; };
#endif #endif

View File

@@ -70,24 +70,36 @@ 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
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 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
{ {
Uint32 fullScreenMode; // Contiene el valor del modo de pantalla completa Uint32 videoMode; // Contiene el valor del modo de pantalla completa
int windowSize; // Contiene el valor por el que se multiplica el tamaño de la ventana int windowSize; // Contiene el valor por el que se multiplica el tamaño de la ventana
Uint32 filter; // Filtro usado para el escalado de la imagen Uint32 filter; // Filtro usado para el escalado de la imagen
bool vSync; // Indica si se quiere usar vsync o no bool vSync; // Indica si se quiere usar vsync o no
int screenWidth; // Ancho de la pantalla o ventana int gameWidth; // Ancho de la resolucion nativa del juego
int screenHeight; // Alto de la pantalla o ventana int gameHeight; // Alto de la resolucion nativa del juego
bool integerScale; // Indica si el escalado de la imagen ha de ser entero en el modo a pantalla completa bool integerScale; // Indica si el escalado de la imagen ha de ser entero en 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 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
palette_e palette; // Paleta de colores a usar en el juego palette_e palette; // Paleta de colores a usar en el juego
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
int rooms; // Cantidad de habitaciones visitadas int rooms; // Cantidad de habitaciones visitadas
int items; // Cantidad de items obtenidos int items; // Cantidad de items obtenidos
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

@@ -168,7 +168,7 @@ void Credits::fillTexture()
{ {
// Inicializa los textos // Inicializa los textos
iniTexts(); iniTexts();
// Rellena la textura de texto // Rellena la textura de texto
SDL_SetRenderTarget(renderer, textTexture); SDL_SetRenderTarget(renderer, textTexture);
color_t c = stringToColor(options->palette, "black"); color_t c = stringToColor(options->palette, "black");
@@ -264,6 +264,9 @@ void Credits::update()
// Actualiza el contador // Actualiza el contador
updateCounter(); updateCounter();
// Actualiza las notificaciones
screen->updateNotifier();
// Actualiza el sprite con el brillo // Actualiza el sprite con el brillo
if (counter > 770) if (counter > 770)
{ {

View File

@@ -153,6 +153,9 @@ void Demo::update()
scoreboard->update(); scoreboard->update();
screen->updateFX(); screen->updateFX();
checkRoomChange(); checkRoomChange();
// Actualiza las notificaciones
screen->updateNotifier();
} }
} }
@@ -189,7 +192,7 @@ void Demo::renderRoomName()
// Recarga todas las texturas // Recarga todas las texturas
void Demo::reLoadTextures() void Demo::reLoadTextures()
{ {
if (options->console) if (options->console)
{ {
std::cout << "** RELOAD REQUESTED" << std::endl; std::cout << "** RELOAD REQUESTED" << std::endl;
} }

View File

@@ -1,3 +1,4 @@
#include "common/jscore.h"
#include "common/utils.h" #include "common/utils.h"
#include "director.h" #include "director.h"
#include <errno.h> #include <errno.h>
@@ -52,11 +53,14 @@ Director::Director(int argc, char *argv[])
resource = new Resource(renderer, asset, options); resource = new Resource(renderer, asset, options);
input = new Input(asset->get("gamecontrollerdb.txt")); input = new Input(asset->get("gamecontrollerdb.txt"));
initInput(); initInput();
screen = new Screen(window, renderer, options, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); screen = new Screen(window, renderer, asset, options);
screen->setBorderColor(borderColor); screen->setBorderColor(borderColor);
screen->setVideoMode(options->fullScreenMode); // screen->setVideoMode(options->videoMode);
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());
// Inicializa los servicios online
// initOnline();
} }
Director::~Director() Director::~Director()
@@ -78,6 +82,56 @@ Director::~Director()
SDL_Quit(); SDL_Quit();
} }
// Inicializa los servicios online
void Director::initOnline()
{
if (!options->online.enabled)
{
return;
}
// Obten el Jailer ID
if (options->online.jailerID == "")
{ // Jailer ID no definido
screen->showText("No ha especificado ningun Jailer ID");
std::cout << "No ha especificado ningun Jailer ID" << std::endl;
}
else
{ // Jailer ID iniciado
// Establece el servidor y el puerto
jscore::init(options->online.server, options->online.port);
// Obtiene la información online
if (jscore::initOnlineScore(options->online.gameID))
{
screen->showText(options->online.jailerID + " ha iniciado sesion");
std::cout << options->online.jailerID << " ha iniciado sesion" << std::endl;
}
else
{
screen->showText("Fallo al conectar a " + options->online.server);
std::cout << "Fallo al conectar a " << options->online.server << std::endl;
options->online.enabled = false;
return;
}
// Obten las estadisticas online
const int points = jscore::getUserPoints(options->online.gameID, options->online.jailerID);
if (points == 0)
{ // Fallo de conexión o no hay registros
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;
}
}
}
// Crea e inicializa las opciones del programa // Crea e inicializa las opciones del programa
void Director::iniOptions() void Director::iniOptions()
{ {
@@ -85,7 +139,9 @@ void Director::iniOptions()
options = new options_t; options = new options_t;
// Inicializa valores // Inicializa valores
options->fullScreenMode = 0; options->gameWidth = GAMECANVAS_WIDTH;
options->gameHeight = GAMECANVAS_HEIGHT;
options->videoMode = 0;
options->windowSize = 3; options->windowSize = 3;
options->filter = FILTER_NEAREST; options->filter = FILTER_NEAREST;
options->vSync = true; options->vSync = true;
@@ -103,6 +159,13 @@ void Director::iniOptions()
options->cheat.altSkin = false; options->cheat.altSkin = false;
options->rooms = 0; options->rooms = 0;
options->items = 0; options->items = 0;
// Online
options->online.enabled = false;
options->online.server = "";
options->online.port = 0;
options->online.gameID = "jaildoctors_dilemma_test";
options->online.jailerID = "";
} }
// Comprueba los parametros del programa // Comprueba los parametros del programa
@@ -193,19 +256,33 @@ bool Director::loadConfig()
saveConfig(); saveConfig();
} }
// Normaliza los valores
const bool a = options->videoMode == 0;
const bool b = options->videoMode == SDL_WINDOW_FULLSCREEN;
const bool c = options->videoMode == SDL_WINDOW_FULLSCREEN_DESKTOP;
if (!(a || b || c))
{
options->videoMode = 0;
}
if (options->windowSize < 1 || options->windowSize > 4)
{
options->windowSize = 3;
}
// Aplica opciones // Aplica opciones
if (options->borderEnabled) // if (options->borderEnabled)
{ //{
const int incWidth = GAMECANVAS_WIDTH * options->borderSize; // const int incWidth = GAMECANVAS_WIDTH * options->borderSize;
const int incHeight = GAMECANVAS_HEIGHT * options->borderSize; // const int incHeight = GAMECANVAS_HEIGHT * options->borderSize;
options->screenWidth = (GAMECANVAS_WIDTH + incWidth) * options->windowSize; // options->gameWidth = GAMECANVAS_WIDTH + incWidth;
options->screenHeight = (GAMECANVAS_HEIGHT + incHeight) * options->windowSize; // options->gameHeight = GAMECANVAS_HEIGHT + incHeight;
} //}
else // else
{ //{
options->screenWidth = GAMECANVAS_WIDTH * options->windowSize; // options->gameWidth = GAMECANVAS_WIDTH;
options->screenHeight = GAMECANVAS_HEIGHT * options->windowSize; // options->gameHeight = GAMECANVAS_HEIGHT;
} //}
return success; return success;
} }
@@ -234,19 +311,20 @@ bool Director::saveConfig()
} }
// Escribe en el fichero // Escribe en el fichero
if (options->fullScreenMode == 0) file << "## VISUAL OPTIONS\n";
if (options->videoMode == 0)
{ {
file << "fullScreenMode=0\n"; file << "videoMode=0\n";
} }
else if (options->fullScreenMode == SDL_WINDOW_FULLSCREEN) else if (options->videoMode == SDL_WINDOW_FULLSCREEN)
{ {
file << "fullScreenMode=SDL_WINDOW_FULLSCREEN\n"; file << "videoMode=SDL_WINDOW_FULLSCREEN\n";
} }
else if (options->fullScreenMode == SDL_WINDOW_FULLSCREEN_DESKTOP) else if (options->videoMode == SDL_WINDOW_FULLSCREEN_DESKTOP)
{ {
file << "fullScreenMode=SDL_WINDOW_FULLSCREEN_DESKTOP\n"; file << "videoMode=SDL_WINDOW_FULLSCREEN_DESKTOP\n";
} }
file << "windowSize=" + std::to_string(options->windowSize) + "\n"; file << "windowSize=" + std::to_string(options->windowSize) + "\n";
@@ -267,6 +345,12 @@ bool Director::saveConfig()
file << "borderSize=" + std::to_string(options->borderSize) + "\n"; file << "borderSize=" + std::to_string(options->borderSize) + "\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";
// Cierra el fichero // Cierra el fichero
file.close(); file.close();
@@ -277,15 +361,15 @@ bool Director::saveConfig()
void Director::createSystemFolder() void Director::createSystemFolder()
{ {
#ifdef _WIN32 #ifdef _WIN32
systemFolder = std::string(getenv("APPDATA")) + "/jailgames/jaildoctors_dilemma"; systemFolder = std::string(getenv("APPDATA")) + "/jaildoctors_dilemma";
#elif __APPLE__ #elif __APPLE__
struct passwd *pw = getpwuid(getuid()); struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir; const char *homedir = pw->pw_dir;
systemFolder = std::string(homedir) + "/Library/Application Support/jailgames/jaildoctors_dilemma"; systemFolder = std::string(homedir) + "/Library/Application Support/jaildoctors_dilemma";
#elif __linux__ #elif __linux__
struct passwd *pw = getpwuid(getuid()); struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir; const char *homedir = pw->pw_dir;
systemFolder = std::string(homedir) + "/.jailgames/jaildoctors_dilemma"; systemFolder = std::string(homedir) + "/.jaildoctors_dilemma";
#endif #endif
struct stat st = {0}; struct stat st = {0};
@@ -883,19 +967,19 @@ bool Director::setOptions(options_t *options, std::string var, std::string value
// Indicador de éxito en la asignación // Indicador de éxito en la asignación
bool success = true; bool success = true;
if (var == "fullScreenMode") if (var == "videoMode")
{ {
if (value == "SDL_WINDOW_FULLSCREEN_DESKTOP") if (value == "SDL_WINDOW_FULLSCREEN_DESKTOP")
{ {
options->fullScreenMode = SDL_WINDOW_FULLSCREEN_DESKTOP; options->videoMode = SDL_WINDOW_FULLSCREEN_DESKTOP;
} }
else if (value == "SDL_WINDOW_FULLSCREEN") else if (value == "SDL_WINDOW_FULLSCREEN")
{ {
options->fullScreenMode = SDL_WINDOW_FULLSCREEN; options->videoMode = SDL_WINDOW_FULLSCREEN;
} }
else else
{ {
options->fullScreenMode = 0; options->videoMode = 0;
} }
} }
@@ -964,7 +1048,31 @@ bool Director::setOptions(options_t *options, std::string var, std::string value
} }
} }
else if (var == "") 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 == "" || var.substr(0, 1) == "#")
{ {
} }
@@ -1044,7 +1152,15 @@ bool Director::initSDL()
} }
// Crea la ventana // Crea la ventana
window = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, options->screenWidth, options->screenHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); int incW = 0;
int incH = 0;
if (options->borderEnabled)
{
incW = options->gameWidth * options->borderSize;
incH = options->gameHeight * options->borderSize;
}
window = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (options->gameWidth + incW) * options->windowSize, (options->gameHeight + incH) * options->windowSize, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI);
if (window == nullptr) if (window == nullptr)
{ {
if (options->console) if (options->console)
@@ -1079,7 +1195,7 @@ bool Director::initSDL()
SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF); SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF);
// Establece el tamaño del buffer de renderizado // Establece el tamaño del buffer de renderizado
SDL_RenderSetLogicalSize(renderer, options->screenWidth, options->screenHeight); SDL_RenderSetLogicalSize(renderer, options->gameWidth, options->gameHeight);
// Establece el modo de mezcla // Establece el modo de mezcla
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);

View File

@@ -51,6 +51,9 @@ private:
section_t section; // Sección y subsección actual del programa; section_t section; // Sección y subsección actual del programa;
std::string systemFolder; // Carpeta del sistema donde guardar datos std::string systemFolder; // Carpeta del sistema donde guardar datos
// Inicializa los servicios online
void initOnline();
// Crea e inicializa las opciones del programa // Crea e inicializa las opciones del programa
void iniOptions(); void iniOptions();

View File

@@ -103,6 +103,9 @@ void Ending::update()
// Actualiza el volumen de la musica // Actualiza el volumen de la musica
updateMusicVolume(); updateMusicVolume();
// Actualiza las notificaciones
screen->updateNotifier();
} }
} }

View File

@@ -102,6 +102,9 @@ void Ending2::update()
// Actualiza el volumen de la musica // Actualiza el volumen de la musica
updateMusicVolume(); updateMusicVolume();
// Actualiza las notificaciones
screen->updateNotifier();
} }
} }

View File

@@ -233,6 +233,9 @@ void Game::update()
updateBlackScreen(); updateBlackScreen();
// Actualiza las notificaciones
screen->updateNotifier();
#ifdef DEBUG #ifdef DEBUG
updateDebugInfo(); updateDebugInfo();
#endif #endif

View File

@@ -73,6 +73,9 @@ void GameOver::update()
// Actualiza los dos sprites // Actualiza los dos sprites
playerSprite->update(); playerSprite->update();
tvSprite->update(); tvSprite->update();
// Actualiza las notificaciones
screen->updateNotifier();
} }
} }
@@ -97,7 +100,6 @@ void GameOver::render()
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, GAMECANVAS_CENTER_Y + 40, "ITEMS: " + itemsTxt, 1, color); text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, GAMECANVAS_CENTER_Y + 40, "ITEMS: " + itemsTxt, 1, color);
text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, GAMECANVAS_CENTER_Y + 55, "ROOMS: " + roomsTxt, 1, color); text->writeDX(TXT_CENTER | TXT_COLOR, GAMECANVAS_CENTER_X, GAMECANVAS_CENTER_Y + 55, "ROOMS: " + roomsTxt, 1, color);
// Vuelca el contenido del renderizador en pantalla // Vuelca el contenido del renderizador en pantalla
screen->blit(); screen->blit();
} }

View File

@@ -251,6 +251,9 @@ void Intro::update()
// Gestiona el contador de carga // Gestiona el contador de carga
updateLoad(); updateLoad();
// Actualiza las notificaciones
screen->updateNotifier();
// Comprueba si ha terminado la intro // Comprueba si ha terminado la intro
if (loadCounter >= 768) if (loadCounter >= 768)
{ {
@@ -281,7 +284,7 @@ void Intro::render()
section_t Intro::run() section_t Intro::run()
{ {
// Inicia el sonido de carga // Inicia el sonido de carga
JA_SetVolume(64); JA_SetVolume(64);
JA_PlayMusic(loadingSound1); JA_PlayMusic(loadingSound1);
while (section.name == SECTION_PROG_INTRO) while (section.name == SECTION_PROG_INTRO)
@@ -290,7 +293,7 @@ section_t Intro::run()
render(); render();
} }
JA_SetVolume(128); JA_SetVolume(128);
return section; return section;
} }

View File

@@ -85,7 +85,7 @@ void Logo::checkEventHandler()
switch (eventHandler->key.keysym.scancode) switch (eventHandler->key.keysym.scancode)
{ {
case SDL_SCANCODE_ESCAPE: case SDL_SCANCODE_ESCAPE:
//std::cout << "PULSADO ESCAPE" << std::endl; // std::cout << "PULSADO ESCAPE" << std::endl;
section.name = SECTION_PROG_QUIT; section.name = SECTION_PROG_QUIT;
break; break;
@@ -262,6 +262,9 @@ void Logo::update()
// Gestiona el color de las texturas // Gestiona el color de las texturas
updateTextureColors(); updateTextureColors();
// Actualiza las notificaciones
screen->updateNotifier();
// Comprueba si ha terminado el logo // Comprueba si ha terminado el logo
if (counter == endLogo + postLogo) if (counter == endLogo + postLogo)
{ {

View File

@@ -176,6 +176,9 @@ void Title::update()
// Actualiza la marquesina // Actualiza la marquesina
updateMarquee(); updateMarquee();
// Actualiza las notificaciones
screen->updateNotifier();
// Comprueba si ha terminado la marquesina y acaba con el titulo // Comprueba si ha terminado la marquesina y acaba con el titulo
if (letters.at(letters.size() - 1).x < -10) if (letters.at(letters.size() - 1).x < -10)
{ {