This commit is contained in:
2026-04-17 22:20:37 +02:00
parent 513eacf356
commit 20b9a95619
38 changed files with 310 additions and 622 deletions

View File

@@ -261,15 +261,13 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
stoppedCounter = 0;
blinking = false;
visible = true;
invulnerable = true;
beingCreated = true;
creationCounter = creationtimer;
creationCounterIni = creationtimer;
popping = false;
// Actualiza valores
beingCreated = creationCounter == 0 ? false : true;
invulnerable = beingCreated == false ? false : true;
// Valores iniciales dependentes del timer
beingCreated = creationCounter != 0;
invulnerable = beingCreated;
counter = 0;
travelY = 1.0f;

View File

@@ -107,9 +107,6 @@ void Item::move() {
// Si el objeto se sale por la parte inferior
if (posY + height > PLAY_AREA_BOTTOM) {
// Corrige
posY -= velY;
// Detiene el objeto
velY = 0;
velX = 0;

View File

@@ -8,7 +8,7 @@
#include "game/defaults.hpp" // for PLAY_AREA_LEFT, PLAY_AREA_RIGHT
// Constructor
Player::Player(float x, int y, SDL_Renderer *renderer, std::vector<Texture *> texture, std::vector<std::vector<std::string> *> animations) {
Player::Player(float x, int y, SDL_Renderer *renderer, const std::vector<Texture *> &texture, const std::vector<std::vector<std::string> *> &animations) {
// Copia los punteros
this->renderer = renderer;
@@ -189,19 +189,12 @@ void Player::render() {
// Establece el estado del jugador cuando camina
void Player::setWalkingStatus(Uint8 status) {
// Si cambiamos de estado, reiniciamos la animación
if (statusWalking != status) {
statusWalking = status;
// legsSprite->setCurrentFrame(0);
}
statusWalking = status;
}
// Establece el estado del jugador cuando dispara
void Player::setFiringStatus(Uint8 status) {
// Si cambiamos de estado, reiniciamos la animación
if (statusFiring != status) {
statusFiring = status;
}
statusFiring = status;
}
// Establece la animación correspondiente al estado
@@ -521,7 +514,7 @@ void Player::updatePowerUpHeadOffset() {
}
// Pone las texturas del jugador
void Player::setPlayerTextures(std::vector<Texture *> texture) {
void Player::setPlayerTextures(const std::vector<Texture *> &texture) {
headSprite->setTexture(texture[0]);
bodySprite->setTexture(texture[1]);
legsSprite->setTexture(texture[2]);

View File

@@ -81,7 +81,7 @@ class Player {
public:
// Constructor
Player(float x, int y, SDL_Renderer *renderer, std::vector<Texture *> texture, std::vector<std::vector<std::string> *> animations);
Player(float x, int y, SDL_Renderer *renderer, const std::vector<Texture *> &texture, const std::vector<std::vector<std::string> *> &animations);
// Destructor
~Player();
@@ -96,7 +96,7 @@ class Player {
void render();
// Pone las texturas del jugador
void setPlayerTextures(std::vector<Texture *> texture);
void setPlayerTextures(const std::vector<Texture *> &texture);
// Actua en consecuencia de la entrada recibida
void setInput(Uint8 input);

View File

@@ -4,6 +4,7 @@
#include <stdlib.h> // for rand
#include <algorithm> // for max, min
#include <numeric> // for accumulate
#include <fstream> // for basic_ifstream
#include <iostream> // for basic_ostream, char_traits, operator<<
@@ -30,7 +31,8 @@
struct JA_Sound_t;
// Constructor
Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, bool demo, section_t *section) {
Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, bool demo, section_t *section)
: lastStageReached(currentStage) {
// Copia los punteros
this->renderer = renderer;
this->section = section;
@@ -43,7 +45,6 @@ Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, bool demo,
#else
this->currentStage = currentStage;
#endif
lastStageReached = currentStage;
if (numPlayers == 1) { // Si solo juega un jugador, permite jugar tanto con teclado como con mando
onePlayerControl = Options::inputs[0].deviceType;
Options::inputs[0].deviceType = INPUT_USE_ANY;
@@ -961,7 +962,6 @@ void Game::initEnemyFormations() {
// #24 - Treinta enemigos BALLOON1. Del centro hacia los extremos. Juntos. Simetricos
j = 24;
enemyFormation[j].numberOfEnemies = 30;
incX = 0;
incTime = 5;
for (int i = 0; i < enemyFormation[j].numberOfEnemies; i++) {
Uint8 half = enemyFormation[j].numberOfEnemies / 2;
@@ -981,7 +981,6 @@ void Game::initEnemyFormations() {
// #25 - Treinta enemigos BALLOON1. Del centro hacia adentro. Juntos. Simetricos
j = 25;
enemyFormation[j].numberOfEnemies = 30;
incX = BALLOON_WIDTH_1 + 1;
incTime = 5;
for (int i = 0; i < enemyFormation[j].numberOfEnemies; i++) {
Uint8 half = enemyFormation[j].numberOfEnemies / 2;
@@ -1486,12 +1485,12 @@ void Game::updateStage() {
// Actualiza el estado de muerte
void Game::updateDeath() {
// Comprueba si todos los jugadores estan muertos
bool allPlayersAreDead = true;
bool allDead = true;
for (auto player : players) {
allPlayersAreDead &= (!player->isAlive());
allDead &= (!player->isAlive());
}
if (allPlayersAreDead) {
if (allDead) {
if (deathCounter > 0) {
deathCounter--;
@@ -1608,30 +1607,6 @@ void Game::incBalloonSpeed() {
}
}
// Decrementa la velocidad de los globos
void Game::decBalloonSpeed() {
// La velocidad solo se decrementa en el modo normal
if (difficulty == DIFFICULTY_NORMAL) {
if (enemySpeed == BALLOON_SPEED_5) {
enemySpeed = BALLOON_SPEED_4;
}
else if (enemySpeed == BALLOON_SPEED_4) {
enemySpeed = BALLOON_SPEED_3;
}
else if (enemySpeed == BALLOON_SPEED_3) {
enemySpeed = BALLOON_SPEED_2;
}
else if (enemySpeed == BALLOON_SPEED_2) {
enemySpeed = BALLOON_SPEED_1;
}
setBalloonSpeed(enemySpeed);
}
}
// Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
void Game::updateBalloonSpeed() {
const float percent = (float)stage[currentStage].currentPower / (float)stage[currentStage].powerToComplete;
@@ -1761,17 +1736,6 @@ void Game::destroyBalloon(Balloon *balloon) {
evaluateAndSetMenace();
}
// Explosiona todos los globos
void Game::popAllBalloons() {
for (auto balloon : balloons) {
if ((balloon->isEnabled()) && (!balloon->isPopping()) && (!balloon->isBeingCreated())) {
popBalloon(balloon);
}
}
JA_PlaySound(balloonSound);
}
// Destruye todos los globos
void Game::destroyAllBalloons() {
for (auto balloon : balloons) {
@@ -1808,21 +1772,6 @@ void Game::startAllBalloons() {
}
}
// Obtiene el numero de globos activos
Uint8 Game::countBalloons() {
Uint8 num = 0;
for (auto balloon : balloons) {
if (balloon->isEnabled()) {
if (!balloon->isPopping()) {
num++;
}
}
}
return num;
}
// Vacia el vector de globos
void Game::freeBalloons() {
if (balloons.empty() == false) {
@@ -2090,7 +2039,7 @@ void Game::freeItems() {
}
// Crea un objeto SmartSprite para mostrar la puntuación al coger un objeto
void Game::createItemScoreSprite(int x, int y, SmartSprite *sprite) {
void Game::createItemScoreSprite(int x, int y, const SmartSprite *sprite) {
SmartSprite *ss = new SmartSprite(nullptr, renderer);
smartSprites.push_back(ss);
@@ -2235,12 +2184,8 @@ void Game::updateDeathSequence() {
// Calcula y establece el valor de amenaza en funcion de los globos activos
void Game::evaluateAndSetMenace() {
menaceCurrent = 0;
for (auto balloon : balloons) {
if (balloon->isEnabled()) {
menaceCurrent += balloon->getMenace();
}
}
menaceCurrent = std::accumulate(balloons.begin(), balloons.end(), Uint8(0),
[](Uint8 acc, Balloon *b) { return b->isEnabled() ? acc + b->getMenace() : acc; });
}
// Obtiene el valor de la variable
@@ -2685,19 +2630,19 @@ void Game::renderMessages() {
// STAGE NUMBER
if (stageBitmapCounter < STAGE_COUNTER) {
const int stageNum = stage[currentStage].number;
std::string text;
std::string stageText;
if (stageNum == 10) { // Ultima fase
text = Lang::get()->getText(79);
stageText = Lang::get()->getText(79);
} else { // X fases restantes
text = std::to_string(11 - stage[currentStage].number) + Lang::get()->getText(38);
stageText = std::to_string(11 - stage[currentStage].number) + Lang::get()->getText(38);
}
if (!gameCompleted) { // Escribe el numero de fases restantes
textNokiaBig2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, stageBitmapPath[stageBitmapCounter], text, -2, noColor, 2, shdwTxtColor);
textNokiaBig2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, stageBitmapPath[stageBitmapCounter], stageText, -2, noColor, 2, shdwTxtColor);
} else { // Escribe el texto de juego completado
text = Lang::get()->getText(50);
textNokiaBig2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, stageBitmapPath[stageBitmapCounter], text, -2, noColor, 1, shdwTxtColor);
stageText = Lang::get()->getText(50);
textNokiaBig2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, stageBitmapPath[stageBitmapCounter], stageText, -2, noColor, 1, shdwTxtColor);
textNokia2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, stageBitmapPath[stageBitmapCounter] + textNokiaBig2->getCharacterSize() + 2, Lang::get()->getText(76), -1, noColor, 1, shdwTxtColor);
}
}
@@ -2813,7 +2758,7 @@ bool Game::hasFinished() const {
}
// Procesa un evento individual
void Game::handleEvent(SDL_Event *event) {
void Game::handleEvent(const SDL_Event *event) {
// SDL_EVENT_QUIT ya lo maneja Director
if (event->type == SDL_EVENT_WINDOW_FOCUS_LOST) {
@@ -3025,23 +2970,6 @@ void Game::updateGameOverScreen() {
}
}
// Comprueba los eventos de la pantalla de game over
void Game::checkGameOverEvents() {
while (SDL_PollEvent(eventHandler) != 0) {
// Evento de salida de la aplicación
if (eventHandler->type == SDL_EVENT_QUIT) {
section->name = SECTION_PROG_QUIT;
break;
} else if (eventHandler->type == SDL_EVENT_KEY_DOWN && eventHandler->key.repeat == 0) {
if (gameCompleted) {
gameOverPostFade = 1;
fade->activateFade();
JA_PlaySound(itemPickUpSound);
}
}
}
}
// Dibuja los elementos de la pantalla de game over
void Game::renderGameOverScreen() {
// Prepara para empezar a dibujar en la textura de juego
@@ -3120,15 +3048,8 @@ bool Game::canPowerBallBeCreated() {
// Calcula el poder actual de los globos en pantalla
int Game::calculateScreenPower() {
int power = 0;
for (auto balloon : balloons) {
if (balloon->isEnabled()) {
power += balloon->getPower();
}
}
return power;
return std::accumulate(balloons.begin(), balloons.end(), 0,
[](int acc, Balloon *b) { return b->isEnabled() ? acc + b->getPower() : acc; });
}
// Inicializa las variables que contienen puntos de ruta para mover objetos
@@ -3234,28 +3155,6 @@ bool Game::allPlayersAreDead() {
return success;
}
// Comprueba los eventos que hay en cola
void Game::checkEvents() {
while (SDL_PollEvent(eventHandler) != 0) {
// Evento de salida de la aplicación
if (eventHandler->type == SDL_EVENT_QUIT) {
section->name = SECTION_PROG_QUIT;
break;
}
else if (eventHandler->type == SDL_EVENT_WINDOW_FOCUS_LOST) {
section->subsection = SUBSECTION_GAME_PAUSE;
}
#ifdef PAUSE
else if (eventHandler->type == SDL_EVENT_KEY_DOWN) {
if (eventHandler->key.scancode == SDL_SCANCODE_P) {
pause = !pause;
}
}
#endif
}
}
// Elimina todos los objetos contenidos en vectores
void Game::deleteAllVectorObjects() {
for (auto player : players) {
@@ -3284,33 +3183,6 @@ void Game::deleteAllVectorObjects() {
smartSprites.clear();
}
// Recarga las texturas
void Game::reloadTextures() {
for (auto texture : itemTextures) {
texture->reLoad();
}
for (auto texture : balloonTextures) {
texture->reLoad();
}
for (auto texture : player1Textures) {
texture->reLoad();
}
for (auto texture : player2Textures) {
texture->reLoad();
}
bulletTexture->reLoad();
gameBuildingsTexture->reLoad();
gameCloudsTexture->reLoad();
gameGrassTexture->reLoad();
gamePowerMeterTexture->reLoad();
gameSkyColorsTexture->reLoad();
gameTextTexture->reLoad();
}
// Establece la máxima puntuación desde fichero o desde las puntuaciones online
void Game::setHiScore() {
// Carga el fichero de puntos

View File

@@ -259,9 +259,6 @@ class Game {
// Dibuja el juego
void render();
// Comprueba los eventos que hay en cola
void checkEvents();
// Inicializa las variables necesarias para la sección 'Game'
void init();
@@ -340,9 +337,6 @@ class Game {
// Incrementa la velocidad de los globos
void incBalloonSpeed();
// Decrementa la velocidad de los globos
void decBalloonSpeed();
// Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
void updateBalloonSpeed();
@@ -352,9 +346,6 @@ class Game {
// Explosiona un globo. Lo destruye
void destroyBalloon(Balloon *balloon);
// Explosiona todos los globos
void popAllBalloons();
// Destruye todos los globos
void destroyAllBalloons();
@@ -364,9 +355,6 @@ class Game {
// Pone en marcha todos los globos
void startAllBalloons();
// Obtiene el numero de globos activos
Uint8 countBalloons();
// Vacia el vector de globos
void freeBalloons();
@@ -407,7 +395,7 @@ class Game {
void freeItems();
// Crea un objeto SmartSprite
void createItemScoreSprite(int x, int y, SmartSprite *sprite);
void createItemScoreSprite(int x, int y, const SmartSprite *sprite);
// Vacia el vector de smartsprites
void freeSmartSprites();
@@ -505,9 +493,6 @@ class Game {
// Inicializa el estado de game over
void enterGameOverScreen();
// Comprueba los eventos de la pantalla de game over
void checkGameOverEvents();
// Indica si se puede crear una powerball
bool canPowerBallBeCreated();
@@ -529,9 +514,6 @@ class Game {
// Elimina todos los objetos contenidos en vectores
void deleteAllVectorObjects();
// Recarga las texturas
void reloadTextures();
// Establece la máxima puntuación desde fichero o desde las puntuaciones online
void setHiScore();
@@ -552,5 +534,5 @@ class Game {
bool hasFinished() const;
// Procesa un evento
void handleEvent(SDL_Event *event);
void handleEvent(const SDL_Event *event);
};

View File

@@ -145,8 +145,8 @@ Intro::Intro(SDL_Renderer *renderer, section_t *section) {
texts[8]->setCaption(Lang::get()->getText(35));
texts[8]->setSpeed(16);
for (auto text : texts) {
text->center(GAMECANVAS_CENTER_X);
for (auto *t : texts) {
t->center(GAMECANVAS_CENTER_X);
}
JA_PlayMusic(music, 0);
@@ -166,25 +166,6 @@ Intro::~Intro() {
}
}
// Carga los recursos (ya no carga nada, se mantiene por si hay callers)
bool Intro::loadMedia() {
return true;
}
// Comprueba los eventos
void Intro::checkEvents() {
#ifndef __EMSCRIPTEN__
// Comprueba los eventos que hay en la cola
while (SDL_PollEvent(eventHandler) != 0) {
// Evento de salida de la aplicación
if (eventHandler->type == SDL_EVENT_QUIT) {
section->name = SECTION_PROG_QUIT;
break;
}
}
#endif
}
// Comprueba las entradas
void Intro::checkInput() {
#ifndef __EMSCRIPTEN__
@@ -352,8 +333,8 @@ void Intro::update() {
bitmap->update();
}
for (auto text : texts) {
text->update();
for (auto *t : texts) {
t->update();
}
// Actualiza las escenas de la intro
@@ -374,8 +355,8 @@ void Intro::render() {
bitmap->render();
}
for (auto text : texts) {
text->render();
for (auto *t : texts) {
t->render();
}
// Vuelca el contenido del renderizador en pantalla
@@ -398,6 +379,6 @@ void Intro::iterate() {
}
// Procesa un evento individual
void Intro::handleEvent(SDL_Event *event) {
void Intro::handleEvent(const SDL_Event *event) {
// SDL_EVENT_QUIT ya lo maneja Director
}

View File

@@ -34,12 +34,6 @@ class Intro {
// Dibuja el objeto en pantalla
void render();
// Carga los recursos
bool loadMedia();
// Comprueba los eventos
void checkEvents();
// Comprueba las entradas
void checkInput();
@@ -60,5 +54,5 @@ class Intro {
void iterate();
// Procesa un evento
void handleEvent(SDL_Event *event);
void handleEvent(const SDL_Event *event);
};

View File

@@ -56,20 +56,6 @@ void Logo::checkLogoEnd() {
}
}
// Comprueba los eventos
void Logo::checkEvents() {
#ifndef __EMSCRIPTEN__
// Comprueba los eventos que hay en la cola
while (SDL_PollEvent(eventHandler) != 0) {
// Evento de salida de la aplicación
if (eventHandler->type == SDL_EVENT_QUIT) {
section->name = SECTION_PROG_QUIT;
break;
}
}
#endif
}
// Comprueba las entradas
void Logo::checkInput() {
#ifndef __EMSCRIPTEN__
@@ -148,6 +134,6 @@ void Logo::iterate() {
}
// Procesa un evento individual
void Logo::handleEvent(SDL_Event *event) {
void Logo::handleEvent(const SDL_Event *event) {
// SDL_EVENT_QUIT ya lo maneja Director
}

View File

@@ -29,9 +29,6 @@ class Logo {
// Comprueba si ha terminado el logo
void checkLogoEnd();
// Comprueba los eventos
void checkEvents();
// Comprueba las entradas
void checkInput();
@@ -52,5 +49,5 @@ class Logo {
void iterate();
// Procesa un evento
void handleEvent(SDL_Event *event);
void handleEvent(const SDL_Event *event);
};

View File

@@ -112,16 +112,16 @@ void Title::init() {
// Pone valores por defecto a las opciones de control
Options::inputs.clear();
input_t i;
i.id = 0;
i.name = "KEYBOARD";
i.deviceType = INPUT_USE_KEYBOARD;
Options::inputs.push_back(i);
input_t inp;
inp.id = 0;
inp.name = "KEYBOARD";
inp.deviceType = INPUT_USE_KEYBOARD;
Options::inputs.push_back(inp);
i.id = 0;
i.name = "GAME CONTROLLER";
i.deviceType = INPUT_USE_GAMECONTROLLER;
Options::inputs.push_back(i);
inp.id = 0;
inp.name = "GAME CONTROLLER";
inp.deviceType = INPUT_USE_GAMECONTROLLER;
Options::inputs.push_back(inp);
// Comprueba si hay mandos conectados
checkInputDevices();
@@ -609,32 +609,6 @@ void Title::render() {
}
}
// Comprueba los eventos
void Title::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_EVENT_QUIT) {
section->name = SECTION_PROG_QUIT;
break;
}
else if (eventHandler->type == SDL_EVENT_RENDER_DEVICE_RESET || eventHandler->type == SDL_EVENT_RENDER_TARGETS_RESET) {
reLoadTextures();
}
if (section->subsection == SUBSECTION_TITLE_3) { // Si se pulsa alguna tecla durante la tercera sección del titulo
if ((eventHandler->type == SDL_EVENT_KEY_UP) || (eventHandler->type == SDL_EVENT_JOYSTICK_BUTTON_UP)) {
// Muestra el menu
menuVisible = true;
// Reinicia el contador
counter = TITLE_COUNTER;
}
}
}
}
// Comprueba las entradas
void Title::checkInput() {
#ifndef __EMSCRIPTEN__
@@ -915,7 +889,7 @@ void Title::iterate() {
}
// Procesa un evento individual
void Title::handleEvent(SDL_Event *event) {
void Title::handleEvent(const SDL_Event *event) {
// Si hay un sub-estado activo, delega el evento
if (instructionsActive && instructions) {
// SDL_EVENT_QUIT ya lo maneja Director

View File

@@ -107,9 +107,6 @@ class Title {
// Dibuja el objeto en pantalla
void render();
// Comprueba los eventos
void checkEvents();
// Comprueba las entradas
void checkInput();
@@ -157,5 +154,5 @@ class Title {
void iterate();
// Procesa un evento
void handleEvent(SDL_Event *event);
void handleEvent(const SDL_Event *event);
};

View File

@@ -2,6 +2,7 @@
#include <algorithm> // for max, min
#include <fstream> // for char_traits, basic_ifstream, basic_istream
#include <numeric> // for accumulate
#include <sstream> // for basic_stringstream
#include "core/audio/jail_audio.hpp" // for JA_LoadSound, JA_PlaySound, JA_DeleteSound
@@ -11,7 +12,10 @@
#include "core/resources/resource_helper.h"
// Constructor
Menu::Menu(SDL_Renderer *renderer, std::string file) {
Menu::Menu(SDL_Renderer *renderer, const std::string &file)
: colorGreyed{128, 128, 128},
font_png(""),
font_txt("") {
// Copia punteros
this->renderer = renderer;
@@ -21,7 +25,6 @@ Menu::Menu(SDL_Renderer *renderer, std::string file) {
soundCancel = nullptr;
// Inicializa variables
name = "";
selector.index = 0;
selector.previousIndex = 0;
itemSelected = MENU_NO_OPTION;
@@ -38,10 +41,7 @@ Menu::Menu(SDL_Renderer *renderer, std::string file) {
centerX = 0;
centerY = 0;
widestItem = 0;
colorGreyed = {128, 128, 128};
defaultActionWhenCancel = 0;
font_png = "";
font_txt = "";
// Selector
selector.originY = 0;
@@ -63,7 +63,7 @@ Menu::Menu(SDL_Renderer *renderer, std::string file) {
// Inicializa las variables desde un fichero. Si no se pasa fichero, el
// llamante (p.ej. Resource::preloadAll) usará loadFromBytes después —
// y ese método ya llama a setSelectorItemColors() y reset() al final.
if (file != "") {
if (!file.empty()) {
load(file);
setSelectorItemColors();
reset();
@@ -99,24 +99,24 @@ bool Menu::parseFromStream(std::istream &file, const std::string &filename) {
while (std::getline(file, line)) {
if (line == "[item]") {
item_t item;
item.label = "";
item.hPaddingDown = 1;
item.selectable = true;
item.greyed = false;
item.linkedDown = false;
item.visible = true;
item.line = false;
item_t newItem;
newItem.label = "";
newItem.hPaddingDown = 1;
newItem.selectable = true;
newItem.greyed = false;
newItem.linkedDown = false;
newItem.visible = true;
newItem.line = false;
do {
std::getline(file, line);
int pos = line.find("=");
if (!setItem(&item, line.substr(0, pos), line.substr(pos + 1, line.length()))) {
if (!setItem(&newItem, line.substr(0, pos), line.substr(pos + 1, line.length()))) {
success = false;
}
} while (line != "[/item]");
addItem(item);
addItem(newItem);
} else {
int pos = line.find("=");
if (!setVars(line.substr(0, pos), line.substr(pos + 1, line.length()))) {
@@ -137,7 +137,7 @@ bool Menu::parseFromStream(std::istream &file, const std::string &filename) {
}
// Carga la configuración del menu desde un archivo de texto
bool Menu::load(std::string file_path) {
bool Menu::load(const std::string &file_path) {
const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
std::ifstream file(file_path);
if (!file.good()) {
@@ -158,7 +158,7 @@ bool Menu::loadFromBytes(const std::vector<uint8_t> &bytes, const std::string &n
}
// Asigna variables a partir de dos cadenas
bool Menu::setItem(item_t *item, std::string var, std::string value) {
bool Menu::setItem(item_t *item, const std::string &var, const std::string &value) {
// Indicador de éxito en la asignación
bool success = true;
@@ -201,7 +201,7 @@ bool Menu::setItem(item_t *item, std::string var, std::string value) {
}
// Asigna variables a partir de dos cadenas
bool Menu::setVars(std::string var, std::string value) {
bool Menu::setVars(const std::string &var, const std::string &value) {
// Indicador de éxito en la asignación
bool success = true;
@@ -319,7 +319,7 @@ bool Menu::setVars(std::string var, std::string value) {
}
// Carga los ficheros de audio
void Menu::loadAudioFile(std::string file, int sound) {
void Menu::loadAudioFile(const std::string &file, int sound) {
switch (sound) {
case SOUND_ACCEPT:
soundAccept = JA_LoadSound(file.c_str());
@@ -339,7 +339,7 @@ void Menu::loadAudioFile(std::string file, int sound) {
}
// Obtiene el nombre del menu
std::string Menu::getName() {
const std::string &Menu::getName() const {
return name;
}
@@ -430,14 +430,8 @@ void Menu::setSelectorPos(int index) {
// Obtiene la anchura del elemento más ancho del menu
int Menu::getWidestItem() {
int result = 0;
// Obtenemos la anchura del item mas ancho
for (auto &i : item) {
result = std::max(result, i.rect.w);
}
return result;
return std::accumulate(item.begin(), item.end(), 0,
[](int acc, const item_t &i) { return std::max(acc, i.rect.w); });
}
// Deja el menu apuntando al primer elemento
@@ -474,7 +468,7 @@ void Menu::reorganize() {
}
// Deja el menu apuntando al siguiente elemento
bool Menu::increaseSelectorIndex() {
void Menu::increaseSelectorIndex() {
// Guarda el indice actual antes de modificarlo
selector.previousIndex = selector.index;
@@ -499,12 +493,10 @@ bool Menu::increaseSelectorIndex() {
if (selector.incH != 0) {
selector.resizing = true;
}
return true;
}
// Deja el menu apuntando al elemento anterior
bool Menu::decreaseSelectorIndex() {
void Menu::decreaseSelectorIndex() {
// Guarda el indice actual antes de modificarlo
selector.previousIndex = selector.index;
@@ -538,8 +530,6 @@ bool Menu::decreaseSelectorIndex() {
if (selector.incH != 0) {
selector.resizing = true;
}
return true;
}
// Actualiza la logica del menu
@@ -752,7 +742,7 @@ void Menu::addItem(item_t temp) {
}
// Cambia el texto de un item
void Menu::setItemCaption(int index, std::string text) {
void Menu::setItemCaption(int index, const std::string &text) {
item[index].label = text;
item[index].rect.w = this->text->lenght(item[index].label);
item[index].rect.h = this->text->getCharacterSize();
@@ -767,18 +757,16 @@ void Menu::setDefaultActionWhenCancel(int item) {
// Gestiona la entrada de teclado y mando durante el menu
void Menu::checkInput() {
if (Input::get()->checkInput(input_up, REPEAT_FALSE)) {
if (decreaseSelectorIndex()) {
if (soundMove) {
JA_PlaySound(soundMove);
}
decreaseSelectorIndex();
if (soundMove) {
JA_PlaySound(soundMove);
}
}
if (Input::get()->checkInput(input_down, REPEAT_FALSE)) {
if (increaseSelectorIndex()) {
if (soundMove) {
JA_PlaySound(soundMove);
}
increaseSelectorIndex();
if (soundMove) {
JA_PlaySound(soundMove);
}
}
@@ -804,12 +792,8 @@ int Menu::findWidth() {
// Calcula el alto del menu
int Menu::findHeight() {
int height = 0;
// Obtenemos la altura de la suma de alturas de los items
for (auto &i : item) {
height += i.rect.h + i.hPaddingDown;
}
const int height = std::accumulate(item.begin(), item.end(), 0,
[](int acc, const item_t &i) { return acc + i.rect.h + i.hPaddingDown; });
return height - item.back().hPaddingDown;
}
@@ -853,7 +837,7 @@ int Menu::getSelectorHeight(int value) {
}
// Establece el nombre del menu
void Menu::setName(std::string name) {
void Menu::setName(const std::string &name) {
this->name = name;
}
@@ -869,7 +853,7 @@ void Menu::setBackgroundType(int value) {
}
// Establece la fuente de texto que se utilizará
void Menu::setText(std::string font_png, std::string font_txt) {
void Menu::setText(const std::string &font_png, const std::string &font_txt) {
if (!text) {
text = new Text(Asset::get()->get(font_png), Asset::get()->get(font_txt), renderer);
}

View File

@@ -96,25 +96,25 @@ class Menu {
std::string font_txt;
// Carga la configuración del menu desde un archivo de texto
bool load(std::string file_path);
bool load(const std::string &file_path);
// Parser compartido (recibe cualquier istream)
bool parseFromStream(std::istream &file, const std::string &filename);
// Asigna variables a partir de dos cadenas
bool setVars(std::string var, std::string value);
bool setVars(const std::string &var, const std::string &value);
// Asigna variables a partir de dos cadenas
bool setItem(item_t *item, std::string var, std::string value);
bool setItem(item_t *item, const std::string &var, const std::string &value);
// Actualiza el menu para recolocarlo correctamente y establecer el tamaño
void reorganize();
// Deja el menu apuntando al siguiente elemento
bool increaseSelectorIndex();
void increaseSelectorIndex();
// Deja el menu apuntando al elemento anterior
bool decreaseSelectorIndex();
void decreaseSelectorIndex();
// Actualiza la posicion y el estado del selector
void updateSelector();
@@ -142,7 +142,7 @@ class Menu {
public:
// Constructor
Menu(SDL_Renderer *renderer, std::string file = "");
explicit Menu(SDL_Renderer *renderer, const std::string &file = "");
// Destructor
~Menu();
@@ -151,10 +151,10 @@ class Menu {
bool loadFromBytes(const std::vector<uint8_t> &bytes, const std::string &nameForLogs = "");
// Carga los ficheros de audio
void loadAudioFile(std::string file, int sound);
void loadAudioFile(const std::string &file, int sound);
// Obtiene el nombre del menu
std::string getName();
const std::string &getName() const;
// Obtiene el valor de la variable
int getItemSelected();
@@ -193,7 +193,7 @@ class Menu {
void addItem(item_t item);
// Cambia el texto de un item
void setItemCaption(int index, std::string text);
void setItemCaption(int index, const std::string &text);
// Establece el indice del item que se usará por defecto al cancelar el menu
void setDefaultActionWhenCancel(int item);
@@ -214,7 +214,7 @@ class Menu {
void setVisible(int index, bool value);
// Establece el nombre del menu
void setName(std::string name);
void setName(const std::string &name);
// Establece la posición del menu
void setPos(int x, int y);
@@ -223,7 +223,7 @@ class Menu {
void setBackgroundType(int value);
// Establece la fuente de texto que se utilizará
void setText(std::string font_png, std::string font_txt);
void setText(const std::string &font_png, const std::string &font_txt);
// Establece el rectangulo de fondo del menu
void setRectSize(int w = 0, int h = 0);