diff --git a/source/animatedsprite.cpp b/source/animatedsprite.cpp index 933a7df..132ab02 100644 --- a/source/animatedsprite.cpp +++ b/source/animatedsprite.cpp @@ -1,121 +1,308 @@ -#include "const.h" + #include "animatedsprite.h" // Constructor -AnimatedSprite::AnimatedSprite() +AnimatedSprite::AnimatedSprite(LTexture *texture, SDL_Renderer *renderer, std::string file) { + // Copia los punteros + setTexture(texture); + setRenderer(renderer); + + // Carga las animaciones + load(file); + + // Inicializa variables + currentAnimation = 0; } // Destructor AnimatedSprite::~AnimatedSprite() { + for (auto &a : animation) + { + a.frames.clear(); + } + animation.clear(); } -// Iniciador -void AnimatedSprite::init(LTexture *texture, SDL_Renderer *renderer) +// Obtiene el indice de la animación a partir del nombre +int AnimatedSprite::getIndex(std::string name) { - mRenderer = renderer; - mTexture = texture; - for (int i = 0; i < 20; i++) + int index = -1; + + for (auto a : animation) { - mAnimation[i].numFrames = 0; - mAnimation[i].speed = 0; - mAnimation[i].loop = true; - mAnimation[i].completed = false; - for (int j = 0; i < 20; i++) + index++; + if (a.name == name) { - mAnimation[i].frames[j].x = 0; - mAnimation[i].frames[j].y = 0; - mAnimation[i].frames[j].w = 0; - mAnimation[i].frames[j].h = 0; + return index; } } - mCurrentFrame = 0; - mAnimationCounter = 0; + + printf("** Warning: could not find \"%s\" animation\n", name.c_str()); + + return -1; } // Calcula el frame correspondiente a la animación -void AnimatedSprite::animate(int index) +void AnimatedSprite::animate() { - if (mEnabled) + if (!enabled || animation[currentAnimation].speed == 0) { - // Calcula el frame actual a partir del contador - mCurrentFrame = mAnimationCounter / mAnimation[index].speed; + return; + } - // Si alcanza el final de la animación, reinicia el contador de la animación - // en función de la variable loop - if (mCurrentFrame >= mAnimation[index].numFrames) - { - if (mAnimation[index].loop) - mAnimationCounter = 0; - else - mCurrentFrame = mAnimation[index].numFrames; + // Calcula el frame actual a partir del contador + animation[currentAnimation].currentFrame = animation[currentAnimation].counter / animation[currentAnimation].speed; + + // Si alcanza el final de la animación, reinicia el contador de la animación + // en función de la variable loop y coloca el nuevo frame + if (animation[currentAnimation].currentFrame >= (int)animation[currentAnimation].frames.size()) + { + if (animation[currentAnimation].loop == -1) + { // Si no hay loop, deja el último frame + animation[currentAnimation].currentFrame = animation[currentAnimation].frames.size(); + animation[currentAnimation].completed = true; } - // En caso contrario else - { - // Escoge el frame correspondiente de la animación - setSpriteClip(mAnimation[index].frames[mCurrentFrame]); - - // Incrementa el contador de la animacion - mAnimationCounter++; + { // Si hay loop, vuelve al frame indicado + animation[currentAnimation].counter = 0; + animation[currentAnimation].currentFrame = animation[currentAnimation].loop; } } + // En caso contrario + else + { + // Escoge el frame correspondiente de la animación + setSpriteClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]); + + // Incrementa el contador de la animacion + animation[currentAnimation].counter++; + } } // Establece el frame actual de la animación -void AnimatedSprite::setCurrentFrame(Uint8 num) +void AnimatedSprite::setCurrentFrame(int num) { - mCurrentFrame = num; + // Descarta valores fuera de rango + if (num >= (int)animation[currentAnimation].frames.size()) + { + num = 0; + } + + // Cambia el valor de la variable + animation[currentAnimation].counter = animation[currentAnimation].speed * num; + + // Escoge el frame correspondiente de la animación + setSpriteClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]); } // Establece el valor del contador -void AnimatedSprite::setAnimationCounter(Uint16 num) +void AnimatedSprite::setAnimationCounter(std::string name, int num) { - mAnimationCounter = num; + animation[getIndex(name)].counter = num; +} + +// Establece el valor del contador +void AnimatedSprite::setAnimationCounter(int index, int num) +{ + animation[index].counter = num; +} + +// Establece la velocidad de una animación +void AnimatedSprite::setAnimationSpeed(std::string name, int speed) +{ + animation[getIndex(name)].counter = speed; +} + +// Establece si la animación se reproduce en bucle +void AnimatedSprite::setAnimationLoop(std::string name, int loop) +{ + animation[getIndex(name)].loop = loop; +} + +// Establece el valor de la variable +void AnimatedSprite::setAnimationCompleted(std::string name, bool value) +{ + animation[getIndex(name)].completed = value; +} + +// Comprueba si ha terminado la animación +bool AnimatedSprite::animationIsCompleted() +{ + return animation[currentAnimation].completed; +} + +// Devuelve el rectangulo de una animación y frame concreto +SDL_Rect AnimatedSprite::getAnimationClip(std::string name, Uint8 index) +{ + return animation[getIndex(name)].frames[index]; +} + +// Carga la animación desde un fichero +bool AnimatedSprite::load(std::string filePath) +{ + int frames_per_row = 0; + int frame_width = 0; + int frame_height = 0; + + // Indicador de éxito en la carga + bool success = true; + + const std::string filename = filePath.substr(filePath.find_last_of("\\/") + 1); + std::ifstream file(filePath); + std::string line; + + // El fichero se puede abrir + if (file.good()) + { + // Procesa el fichero linea a linea + printf("Reading file %s\n", filename.c_str()); + while (std::getline(file, line)) + { + // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación + if (line == "[animation]") + { + t_animation buffer; + buffer.counter = 0; + buffer.currentFrame = 0; + buffer.completed = false; + + do + { + std::getline(file, line); + + // Encuentra la posición del caracter '=' + int pos = line.find("="); + + // Procesa las dos subcadenas + if (pos != (int)line.npos) + { + if (line.substr(0, pos) == "name") + { + buffer.name = line.substr(pos + 1, line.length()); + } + else if (line.substr(0, pos) == "speed") + { + buffer.speed = std::stoi(line.substr(pos + 1, line.length())); + } + else if (line.substr(0, pos) == "loop") + { + buffer.loop = std::stoi(line.substr(pos + 1, line.length())); + } + else if (line.substr(0, pos) == "frames") + { + // Se introducen los valores separados por comas en un vector + std::stringstream ss(line.substr(pos + 1, line.length())); + std::string tmp; + SDL_Rect rect = {0, 0, frame_width, frame_height}; + while (getline(ss, tmp, ',')) + { + int num_tile = std::stoi(tmp); + rect.x = (num_tile % frames_per_row) * frame_width; + rect.y = (num_tile / frames_per_row) * frame_height; + buffer.frames.push_back(rect); + } + } + else + { + printf("Warning: file %s, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str()); + success = false; + } + } + } while (line != "[/animation]"); + + // Añade la animación al vector de animaciones + animation.push_back(buffer); + } + + // En caso contrario se parsea el fichero para buscar las variables y los valores + else + { + // Encuentra la posición del caracter '=' + int pos = line.find("="); + + // Procesa las dos subcadenas + if (pos != (int)line.npos) + { + if (line.substr(0, pos) == "frames_per_row") + { + frames_per_row = std::stoi(line.substr(pos + 1, line.length())); + } + + else if (line.substr(0, pos) == "frame_width") + { + frame_width = std::stoi(line.substr(pos + 1, line.length())); + + // Normaliza valores + if (frames_per_row == 0) + { + frames_per_row = texture->getWidth() / frame_width; + } + } + + else if (line.substr(0, pos) == "frame_height") + { + frame_height = std::stoi(line.substr(pos + 1, line.length())); + } + + else + { + printf("Warning: file %s, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str()); + success = false; + } + } + } + } + + // Cierra el fichero + printf("Closing file %s\n\n", filename.c_str()); + file.close(); + } + // El fichero no se puede abrir + else + { + printf("Warning: Unable to open %s file\n", filename.c_str()); + success = false; + } + + // Pone un valor por defecto + setPos({0, 0, frame_width, frame_height}); + + return success; +} + +// Establece la animacion actual +void AnimatedSprite::setCurrentAnimation(std::string name) +{ + const int newAnimation = getIndex(name); + if (currentAnimation != newAnimation) + { + currentAnimation = newAnimation; + animation[currentAnimation].currentFrame = 0; + animation[currentAnimation].counter = 0; + animation[currentAnimation].completed = false; + } +} + +// Actualiza las variables del objeto +void AnimatedSprite::update() +{ + animate(); + MovingSprite::update(); } // Establece el rectangulo para un frame de una animación void AnimatedSprite::setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h) { - mAnimation[index_animation].frames[index_frame].x = x; - mAnimation[index_animation].frames[index_frame].y = y; - mAnimation[index_animation].frames[index_frame].w = w; - mAnimation[index_animation].frames[index_frame].h = h; -} - -// Establece la velocidad de una animación -void AnimatedSprite::setAnimationSpeed(Uint8 index, Uint8 speed) -{ - mAnimation[index].speed = speed; + animation[index_animation].frames[index_frame].x = x; + animation[index_animation].frames[index_frame].y = y; + animation[index_animation].frames[index_frame].w = w; + animation[index_animation].frames[index_frame].h = h; } // Establece el numero de frames de una animación void AnimatedSprite::setAnimationNumFrames(Uint8 index, Uint8 num) { - mAnimation[index].numFrames = num; -} - -// Establece si la animación se reproduce en bucle -void AnimatedSprite::setAnimationLoop(Uint8 index, bool loop) -{ - mAnimation[index].loop = loop; -} - -// Establece el valor de la variable -void AnimatedSprite::setCompleted(Uint8 index, bool value) -{ - mAnimation[index].completed = value; -} - -// Comprueba si ha terminado la animación -bool AnimatedSprite::isCompleted(Uint8 index) -{ - return mAnimation[index].completed; -} - -// Devuelve el rectangulo de una animación y frame concreto -SDL_Rect AnimatedSprite::getAnimationClip(Uint8 index_animation, Uint8 index_frame) -{ - return mAnimation[index_animation].frames[index_frame]; + animation[index].numFrames = num; } \ No newline at end of file diff --git a/source/animatedsprite.h b/source/animatedsprite.h index 1f34a03..a88fe16 100644 --- a/source/animatedsprite.h +++ b/source/animatedsprite.h @@ -2,69 +2,80 @@ #include #include "movingsprite.h" +#include +#include +#include +#include #ifndef ANIMATEDSPRITE_H #define ANIMATEDSPRITE_H -#define MAX_FRAMES 30 -#define MAX_ANIMATIONS 20 - // Clase AnimatedSprite class AnimatedSprite : public MovingSprite { private: - struct sAnimation + struct t_animation { - SDL_Rect frames[MAX_FRAMES]; // Cada uno de los frames que componen la animación - Uint8 numFrames; // Numero de frames que componen la animación - Uint8 speed; // Velocidad de la animación - bool loop; // Indica si la animación se reproduce en bucle - bool completed; // Indica si ha finalizado la animación + std::string name; // Nombre de la animacion + std::vector frames; // Cada uno de los frames que componen la animación + int speed; // Velocidad de la animación + int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva + bool completed; // Indica si ha finalizado la animación + int currentFrame; // Frame actual + int counter; // Contador para las animaciones }; - sAnimation mAnimation[MAX_ANIMATIONS]; // Vector con las diferentes animaciones - - Uint8 mCurrentFrame; // Frame actual - Uint16 mAnimationCounter; // Contador para las animaciones + std::vector animation; // Vector con las diferentes animaciones + int currentAnimation; // Animacion activa public: // Constructor - AnimatedSprite(); + AnimatedSprite(LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = ""); // Destructor ~AnimatedSprite(); - // Iniciador - void init(LTexture *texture, SDL_Renderer *renderer); - - // Calcula el frame correspondiente a la animación - void animate(int index); + // Calcula el frame correspondiente a la animación actual + void animate(); // Establece el frame actual de la animación - void setCurrentFrame(Uint8 num); + void setCurrentFrame(int num); // Establece el valor del contador - void setAnimationCounter(Uint16 num); + void setAnimationCounter(std::string name, int num); + void setAnimationCounter(int index, int num); + + // Establece la velocidad de una animación + void setAnimationSpeed(std::string name, int speed); + + // Establece el frame al que vuelve la animación al finalizar + void setAnimationLoop(std::string name, int loop); + + // Establece el valor de la variable + void setAnimationCompleted(std::string name, bool value); + + // Comprueba si ha terminado la animación + bool animationIsCompleted(); + + // Devuelve el rectangulo de una animación y frame concreto + SDL_Rect getAnimationClip(std::string name, Uint8 index); + + // Obtiene el indice de la animación a partir del nombre + int getIndex(std::string name); + + // Carga la animación desde un fichero + bool load(std::string filePath); + + // Establece la animacion actual + void setCurrentAnimation(std::string name = "default"); + + // Actualiza las variables del objeto + void update(); // Establece el rectangulo para un frame de una animación void setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h); - // Establece la velocidad de una animación - void setAnimationSpeed(Uint8 index, Uint8 speed); - // Establece el numero de frames de una animación - void setAnimationNumFrames(Uint8 index, Uint8 num); - - // Establece si la animación se reproduce en bucle - void setAnimationLoop(Uint8 index, bool loop); - - // Establece el valor de la variable - void setCompleted(Uint8 index, bool value); - - // Comprueba si ha terminado la animación - bool isCompleted(Uint8 index); - - // Devuelve el rectangulo de una animación y frame concreto - SDL_Rect getAnimationClip(Uint8 index_animation, Uint8 index_frame); + void setAnimationNumFrames(Uint8 index, Uint8 num) }; #endif \ No newline at end of file diff --git a/source/game.cpp b/source/game.cpp index d51e623..8739f2b 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -63,11 +63,11 @@ Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, Screen *scr mTexturePlayer2Death = new LTexture(mRenderer); mTexturePlayer2Legs = new LTexture(mRenderer); - mText = new Text(mAsset->get("smb2.png"),mAsset->get("smb2.txt"), mRenderer); - mTextScoreBoard = new Text(mAsset->get("8bithud.png"),mAsset->get("8bithud.txt"), mRenderer); - mTextBig = new Text(mAsset->get("smb2_big.png"),mAsset->get("smb2_big.txt"), mRenderer); - mTextNokia2 = new Text(mAsset->get("nokia2.png"),mAsset->get("nokia2.txt"), mRenderer); - mTextNokiaBig2 = new Text(mAsset->get("nokia_big2.png"),mAsset->get("nokia_big2.txt"), mRenderer); + mText = new Text(mAsset->get("smb2.png"), mAsset->get("smb2.txt"), mRenderer); + mTextScoreBoard = new Text(mAsset->get("8bithud.png"), mAsset->get("8bithud.txt"), mRenderer); + mTextBig = new Text(mAsset->get("smb2_big.png"), mAsset->get("smb2_big.txt"), mRenderer); + mTextNokia2 = new Text(mAsset->get("nokia2.png"), mAsset->get("nokia2.txt"), mRenderer); + mTextNokiaBig2 = new Text(mAsset->get("nokia_big2.png"), mAsset->get("nokia_big2.txt"), mRenderer); mMenuGameOver = new Menu(mRenderer, mAsset, mInput); mMenuPause = new Menu(mRenderer, mAsset, mInput); @@ -108,25 +108,25 @@ Game::~Game() delete mPlayer[i]; mPlayer[i] = nullptr; } - + for (int i = 0; i < MAX_BALLOONS; i++) { delete mBalloon[i]; mBalloon[i] = nullptr; } - + for (int i = 0; i < MAX_BULLETS; i++) { delete mBullet[i]; mBullet[i] = nullptr; } - + for (int i = 0; i < MAX_ITEMS; i++) { delete mItem[i]; mItem[i] = nullptr; } - + for (int i = 0; i < MAX_SMART_SPRITES; i++) { delete mSmartSprite[i]; @@ -388,7 +388,9 @@ void Game::init() mFade->init(0x27, 0x27, 0x36); // Inicializa el objeto con el menu de pausa - mMenuPause->init("PAUSE", 0, 12 * BLOCK, MENU_BACKGROUND_SOLID); + mMenuPause->setName("PAUSE"); + mMenuPause->setPos(0, 12 * BLOCK); + mMenuPause->setBackgroundType(MENU_BACKGROUND_SOLID); mMenuPause->addItem(mLang->getText(46), 2); mMenuPause->addItem(mLang->getText(47), 0); mMenuPause->setDefaultActionWhenCancel(0); @@ -399,11 +401,13 @@ void Game::init() mMenuPause->centerMenuElementsOnX(); // Inicializa el objeto con el menu de la pantalla de game over - mMenuGameOver->init("GAME OVER", 0, PLAY_AREA_CENTER_Y + BLOCK * 4, MENU_BACKGROUND_TRANSPARENT); + mMenuGameOver->setName("GAME OVER"); + mMenuGameOver->setPos(0, PLAY_AREA_CENTER_Y + BLOCK * 4); + mMenuGameOver->setBackgroundType(MENU_BACKGROUND_TRANSPARENT); mMenuGameOver->addItem(mLang->getText(48), 2); mMenuGameOver->addItem(mLang->getText(49)); mMenuGameOver->setDefaultActionWhenCancel(1); - mMenuGameOver->setBackgroundColor(0, 0, 0, 255); + mMenuGameOver->setBackgroundColor({0, 0, 0}, 255); mMenuGameOver->setSelectorColor({0x54, 0x6e, 0x7a}, 255); mMenuGameOver->setSelectorColor({0x54, 0x6e, 0x7a}, 0); mMenuGameOver->setSelectorTextColor({0xFF, 0xFF, 0xFF}); @@ -528,12 +532,6 @@ bool Game::loadMedia() bool success = true; // Texturas - success &= loadTextureFromFile(mTextureText, mAsset->get("smb2.png"), mRenderer); - success &= loadTextureFromFile(mTextureTextScoreBoard, mAsset->get("8bithud.png"), mRenderer); - success &= loadTextureFromFile(mTextureTextBig, mAsset->get("smb2_big.png"), mRenderer); - success &= loadTextureFromFile(mTextureTextNokia2, mAsset->get("nokia2.png"), mRenderer); - success &= loadTextureFromFile(mTextureTextNokiaBig2, mAsset->get("nokia_big2.png"), mRenderer); - success &= loadTextureFromFile(mTexturePlayer1Legs, mAsset->get("player1_legs.png"), mRenderer); success &= loadTextureFromFile(mTexturePlayer1Head, mAsset->get("player1_head.png"), mRenderer); success &= loadTextureFromFile(mTexturePlayer1Body, mAsset->get("player1_body.png"), mRenderer); @@ -623,12 +621,18 @@ bool Game::loadScoreFile() // Establece el valor de la máxima puntuación a partir del vector con los datos if (mScoreDataFile[0] == 0) - {mHiScore = 10000;} + { + mHiScore = 10000; + } // Comprueba el checksum para ver si se ha modificado el fichero else if (mScoreDataFile[0] % 43 == mScoreDataFile[1]) - {mHiScore = mScoreDataFile[0];} + { + mHiScore = mScoreDataFile[0]; + } else - {mHiScore = 10000;} + { + mHiScore = 10000; + } return success; } @@ -3118,7 +3122,7 @@ void Game::renderMessages() { // Escribe el texto de juego completado text = mLang->getText(50); mTextNokiaBig2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, mStageBitmapPath[mStageBitmapCounter], text, -2, noColor, 1, shdwTxtColor); - mTextNokia2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, mStageBitmapPath[mStageBitmapCounter] + mTextNokiaBig2->getCharacterWidth() + 2, mLang->getText(76), -1, noColor, 1, shdwTxtColor); + mTextNokia2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, mStageBitmapPath[mStageBitmapCounter] + mTextNokiaBig2->getCharacterSize() + 2, mLang->getText(76), -1, noColor, 1, shdwTxtColor); } } } diff --git a/source/instructions.cpp b/source/instructions.cpp index 9fb9e10..a6e7cd6 100644 --- a/source/instructions.cpp +++ b/source/instructions.cpp @@ -14,9 +14,8 @@ Instructions::Instructions(SDL_Renderer *renderer, Screen *screen, Asset *mAsset // Reserva memoria para los punteros mEventHandler = new SDL_Event(); mItemTexture = new LTexture(mRenderer); - mTextTexture = new LTexture(mRenderer); mSprite = new Sprite(); - mText = new Text(mAsset->get("smb2.txt"), mTextTexture, mRenderer); + mText = new Text(mAsset->get("smb2.png"), mAsset->get("smb2.txt"), mRenderer); // Crea un backbuffer para el renderizador mBackbuffer = SDL_CreateTexture(mRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT); @@ -38,10 +37,6 @@ Instructions::~Instructions() delete mItemTexture; mItemTexture = nullptr; - mTextTexture->unload(); - delete mTextTexture; - mTextTexture = nullptr; - delete mSprite; mSprite = nullptr; @@ -61,7 +56,6 @@ bool Instructions::loadMedia() bool success = true; success &= loadTextureFromFile(mItemTexture, mAsset->get("items.png"), mRenderer); - success &= loadTextureFromFile(mTextTexture, mAsset->get("smb2.png"), mRenderer); return success; } diff --git a/source/instructions.h b/source/instructions.h index 4bfc3cd..22116ae 100644 --- a/source/instructions.h +++ b/source/instructions.h @@ -26,7 +26,6 @@ private: SDL_Renderer *mRenderer; // El renderizador de la ventana Screen *mScreen; // Objeto encargado de dibujar en pantalla LTexture *mItemTexture; // Textura con los graficos - LTexture *mTextTexture; // Textura con los graficos SDL_Event *mEventHandler; // Manejador de eventos SDL_Texture *mBackbuffer; // Textura para usar como backbuffer Sprite *mSprite; // Sprite con la textura de las instrucciones diff --git a/source/intro.cpp b/source/intro.cpp index 474613e..9d9b948 100644 --- a/source/intro.cpp +++ b/source/intro.cpp @@ -12,8 +12,7 @@ Intro::Intro(SDL_Renderer *renderer, Screen *screen, Asset *mAsset, Lang *lang) // Reserva memoria para los punteros mEventHandler = new SDL_Event(); mBitmapTexture = new LTexture(mRenderer); - mTextTexture = new LTexture(mRenderer); - mText = new Text(mAsset->get("nokia.txt"), mTextTexture, mRenderer); + mText = new Text(mAsset->get("nokia.png"), mAsset->get("nokia.txt"), mRenderer); for (int i = 0; i < INTRO_TOTAL_BITMAPS; i++) { @@ -41,15 +40,12 @@ Intro::~Intro() delete mBitmapTexture; mBitmapTexture = nullptr; - mTextTexture->unload(); - delete mTextTexture; - mTextTexture = nullptr; - for (int i = 0; i < INTRO_TOTAL_BITMAPS; i++) { delete mBitmap[i]; mBitmap[i] = nullptr; } + for (int i = 0; i < INTRO_TOTAL_TEXTS; i++) { delete mWriter[i]; @@ -197,7 +193,6 @@ bool Intro::loadMedia() // Texturas success &= loadTextureFromFile(mBitmapTexture, mAsset->get("intro.png"), mRenderer); - success &= loadTextureFromFile(mTextTexture, mAsset->get("nokia.png"), mRenderer); // Musicas mMusic = JA_LoadMusic(mAsset->get("intro.ogg").c_str()); diff --git a/source/intro.h b/source/intro.h index 6fb09df..c8c45b0 100644 --- a/source/intro.h +++ b/source/intro.h @@ -41,7 +41,6 @@ private: SDL_Renderer *mRenderer; // El renderizador de la ventana Screen *mScreen; // Objeto encargado de dibujar en pantalla LTexture *mBitmapTexture; // Textura con los graficos - LTexture *mTextTexture; // Textura con los caracteres de texto SDL_Event *mEventHandler; // Manejador de eventos Asset *mAsset; // Objeto que gestiona todos los ficheros de recursos Lang *mLang; // Objeto para gestionar los textos en diferentes idiomas diff --git a/source/menu.cpp b/source/menu.cpp index 78a2627..a3e2420 100644 --- a/source/menu.cpp +++ b/source/menu.cpp @@ -887,4 +887,23 @@ int Menu::getSelectorHeight(int value) { return item[value].rect.h; } +} + +// Establece el nombre del menu +void Menu::setName(std::string name) +{ + this->name = name; +} + +// Establece la posición del menu +void Menu::setPos(int x, int y) +{ + this->x = x; + this->y = y; +} + +// Establece el tipo de fondo del menu +void Menu::setBackgroundType(int value) +{ + backgroundType = value; } \ No newline at end of file diff --git a/source/menu.h b/source/menu.h index 1b916cf..a90cfa4 100644 --- a/source/menu.h +++ b/source/menu.h @@ -208,6 +208,15 @@ public: // Establece el estado de enlace de un item void setLinkedDown(int index, bool value); + // Establece el nombre del menu + void setName(std::string name); + + // Establece la posición del menu + void setPos(int x, int y); + + // Establece el tipo de fondo del menu + void setBackgroundType(int value); + // hacer procedimientos para establecer el titulo, la x, la y, la tipografia y el tipo de fondo }; diff --git a/source/movingsprite.cpp b/source/movingsprite.cpp index e11493b..8500651 100644 --- a/source/movingsprite.cpp +++ b/source/movingsprite.cpp @@ -2,244 +2,256 @@ #include "movingsprite.h" // Constructor -MovingSprite::MovingSprite() +MovingSprite::MovingSprite(float x, float y, int w, int h, float velx, float vely, float accelx, float accely, LTexture *texture, SDL_Renderer *renderer) { - clear(); -} + // Copia los punteros + this->texture = texture; + this->renderer = renderer; + + // Establece el alto y el ancho del sprite + this->w = w; + this->h = h; + + // Establece la posición X,Y del sprite + this->x = x; + this->y = y; + xPrev = x; + yPrev = y; + + // Establece la velocidad X,Y del sprite + vx = velx; + vy = vely; + + // Establece la aceleración X,Y del sprite + ax = accelx; + ay = accely; + + // Establece el zoom W,H del sprite + zoomW = 1; + zoomH = 1; + + // Establece el angulo con el que se dibujará + angle = (double)0; + + // Establece los valores de rotacion + rotateEnabled = false; + rotateSpeed = 0; + rotateAmount = (double)0; + + // Contador interno + counter = 0; + + // Establece el rectangulo de donde coger la imagen + spriteClip = {0, 0, w, h}; + + // Establece el centro de rotación + center = {0, 0}; + + // Establece el tipo de volteado + currentFlip = SDL_FLIP_NONE; +}; // Destructor MovingSprite::~MovingSprite() { - clear(); } // Reinicia todas las variables void MovingSprite::clear() { - mPosX = 0.0f; // Posición en el eje X - mPosY = 0.0f; // Posición en el eje Y + x = 0.0f; // Posición en el eje X + y = 0.0f; // Posición en el eje Y - mVelX = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse - mVelY = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse + vx = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse + vy = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse - mAccelX = 0.0f; // Aceleración en el eje X. Variación de la velocidad - mAccelY = 0.0f; // Aceleración en el eje Y. Variación de la velocidad + ax = 0.0f; // Aceleración en el eje X. Variación de la velocidad + ay = 0.0f; // Aceleración en el eje Y. Variación de la velocidad - mZoomW = 1.0f; // Zoom aplicado a la anchura - mZoomH = 1.0f; // Zoom aplicado a la altura + zoomW = 1.0f; // Zoom aplicado a la anchura + zoomH = 1.0f; // Zoom aplicado a la altura - mAngle = 0.0; // Angulo para dibujarlo - mRotate = false; // Indica si ha de rotar - mRotateSpeed = 0; // Velocidad de giro - mRotateAmount = 0.0; // Cantidad de grados a girar en cada iteración - mCounter = 0; // Contador interno -} + angle = 0.0; // Angulo para dibujarlo + rotateEnabled = false; // Indica si ha de rotar + center = {0, 0}; // Centro de rotación + rotateSpeed = 0; // Velocidad de giro + rotateAmount = 0.0; // Cantidad de grados a girar en cada iteración + counter = 0; // Contador interno -// Iniciador -void MovingSprite::init(float x, float y, int w, int h, float velx, float vely, float accelx, float accely, LTexture *texture, SDL_Renderer *renderer) -{ - // Establece el alto y el ancho del sprite - setWidth(w); - setHeight(h); - - // Establece la posición X,Y del sprite - setPosX(x); - setPosY(y); - - // Establece la velocidad X,Y del sprite - setVelX(velx); - setVelY(vely); - - // Establece la aceleración X,Y del sprite - setAccelX(accelx); - setAccelY(accely); - - // Establece el zoom W,H del sprite - setZoomW(1); - setZoomH(1); - - // Establece el angulo con el que se dibujará - setAngle(0.0); - - // Establece los valores de rotacion - setRotate(false); - setRotateSpeed(0); - setRotateAmount(0.0); - - // Contador interno - mCounter = 0; - - // Establece la textura donde están los gráficos para el sprite - setTexture(texture); - - // Establece el renderizador - setRenderer(renderer); - - // Establece el rectangulo de donde coger la imagen - setSpriteClip(0, 0, w, h); + currentFlip = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite } // Mueve el sprite void MovingSprite::move() { - if (mEnabled) + if (enabled) { - mPosX += mVelX; - mPosY += mVelY; + xPrev = x; + yPrev = y; - mVelX += mAccelX; - mVelY += mAccelY; + x += vx; + y += vy; + + vx += ax; + vy += ay; } } // Muestra el sprite por pantalla void MovingSprite::render() { - if (mEnabled) - mTexture->render(mRenderer, (int)mPosX, (int)mPosY, &mSpriteClip, mZoomW, mZoomH, mAngle); + if (enabled) + texture->render(renderer, (int)x, (int)y, &spriteClip, zoomW, zoomH, angle, ¢er, currentFlip); } // Obtiene el valor de la variable float MovingSprite::getPosX() { - return mPosX; + return x; } // Obtiene el valor de la variable float MovingSprite::getPosY() { - return mPosY; + return y; } // Obtiene el valor de la variable float MovingSprite::getVelX() { - return mVelX; + return vx; } // Obtiene el valor de la variable float MovingSprite::getVelY() { - return mVelY; + return vy; } // Obtiene el valor de la variable float MovingSprite::getAccelX() { - return mAccelX; + return ax; } // Obtiene el valor de la variable float MovingSprite::getAccelY() { - return mAccelY; + return ay; } // Obtiene el valor de la variable float MovingSprite::getZoomW() { - return mZoomW; + return zoomW; } // Obtiene el valor de la variable float MovingSprite::getZoomH() { - return mZoomH; + return zoomH; } // Obtiene el valor de la variable double MovingSprite::getAngle() { - return mAngle; + return angle; +} + +// Establece la posición del objeto +void MovingSprite::setPos(SDL_Rect rect) +{ + x = (float)rect.x; + y = (float)rect.y; } // Establece el valor de la variable -void MovingSprite::setPosX(float x) +void MovingSprite::setPosX(float value) { - mPosX = x; + x = value; } // Establece el valor de la variable -void MovingSprite::setPosY(float y) +void MovingSprite::setPosY(float value) { - mPosY = y; + y = value; } // Establece el valor de la variable -void MovingSprite::setVelX(float x) +void MovingSprite::setVelX(float value) { - mVelX = x; + vx = value; } // Establece el valor de la variable -void MovingSprite::setVelY(float y) +void MovingSprite::setVelY(float value) { - mVelY = y; + vy = value; } // Establece el valor de la variable -void MovingSprite::setAccelX(float x) +void MovingSprite::setAccelX(float value) { - mAccelX = x; + ax = value; } // Establece el valor de la variable -void MovingSprite::setAccelY(float y) +void MovingSprite::setAccelY(float value) { - mAccelY = y; + ay = value; } // Establece el valor de la variable -void MovingSprite::setZoomW(float w) +void MovingSprite::setZoomW(float value) { - mZoomW = w; + zoomW = value; } // Establece el valor de la variable -void MovingSprite::setZoomH(float h) +void MovingSprite::setZoomH(float value) { - mZoomH = h; + zoomH = value; } // Establece el valor de la variable -void MovingSprite::setAngle(double a) +void MovingSprite::setAngle(double value) { - mAngle = a; + angle = value; } // Incrementa el valor de la variable -void MovingSprite::incAngle(double inc) +void MovingSprite::incAngle(double value) { - mAngle += inc; + angle += value; } // Decrementa el valor de la variable -void MovingSprite::decAngle(double dec) +void MovingSprite::decAngle(double value) { - mAngle -= dec; + angle -= value; } // Obtiene el valor de la variable bool MovingSprite::getRotate() { - return mRotate; + return rotateEnabled; } // Obtiene el valor de la variable Uint16 MovingSprite::getRotateSpeed() { - return mRotateSpeed; + return rotateSpeed; } // Establece la rotacion void MovingSprite::rotate() { - if (mEnabled) - if (mRotate) + if (enabled) + if (rotateEnabled) { - if (mCounter % mRotateSpeed == 0) + if (counter % rotateSpeed == 0) { - incAngle(mRotateAmount); + incAngle(rotateAmount); } } } @@ -247,26 +259,26 @@ void MovingSprite::rotate() // Establece el valor de la variable void MovingSprite::setRotate(bool value) { - mRotate = value; + rotateEnabled = value; } // Establece el valor de la variable -void MovingSprite::setRotateSpeed(Uint16 value) +void MovingSprite::setRotateSpeed(int value) { - mRotateSpeed = value; + rotateSpeed = value; } // Establece el valor de la variable void MovingSprite::setRotateAmount(double value) { - mRotateAmount = value; + rotateAmount = value; } // Establece el valor de la variable void MovingSprite::disableRotate() { - mRotate = false; - mAngle = 0; + rotateEnabled = false; + angle = (double)0; } // Actualiza las variables internas del objeto @@ -275,12 +287,79 @@ void MovingSprite::update() move(); rotate(); - if (mEnabled) - ++mCounter %= 60000; + if (enabled) + { + ++counter %= 60000; + } } // Cambia el sentido de la rotación void MovingSprite::switchRotate() { - mRotateAmount *= -1; + rotateAmount *= -1; +} + +// Establece el valor de la variable +void MovingSprite::setFlip(SDL_RendererFlip flip) +{ + currentFlip = flip; +} + +// Gira el sprite horizontalmente +void MovingSprite::flip() +{ + currentFlip = (currentFlip == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; +} + +// Obtiene el valor de la variable +SDL_RendererFlip MovingSprite::getFlip() +{ + return currentFlip; +} + +// Devuelve el rectangulo donde está el sprite +SDL_Rect MovingSprite::getRect() +{ + const SDL_Rect rect = {(int)x, (int)y, w, h}; + return rect; +} + +// Establece los valores de posición y tamaño del sprite +void MovingSprite::setRect(SDL_Rect rect) +{ + x = (float)rect.x; + y = (float)rect.y; + w = rect.w; + h = rect.h; +} + +// Deshace el último movimiento +void MovingSprite::undoMove() +{ + x = xPrev; + y = yPrev; +} + +// Deshace el último movimiento en el eje X +void MovingSprite::undoMoveX() +{ + x = xPrev; +} + +// Deshace el último movimiento en el eje Y +void MovingSprite::undoMoveY() +{ + y = yPrev; +} + +// Pone a cero las velocidades de desplacamiento +void MovingSprite::clearVel() +{ + vx = vy = 0.0f; +} + +// Devuelve el incremento en el eje X en pixels +int MovingSprite::getIncX() +{ + return (int)x - (int)xPrev; } \ No newline at end of file diff --git a/source/movingsprite.h b/source/movingsprite.h index de4e88d..aeedcab 100644 --- a/source/movingsprite.h +++ b/source/movingsprite.h @@ -10,34 +10,36 @@ class MovingSprite : public Sprite { protected: - float mPosX; // Posición en el eje X - float mPosY; // Posición en el eje Y + float x; // Posición en el eje X + float y; // Posición en el eje Y - float mVelX; // Velocidad en el eje X. Cantidad de pixeles a desplazarse - float mVelY; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse + float xPrev; // Posición anterior en el eje X + float yPrev; // Posición anterior en el eje Y - float mAccelX; // Aceleración en el eje X. Variación de la velocidad - float mAccelY; // Aceleración en el eje Y. Variación de la velocidad + float vx; // Velocidad en el eje X. Cantidad de pixeles a desplazarse + float vy; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse - float mZoomW; // Zoom aplicado a la anchura - float mZoomH; // Zoom aplicado a la altura + float ax; // Aceleración en el eje X. Variación de la velocidad + float ay; // Aceleración en el eje Y. Variación de la velocidad - double mAngle; // Angulo para dibujarlo - bool mRotate; // Indica si ha de rotar - Uint16 mRotateSpeed; // Velocidad de giro - double mRotateAmount; // Cantidad de grados a girar en cada iteración - Uint16 mCounter; // Contador interno + float zoomW; // Zoom aplicado a la anchura + float zoomH; // Zoom aplicado a la altura + + double angle; // Angulo para dibujarlo + bool rotateEnabled; // Indica si ha de rotar + int rotateSpeed; // Velocidad de giro + double rotateAmount; // Cantidad de grados a girar en cada iteración + int counter; // Contador interno + SDL_Point center; // Centro de rotación + SDL_RendererFlip currentFlip; // Indica como se voltea el sprite public: // Constructor - MovingSprite(); + MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr); // Destructor ~MovingSprite(); - // Iniciador - void init(float x, float y, int w, int h, float velx, float vely, float accelx, float accely, LTexture *texture, SDL_Renderer *renderer); - // Mueve el sprite void move(); @@ -86,44 +88,47 @@ public: // Obtiene el valor de la variable Uint16 getRotateSpeed(); - // Establece el valor de la variable - void setPosX(float x); + // Establece la posición del objeto + void setPos(SDL_Rect rect); // Establece el valor de la variable - void setPosY(float y); + void setPosX(float value); // Establece el valor de la variable - void setVelX(float x); + void setPosY(float value); // Establece el valor de la variable - void setVelY(float y); + void setVelX(float value); // Establece el valor de la variable - void setAccelX(float x); + void setVelY(float value); // Establece el valor de la variable - void setAccelY(float y); + void setAccelX(float value); // Establece el valor de la variable - void setZoomW(float w); + void setAccelY(float value); // Establece el valor de la variable - void setZoomH(float h); + void setZoomW(float value); // Establece el valor de la variable - void setAngle(double a); + void setZoomH(float value); + + // Establece el valor de la variable + void setAngle(double vaue); // Incrementa el valor de la variable - void incAngle(double inc); + void incAngle(double value); // Decrementa el valor de la variable - void decAngle(double dec); + void decAngle(double value); // Establece el valor de la variable void setRotate(bool value); // Establece el valor de la variable - void setRotateSpeed(Uint16 value); + void setRotateSpeed(int value); // Establece el valor de la variable void setRotateAmount(double value); @@ -133,6 +138,36 @@ public: // Cambia el sentido de la rotación void switchRotate(); + + // Establece el valor de la variable + void setFlip(SDL_RendererFlip flip); + + // Gira el sprite horizontalmente + void flip(); + + // Obtiene el valor de la variable + SDL_RendererFlip getFlip(); + + // Devuelve el rectangulo donde está el sprite + SDL_Rect getRect(); + + // Establece los valores de posición y tamaño del sprite + void setRect(SDL_Rect rect); + + // Deshace el último movimiento + void undoMove(); + + // Deshace el último movimiento en el eje X + void undoMoveX(); + + // Deshace el último movimiento en el eje Y + void undoMoveY(); + + // Pone a cero las velocidades de desplacamiento + void clearVel(); + + // Devuelve el incremento en el eje X en pixels + int getIncX(); }; #endif diff --git a/source/sprite.cpp b/source/sprite.cpp index a032c51..c354b59 100644 --- a/source/sprite.cpp +++ b/source/sprite.cpp @@ -1,165 +1,183 @@ #include "sprite.h" // Constructor -Sprite::Sprite() +Sprite::Sprite(int x, int y, int w, int h, LTexture *texture, SDL_Renderer *renderer) { - init(0, 0, 0, 0, nullptr, nullptr); + // Establece la posición X,Y del sprite + this->x = x; + this->y = y; + + // Establece el alto y el ancho del sprite + this->w = w; + this->h = h; + + // Establece el puntero al renderizador de la ventana + this->renderer = renderer; + + // Establece la textura donde están los gráficos para el sprite + this->texture = texture; + + // Establece el rectangulo de donde coger la imagen + spriteClip = {x, y, w, h}; + + // Inicializa variables + enabled = true; +} + +Sprite::Sprite(SDL_Rect rect, LTexture *texture, SDL_Renderer *renderer) +{ + // Establece la posición X,Y del sprite + x = rect.x; + y = rect.y; + + // Establece el alto y el ancho del sprite + w = rect.w; + h = rect.h; + + // Establece el puntero al renderizador de la ventana + this->renderer = renderer; + + // Establece la textura donde están los gráficos para el sprite + this->texture = texture; + + // Establece el rectangulo de donde coger la imagen + spriteClip = {x, y, w, h}; + + // Inicializa variables + enabled = true; } // Destructor Sprite::~Sprite() { - mTexture = nullptr; - mRenderer = nullptr; -} - -// Inicializador -void Sprite::init(int x, int y, int w, int h, LTexture *texture, SDL_Renderer *renderer) -{ - // Establece la posición X,Y del sprite - setPosX(x); - setPosY(y); - - // Establece el alto y el ancho del sprite - setWidth(w); - setHeight(h); - - // Establece el puntero al renderizador de la ventana - setRenderer(renderer); - - // Establece la textura donde están los gráficos para el sprite - setTexture(texture); - - // Establece el rectangulo de donde coger la imagen - setSpriteClip(0, 0, w, h); - - // Habilita el objeto - setEnabled(true); -} - -// Inicializador -void Sprite::init(SDL_Rect rect, LTexture *texture, SDL_Renderer *renderer) -{ - // Establece el alto y el ancho del sprite - mWidth = rect.w; - mHeight = rect.h; - - // Establece la posición X,Y del sprite - mPosX = rect.x; - mPosY = rect.y; - - // Establece el puntero al renderizador de la ventana - setRenderer(renderer); - - // Establece la textura donde están los gráficos para el sprite - setTexture(texture); - - // Establece el rectangulo de donde coger la imagen - setSpriteClip(rect); + texture = nullptr; + renderer = nullptr; } // Muestra el sprite por pantalla void Sprite::render() { - if (mEnabled) - mTexture->render(mRenderer, mPosX, mPosY, &mSpriteClip); + if (enabled) + { + texture->render(renderer, x, y, &spriteClip); + } } // Obten el valor de la variable int Sprite::getPosX() { - return mPosX; + return x; } // Obten el valor de la variable int Sprite::getPosY() { - return mPosY; + return y; } // Obten el valor de la variable int Sprite::getWidth() { - return mWidth; + return w; } // Obten el valor de la variable int Sprite::getHeight() { - return mHeight; + return h; +} + +// Establece la posición del objeto +void Sprite::setPos(SDL_Rect rect) +{ + x = rect.x; + y = rect.y; } // Establece el valor de la variable void Sprite::setPosX(int x) { - mPosX = x; + this->x = x; } // Establece el valor de la variable void Sprite::setPosY(int y) { - mPosY = y; + this->y = y; } // Establece el valor de la variable void Sprite::setWidth(int w) { - mWidth = w; + this->w = w; } // Establece el valor de la variable void Sprite::setHeight(int h) { - mHeight = h; + this->h = h; } // Obten el valor de la variable SDL_Rect Sprite::getSpriteClip() { - return mSpriteClip; + return spriteClip; } // Establece el valor de la variable void Sprite::setSpriteClip(SDL_Rect rect) { - mSpriteClip = rect; + spriteClip = rect; } // Establece el valor de la variable void Sprite::setSpriteClip(int x, int y, int w, int h) { - mSpriteClip.x = x; - mSpriteClip.y = y; - mSpriteClip.w = w; - mSpriteClip.h = h; + spriteClip = {x, y, w, h}; } // Obten el valor de la variable LTexture *Sprite::getTexture() { - return mTexture; + return texture; } // Establece el valor de la variable void Sprite::setTexture(LTexture *texture) { - mTexture = texture; + this->texture = texture; } // Establece el valor de la variable void Sprite::setRenderer(SDL_Renderer *renderer) { - mRenderer = renderer; + this->renderer = renderer; } // Establece el valor de la variable void Sprite::setEnabled(bool value) { - mEnabled = value; + enabled = value; } // Comprueba si el objeto está habilitado bool Sprite::isEnabled() { - return mEnabled; + return enabled; +} + +// Devuelve el rectangulo donde está el sprite +SDL_Rect Sprite::getRect() +{ + SDL_Rect rect = {x, y, w, h}; + return rect; +} + +// Establece los valores de posición y tamaño del sprite +void Sprite::setRect(SDL_Rect rect) +{ + x = rect.x; + y = rect.y; + w = rect.w; + h = rect.h; } \ No newline at end of file diff --git a/source/sprite.h b/source/sprite.h index bef20a5..96e1687 100644 --- a/source/sprite.h +++ b/source/sprite.h @@ -10,28 +10,25 @@ class Sprite { protected: - int mPosX; // Posición en el eje X donde dibujar el sprite - int mPosY; // Posición en el eje Y donde dibujar el sprite - Uint16 mWidth; // Ancho del sprite - Uint16 mHeight; // Alto del sprite + int x; // Posición en el eje X donde dibujar el sprite + int y; // Posición en el eje Y donde dibujar el sprite + int w; // Ancho del sprite + int h; // Alto del sprite - SDL_Renderer *mRenderer; // Puntero al renderizador de la ventana - LTexture *mTexture; // Textura donde estan todos los dibujos del sprite - SDL_Rect mSpriteClip; // Rectangulo de origen de la textura que se dibujará en pantalla + SDL_Renderer *renderer; // Puntero al renderizador de la ventana + LTexture *texture; // Textura donde estan todos los dibujos del sprite + SDL_Rect spriteClip; // Rectangulo de origen de la textura que se dibujará en pantalla - bool mEnabled; // Indica si el sprite esta habilitado + bool enabled; // Indica si el sprite esta habilitado public: // Constructor - Sprite(); + Sprite(int x = 0, int y = 0, int w = 0, int h = 0, LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr); + Sprite(SDL_Rect rect, LTexture *texture, SDL_Renderer *renderer); // Destructor ~Sprite(); - // Inicializador - void init(int x, int y, int w, int h, LTexture *texture, SDL_Renderer *renderer); - void init(SDL_Rect rect, LTexture *texture, SDL_Renderer *renderer); - // Muestra el sprite por pantalla void render(); @@ -47,6 +44,9 @@ public: // Obten el valor de la variable int getHeight(); + // Establece la posición del objeto + void setPos(SDL_Rect rect); + // Establece el valor de la variable void setPosX(int x); @@ -82,6 +82,12 @@ public: // Comprueba si el objeto está habilitado bool isEnabled(); + + // Devuelve el rectangulo donde está el sprite + SDL_Rect getRect(); + + // Establece los valores de posición y tamaño del sprite + void setRect(SDL_Rect rect); }; #endif