En proceso de eliminar el online y los menus

This commit is contained in:
2024-05-10 14:04:50 +02:00
parent 5587b25e41
commit b5c04c6c26
11 changed files with 11 additions and 1236 deletions

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

@@ -1,4 +1,3 @@
#include "common/jscore.h"
#include "common/utils.h"
#include "const.h"
#include "director.h"
@@ -60,9 +59,6 @@ Director::Director(int argc, char *argv[])
initInput();
screen = new Screen(window, renderer, asset, options);
// Inicializa los servicios online
initOnline();
}
Director::~Director()
@@ -719,66 +715,6 @@ void Director::run()
}
}
// Inicializa los servicios online
void Director::initOnline()
{
if (options->online.sessionEnabled)
{ // Si ya ha iniciado la sesión, que no continue
return;
}
if (options->online.jailerID == "")
{ // Jailer ID no definido
options->online.enabled = 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 = options->online.jailerID + " (DEBUG)";
#else
const std::string caption = options->online.jailerID;
#endif
//screen->showNotification(caption, lang->getText(85), 12);
screen->showNotification(caption, lang->getText(85));
if (options->console)
{
std::cout << caption << std::endl;
}
// Obtiene la información de puntuaciones online
if (!jscore::initOnlineScore(options->online.gameID))
{
screen->showNotification(lang->getText(80), options->online.server);
if (options->console)
{
std::cout << "Can't connect to " << options->online.server << std::endl;
}
options->online.enabled = false;
return;
}
// Obten la puntuación online para el jailerID
const int points = jscore::getUserPoints(options->online.gameID, options->online.jailerID);
if (points == 0)
{ // Fallo de conexión o no hay registros
screen->showNotification(lang->getText(81), lang->getText(82));
if (options->console)
{
std::cout << "Can't get online scores" << std::endl;
}
}
else
{
options->online.score = points;
}
}
}
// Asigna variables a partir de dos cadenas
bool Director::setOptions(options_t *options, std::string var, std::string value)
{

View File

@@ -59,9 +59,6 @@ private:
// Inicializa el objeto input
void initInput();
// Inicializa los servicios online
void initOnline();
// Inicializa las opciones del programa
void initOptions();

View File

@@ -1,348 +0,0 @@
#include "common/jail_audio.h"
#include "common/jscore.h"
#include "const.h"
#include "enter_id.h"
#include <iostream>
// Constructor
EnterID::EnterID(SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang, options_t *options, section_t *section)
{
// Copia la dirección de los objetos
this->renderer = renderer;
this->screen = screen;
this->asset = asset;
this->lang = lang;
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;
}
// Bucle principal
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_PROG_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_PROG_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;
}
}
}
}
// 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->blit();
}
// Inicializa los textos
void EnterID::iniTexts()
{
const color_t orangeColor = {0xFF, 0x7A, 0x00};
const color_t noColor = {0xFF, 0xFF, 0xFF};
texts.clear();
texts.push_back({lang->getText(89), orangeColor});
texts.push_back({"", noColor});
texts.push_back({lang->getText(90), noColor});
texts.push_back({lang->getText(91), noColor});
texts.push_back({lang->getText(92), noColor});
texts.push_back({"", noColor});
texts.push_back({"", noColor});
texts.push_back({"", noColor});
texts.push_back({"JAILER_ID:", orangeColor});
}
// Escribe el texto en la textura
void EnterID::fillTexture()
{
const color_t shdwTxtColor = {0x43, 0x43, 0x4F};
// Inicializa los textos
iniTexts();
// Rellena la textura con un color de fondo
SDL_SetRenderTarget(renderer, textTexture);
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 0xFF);
SDL_RenderClear(renderer);
// Añade el efecto de degradado en el fondo
//Texture *gradient = new Texture(renderer, asset->get("title_gradient.png"));
//SDL_Rect rect = {0, 0, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT};
//gradient->render(renderer, 0, 0, &rect);
//delete gradient;
// Escribe el texto en la textura
const int desp = 40;
const int size = text->getCharacterSize() + 2;
int i = 0;
for (auto t : texts)
{
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, PLAY_AREA_CENTER_X, (i * size) + desp, t.label, 1, t.color, 1, shdwTxtColor);
i++;
}
jailerIDPos = ((i + 1) * size) + desp;
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 = options->online.jailerID + " (DEBUG)";
#else
const std::string caption = options->online.jailerID;
#endif
// screen->showNotification(caption, lang->getText(85), 12);
screen->showNotification(caption, lang->getText(85));
if (options->console)
{
std::cout << caption << std::endl;
}
// Obtiene la información de puntuaciones online
if (!jscore::initOnlineScore(options->online.gameID))
{
screen->showNotification(lang->getText(80), options->online.server);
if (options->console)
{
std::cout << "Can't connect to " << options->online.server << std::endl;
}
options->online.enabled = false;
return;
}
// Obten la puntuación online para el jailerID
const int points = jscore::getUserPoints(options->online.gameID, options->online.jailerID);
if (points == 0)
{ // Fallo de conexión o no hay registros
screen->showNotification(lang->getText(81), lang->getText(82));
if (options->console)
{
std::cout << "Can't get online scores" << std::endl;
}
}
else
{
options->online.score = points;
}
}
}
// 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;
}
}

View File

@@ -1,85 +0,0 @@
#pragma once
#include <SDL2/SDL.h>
#include "common/asset.h"
#include "common/screen.h"
#include "common/utils.h"
#include "common/text.h"
#include "common/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
Lang *lang; // Objeto para gestionar los textos en diferentes idiomas
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();
public:
// Constructor
EnterID(SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang, options_t *options, section_t *section);
// Destructor
~EnterID();
// Bucle principal
void run();
};
#endif

View File

@@ -1,5 +1,4 @@
#include "game.h"
#include "common/jscore.h"
// Constructor
Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, Screen *screen, Asset *asset, Lang *lang, Input *input, bool demo, options_t *options, section_t *section)
@@ -62,7 +61,6 @@ Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, Screen *scr
Game::~Game()
{
saveScoreFile();
sendOnlineScore();
saveDemoFile();
// Restaura el metodo de control
@@ -766,38 +764,6 @@ bool Game::saveScoreFile()
return success;
}
// Sube la puntuación online
bool Game::sendOnlineScore()
{
if (!options->online.enabled)
{
return true;
}
if (demo.enabled)
{
return true;
}
const int score = players[0]->getScore();
if (score <= options->online.score)
{
return true;
}
if (jscore::updateUserPoints(options->online.gameID, options->online.jailerID, score))
{
options->online.score = score;
screen->showNotification(lang->getText(86) + std::to_string(score), "", 2);
return true;
}
else
{
screen->showNotification(lang->getText(86), lang->getText(87));
return false;
}
}
// Guarda el fichero de datos para la demo
bool Game::saveDemoFile()
{
@@ -3681,9 +3647,6 @@ void Game::runGameOverScreen()
// Guarda los puntos
saveScoreFile();
// Sube la puntuación online
sendOnlineScore();
// Reinicia el menu
gameOverMenu->reset();
@@ -3964,22 +3927,5 @@ void Game::setHiScore()
// Carga el fichero de puntos
loadScoreFile();
// Establece el resto de variables
if (options->online.enabled)
{
if (jscore::getNumUsers() > 0)
{
hiScoreName = jscore::getUserName(0).substr(0, 12) + " - ";
hiScore = (Uint32)jscore::getPoints(0);
}
else
{
hiScoreName = "Bacteriol - ";
hiScore = 10;
}
}
else
{
hiScoreName = "";
}
hiScoreName = "";
}

View File

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

View File

@@ -1,5 +1,4 @@
#include "hiscore_table.h"
#include "common/jscore.h"
#include <iostream>
const Uint8 SELF = 0;
@@ -109,41 +108,23 @@ void HiScoreTable::render()
// Escribe el texto: Mejores puntuaciones
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, GAMECANVAS_CENTER_X, 8, lang->getText(42), 1, orangeColor, 1, shdwTxtColor);
// Escribe la lista de jugadores
int numUsers = jscore::getNumUsers();
for (int i = 0; i < numUsers; ++i)
// Rellena la lista con nombres
std::vector<std::string> names;
names.insert(names.end(), {"Bry", "Usufondo", "G.Lucas", "P.Delgat", "P.Arrabalera", "Pelechano", "Sahuquillo", "Bacteriol", "Pepe", "Rosita"});
for (int i = 0; i < 10; ++i)
{
const std::string userName = jscore::getUserName(i).substr(0, 17);
const int nameLenght = (int)userName.length();
const int nameLenght = names[i].length();
const int numDots = 20 - nameLenght;
std::string dots = "";
for (int j = 0; j < numDots; ++j)
{
dots = dots + ".";
}
const std::string line = userName + dots + scoreToString(jscore::getPoints(i));
const std::string line = names[i] + dots + "0000000";
text->writeDX(TXT_CENTER | TXT_SHADOW, GAMECANVAS_CENTER_X, (i * spaceBetweenLines) + spaceBetweenHeader, line, 1, orangeColor, 1, shdwTxtColor);
}
// Rellena la lista con otros nombres
if (numUsers < 10)
{
std::vector<std::string> names;
names.insert(names.end(), {"Bry", "Usufondo", "G.Lucas", "P.Delgat", "P.Arrabalera", "Pelechano", "Sahuquillo", "Bacteriol", "Pepe", "Rosita"});
for (int i = numUsers; i < 10; ++i)
{
const int nameLenght = names[i - numUsers].length();
const int numDots = 20 - nameLenght;
std::string dots = "";
for (int j = 0; j < numDots; ++j)
{
dots = dots + ".";
}
const std::string line = names[i - numUsers] + dots + "0000000";
text->writeDX(TXT_CENTER | TXT_SHADOW, GAMECANVAS_CENTER_X, (i * spaceBetweenLines) + spaceBetweenHeader, line, 1, orangeColor, 1, shdwTxtColor);
}
}
if ((mode == mhst_manual) && (counter % 50 > 14))
{

View File

@@ -1,5 +1,4 @@
#include "title.h"
#include "common/jscore.h"
// Constructor
Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset, options_t *options, Lang *lang, section_t *section)
@@ -31,15 +30,6 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset,
text1 = new Text(asset->get("smb2.png"), asset->get("smb2.txt"), renderer);
text2 = new Text(asset->get("8bithud.png"), asset->get("8bithud.txt"), renderer);
#ifdef GAME_CONSOLE
menu.title = new Menu(renderer, asset, input, asset->get("title_gc.men"));
menu.options = new Menu(renderer, asset, input, asset->get("options_gc.men"));
#else
menu.title = new Menu(renderer, asset, input, asset->get("title.men"));
menu.options = new Menu(renderer, asset, input, asset->get("options.men"));
#endif
menu.playerSelect = new Menu(renderer, asset, input, asset->get("player_select.men"));
// Sonidos
crashSound = JA_LoadSound(asset->get("title.wav").c_str());
@@ -77,10 +67,6 @@ Title::~Title()
delete text1;
delete text2;
delete menu.title;
delete menu.options;
delete menu.playerSelect;
JA_DeleteSound(crashSound);
JA_DeleteMusic(titleMusic);
@@ -96,7 +82,6 @@ void Title::init()
backgroundCounter = 0;
backgroundMode = rand() % 2;
menuVisible = false;
menu.active = menu.title;
nextSection.name = SECTION_PROG_GAME;
postFade = 0;
ticks = 0;
@@ -133,11 +118,6 @@ void Title::init()
options->input[1].name = availableInputDevices[deviceIndex[1]].name;
options->input[1].deviceType = availableInputDevices[deviceIndex[1]].deviceType;
}
else
{ // Si no ha encontrado un mando, deshabilita la opción de jugar a 2 jugadores
menu.title->setSelectable(1, false);
menu.title->setGreyed(1, true);
}
// Inicializa el bitmap de Coffee
coffeeBitmap->init();
@@ -203,12 +183,6 @@ void Title::init()
{
sin[i] = SDL_sinf((float)i * 3.14f / 180.0f);
}
// Actualiza los textos de los menus
updateMenuLabels();
// Comprueba si se puede acceder a la tabla de puntuaciones y habilita la opción de menu
setHiScoreTableOptionMenu();
}
// Actualiza las variables del objeto
@@ -313,7 +287,6 @@ void Title::update()
case 3: // TIME OUT
counter = TITLE_COUNTER;
menu.active->reset();
if (demo)
{
runDemoGame();
@@ -337,179 +310,6 @@ void Title::update()
// Actualiza el tileado de fondo
updateBG();
// Comprueba las entradas para el menu
if (menuVisible == true)
{
menu.active->update();
}
// Comprueba si se ha seleccionado algún item del menú de titulo
if (menu.active->getName() == "TITLE")
{
switch (menu.active->getItemSelected())
{
case 0: // 1 PLAYER -> Cambia al manu de selección de jugador
menu.active = menu.playerSelect;
break;
case 1: // 2 PLAYERS
postFade = 1;
fade->activateFade();
break;
case 2: // OPTIONS
menu.active = menu.options;
optionsPrevious = *options;
break;
case 3: // QUIT
postFade = 2;
fade->activateFade();
break;
default:
break;
}
}
// Comprueba si se ha seleccionado algún item del menú de selección de jugador
if (menu.active->getName() == "PLAYER_SELECT")
{
switch (menu.active->getItemSelected())
{
case 0:
// Este item no se puede seleccionar y actua de titulo
break;
case 1: // BAL1
postFade = 0;
options->playerSelected = 0;
fade->activateFade();
break;
case 2: // AROUNDER
postFade = 0;
options->playerSelected = 1;
fade->activateFade();
break;
case 3: // BACK
menu.active = menu.title;
menu.playerSelect->reset();
break;
default:
break;
}
}
// Comprueba si se ha seleccionado algún item de opciones
if (menu.active->getName() == "OPTIONS")
{
switch (menu.active->getItemSelected())
{
case 0: // Difficulty
if (options->difficulty == DIFFICULTY_EASY)
options->difficulty = DIFFICULTY_NORMAL;
else if (options->difficulty == DIFFICULTY_NORMAL)
options->difficulty = DIFFICULTY_HARD;
else
options->difficulty = DIFFICULTY_EASY;
updateMenuLabels();
break;
case 1: // PLAYER 1 CONTROLS
updatePlayerInputs(0);
updateMenuLabels();
break;
case 3: // PLAYER 2 CONTROLS
updatePlayerInputs(1);
updateMenuLabels();
break;
case 5: // Language
options->language++;
if (options->language == 3)
options->language = 0;
updateMenuLabels();
break;
case 6: // Display mode
switchFullScreenModeVar();
if (options->videoMode != 0)
{
menu.options->setSelectable(8, false);
menu.options->setGreyed(8, true);
}
else
{
menu.options->setSelectable(8, true);
menu.options->setGreyed(8, false);
}
updateMenuLabels();
break;
case 8: // Windows size
options->windowSize++;
if (options->windowSize == 5)
options->windowSize = 1;
updateMenuLabels();
break;
case 9: // FILTER
if (options->filter == FILTER_LINEAL)
options->filter = FILTER_NEAREST;
else
options->filter = FILTER_LINEAL;
updateMenuLabels();
break;
case 10: // VSYNC
if (options->vSync)
options->vSync = false;
else
options->vSync = true;
updateMenuLabels();
break;
case 11: // HOW TO PLAY
runInstructions(m_manual);
break;
case 12: // HISCORE TABLE
runHiScoreTable(mhst_manual);
break;
case 13: // JAILERID:
runEnterID();
setHiScoreTableOptionMenu();
updateMenuLabels();
break;
case 14: // ACCEPT
applyOptions();
menu.active->reset();
menu.active = menu.title;
break;
case 15: // CANCEL
options = &optionsPrevious;
updateMenuLabels();
menu.active->reset();
menu.active = menu.title;
break;
default:
break;
}
}
if (menu.active->getName() == "TITLE")
{
counter--;
}
}
else if (counter == 0)
{
@@ -637,22 +437,7 @@ void Title::render()
// Dibuja el degradado
gradient->render();
// Dibuja los objetos
if (menu.active->getName() != "OPTIONS")
{
// Bitmaps con el logo/titulo del juego
coffeeBitmap->render();
crisisBitmap->render();
// Texto con el copyright y versión
text2->writeDX(TXT_CENTER | TXT_SHADOW, GAMECANVAS_CENTER_X, GAMECANVAS_HEIGHT - (BLOCK * 2), TEXT_COPYRIGHT, 1, noColor, 1, shdwTxtColor);
}
if (menuVisible == true)
{
menu.active->render();
}
// Dibuja el polvillo del título
dustBitmapR->render();
dustBitmapL->render();
@@ -768,223 +553,6 @@ void Title::switchFullScreenModeVar()
}
}
// Actualiza los elementos de los menus
void Title::updateMenuLabels()
{
int i = 0;
// DIFFICULTY
switch (options->difficulty)
{
case DIFFICULTY_EASY:
menu.options->setItemCaption(i, lang->getText(59) + ": " + lang->getText(66)); // EASY
break;
case DIFFICULTY_NORMAL:
menu.options->setItemCaption(i, lang->getText(59) + ": " + lang->getText(67)); // NORMAL
break;
case DIFFICULTY_HARD:
menu.options->setItemCaption(i, lang->getText(59) + ": " + lang->getText(68)); // HARD
break;
default:
menu.options->setItemCaption(i, lang->getText(59) + ": " + lang->getText(67)); // NORMAL
break;
}
i++;
// PLAYER 1 CONTROLS
menu.options->setItemCaption(i, lang->getText(62));
i++;
// PLAYER 1 CONTROLS - OPTIONS
switch (options->input[0].deviceType)
{
case INPUT_USE_KEYBOARD:
menu.options->setItemCaption(i, lang->getText(69)); // KEYBOARD
menu.options->setGreyed(i, false);
break;
case INPUT_USE_GAMECONTROLLER:
menu.options->setItemCaption(i, lang->getText(70)); // GAME CONTROLLER
if (!input->gameControllerFound())
menu.options->setGreyed(i, true);
else
{
menu.options->setGreyed(i, false);
menu.options->setItemCaption(i, options->input[0].name);
}
break;
default:
menu.options->setItemCaption(i, lang->getText(69)); // KEYBOARD
break;
}
i++;
// PLAYER 2 CONTROLS
menu.options->setItemCaption(i, lang->getText(63));
i++;
// PLAYER 2 CONTROLS - OPTIONS
switch (options->input[1].deviceType)
{
case INPUT_USE_KEYBOARD:
menu.options->setItemCaption(i, lang->getText(69)); // KEYBOARD
menu.options->setGreyed(i, false);
break;
case INPUT_USE_GAMECONTROLLER:
menu.options->setItemCaption(i, lang->getText(70)); // GAME CONTROLLER
if (!input->gameControllerFound())
menu.options->setGreyed(i, true);
else
{
menu.options->setGreyed(i, false);
menu.options->setItemCaption(i, options->input[1].name);
}
break;
default:
menu.options->setItemCaption(i, lang->getText(69)); // KEYBOARD
break;
}
i++;
// LANGUAGE
switch (options->language)
{
case es_ES:
menu.options->setItemCaption(i, lang->getText(8) + ": " + lang->getText(24)); // SPANISH
break;
case ba_BA:
menu.options->setItemCaption(i, lang->getText(8) + ": " + lang->getText(25)); // VALENCIAN
break;
case en_UK:
menu.options->setItemCaption(i, lang->getText(8) + ": " + lang->getText(26)); // ENGLISH
break;
default:
menu.options->setItemCaption(i, lang->getText(8) + ": " + lang->getText(26)); // ENGLISH
break;
}
i++;
// DISPLAY MODE
menu.options->setItemCaption(i, lang->getText(58));
i++;
// DISPLAY MODE - OPTIONS
switch (options->videoMode)
{
case 0:
menu.options->setItemCaption(i, lang->getText(4)); // WINDOW
break;
case SDL_WINDOW_FULLSCREEN:
menu.options->setItemCaption(i, lang->getText(5)); // FULLSCREEN
break;
case SDL_WINDOW_FULLSCREEN_DESKTOP:
menu.options->setItemCaption(i, lang->getText(6)); // FAKE FULLSCREEN
break;
default:
menu.options->setItemCaption(i, lang->getText(4)); // WINDOW
break;
}
i++;
// WINDOW SIZE
menu.options->setItemCaption(i, lang->getText(7) + " x" + std::to_string(options->windowSize)); // WINDOW SIZE
i++;
// FILTER
if (options->filter == FILTER_LINEAL)
menu.options->setItemCaption(i, lang->getText(60) + ": " + lang->getText(71)); // BILINEAL
else
menu.options->setItemCaption(i, lang->getText(60) + ": " + lang->getText(72)); // LINEAL
i++;
// VSYNC
if (options->vSync)
menu.options->setItemCaption(i, lang->getText(61) + ": " + lang->getText(73)); // ON
else
menu.options->setItemCaption(i, lang->getText(61) + ": " + lang->getText(74)); // OFF
i++;
// HOW TO PLAY
menu.options->setItemCaption(i, lang->getText(2));
i++;
// HISCORE TABLE
menu.options->setItemCaption(i, lang->getText(93));
i++;
// JAILERID;
const std::string jailerID = options->online.jailerID == "" ? lang->getText(64) : options->online.jailerID;
menu.options->setItemCaption(i, "JAILERID: " + jailerID);
i++;
// ACCEPT
menu.options->setItemCaption(i, lang->getText(9)); // ACCEPT
i++;
// CANCEL
menu.options->setItemCaption(i, lang->getText(10)); // CANCEL
// Recoloca el menu de opciones
menu.options->centerMenuOnX(GAMECANVAS_CENTER_X);
menu.options->centerMenuOnY(GAMECANVAS_CENTER_Y);
menu.options->centerMenuElementsOnX();
// Establece las etiquetas del menu de titulo
#ifdef GAME_CONSOLE
menu.title->setItemCaption(0, lang->getText(0)); // PLAY
#else
menu.title->setItemCaption(0, lang->getText(51)); // 1 PLAYER
#endif
menu.title->setItemCaption(1, lang->getText(52)); // 2 PLAYERS
menu.title->setItemCaption(2, lang->getText(1)); // OPTIONS
menu.title->setItemCaption(3, lang->getText(3)); // QUIT
// Recoloca el menu de titulo
menu.title->centerMenuOnX(GAMECANVAS_CENTER_X);
menu.title->centerMenuElementsOnX();
// Establece las etiquetas del menu de seleccion de jugador
menu.playerSelect->setItemCaption(0, lang->getText(39)); // SELECT PLAYER
menu.playerSelect->setItemCaption(3, lang->getText(40)); // BACK
// Recoloca el menu de selección de jugador
menu.playerSelect->centerMenuOnX(GAMECANVAS_CENTER_X);
menu.playerSelect->centerMenuElementsOnX();
#ifdef GAME_CONSOLE
menu.options->setGreyed(1, true);
menu.options->setSelectable(1, false);
menu.options->setGreyed(2, true);
menu.options->setSelectable(2, false);
menu.options->setGreyed(3, true);
menu.options->setSelectable(3, false);
menu.options->setGreyed(4, true);
menu.options->setSelectable(4, false);
#endif
}
// Aplica las opciones de menu seleccionadas
void Title::applyOptions()
{
screen->setVideoMode(options->videoMode);
lang->setLang(options->language);
updateMenuLabels();
createTiledBackground();
}
// Bucle para el titulo del juego
void Title::run()
{
@@ -1028,14 +596,6 @@ void Title::runDemoGame()
delete demoGame;
}
// Introduce el JailerID
void Title::runEnterID()
{
enterID = new EnterID(renderer, screen, asset, lang, options, section);
enterID->run();
delete enterID;
}
// Modifica las opciones para los controles de los jugadores
bool Title::updatePlayerInputs(int numPlayer)
{
@@ -1186,19 +746,4 @@ void Title::reLoadTextures()
crisisTexture->reLoad();
gradientTexture->reLoad();
createTiledBackground();
}
// Comprueba si se puede acceder a la tabla de puntuaciones y habilita la opción de menu
void Title::setHiScoreTableOptionMenu()
{
if (options->online.sessionEnabled)
{
menu.options->setSelectable(12, true);
menu.options->setGreyed(12, false);
}
else
{
menu.options->setSelectable(12, false);
menu.options->setGreyed(12, true);
}
}

View File

@@ -14,7 +14,6 @@
#include "const.h"
#include "fade.h"
#include "game.h"
#include "enter_id.h"
#include "hiscore_table.h"
#include "instructions.h"
#include "item.h"
@@ -23,7 +22,7 @@
#define TITLE_H
// Textos
#define TEXT_COPYRIGHT "@2020,2023 JailDesigner (v2.3)"
#define TEXT_COPYRIGHT "@2020,2024 JailDesigner (v0.1)"
// Contadores
#define TITLE_COUNTER 800
@@ -34,15 +33,6 @@
class Title
{
private:
struct menu_t
{
Menu *title; // Menu de la pantalla de título
Menu *options; // Menú de la pantalla de opciones
Menu *playerSelect; // Menu para elegir jugador
Menu *active; // Menu activo (de momento para la pantalla del titulo)
bool keyPressed; // Variable para evitar la repetición de teclas en los menus
};
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
@@ -52,7 +42,6 @@ private:
Instructions *instructions; // Objeto para la sección de las instrucciones
HiScoreTable *hiScoreTable; // Objeto para mostrar las mejores puntuaciones online
Game *demoGame; // Objeto para lanzar la demo del juego
EnterID *enterID; // Objeto para introducir o modificar el JailerID
SDL_Event *eventHandler; // Manejador de eventos
section_t *section; // Indicador para el bucle del titulo
@@ -89,7 +78,6 @@ private:
section_t nextSection; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
Uint8 postFade; // Opción a realizar cuando termina el fundido
menu_t menu; // Variable con todos los objetos menus y sus variables
struct options_t *options; // Variable con todas las variables de las opciones del programa
options_t optionsPrevious; // Variable de respaldo para las opciones
std::vector<input_t> availableInputDevices; // Vector con todos los metodos de control disponibles
@@ -116,12 +104,6 @@ private:
// Cambia el valor de la variable de modo de pantalla completa
void switchFullScreenModeVar();
// Actualiza los elementos de los menus
void updateMenuLabels();
// Aplica las opciones de menu seleccionadas
void applyOptions();
// Ejecuta la parte donde se muestran las instrucciones
void runInstructions(mode_e mode);
@@ -131,9 +113,6 @@ private:
// Ejecuta el juego en modo demo
void runDemoGame();
// Introduce el JailerID
void runEnterID();
// Modifica las opciones para los controles de los jugadores
bool updatePlayerInputs(int numPlayer);
@@ -146,9 +125,6 @@ private:
// Recarga las texturas
void reLoadTextures();
// Comprueba si se puede acceder a la tabla de puntuaciones y habilita la opción de menu
void setHiScoreTableOptionMenu();
public:
// Constructor
Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset, options_t *options, Lang *lang, section_t *section);