Retocando la clase menu

This commit is contained in:
2022-08-24 13:58:52 +02:00
parent 0749862af2
commit 1f4d094593
4 changed files with 182 additions and 77 deletions

View File

@@ -2,12 +2,15 @@
#include "menu.h" #include "menu.h"
// Constructor // Constructor
Menu::Menu(SDL_Renderer *renderer, Text *text, Input *input, Asset *asset) Menu::Menu(SDL_Renderer *renderer, Text *text, Input *input)
{ {
this->renderer = renderer; this->renderer = renderer;
this->text = text; this->text = text;
this->input = input; this->input = input;
this->asset = asset;
soundMove = nullptr;
soundAccept = nullptr;
soundCancel = nullptr;
} }
Menu::~Menu() Menu::~Menu()
@@ -15,21 +18,26 @@ Menu::~Menu()
renderer = nullptr; renderer = nullptr;
text = nullptr; text = nullptr;
input = nullptr; input = nullptr;
asset = nullptr;
JA_DeleteSound(soundAccept); if (soundMove)
JA_DeleteSound(soundCancel); {
JA_DeleteSound(soundMove); JA_DeleteSound(soundMove);
}
if (soundAccept)
{
JA_DeleteSound(soundAccept);
}
if (soundCancel)
{
JA_DeleteSound(soundCancel);
}
} }
// Inicializador // Inicializador
void Menu::init(std::string name, int x, int y, int backgroundType) void Menu::init(std::string name, int x, int y, int backgroundType)
{ {
// Sonidos
soundMove = JA_LoadSound(asset->get("sound_menu_move.wav").c_str());
soundAccept = JA_LoadSound(asset->get("sound_menu_select.wav").c_str());
soundCancel = JA_LoadSound(asset->get("sound_menu_cancel.wav").c_str());
// Inicia variables // Inicia variables
this->name = name; this->name = name;
selector.index = 0; selector.index = 0;
@@ -66,6 +74,28 @@ void Menu::init(std::string name, int x, int y, int backgroundType)
selector.a = 255; selector.a = 255;
} }
// Carga los ficheros de audio
void Menu::loadAudioFile(std::string file, int sound)
{
switch (sound)
{
case SOUND_ACCEPT:
soundAccept = JA_LoadSound(file.c_str());
break;
case SOUND_CANCEL:
soundCancel = JA_LoadSound(file.c_str());
break;
case SOUND_MOVE:
soundMove = JA_LoadSound(file.c_str());
break;
default:
break;
}
}
// Obtiene el nombre del menu // Obtiene el nombre del menu
std::string Menu::getName() std::string Menu::getName()
{ {
@@ -185,19 +215,26 @@ void Menu::reset()
void Menu::reorganize() void Menu::reorganize()
{ {
setRectSize(); setRectSize();
if (isCenteredOnX) if (isCenteredOnX)
{
centerMenuOnX(centerX); centerMenuOnX(centerX);
}
if (isCenteredOnY) if (isCenteredOnY)
{
centerMenuOnY(centerY); centerMenuOnY(centerY);
}
if (areElementsCenteredOnX) if (areElementsCenteredOnX)
{
centerMenuElementsOnX(); centerMenuElementsOnX();
}
} }
// Deja el menu apuntando al siguiente elemento // Deja el menu apuntando al siguiente elemento
bool Menu::increaseSelectorIndex() bool Menu::increaseSelectorIndex()
{ {
bool success = false;
// Obten las coordenadas del elemento actual // Obten las coordenadas del elemento actual
selector.y = selector.originY = item[selector.index].rect.y; selector.y = selector.originY = item[selector.index].rect.y;
selector.h = selector.originH = getSelectorHeight(selector.index); selector.h = selector.originH = getSelectorHeight(selector.index);
@@ -208,11 +245,8 @@ bool Menu::increaseSelectorIndex()
{ {
++selector.index %= item.size(); ++selector.index %= item.size();
} }
success = true;
// Establece las coordenadas y altura de destino // Establece las coordenadas y altura de destino
if (success)
{
selector.targetY = item[selector.index].rect.y; selector.targetY = item[selector.index].rect.y;
selector.despY = (selector.targetY - selector.originY) / selector.numJumps; selector.despY = (selector.targetY - selector.originY) / selector.numJumps;
@@ -221,17 +255,16 @@ bool Menu::increaseSelectorIndex()
selector.moving = true; selector.moving = true;
if (selector.incH != 0) if (selector.incH != 0)
{
selector.resizing = true; selector.resizing = true;
} }
return success; return true;
} }
// Deja el menu apuntando al elemento anterior // Deja el menu apuntando al elemento anterior
bool Menu::decreaseSelectorIndex() bool Menu::decreaseSelectorIndex()
{ {
bool success = false;
// Obten las coordenadas del elemento actual // Obten las coordenadas del elemento actual
selector.y = selector.originY = item[selector.index].rect.y; selector.y = selector.originY = item[selector.index].rect.y;
selector.h = selector.originH = getSelectorHeight(selector.index); selector.h = selector.originH = getSelectorHeight(selector.index);
@@ -245,18 +278,20 @@ bool Menu::decreaseSelectorIndex()
{ {
selector.index--; selector.index--;
} }
while (!item[selector.index].selectable) while (!item[selector.index].selectable)
{ {
if (selector.index == 0) if (selector.index == 0)
{
selector.index = item.size(); selector.index = item.size();
}
else else
{
selector.index--; selector.index--;
} }
success = true; }
// Establece las coordenadas y altura de destino // Establece las coordenadas y altura de destino
if (success)
{
selector.targetY = item[selector.index].rect.y; selector.targetY = item[selector.index].rect.y;
selector.despY = (selector.targetY - selector.originY) / selector.numJumps; selector.despY = (selector.targetY - selector.originY) / selector.numJumps;
@@ -265,15 +300,17 @@ bool Menu::decreaseSelectorIndex()
selector.moving = true; selector.moving = true;
if (selector.incH != 0) if (selector.incH != 0)
{
selector.resizing = true; selector.resizing = true;
} }
return success; return true;
} }
// Actualiza la logica del menu // Actualiza la logica del menu
void Menu::update() void Menu::update()
{ {
checkInput();
updateSelector(); updateSelector();
} }
@@ -288,9 +325,9 @@ void Menu::render()
} }
// Renderiza el rectangulo del selector // Renderiza el rectangulo del selector
SDL_Rect temp = selector.rect; const SDL_Rect temp = {selector.rect.x, selector.rect.y - 1, selector.rect.w, selector.rect.h + 1};
temp.y--; // temp.y--;
temp.h++; // temp.h++;
SDL_SetRenderDrawColor(renderer, selector.color.r, selector.color.g, selector.color.b, selector.a); SDL_SetRenderDrawColor(renderer, selector.color.r, selector.color.g, selector.color.b, selector.a);
SDL_RenderFillRect(renderer, &temp); SDL_RenderFillRect(renderer, &temp);
@@ -317,7 +354,8 @@ void Menu::render()
{ {
text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, colorGreyed); text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, colorGreyed);
} }
else // No seleccionable else
// No seleccionable
{ {
if ((item[i].linkedUp) && (i == selector.index + 1)) if ((item[i].linkedUp) && (i == selector.index + 1))
{ {
@@ -436,11 +474,15 @@ void Menu::addItem(std::string text, int hPaddingDown, bool selectable, bool gre
temp.linkedDown = linkedDown; temp.linkedDown = linkedDown;
item.push_back(temp); item.push_back(temp);
setItemCaption(item.size(), text); setItemCaption(item.size() - 1, text);
if (item.size() > 0) if (item.size() > 0)
{
if (item[item.size() - 1].linkedDown) if (item[item.size() - 1].linkedDown)
{
item[item.size()].linkedUp = true; item[item.size()].linkedUp = true;
}
}
centerX = x + (findWidth() / 2); centerX = x + (findWidth() / 2);
reorganize(); reorganize();
@@ -465,24 +507,44 @@ void Menu::setDefaultActionWhenCancel(int item)
void Menu::checkInput() void Menu::checkInput()
{ {
if (input->checkInput(INPUT_UP, REPEAT_FALSE)) if (input->checkInput(INPUT_UP, REPEAT_FALSE))
{
if (decreaseSelectorIndex()) if (decreaseSelectorIndex())
{
if (soundMove)
{
JA_PlaySound(soundMove); JA_PlaySound(soundMove);
}
}
}
if (input->checkInput(INPUT_DOWN, REPEAT_FALSE)) if (input->checkInput(INPUT_DOWN, REPEAT_FALSE))
{
if (increaseSelectorIndex()) if (increaseSelectorIndex())
{
if (soundMove)
{
JA_PlaySound(soundMove); JA_PlaySound(soundMove);
}
}
}
if (input->checkInput(INPUT_ACCEPT, REPEAT_FALSE)) if (input->checkInput(INPUT_ACCEPT, REPEAT_FALSE))
{ {
itemSelected = selector.index; itemSelected = selector.index;
if (soundAccept)
{
JA_PlaySound(soundAccept); JA_PlaySound(soundAccept);
} }
}
if (input->checkInput(INPUT_CANCEL, REPEAT_FALSE)) if (input->checkInput(INPUT_CANCEL, REPEAT_FALSE))
{ {
itemSelected = defaultActionWhenCancel; itemSelected = defaultActionWhenCancel;
if (soundCancel)
{
JA_PlaySound(soundCancel); JA_PlaySound(soundCancel);
} }
}
} }
// Calcula el ancho del menu // Calcula el ancho del menu
@@ -511,7 +573,9 @@ void Menu::replaceElementsOnY()
item[0].rect.y = y; item[0].rect.y = y;
for (int i = 1; i < item.size(); i++) for (int i = 1; i < item.size(); i++)
{
item[i].rect.y = item[i - 1].rect.y + item[i - 1].rect.h + item[i - 1].hPaddingDown; item[i].rect.y = item[i - 1].rect.y + item[i - 1].rect.h + item[i - 1].hPaddingDown;
}
} }
// Establece el estado seleccionable de un item // Establece el estado seleccionable de un item
@@ -536,7 +600,11 @@ void Menu::setLinkedDown(int index, bool value)
int Menu::getSelectorHeight(int value) int Menu::getSelectorHeight(int value)
{ {
if (item[value].linkedDown) if (item[value].linkedDown)
{
return item[value].rect.h + item[value].hPaddingDown + item[value + 1].rect.h; return item[value].rect.h + item[value].hPaddingDown + item[value + 1].rect.h;
}
else else
{
return item[value].rect.h; return item[value].rect.h;
}
} }

View File

@@ -5,7 +5,6 @@
#include "sprite.h" #include "sprite.h"
#include "text.h" #include "text.h"
#include "input.h" #include "input.h"
#include "asset.h"
#include "utils.h" #include "utils.h"
#include "jail_audio.h" #include "jail_audio.h"
@@ -16,6 +15,11 @@
#define MENU_BACKGROUND_TRANSPARENT 0 #define MENU_BACKGROUND_TRANSPARENT 0
#define MENU_BACKGROUND_SOLID 1 #define MENU_BACKGROUND_SOLID 1
// Tipos de archivos de audio
#define SOUND_ACCEPT 0
#define SOUND_MOVE 1
#define SOUND_CANCEL 2
// Opciones de menu // Opciones de menu
#define MENU_NO_OPTION -1 #define MENU_NO_OPTION -1
@@ -23,36 +27,12 @@
class Menu class Menu
{ {
private: private:
std::string name; // Nombre del menu
int x; // Posición en el eje X de la primera letra del primer elemento
int y; // Posición en el eje Y de la primera letra del primer elemento
int h; // Altura del menu
int w; // Anchura del menu
int itemSelected; // Índice del item del menu que ha sido seleccionado
int defaultActionWhenCancel; // Indice del item del menu que se selecciona cuando se cancela el menu
int backgroundType; // Tipo de fondo para el menu
int centerX; // Centro del menu en el eje X
int centerY; // Centro del menu en el eje Y
bool isCenteredOnX; // Variable para saber si el menu debe estar centrado respecto a un punto en el eje X
bool isCenteredOnY; // Variable para saber si el menu debe estar centrado respecto a un punto en el eje Y
bool areElementsCenteredOnX; // Variable para saber si los elementos van centrados en el eje X
int widestItem; // Anchura del elemento más ancho
JA_Sound soundAccept; // Sonido al aceptar o elegir una opción del menu
JA_Sound soundCancel; // Sonido al cancelar el menu
JA_Sound soundMove; // Sonido al mover el selector
SDL_Renderer *renderer; // Puntero al renderizador de la ventana
Asset *asset; // Objeto encargado de gestionar los ficheros de recursos
Text *text; // Texto para poder escribir los items del menu
Input *input; // Gestor de eventos de entrada de teclado o gamepad
color_t colorGreyed; // Color para los elementos agrisados
struct rectangle_t struct rectangle_t
{ {
SDL_Rect rect; // Rectangulo SDL_Rect rect; // Rectangulo
color_t color; // Color color_t color; // Color
int a; // Transparencia int a; // Transparencia
}; };
rectangle_t rectBG; // Rectangulo de fondo del menu
struct item_t struct item_t
{ {
@@ -64,7 +44,6 @@ private:
bool linkedDown; // Indica si el elemento actual y el siguiente se tratan como uno solo. Afecta al selector bool linkedDown; // Indica si el elemento actual y el siguiente se tratan como uno solo. Afecta al selector
bool linkedUp; // Indica si el elemento actual y el anterior se tratan como uno solo. Afecta al selector bool linkedUp; // Indica si el elemento actual y el anterior se tratan como uno solo. Afecta al selector
}; };
std::vector<item_t> item; // Estructura para cada elemento del menu
struct selector_t struct selector_t
{ {
@@ -85,6 +64,30 @@ private:
color_t itemColor; // Color del item color_t itemColor; // Color del item
int a; // Cantidad de transparencia para el rectangulo del selector int a; // Cantidad de transparencia para el rectangulo del selector
}; };
std::string name; // Nombre del menu
int x; // Posición en el eje X de la primera letra del primer elemento
int y; // Posición en el eje Y de la primera letra del primer elemento
int h; // Altura del menu
int w; // Anchura del menu
int itemSelected; // Índice del item del menu que ha sido seleccionado
int defaultActionWhenCancel; // Indice del item del menu que se selecciona cuando se cancela el menu
int backgroundType; // Tipo de fondo para el menu
int centerX; // Centro del menu en el eje X
int centerY; // Centro del menu en el eje Y
bool isCenteredOnX; // Variable para saber si el menu debe estar centrado respecto a un punto en el eje X
bool isCenteredOnY; // Variable para saber si el menu debe estar centrado respecto a un punto en el eje Y
bool areElementsCenteredOnX; // Variable para saber si los elementos van centrados en el eje X
int widestItem; // Anchura del elemento más ancho
JA_Sound soundAccept; // Sonido al aceptar o elegir una opción del menu
JA_Sound soundCancel; // Sonido al cancelar el menu
JA_Sound soundMove; // Sonido al mover el selector
SDL_Renderer *renderer; // Puntero al renderizador de la ventana
Text *text; // Texto para poder escribir los items del menu
Input *input; // Gestor de eventos de entrada de teclado o gamepad
color_t colorGreyed; // Color para los elementos agrisados
rectangle_t rectBG; // Rectangulo de fondo del menu
std::vector<item_t> item; // Estructura para cada elemento del menu
selector_t selector; // Variables para pintar el selector del menu selector_t selector; // Variables para pintar el selector del menu
// Establece el rectangulo de fondo del menu // Establece el rectangulo de fondo del menu
@@ -122,7 +125,7 @@ private:
public: public:
// Constructor // Constructor
Menu(SDL_Renderer *renderer, Text *text, Input *input, Asset *asset); Menu(SDL_Renderer *renderer, Text *text, Input *input);
// Destructor // Destructor
~Menu(); ~Menu();
@@ -130,6 +133,9 @@ public:
// Inicializador // Inicializador
void init(std::string name, int x, int y, int backgroundType); void init(std::string name, int x, int y, int backgroundType);
// Carga los ficheros de audio
void loadAudioFile(std::string file, int sound);
// Obtiene el nombre del menu // Obtiene el nombre del menu
std::string getName(); std::string getName();

View File

@@ -15,8 +15,10 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Asset *asset, Input *input)
loadTextureFromFile(texture, asset->get("intro.png"), renderer); loadTextureFromFile(texture, asset->get("intro.png"), renderer);
sprite = new AnimatedSprite(texture, renderer, asset->get("intro.ani")); sprite = new AnimatedSprite(texture, renderer, asset->get("intro.ani"));
sprite->setCurrentAnimation("menu"); sprite->setCurrentAnimation("menu");
text = new Text(asset->get("debug.png"), asset->get("debug.txt"), renderer); text = new Text(asset->get("dogica.png"), asset->get("dogica.txt"), renderer);
music = JA_LoadMusic(asset->get("music_title.ogg").c_str()); music = JA_LoadMusic(asset->get("music_title.ogg").c_str());
menu = new Menu(renderer, text, input);
initMenu();
// Inicializa variables // Inicializa variables
section = {SECTION_PROG_TITLE, 0}; section = {SECTION_PROG_TITLE, 0};
@@ -44,9 +46,31 @@ Title::~Title()
delete text; delete text;
text = nullptr; text = nullptr;
delete menu;
menu = nullptr;
JA_DeleteMusic(music); JA_DeleteMusic(music);
} }
// Crea el menu
void Title::initMenu()
{
menu->loadAudioFile(asset->get("sound_menu_cancel.wav"), SOUND_CANCEL);
menu->loadAudioFile(asset->get("sound_menu_select.wav"), SOUND_ACCEPT);
menu->loadAudioFile(asset->get("sound_menu_move.wav"), SOUND_MOVE);
menu->init("TITLE", 0, 0, MENU_BACKGROUND_SOLID);
menu->addItem("START",2);
menu->addItem("OPTIONS", 5);
menu->addItem("EXIT");
menu->setDefaultActionWhenCancel(2);
menu->setBackgroundColor({0x30, 0x30, 0x40}, 192);
menu->setSelectorColor({0xe5, 0x1c, 0x23}, 0);
menu->setSelectorTextColor({0xFF, 0xB4, 0x00});
menu->centerMenuOnX(160);
menu->centerMenuElementsOnX();
}
// Actualiza las variables // Actualiza las variables
void Title::update() void Title::update()
{ {
@@ -74,6 +98,7 @@ void Title::update()
} }
} }
sprite->animate(); sprite->animate();
menu->update();
} }
} }
@@ -89,6 +114,7 @@ void Title::render()
// Dibuja los objetos // Dibuja los objetos
sprite->render(); sprite->render();
text->writeDX(TXT_CENTER | TXT_COLOR, 160, 200, "@2016,2022 JAILDESIGNER & JAILBROTHER (v0.6)", -1, {255, 93, 4}); text->writeDX(TXT_CENTER | TXT_COLOR, 160, 200, "@2016,2022 JAILDESIGNER & JAILBROTHER (v0.6)", -1, {255, 93, 4});
menu->render();
// Vuelca el contenido del renderizador en pantalla // Vuelca el contenido del renderizador en pantalla
screen->blit(); screen->blit();

View File

@@ -7,6 +7,7 @@
#include "input.h" #include "input.h"
#include "screen.h" #include "screen.h"
#include "text.h" #include "text.h"
#include "menu.h"
#include "animatedsprite.h" #include "animatedsprite.h"
#include "jail_audio.h" #include "jail_audio.h"
@@ -24,6 +25,7 @@ private:
Asset *asset; // Objeto con los ficheros de recurso Asset *asset; // Objeto con los ficheros de recurso
Input *input; // Objeto para gestionar las entradas Input *input; // Objeto para gestionar las entradas
Text *text; // Objeto para escribir texto en pantalla Text *text; // Objeto para escribir texto en pantalla
Menu *menu; // Objeto para gestionar el menu del titulo
AnimatedSprite *sprite; // Sprite para dibujar los graficos de la intro AnimatedSprite *sprite; // Sprite para dibujar los graficos de la intro
JA_Music music; // Musica del titulo del juego JA_Music music; // Musica del titulo del juego
section_t section; // Estado del bucle principal para saber si continua o se sale section_t section; // Estado del bucle principal para saber si continua o se sale
@@ -36,6 +38,9 @@ private:
// Dibuja en pantalla // Dibuja en pantalla
void render(); void render();
// Crea el menu
void initMenu();
public: public:
// Constructor // Constructor
Title(SDL_Renderer *renderer, Screen *screen, Asset *asset, Input *input); Title(SDL_Renderer *renderer, Screen *screen, Asset *asset, Input *input);