From 31cded15ccc1a64f7404243d140dacb6e588157c Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Sat, 1 Mar 2025 17:01:50 +0100 Subject: [PATCH] Arreglos en la estructura i format del codi --- source/cheevos.cpp | 2 +- source/cheevos.h | 8 +- source/credits.cpp | 52 +++-- source/credits.h | 3 - source/debug.cpp | 28 +-- source/debug.h | 4 - source/demo.cpp | 46 +---- source/demo.h | 8 +- source/ending.cpp | 4 +- source/ending2.cpp | 96 ++++----- source/enemy.cpp | 36 ++-- source/enemy.h | 2 +- source/game.cpp | 400 +++++++++++++++++--------------------- source/game.h | 55 +++--- source/game_over.cpp | 2 +- source/input.cpp | 23 --- source/input.h | 19 +- source/item.cpp | 14 +- source/item.h | 19 +- source/item_tracker.cpp | 2 +- source/item_tracker.h | 2 +- source/loading_screen.cpp | 151 ++++++-------- source/loading_screen.h | 3 - source/logo.cpp | 113 +++++------ source/options.cpp | 4 +- source/options.h | 2 +- source/player.cpp | 2 +- source/player.h | 7 +- source/room.cpp | 50 ++--- source/room.h | 9 +- source/room_tracker.cpp | 17 +- source/room_tracker.h | 8 +- source/scoreboard.cpp | 27 ++- source/scoreboard.h | 31 +-- source/title.cpp | 2 +- 35 files changed, 496 insertions(+), 755 deletions(-) diff --git a/source/cheevos.cpp b/source/cheevos.cpp index ca5d801..2e19896 100644 --- a/source/cheevos.cpp +++ b/source/cheevos.cpp @@ -187,7 +187,7 @@ void Cheevos::saveToFile() int Cheevos::unlocked() { int count = 0; - for (auto cheevo : cheevos_list_) + for (const auto &cheevo : cheevos_list_) { if (cheevo.completed) { diff --git a/source/cheevos.h b/source/cheevos.h index 5b4a676..7d5cc2a 100644 --- a/source/cheevos.h +++ b/source/cheevos.h @@ -1,7 +1,7 @@ #pragma once -#include // for string -#include // for vector +#include // for string +#include // for vector // Struct para los logros struct Achievement @@ -45,7 +45,7 @@ private: void saveToFile(); // Constructor - Cheevos(const std::string &file); + explicit Cheevos(const std::string &file); // Destructor ~Cheevos(); @@ -76,5 +76,5 @@ public: int unlocked(); // Devuelve el número total de logros - int count() { return cheevos_list_.size(); } + int size() { return cheevos_list_.size(); } }; diff --git a/source/credits.cpp b/source/credits.cpp index 7325b5e..609fa41 100644 --- a/source/credits.cpp +++ b/source/credits.cpp @@ -90,21 +90,24 @@ void Credits::checkInput() // Inicializa los textos void Credits::iniTexts() { +#ifndef GAME_CONSOLE std::string keys = ""; - if (options.keys == ControlScheme::CURSOR) + + switch (options.keys) { + case ControlScheme::CURSOR: keys = "CURSORS"; - } - else if (options.keys == ControlScheme::OPQA) - { + break; + case ControlScheme::OPQA: keys = "O,P AND Q"; - } - else - { + break; + case ControlScheme::WASD: keys = "A,D AND W"; + break; + default: + break; } -#ifndef GAME_CONSOLE texts_.clear(); texts_.push_back({"", stringToColor(options.video.palette, "white")}); texts_.push_back({"INSTRUCTIONS:", stringToColor(options.video.palette, "yellow")}); @@ -173,37 +176,37 @@ void Credits::fillTexture() // Rellena la textura de texto SDL_SetRenderTarget(renderer_, text_texture_); - Color c = stringToColor(options.video.palette, "black"); - SDL_SetRenderDrawColor(renderer_, c.r, c.g, c.b, 0xFF); + Color color = stringToColor(options.video.palette, "black"); + SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); SDL_RenderClear(renderer_); // Escribe el texto en la textura - const int size = text_->getCharacterSize(); - int i = 0; + const int SIZE = text_->getCharacterSize(); + int pos_y = 0; - for (auto t : texts_) + for (const auto &t : texts_) { - text_->writeDX(TEXT_CENTER | TEXT_COLOR, PLAY_AREA_CENTER_X, i * size, t.label, 1, t.color); - i++; + text_->writeDX(TEXT_CENTER | TEXT_COLOR, PLAY_AREA_CENTER_X, pos_y * SIZE, t.label, 1, t.color); + pos_y++; } // Escribe el corazón - const int textLenght = text_->lenght(texts_[22].label, 1) - text_->lenght(" ", 1); // Se resta el ultimo caracter que es un espacio - const int posX = ((PLAY_AREA_WIDTH - textLenght) / 2) + textLenght; - text_->writeColored(posX, 176, "}", stringToColor(options.video.palette, "bright_red")); + const int TEXT_LENGHT = text_->lenght(texts_[22].label, 1) - text_->lenght(" ", 1); // Se resta el ultimo caracter que es un espacio + const int POS_X = ((PLAY_AREA_WIDTH - TEXT_LENGHT) / 2) + TEXT_LENGHT; + text_->writeColored(POS_X, 176, "}", stringToColor(options.video.palette, "bright_red")); // Recoloca el sprite del brillo - sprite_->setPosX(posX + 2); + sprite_->setPosX(POS_X + 2); SDL_SetRenderTarget(renderer_, nullptr); // Rellena la textura que cubre el texto con color transparente SDL_SetRenderTarget(renderer_, cover_texture_); - SDL_SetRenderDrawColor(renderer_, c.r, c.g, c.b, 0x00); + SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0x00); SDL_RenderClear(renderer_); // Los primeros 8 pixels crea una malla - SDL_SetRenderDrawColor(renderer_, c.r, c.g, c.b, 0xFF); + SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); for (int i = 0; i < 256; i += 2) { SDL_RenderDrawPoint(renderer_, i, 0); @@ -313,11 +316,4 @@ void Credits::run() checkEvents(); render(); } -} - -// Cambia la paleta -void Credits::switchPalette() -{ - options.video.palette = options.video.palette == Palette::ZXSPECTRUM ? Palette::ZXARNE : Palette::ZXSPECTRUM; - fillTexture(); } \ No newline at end of file diff --git a/source/credits.h b/source/credits.h index e1d9b34..3d944f3 100644 --- a/source/credits.h +++ b/source/credits.h @@ -61,9 +61,6 @@ private: // Escribe el texto en la textura void fillTexture(); - // Cambia la paleta - void switchPalette(); - public: // Constructor Credits(); diff --git a/source/debug.cpp b/source/debug.cpp index 18fd618..c954335 100644 --- a/source/debug.cpp +++ b/source/debug.cpp @@ -1,9 +1,9 @@ #include "debug.h" -#include // for max -#include "resource.h" // for Resource -#include "screen.h" // for Screen -#include "text.h" // for Text -#include "utils.h" // for Color +#include // for max +#include "resource.h" // for Resource +#include "screen.h" // for Screen +#include "text.h" // for Text +#include "utils.h" // for Color // [SINGLETON] Debug *Debug::debug_ = nullptr; @@ -28,19 +28,9 @@ Debug *Debug::get() // Constructor Debug::Debug() - // Copia la dirección de los objetos : screen_(Screen::get()), - renderer_(Screen::get()->getRenderer()) -{ - // Reserva memoria para los punteros - texture_ = Resource::get()->getTexture("debug.png"); - text_ = Resource::get()->getText("debug"); -} - -// Actualiza las variables -void Debug::update() -{ -} + renderer_(Screen::get()->getRenderer()), + text_(Resource::get()->getText("debug")) {} // Dibuja en pantalla void Debug::render() @@ -48,7 +38,7 @@ void Debug::render() int y = y_; int w = 0; - for (auto s : slot_) + for (const auto &s : slot_) { text_->write(x_, y, s); w = (std::max(w, (int)s.length())); @@ -61,7 +51,7 @@ void Debug::render() } y = 0; - for (auto l : log_) + for (const auto &l : log_) { text_->writeColored(x_ + 10, y, l, Color(255, 255, 255)); y += text_->getCharacterSize() + 1; diff --git a/source/debug.h b/source/debug.h index 62fd5e6..f90451f 100644 --- a/source/debug.h +++ b/source/debug.h @@ -20,7 +20,6 @@ private: Screen *screen_; // Objeto encargado de dibujar en pantalla SDL_Renderer *renderer_; // El renderizador de la ventana std::shared_ptr text_; // Objeto encargado de escribir texto en pantalla - std::shared_ptr texture_; // Textura para el texto // Variables std::vector slot_; // Vector con los textos a escribir @@ -45,9 +44,6 @@ public: // [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él static Debug *get(); - // Actualiza las variables - void update(); - // Dibuja en pantalla void render(); diff --git a/source/demo.cpp b/source/demo.cpp index e0fc6b6..bf31aae 100644 --- a/source/demo.cpp +++ b/source/demo.cpp @@ -24,10 +24,10 @@ Demo::Demo() resource_(Resource::get()), asset_(Asset::get()), input_(Input::get()), - debug_(Debug::get()) + debug_(Debug::get()), + board_(std::make_shared()) { // Inicia algunas variables - board_ = std::make_shared(); board_->ini_clock = SDL_GetTicks(); rooms_.push_back("04.room"); rooms_.push_back("54.room"); @@ -44,7 +44,7 @@ Demo::Demo() // Crea los objetos ItemTracker::init(); scoreboard_ = std::make_shared(board_); - room_ = std::make_shared(resource_->getRoom(current_room_), board_); + room_ = std::make_shared(current_room_, board_); text_ = resource_->getText("smb2"); // Inicializa el resto de variables @@ -145,49 +145,17 @@ void Demo::renderRoomName() text_->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, 16 * 8 + 4, room_->getName(), 1, room_->getBGColor()); } -// Recarga todas las texturas -void Demo::reLoadTextures() -{ - if (options.console) - { - std::cout << "** RELOAD REQUESTED" << std::endl; - } - room_->reLoadTexture(); - scoreboard_->reLoadTexture(); - text_->reLoadTexture(); -} - -// Cambia la paleta -void Demo::switchPalette() -{ - // Modifica la variable - if (options.video.palette == Palette::ZXSPECTRUM) - { - options.video.palette = Palette::ZXARNE; - } - else - { - options.video.palette = Palette::ZXSPECTRUM; - } - - room_->reLoadPalette(); - scoreboard_->reLoadPalette(); - - // Pone el color del marcador en función del color del borde de la habitación - setScoreBoardColor(); -} - // Cambia de habitación -bool Demo::changeRoom(std::string file) +bool Demo::changeRoom(const std::string &room_path) { // En las habitaciones los limites tienen la cadena del fichero o un 0 en caso de no limitar con nada - if (file != "0") + if (room_path != "0") { // Verifica que exista el fichero que se va a cargar - if (asset_->get(file) != "") + if (asset_->get(room_path) != "") { // Crea un objeto habitación a partir del fichero - room_ = std::make_shared(resource_->getRoom(file), board_); + room_ = std::make_shared(room_path, board_); // Pone el color del marcador en función del color del borde de la habitación setScoreBoardColor(); diff --git a/source/demo.h b/source/demo.h index b30a211..b198665 100644 --- a/source/demo.h +++ b/source/demo.h @@ -53,14 +53,8 @@ private: // Escribe el nombre de la pantalla void renderRoomName(); - // Recarga todas las texturas - void reLoadTextures(); - - // Cambia la paleta - void switchPalette(); - // Cambia de habitación - bool changeRoom(std::string file); + bool changeRoom(const std::string &file); // Comprueba si se ha de cambiar de habitación void checkRoomChange(); diff --git a/source/ending.cpp b/source/ending.cpp index 48bbafd..48cb2d9 100644 --- a/source/ending.cpp +++ b/source/ending.cpp @@ -188,7 +188,7 @@ void Ending::iniTexts() // Crea los sprites sprite_texts_.clear(); - for (auto t : texts) + for (const auto &t : texts) { EndingTexture st; const int width = text_->lenght(t.caption, 1) + 2 + 2; @@ -275,7 +275,7 @@ void Ending::iniPics() // Crea los sprites sprite_pics_.clear(); - for (auto p : pics) + for (const auto &p : pics) { EndingTexture sp; diff --git a/source/ending2.cpp b/source/ending2.cpp index 69a440b..18f99b5 100644 --- a/source/ending2.cpp +++ b/source/ending2.cpp @@ -25,12 +25,10 @@ Ending2::Ending2() renderer_(Screen::get()->getRenderer()), resource_(Resource::get()), asset_(Asset::get()), - input_(Input::get()) + input_(Input::get()), + text_(resource_->getText("smb2")), + music_(resource_->getMusic("ending2.ogg")) { - // Reserva memoria para los punteros a objetos - text_ = resource_->getText("smb2"); - music_ = resource_->getMusic("ending2.ogg"); - // Inicializa variables counter_enabled_ = false; pre_counter_ = 0; @@ -45,7 +43,7 @@ Ending2::Ending2() // Inicializa el vector de colores const std::vector color_list = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"}; - for (auto color : color_list) + for (const auto &color : color_list) { colors_.push_back(stringToColor(options.video.palette, color)); } @@ -124,49 +122,25 @@ void Ending2::render() // Dibuja los sprites con el texto del final renderTexts(); - const std::string txt = std::to_string(post_counter_); - // text->write(0, 192 - 8, txt); - - // Dibuja la cuadricula - /*{ - SDL_SetRenderDrawColor(renderer, 128, 128, 128, 255); - const int sw = maxSpriteWidth + 6; - const int sh = maxSpriteHeight + 6; - for (int i = 0; i < 256; i += sw) - { - SDL_RenderDrawLine(renderer, i, 0, i, 192); - } - for (int i = 0; i < 192; i += sh) - { - SDL_RenderDrawLine(renderer, 0, i, 255, i); - } - }*/ - + // Dibuja una trama arriba y abajo + SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 0xFF); + for (int i = 0; i < 256; i += 2) { - // Dibuja una trama arriba y abajo - SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 0xFF); - for (int i = 0; i < 256; i += 2) - { - SDL_RenderDrawPoint(renderer_, i + 0, 0); - SDL_RenderDrawPoint(renderer_, i + 1, 1); - SDL_RenderDrawPoint(renderer_, i + 0, 2); - SDL_RenderDrawPoint(renderer_, i + 1, 3); + SDL_RenderDrawPoint(renderer_, i + 0, 0); + SDL_RenderDrawPoint(renderer_, i + 1, 1); + SDL_RenderDrawPoint(renderer_, i + 0, 2); + SDL_RenderDrawPoint(renderer_, i + 1, 3); - SDL_RenderDrawPoint(renderer_, i, 4); - SDL_RenderDrawPoint(renderer_, i, 6); + SDL_RenderDrawPoint(renderer_, i, 4); + SDL_RenderDrawPoint(renderer_, i, 6); - SDL_RenderDrawPoint(renderer_, i + 0, 191); - SDL_RenderDrawPoint(renderer_, i + 1, 190); - SDL_RenderDrawPoint(renderer_, i + 0, 189); - SDL_RenderDrawPoint(renderer_, i + 1, 188); + SDL_RenderDrawPoint(renderer_, i + 0, 191); + SDL_RenderDrawPoint(renderer_, i + 1, 190); + SDL_RenderDrawPoint(renderer_, i + 0, 189); + SDL_RenderDrawPoint(renderer_, i + 1, 188); - SDL_RenderDrawPoint(renderer_, i, 187); - SDL_RenderDrawPoint(renderer_, i, 185); - } - // SDL_RenderDrawLine(renderer, 0, 1, 255, 1); - // SDL_RenderDrawLine(renderer, 0, 3, 255, 3); - // SDL_RenderDrawLine(renderer, 0, 188, 255, 188); - // SDL_RenderDrawLine(renderer, 0, 190, 255, 190); + SDL_RenderDrawPoint(renderer_, i, 187); + SDL_RenderDrawPoint(renderer_, i, 185); } // Vuelca el contenido del renderizador en pantalla @@ -316,7 +290,7 @@ void Ending2::loadSprites() sprite_max_height_ = 0; // Carga los sprites - for (auto sl : sprite_list_) + for (const auto &sl : sprite_list_) { sprites_.emplace_back(std::make_shared(resource_->getTexture(sl + ".png"), resource_->getAnimations(sl + ".ani"))); sprite_max_width_ = std::max(sprites_.back()->getWidth(), sprite_max_width_); @@ -414,23 +388,23 @@ void Ending2::placeSprites() { for (int i = 0; i < (int)sprites_.size(); ++i) { - const int x = i % 2 == 0 ? FIRST_COL_ : SECOND_COL_; - const int y = (i / 1) * (sprite_max_height_ + dist_sprite_text_ + text_->getCharacterSize() + dist_sprite_sprite_) + GAMECANVAS_HEIGHT + 40; - const int w = sprites_[i]->getWidth(); - const int h = sprites_[i]->getHeight(); - const int dx = -(w / 2); - const int dy = i % 1 == 0 ? sprite_max_height_ - h : (int)(sprite_max_height_ * 1.5f) - h; + const int X = i % 2 == 0 ? FIRST_COL_ : SECOND_COL_; + const int Y = (i / 1) * (sprite_max_height_ + dist_sprite_text_ + text_->getCharacterSize() + dist_sprite_sprite_) + GAMECANVAS_HEIGHT + 40; + const int W = sprites_.at(i)->getWidth(); + const int H = sprites_.at(i)->getHeight(); + const int DX = -(W / 2); + const int DY = sprite_max_height_ - H; - sprites_[i]->setPosition({x + dx, y + dy, w, h}); - sprites_[i]->setVelY(sprite_desp_speed_); + sprites_.at(i)->setPosition({X + DX, Y + DY, W, H}); + sprites_.at(i)->setVelY(sprite_desp_speed_); } // Recoloca el último sprite, que es el del jugador - const int w = sprites_.back()->getWidth(); - const int x = GAMECANVAS_CENTER_X - (w / 2); - const int y = sprites_.back()->getPosY() + sprite_max_height_ * 2; - sprites_.back()->setPosX(x); - sprites_.back()->setPosY(y); + const int W = sprites_.back()->getWidth(); + const int X = GAMECANVAS_CENTER_X - (W / 2); + const int Y = sprites_.back()->getPosY() + sprite_max_height_ * 2; + sprites_.back()->setPosX(X); + sprites_.back()->setPosY(Y); sprites_.back()->setCurrentAnimation("walk"); } @@ -448,7 +422,7 @@ void Ending2::createSpriteTexts() const int h = text_->getCharacterSize(); const int x = i % 2 == 0 ? FIRST_COL_ : SECOND_COL_; const int dx = -(w / 2); - const int y = sprites_[i]->getPosY() + sprites_[i]->getHeight() + dist_sprite_text_; + const int y = sprites_.at(i)->getPosY() + sprites_.at(i)->getHeight() + dist_sprite_text_; // Cambia la posición del último sprite const int X = (i == (int)sprite_list_.size() - 1) ? GAMECANVAS_CENTER_X - (w / 2) : x + dx; @@ -535,7 +509,7 @@ void Ending2::updateFinalFade() const float step = std::min(std::max(post_counter_, 500) - 500, 40) / 40.0f; const int index = (colors_.size() - 1) * step; - for (auto t : texts_) + for (const auto &t : texts_) { t->getTexture()->setColor(colors_[index].r, colors_[index].g, colors_[index].b); } diff --git a/source/enemy.cpp b/source/enemy.cpp index 0eead01..27a0c8b 100644 --- a/source/enemy.cpp +++ b/source/enemy.cpp @@ -7,17 +7,17 @@ #include "texture.h" // for Texture // Constructor -Enemy::Enemy(EnemyData enemy) +Enemy::Enemy(const EnemyData enemy) + : sprite_(std::make_shared(Resource::get()->getTexture(enemy.texture_path), Resource::get()->getAnimations(enemy.animation_path))), + color_string_(enemy.color), + x1_(enemy.x1), + x2_(enemy.x2), + y1_(enemy.y1), + y2_(enemy.y2), + should_flip_(enemy.flip), + should_mirror_(enemy.mirror) { - // Crea objetos - sprite_ = std::make_shared(Resource::get()->getTexture(enemy.texture_path), Resource::get()->getAnimations(enemy.animation_path)); - // Obten el resto de valores - x1_ = enemy.x1; - x2_ = enemy.x2; - y1_ = enemy.y1; - y2_ = enemy.y2; - color_string_ = enemy.color; setPalette(options.video.palette); sprite_->setPosX(enemy.x); sprite_->setPosY(enemy.y); @@ -25,24 +25,16 @@ Enemy::Enemy(EnemyData enemy) sprite_->setVelY(enemy.vy); sprite_->setWidth(enemy.w); sprite_->setHeight(enemy.h); - should_flip_ = enemy.flip; - should_mirror_ = enemy.mirror; - const SDL_RendererFlip flip = (should_flip_ && enemy.vx < 0.0f) ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; - const SDL_RendererFlip mirror = should_mirror_ ? SDL_FLIP_VERTICAL : SDL_FLIP_NONE; - sprite_->setFlip(static_cast(flip | mirror)); + const SDL_RendererFlip FLIP = (should_flip_ && enemy.vx < 0.0f) ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; + const SDL_RendererFlip MIRROR = should_mirror_ ? SDL_FLIP_VERTICAL : SDL_FLIP_NONE; + sprite_->setFlip(static_cast(FLIP | MIRROR)); collider_ = getRect(); // Coloca un frame al azar o el designado - if (enemy.frame == -1) - { - sprite_->setCurrentAnimationFrame(rand() % sprite_->getCurrentAnimationSize()); - } - else - { - sprite_->setCurrentAnimationFrame(enemy.frame); - } + sprite_->setCurrentAnimationFrame( + (enemy.frame == -1) ? (rand() % sprite_->getCurrentAnimationSize()) : enemy.frame); } // Pinta el enemigo en pantalla diff --git a/source/enemy.h b/source/enemy.h index 1a71808..156a210 100644 --- a/source/enemy.h +++ b/source/enemy.h @@ -49,7 +49,7 @@ private: public: // Constructor - Enemy(EnemyData enemy); + explicit Enemy(const EnemyData enemy); // Destructor ~Enemy() = default; diff --git a/source/game.cpp b/source/game.cpp index 6f795cf..a3729ad 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -28,83 +28,30 @@ // Constructor Game::Game() - : screen_(Screen::get()), - renderer_(Screen::get()->getRenderer()), - asset_(Asset::get()), - input_(Input::get()), - resource_(Resource::get()), - debug_(Debug::get()), - cheevos_(Cheevos::get()) + : board_(std::make_shared(0, 9, 0, true, Color(0, 0, 0), SDL_GetTicks(), options.cheats.jail_is_open == Cheat::CheatState::ENABLED)), + scoreboard_(std::make_shared(board_)), + room_tracker_(std::make_shared()), + stats_(std::make_shared(Asset::get()->get("stats.csv"), Asset::get()->get("stats_buffer.csv"))), + // test_surface_(std::make_shared(Screen::get()->getSurface(), "test.gif")), + spawn_point_(PlayerSpawn(25 * BLOCK, 13 * BLOCK, 0, 0, 0, PlayerState::STANDING, SDL_FLIP_HORIZONTAL)) { - // Inicia algunas variables - // test_surface_ = std::make_shared(Screen::get()->getSurface(), "test.gif"); - board_ = std::make_shared(); - board_->ini_clock = SDL_GetTicks(); #ifdef DEBUG current_room_ = "03.room"; - constexpr int X = 25; - constexpr int Y = 13; - spawn_point_ = PlayerSpawn(X * 8, Y * 8, 0, 0, 0, PlayerState::STANDING, SDL_FLIP_HORIZONTAL); + spawn_point_ = PlayerSpawn(25 * BLOC, 13 * BLOCK, 0, 0, 0, PlayerState::STANDING, SDL_FLIP_HORIZONTAL); debug_->setEnabled(false); -#else - current_room_ = "03.room"; - constexpr int X = 25; - constexpr int Y = 13; - spawn_point_ = PlayerSpawn(X * 8, Y * 8, 0, 0, 0, PlayerState::STANDING, SDL_FLIP_HORIZONTAL); #endif - // Crea los objetos + // Crea objetos e inicializa variables ItemTracker::init(); - scoreboard_ = std::make_shared(board_); - room_tracker_ = std::make_shared(); - room_ = std::make_shared(resource_->getRoom(current_room_), board_); - std::string player_texture = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.png" : "player.png"; - std::string player_animations = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.ani" : "player.ani"; - const PlayerData player(spawn_point_, player_texture, player_animations, room_); - player_ = std::make_shared(player); - text_ = resource_->getText("smb2"); - music_ = resource_->getMusic("game.ogg"); - death_sound_ = resource_->getSound("death.wav"); - stats_ = std::make_shared(asset_->get("stats.csv"), asset_->get("stats_buffer.csv")); - - // Crea la textura para poner el nombre de la habitación - room_name_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, text_->getCharacterSize() * 2); - if (room_name_texture_ == nullptr) - { - if (options.console) - { - std::cout << "Error: roomNameTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; - } - } - - // Establece el blend mode de la textura - SDL_SetTextureBlendMode(room_name_texture_, SDL_BLENDMODE_BLEND); - - // Establece el destino de la textura - room_name_rect_ = {0, PLAY_AREA_HEIGHT, GAMECANVAS_WIDTH, text_->getCharacterSize() * 2}; - - // Pone el nombre de la habitación en la textura - fillRoomNameTexture(); - - // Inicializa el resto de variables - ticks_ = 0; - board_->lives = 9; -#ifdef DEBUG - board_->lives = 9; -#endif - board_->items = 0; - board_->rooms = 1; - board_->music = true; - board_->jail_is_open = options.cheats.jail_is_open == Cheat::CheatState::ENABLED; - setScoreBoardColor(); - room_tracker_->addRoom(current_room_); - paused_ = false; - black_screen_ = false; - black_screen_counter_ = 0; - total_items_ = getTotalItems(); + room_ = std::make_shared(current_room_, board_); + initPlayer(spawn_point_, room_); initStats(); - stats_->addVisit(room_->getName()); - cheevos_->enable(!options.cheats.enabled()); // Deshabilita los logros si hay trucos activados + total_items_ = getTotalItems(); + + createRoomNameTexture(); + changeRoom(current_room_); + + Cheevos::get()->enable(!options.cheats.enabled()); // Deshabilita los logros si hay trucos activados options.section.section = Section::GAME; options.section.subsection = Subsection::NONE; @@ -123,58 +70,8 @@ void Game::checkEvents() while (SDL_PollEvent(&event)) { globalEvents::check(event); - #ifdef DEBUG - if (event.type == SDL_KEYDOWN && event.key.repeat == 0) - { - switch (event.key.keysym.scancode) - { - case SDL_SCANCODE_G: - debug_->switchEnabled(); - options.cheats.invincible = static_cast(debug_->getEnabled()); - board_->music = !debug_->getEnabled(); - board_->music ? JA_ResumeMusic() : JA_PauseMusic(); - break; - - case SDL_SCANCODE_R: - resource_->reload(); - break; - - case SDL_SCANCODE_W: - goToRoom(BORDER_TOP); - break; - - case SDL_SCANCODE_A: - goToRoom(BORDER_LEFT); - break; - - case SDL_SCANCODE_S: - goToRoom(BORDER_BOTTOM); - break; - - case SDL_SCANCODE_D: - goToRoom(BORDER_RIGHT); - break; - - case SDL_SCANCODE_F6: - Notifier::get()->show({"ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS"}, NotificationText::LEFT, 2, false, "F6"); - break; - - case SDL_SCANCODE_F7: - Notifier::get()->show({"ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS"}, NotificationText::LEFT, 3, false, "F7"); - break; - - case SDL_SCANCODE_F8: - Notifier::get()->show({"JAILDESIGNER", "IS LOGGED IN"}, NotificationText::LEFT, 4, false); - break; - - case SDL_SCANCODE_F9: - Notifier::get()->show({"JAILDESIGNER", "IS LOGGED IN"}, NotificationText::LEFT, 5, false); - break; - default: - break; - } - } + checkDebugEvents(event); #endif } } @@ -182,16 +79,16 @@ void Game::checkEvents() // Comprueba el teclado void Game::checkInput() { - if (input_->checkInput(InputAction::TOGGLE_MUSIC, REPEAT_FALSE)) + if (Input::get()->checkInput(InputAction::TOGGLE_MUSIC, REPEAT_FALSE)) { board_->music = !board_->music; board_->music ? JA_ResumeMusic() : JA_PauseMusic(); Notifier::get()->show({"MUSIC " + std::string(board_->music ? "ENABLED" : "DISABLED")}, NotificationText::CENTER); } - else if (input_->checkInput(InputAction::PAUSE, REPEAT_FALSE)) + else if (Input::get()->checkInput(InputAction::PAUSE, REPEAT_FALSE)) { - switchPause(); + togglePause(); Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")}, NotificationText::CENTER); } @@ -201,7 +98,7 @@ void Game::checkInput() // Bucle para el juego void Game::run() { - JA_PlayMusic(music_); + JA_PlayMusic(Resource::get()->getMusic("game.ogg")); if (!board_->music) { JA_PauseMusic(); @@ -245,11 +142,10 @@ void Game::update() checkRestoringJail(); checkSomeCheevos(); scoreboard_->update(); - input_->update(); updateBlackScreen(); - screen_->update(); + Screen::get()->update(); #ifdef DEBUG updateDebugInfo(); @@ -261,7 +157,7 @@ void Game::update() void Game::render() { // Prepara para dibujar el frame - screen_->start(); + Screen::get()->start(); // test_surface_->render(0, 0, 10, 10, 64, 64); // Dibuja los elementos del juego en orden @@ -279,7 +175,7 @@ void Game::render() #endif // Actualiza la pantalla - screen_->render(); + Screen::get()->render(); } #ifdef DEBUG @@ -301,47 +197,102 @@ void Game::renderDebugInfo() // Borra el marcador SDL_Rect rect = {0, 18 * BLOCK, PLAY_AREA_WIDTH, GAMECANVAS_HEIGHT - PLAY_AREA_HEIGHT}; - SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 255); - SDL_RenderFillRect(renderer_, &rect); + SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 0, 255); + SDL_RenderFillRect(Screen::get()->getRenderer(), &rect); // Pinta la rejilla - SDL_SetRenderDrawColor(renderer_, 255, 255, 255, 32); + SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 255, 255, 255, 32); for (int i = 0; i < PLAY_AREA_BOTTOM; i += 8) { // Lineas horizontales - SDL_RenderDrawLine(renderer_, 0, i, PLAY_AREA_RIGHT, i); + SDL_RenderDrawLine(Screen::get()->getRenderer(), 0, i, PLAY_AREA_RIGHT, i); } for (int i = 0; i < PLAY_AREA_RIGHT; i += 8) { // Lineas verticales - SDL_RenderDrawLine(renderer_, i, 0, i, PLAY_AREA_BOTTOM - 1); + SDL_RenderDrawLine(Screen::get()->getRenderer(), i, 0, i, PLAY_AREA_BOTTOM - 1); } // Pinta el texto debug_->setPos({1, 18 * 8}); debug_->render(); } + +// Comprueba los eventos +void Game::checkDebugEvents(const SDL_Event &event) +{ + if (event.type == SDL_KEYDOWN && event.key.repeat == 0) + { + switch (event.key.keysym.scancode) + { + case SDL_SCANCODE_G: + Debug::get()->switchEnabled(); + options.cheats.invincible = static_cast(Debug::get()->getEnabled()); + board_->music = !Debug::get()->getEnabled(); + board_->music ? JA_ResumeMusic() : JA_PauseMusic(); + break; + + case SDL_SCANCODE_R: + Resource::get()->reload(); + break; + + case SDL_SCANCODE_W: + changeRoom(room_->getRoom(BORDER_TOP)); + break; + + case SDL_SCANCODE_A: + changeRoom(room_->getRoom(BORDER_LEFT)); + break; + + case SDL_SCANCODE_S: + changeRoom(room_->getRoom(BORDER_BOTTOM)); + break; + + case SDL_SCANCODE_D: + changeRoom(room_->getRoom(BORDER_RIGHT)); + break; + + case SDL_SCANCODE_F6: + Notifier::get()->show({"ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS"}, NotificationText::LEFT, 2, false, "F6"); + break; + + case SDL_SCANCODE_F7: + Notifier::get()->show({"ACHIEVEMENT UNLOCKED!", "I LIKE MY MULTICOLOURED FRIENDS"}, NotificationText::LEFT, 3, false, "F7"); + break; + + case SDL_SCANCODE_F8: + Notifier::get()->show({"JAILDESIGNER", "IS LOGGED IN"}, NotificationText::LEFT, 4, false); + break; + + case SDL_SCANCODE_F9: + Notifier::get()->show({"JAILDESIGNER", "IS LOGGED IN"}, NotificationText::LEFT, 5, false); + break; + default: + break; + } + } +} #endif // Escribe el nombre de la pantalla void Game::renderRoomName() { // Dibuja la textura con el nombre de la habitación - SDL_RenderCopy(renderer_, room_name_texture_, nullptr, &room_name_rect_); + SDL_RenderCopy(Screen::get()->getRenderer(), room_name_texture_, nullptr, &room_name_rect_); } // Cambia de habitación -bool Game::changeRoom(std::string file) +bool Game::changeRoom(const std::string &room_path) { // En las habitaciones los limites tienen la cadena del fichero o un 0 en caso de no limitar con nada - if (file == "0") + if (room_path == "0") { return false; } // Verifica que exista el fichero que se va a cargar - if (asset_->get(file) != "") + if (Asset::get()->get(room_path) != "") { // Crea un objeto habitación nuevo a partir del fichero - room_ = std::make_shared(resource_->getRoom(file), board_); + room_ = std::make_shared(room_path, board_); // Pone el nombre de la habitación en la textura fillRoomNameTexture(); @@ -349,7 +300,7 @@ bool Game::changeRoom(std::string file) // Pone el color del marcador en función del color del borde de la habitación setScoreBoardColor(); - if (room_tracker_->addRoom(file)) + if (room_tracker_->addRoom(room_path)) { // Incrementa el contador de habitaciones visitadas board_->rooms++; @@ -362,6 +313,9 @@ bool Game::changeRoom(std::string file) // Pasa la nueva habitación al jugador player_->setRoom(room_); + // Cambia la habitación actual + current_room_ = room_path; + return true; } @@ -377,7 +331,6 @@ void Game::checkPlayerOnBorder() if (changeRoom(roomName)) { player_->switchBorders(); - current_room_ = roomName; spawn_point_ = player_->getSpawnParams(); } } @@ -436,37 +389,21 @@ void Game::killPlayer() stats_->addDeath(room_->getName()); // Invalida el logro de pasarse el juego sin morir - cheevos_->invalidate(11); + Cheevos::get()->invalidate(11); // Sonido - JA_PlaySound(death_sound_); + JA_PlaySound(Resource::get()->getSound("death.wav")); // Pone la pantalla en negro un tiempo setBlackScreen(); // Crea la nueva habitación y el nuevo jugador - room_ = std::make_shared(resource_->getRoom(current_room_), board_); - std::string player_texture = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.png" : "player.png"; - std::string player_animations = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.ani" : "player.ani"; - const PlayerData player(spawn_point_, player_texture, player_animations, room_); - player_ = std::make_shared(player); + room_ = std::make_shared(current_room_, board_); + initPlayer(spawn_point_, room_); // Pone los objetos en pausa mientras esta la habitación en negro - room_->pause(); - player_->pause(); -} - -// Recarga todas las texturas -void Game::reLoadTextures() -{ - if (options.console) - { - std::cout << "** RELOAD REQUESTED" << std::endl; - } - player_->reLoadTexture(); - room_->reLoadTexture(); - scoreboard_->reLoadTexture(); - text_->reLoadTexture(); + room_->setPaused(true); + player_->setPaused(true); } // Establece la pantalla en negro @@ -486,9 +423,9 @@ void Game::updateBlackScreen() black_screen_ = false; black_screen_counter_ = 0; - player_->resume(); - room_->resume(); - screen_->setBorderColor(room_->getBorderColor()); + player_->setPaused(false); + room_->setPaused(false); + Screen::get()->setBorderColor(room_->getBorderColor()); } } } @@ -498,8 +435,8 @@ void Game::renderBlackScreen() { if (black_screen_) { - screen_->clean(); - screen_->setBorderColor(stringToColor(options.video.palette, "black")); + Screen::get()->clean(); + Screen::get()->setBorderColor(stringToColor(options.video.palette, "black")); } } @@ -544,9 +481,9 @@ bool Game::checkEndGame() int Game::getTotalItems() { int items = 0; - auto rooms = resource_->getRooms(); + auto rooms = Resource::get()->getRooms(); - for (auto room : rooms) + for (const auto &room : rooms) { items += room.room->items.size(); } @@ -554,33 +491,14 @@ int Game::getTotalItems() return items; } -// Va a la habitación designada -void Game::goToRoom(int border) -{ - const std::string roomName = room_->getRoom(border); - if (changeRoom(roomName)) - { - current_room_ = roomName; - } -} - // Pone el juego en pausa -void Game::switchPause() +void Game::togglePause() { - if (paused_) - { - player_->resume(); - room_->resume(); - scoreboard_->resume(); - paused_ = false; - } - else - { - player_->pause(); - room_->pause(); - scoreboard_->pause(); - paused_ = true; - } + paused_ = !paused_; + + player_->setPaused(paused_); + room_->setPaused(paused_); + scoreboard_->setPaused(paused_); } // Da vidas al jugador cuando está en la Jail @@ -603,13 +521,13 @@ void Game::checkRestoringJail() { counter = 0; board_->lives++; - JA_PlaySound(death_sound_); + JA_PlaySound(Resource::get()->getSound("death.wav")); // Invalida el logro de completar el juego sin entrar a la jail const bool haveTheItems = board_->items >= int(total_items_ * 0.9f); if (!haveTheItems) { - cheevos_->invalidate(9); + Cheevos::get()->invalidate(9); } } } @@ -617,9 +535,9 @@ void Game::checkRestoringJail() // Inicializa el diccionario de las estadísticas void Game::initStats() { - auto rooms = resource_->getRooms(); + auto rooms = Resource::get()->getRooms(); - for (auto room : rooms) + for (const auto &room : rooms) { stats_->addDictionary(room.room->number, room.room->name); } @@ -631,86 +549,120 @@ void Game::initStats() void Game::fillRoomNameTexture() { // Pone la textura como destino de renderizado - SDL_SetRenderTarget(renderer_, room_name_texture_); + SDL_SetRenderTarget(Screen::get()->getRenderer(), room_name_texture_); // Rellena la textura de color const Color color = stringToColor(options.video.palette, "white"); - SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); - SDL_RenderClear(renderer_); + SDL_SetRenderDrawColor(Screen::get()->getRenderer(), color.r, color.g, color.b, 0xFF); + SDL_RenderClear(Screen::get()->getRenderer()); // Escribe el texto en la textura - text_->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, text_->getCharacterSize() / 2, room_->getName(), 1, room_->getBGColor()); + auto text = Resource::get()->getText("smb2"); + text->writeDX(TEXT_CENTER | TEXT_COLOR, GAMECANVAS_CENTER_X, text->getCharacterSize() / 2, room_->getName(), 1, room_->getBGColor()); // Deja el renderizador por defecto - SDL_SetRenderTarget(renderer_, nullptr); + SDL_SetRenderTarget(Screen::get()->getRenderer(), nullptr); } // Comprueba algunos logros void Game::checkSomeCheevos() { + auto cheevos = Cheevos::get(); + // Logros sobre la cantidad de items if (board_->items == total_items_) { - cheevos_->unlock(4); - cheevos_->unlock(3); - cheevos_->unlock(2); - cheevos_->unlock(1); + cheevos->unlock(4); + cheevos->unlock(3); + cheevos->unlock(2); + cheevos->unlock(1); } else if (board_->items >= total_items_ * 0.75f) { - cheevos_->unlock(3); - cheevos_->unlock(2); - cheevos_->unlock(1); + cheevos->unlock(3); + cheevos->unlock(2); + cheevos->unlock(1); } else if (board_->items >= total_items_ * 0.5f) { - cheevos_->unlock(2); - cheevos_->unlock(1); + cheevos->unlock(2); + cheevos->unlock(1); } else if (board_->items >= total_items_ * 0.25f) { - cheevos_->unlock(1); + cheevos->unlock(1); } // Logros sobre las habitaciones visitadas if (board_->rooms >= 60) { - cheevos_->unlock(7); - cheevos_->unlock(6); - cheevos_->unlock(5); + cheevos->unlock(7); + cheevos->unlock(6); + cheevos->unlock(5); } else if (board_->rooms >= 40) { - cheevos_->unlock(6); - cheevos_->unlock(5); + cheevos->unlock(6); + cheevos->unlock(5); } else if (board_->rooms >= 20) { - cheevos_->unlock(5); + cheevos->unlock(5); } } // Comprueba los logros de completar el juego void Game::checkEndGameCheevos() { + auto cheevos = Cheevos::get(); + // "Complete the game" - cheevos_->unlock(8); + cheevos->unlock(8); // "Complete the game without entering the jail" - cheevos_->unlock(9); + cheevos->unlock(9); // "Complete the game with all items" if (board_->items == total_items_) { - cheevos_->unlock(10); + cheevos->unlock(10); } // "Complete the game without dying" - cheevos_->unlock(11); + cheevos->unlock(11); // "Complete the game in under 30 minutes" if (scoreboard_->getMinutes() < 30) { - cheevos_->unlock(12); + cheevos->unlock(12); } +} + +// Inicializa al jugador +void Game::initPlayer(PlayerSpawn spawn_point, std::shared_ptr room) +{ + std::string player_texture = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.png" : "player.png"; + std::string player_animations = options.cheats.alternate_skin == Cheat::CheatState::ENABLED ? "player2.ani" : "player.ani"; + const PlayerData player(spawn_point, player_texture, player_animations, room); + player_ = std::make_shared(player); +} + +// Crea la textura para poner el nombre de la habitación +void Game::createRoomNameTexture() +{ + auto text = Resource::get()->getText("smb2"); + room_name_texture_ = SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, text->getCharacterSize() * 2); + if (room_name_texture_ == nullptr) + { + if (options.console) + { + std::cout << "Error: room_name_texture_ could not be created!\nSDL Error: " << SDL_GetError() << std::endl; + } + } + + // Establece el blend mode de la textura + SDL_SetTextureBlendMode(room_name_texture_, SDL_BLENDMODE_BLEND); + + // Establece el destino de la textura + room_name_rect_ = {0, PLAY_AREA_HEIGHT, GAMECANVAS_WIDTH, text->getCharacterSize() * 2}; } \ No newline at end of file diff --git a/source/game.h b/source/game.h index afaa886..1fa9250 100644 --- a/source/game.h +++ b/source/game.h @@ -8,7 +8,7 @@ #include "player.h" // Para playerSpawn_t #include "scoreboard.h" // Para board_t #include "room.h" -//#include "surface.h" +// #include "surface.h" class Asset; class Cheevos; class Debug; @@ -29,34 +29,24 @@ class Game { private: // Objetos y punteros - Screen *screen_; // Objeto encargado de manejar el renderizador - SDL_Renderer *renderer_; // El renderizador de la ventana - Asset *asset_; // Objeto con la ruta a todos los ficheros de recursos - Input *input_; // Objeto pata gestionar la entrada - Resource *resource_; // Objeto con los recursos - Debug *debug_; // Objeto para gestionar la información de debug - Cheevos *cheevos_; // Objeto encargado de gestionar los logros del juego + std::shared_ptr board_; // Estructura con los datos del marcador + std::shared_ptr scoreboard_; // Objeto encargado de gestionar el marcador + std::shared_ptr room_tracker_; // Lleva el control de las habitaciones visitadas std::shared_ptr room_; // Objeto encargado de gestionar cada habitación del juego std::shared_ptr player_; // Objeto con el jugador - std::shared_ptr room_tracker_; // Lleva el control de las habitaciones visitadas - std::shared_ptr text_; // Objeto para los textos del juego - std::shared_ptr scoreboard_; // Objeto encargado de gestionar el marcador std::shared_ptr stats_; // Objeto encargado de gestionar las estadísticas SDL_Texture *room_name_texture_; // Textura para escribir el nombre de la habitación - //std::shared_ptr test_surface_; + // std::shared_ptr test_surface_; // Variables - JA_Music_t *music_; // Musica que suena durante el juego - Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa - std::string current_room_; // Fichero de la habitación actual - PlayerSpawn spawn_point_; // Lugar de la habitación donde aparece el jugador - JA_Sound_t *death_sound_; // Sonido a reproducir cuando muere el jugador - std::shared_ptr board_; // Estructura con los datos del marcador - bool paused_; // Indica si el juego se encuentra en pausa - bool black_screen_; // Indica si la pantalla está en negro. Se utiliza para la muerte del jugador - int black_screen_counter_; // Contador para temporizar la pantalla en negro - int total_items_; // Cantidad total de items que hay en el mapeado del juego - SDL_Rect room_name_rect_; // Rectangulo donde pintar la textura con el nombre de la habitación + Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa + std::string current_room_ = "03.room"; // Fichero de la habitación actual + PlayerSpawn spawn_point_; // Lugar de la habitación donde aparece el jugador + bool paused_ = false; // Indica si el juego se encuentra en pausa + bool black_screen_ = false; // Indica si la pantalla está en negro. Se utiliza para la muerte del jugador + int black_screen_counter_ = 0; // Contador para temporizar la pantalla en negro + int total_items_; // Cantidad total de items que hay en el mapeado del juego + SDL_Rect room_name_rect_; // Rectangulo donde pintar la textura con el nombre de la habitación // Actualiza el juego, las variables, comprueba la entrada, etc. void update(); @@ -73,13 +63,16 @@ private: // Pone la información de debug en pantalla void renderDebugInfo(); + + // Comprueba los eventos + void checkDebugEvents(const SDL_Event &event); #endif // Escribe el nombre de la pantalla void renderRoomName(); // Cambia de habitación - bool changeRoom(std::string file); + bool changeRoom(const std::string &file); // Comprueba el teclado void checkInput(); @@ -102,9 +95,6 @@ private: // Mata al jugador void killPlayer(); - // Recarga todas las texturas - void reLoadTextures(); - // Establece la pantalla en negro void setBlackScreen(); @@ -123,11 +113,8 @@ private: // Obtiene la cantidad total de items que hay en el mapeado del juego int getTotalItems(); - // Va a la habitación designada - void goToRoom(int border); - // Pone el juego en pausa - void switchPause(); + void togglePause(); // Da vidas al jugador cuando está en la Jail void checkRestoringJail(); @@ -144,6 +131,12 @@ private: // Comprueba los logros de completar el juego void checkEndGameCheevos(); + // Inicializa al jugador + void initPlayer(PlayerSpawn spawn_point, std::shared_ptr room); + + // Crea la textura para poner el nombre de la habitación + void createRoomNameTexture(); + public: // Constructor Game(); diff --git a/source/game_over.cpp b/source/game_over.cpp index bcfe861..dfb786c 100644 --- a/source/game_over.cpp +++ b/source/game_over.cpp @@ -43,7 +43,7 @@ GameOver::GameOver() // Inicializa el vector de colores const std::vector colorList = {"white", "yellow", "cyan", "green", "magenta", "red", "blue", "black"}; - for (auto cl : colorList) + for (const auto &cl : colorList) { colors_.push_back(stringToColor(options.video.palette, cl)); } diff --git a/source/input.cpp b/source/input.cpp index 238d47c..2bf0ff8 100644 --- a/source/input.cpp +++ b/source/input.cpp @@ -43,15 +43,6 @@ Input::Input(const std::string &game_controller_db_path) game_controller_bindings_.resize(static_cast(InputAction::SIZE), gcb); } -// Actualiza el estado del objeto -void Input::update() -{ - if (disabled_until_ == d_keyPressed && !checkAnyInput()) - { - enable(); - } -} - // Asigna inputs a teclas void Input::bindKey(InputAction input, SDL_Scancode code) { @@ -316,18 +307,4 @@ int Input::getNumControllers() void Input::setVerbose(bool value) { verbose_ = value; -} - -// Deshabilita las entradas durante un periodo de tiempo -void Input::disableUntil(i_disable_e value) -{ - disabled_until_ = value; - enabled_ = false; -} - -// Hablita las entradas -void Input::enable() -{ - enabled_ = true; - disabled_until_ = d_notDisabled; } \ No newline at end of file diff --git a/source/input.h b/source/input.h index 44c0860..174543f 100644 --- a/source/input.h +++ b/source/input.h @@ -42,13 +42,6 @@ enum class InputAction SIZE }; -enum i_disable_e -{ - d_notDisabled, - d_forever, - d_keyPressed -}; - class Input { private: @@ -74,10 +67,9 @@ private: std::vector key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos std::vector game_controller_bindings_; // Vector con las teclas asociadas a los inputs predefinidos std::vector controller_names_; // Vector con los nombres de los mandos - int num_gamepads_; // Numero de mandos conectados + int num_gamepads_ = 0; // Numero de mandos conectados std::string db_path_; // Ruta al archivo gamecontrollerdb.txt bool verbose_ = true; // Indica si ha de mostrar mensajes - i_disable_e disabled_until_; // Tiempo que esta deshabilitado bool enabled_ = true; // Indica si está habilitado // Constructor @@ -96,9 +88,6 @@ public: // [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él static Input *get(); - // Actualiza el estado del objeto - void update(); - // Asigna inputs a teclas void bindKey(InputAction input, SDL_Scancode code); @@ -125,10 +114,4 @@ public: // Establece si ha de mostrar mensajes void setVerbose(bool value); - - // Deshabilita las entradas durante un periodo de tiempo - void disableUntil(i_disable_e value); - - // Hablita las entradas - void enable(); }; \ No newline at end of file diff --git a/source/item.cpp b/source/item.cpp index 14b88ef..5d8c21b 100644 --- a/source/item.cpp +++ b/source/item.cpp @@ -5,16 +5,12 @@ // Constructor Item::Item(ItemData item) + : sprite_(std::make_shared(Resource::get()->getTexture(item.tile_set_file), item.x, item.y, ITEM_SIZE_, ITEM_SIZE_)), + change_color_speed(4) { - constexpr int ITEMSIZE = 8; - - // Crea objetos; - sprite_ = std::make_shared(Resource::get()->getTexture(item.tile_set_file), item.x, item.y, ITEMSIZE, ITEMSIZE); - // Inicia variables - sprite_->setClip((item.tile % 10) * ITEMSIZE, (item.tile / 10) * ITEMSIZE, ITEMSIZE, ITEMSIZE); + sprite_->setClip((item.tile % 10) * ITEM_SIZE_, (item.tile / 10) * ITEM_SIZE_, ITEM_SIZE_, ITEM_SIZE_); collider_ = sprite_->getRect(); - change_color_speed = 4; counter_ = item.counter * change_color_speed; // Inicializa los colores @@ -28,8 +24,8 @@ Item::Item(ItemData item) // Pinta el objeto en pantalla void Item::render() { - const int index = (counter_ / change_color_speed) % color_.size(); - sprite_->getTexture()->setColor(color_[index].r, color_[index].g, color_[index].b); + const int INDEX = (counter_ / change_color_speed) % color_.size(); + sprite_->getTexture()->setColor(color_.at(INDEX).r, color_.at(INDEX).g, color_.at(INDEX).b); sprite_->render(); sprite_->getTexture()->setColor(255, 255, 255); } diff --git a/source/item.h b/source/item.h index 5857c83..9e6137d 100644 --- a/source/item.h +++ b/source/item.h @@ -11,13 +11,13 @@ struct ItemData { - std::string tile_set_file; // Ruta al fichero con los gráficos del item - int x; // Posición del item en pantalla - int y; // Posición del item en pantalla - int tile; // Número de tile dentro de la textura - int counter; // Contador inicial. Es el que lo hace cambiar de color - Color color1; // Uno de los dos colores que se utiliza para el item - Color color2; // Uno de los dos colores que se utiliza para el item + std::string tile_set_file; // Ruta al fichero con los gráficos del item + int x; // Posición del item en pantalla + int y; // Posición del item en pantalla + int tile; // Número de tile dentro de la textura + int counter; // Contador inicial. Es el que lo hace cambiar de color + Color color1; // Uno de los dos colores que se utiliza para el item + Color color2; // Uno de los dos colores que se utiliza para el item // Constructor ItemData() : x(0), y(0), tile(0), counter(0), color1(), color2() {} @@ -26,6 +26,9 @@ struct ItemData class Item { private: + // Constantes + static constexpr int ITEM_SIZE_ = 8; + // Objetos y punteros std::shared_ptr sprite_; // Sprite del objeto @@ -37,7 +40,7 @@ private: public: // Constructor - Item(ItemData item); + explicit Item(ItemData item); // Destructor ~Item() = default; diff --git a/source/item_tracker.cpp b/source/item_tracker.cpp index 34f11ff..0a43a5a 100644 --- a/source/item_tracker.cpp +++ b/source/item_tracker.cpp @@ -57,7 +57,7 @@ void ItemTracker::addItem(const std::string &name, SDL_Point pos) } // Busca una entrada en la lista por nombre -int ItemTracker::findByName(std::string name) +int ItemTracker::findByName(const std::string &name) { int i = 0; diff --git a/source/item_tracker.h b/source/item_tracker.h index cc0867a..ab739e6 100644 --- a/source/item_tracker.h +++ b/source/item_tracker.h @@ -27,7 +27,7 @@ private: std::vector item_list_; // Lista con todos los objetos recogidos // Busca una entrada en la lista por nombre - int findByName(std::string name); + int findByName(const std::string &name); // Busca una entrada en la lista por posición int findByPos(int index, SDL_Point pos); diff --git a/source/loading_screen.cpp b/source/loading_screen.cpp index 334d2eb..a1a5700 100644 --- a/source/loading_screen.cpp +++ b/source/loading_screen.cpp @@ -1,19 +1,19 @@ #include "loading_screen.h" -#include // for SDL_PollEvent, SDL_Event -#include // for SDL_GetTicks -#include // for rand -#include "asset.h" // for Asset -#include "defines.h" // for GAMECANVAS_HEIGHT, GAMECANVAS_WIDTH -#include "global_events.h" // for check -#include "global_inputs.h" // for check -#include "input.h" // for Input -#include "jail_audio.h" // for JA_PlayMusic, JA_SetVolume, JA_StopMusic -#include "options.h" // for Options, options, OptionsVideo, Section... -#include "resource.h" // for Resource -#include "screen.h" // for Screen -#include "sprite.h" // for Sprite -#include "texture.h" // for Texture -#include "utils.h" // for Color, stringToColor, Palette +#include // for SDL_PollEvent, SDL_Event +#include // for SDL_GetTicks +#include // for rand +#include "asset.h" // for Asset +#include "defines.h" // for GAMECANVAS_HEIGHT, GAMECANVAS_WIDTH +#include "global_events.h" // for check +#include "global_inputs.h" // for check +#include "input.h" // for Input +#include "jail_audio.h" // for JA_PlayMusic, JA_SetVolume, JA_StopMusic +#include "options.h" // for Options, options, OptionsVideo, Section... +#include "resource.h" // for Resource +#include "screen.h" // for Screen +#include "sprite.h" // for Sprite +#include "texture.h" // for Texture +#include "utils.h" // for Color, stringToColor, Palette #include // Constructor @@ -42,13 +42,13 @@ LoadingScreen::LoadingScreen() loading_sound3_ = resource_->getMusic("loading_sound3.ogg"); texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, options.game.width, options.game.height); - if (texture_ == nullptr) - { - if (options.console) - { - std::cout << "LoadingScreen::texture_ could not be created!\nSDL Error: " << SDL_GetError() << std::endl; - } - } + if (texture_ == nullptr) + { + if (options.console) + { + std::cout << "LoadingScreen::texture_ could not be created!\nSDL Error: " << SDL_GetError() << std::endl; + } + } clearTexture(); // Inicializa variables @@ -62,14 +62,12 @@ LoadingScreen::LoadingScreen() { // Primer bloque de 2K line_index_[i] = ((i % 8) * 8) + (i / 8); } - - else if (i >= 64 && i < 128) + else if (i < 128) { // Segundo bloque de 2K line_index_[i] = 64 + ((i % 8) * 8) + ((i - 64) / 8); } - - else if (i >= 128 && i < 192) - { // tercer bloque de 2K + else + { // Tercer bloque de 2K line_index_[i] = 128 + ((i % 8) * 8) + ((i - 128) / 8); } } @@ -169,30 +167,32 @@ void LoadingScreen::renderLoad() // Dibuja el efecto de carga en el borde void LoadingScreen::renderBorder() { - // Pinta el borde de colro azul - Color color = stringToColor(options.video.palette, "blue"); - SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); - SDL_RenderClear(renderer_); + // Pinta el borde de colro azul + Color color = stringToColor(options.video.palette, "blue"); + SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); + SDL_RenderClear(renderer_); - // Añade lineas amarillas - color = stringToColor(options.video.palette, "yellow"); - SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); - const int width = options.game.width + (options.video.border.width * 2); - const int height = options.game.height + (options.video.border.height * 2); - bool drawEnabled = rand() % 2 == 0 ? true : false; - int row = 0; - int rowSize = 1; - while (row < height) - { - rowSize = (rand() % 4) + 3; - if (drawEnabled) - for (int i = row; i < row + rowSize; ++i) - { - SDL_RenderDrawLine(renderer_, 0, i, width, i); - } - row += rowSize; - drawEnabled = !drawEnabled; - } + // Añade lineas amarillas + color = stringToColor(options.video.palette, "yellow"); + SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); + const int WIDTH = options.game.width + (options.video.border.width * 2); + const int HEIGHT = options.game.height + (options.video.border.height * 2); + bool drawEnabled = rand() % 2 == 0 ? true : false; + + int row = 0; + while (row < HEIGHT) + { + const int ROW_HEIGHT = (rand() % 4) + 3; + if (drawEnabled) + { + for (int i = row; i < row + ROW_HEIGHT; ++i) + { + SDL_RenderDrawLine(renderer_, 0, i, WIDTH, i); + } + } + row += ROW_HEIGHT; + drawEnabled = !drawEnabled; + } } // Actualiza las variables @@ -254,70 +254,31 @@ void LoadingScreen::run() JA_SetVolume(128); } -// Reconstruye la pantalla de carga -void LoadingScreen::recreateLoadingScreen() -{ - // Prepara para empezar a dibujar en la textura de juego - screen_->start(); - - // Primera parte de la carga, la parte en blanco y negro - if (loading_first_part_) - { - const int numSteps = 5; - const int step = 51; - - for (int i = 0; i <= counter_; i++) - { - load_counter_ = i / numSteps; - load_rect_.x = step * (i % numSteps); - load_rect_.y = line_index_[load_counter_]; - mono_loading_screen_sprite_->setClip(load_rect_); - mono_loading_screen_sprite_->setPosition(load_rect_); - mono_loading_screen_sprite_->render(); - } - } - // Segunda parte de la carga, la parte de los bloques en color - else - { - for (int i = 0; i <= load_counter_; i++) - { - load_rect_.x = (i * 8) % 256; - load_rect_.y = (i / 32) * 8; - color_loading_screen_sprite_->setClip(load_rect_); - color_loading_screen_sprite_->setPosition(load_rect_); - color_loading_screen_sprite_->render(); - } - } - - // Vuelca el contenido del renderizador en pantalla - screen_->render(); -} - // Dibuja sobre la textura void LoadingScreen::fillTexture() { // Empieza a dibujar en la textura - auto temp = SDL_GetRenderTarget(renderer_); - SDL_SetRenderTarget(renderer_, texture_); + auto temp = SDL_GetRenderTarget(renderer_); + SDL_SetRenderTarget(renderer_, texture_); // Dibuja la pantalla de carga renderLoad(); // Deja el renderizador como estaba - SDL_SetRenderTarget(renderer_, temp); + SDL_SetRenderTarget(renderer_, temp); } // Limpia la textura void LoadingScreen::clearTexture() { // Empieza a dibujar en la textura - auto temp = SDL_GetRenderTarget(renderer_); - SDL_SetRenderTarget(renderer_, texture_); + auto temp = SDL_GetRenderTarget(renderer_); + SDL_SetRenderTarget(renderer_, texture_); // Limpia SDL_SetRenderDrawColor(renderer_, 0x00, 0x00, 0x00, 0xFF); SDL_RenderClear(renderer_); // Deja el renderizador como estaba - SDL_SetRenderTarget(renderer_, temp); + SDL_SetRenderTarget(renderer_, temp); } \ No newline at end of file diff --git a/source/loading_screen.h b/source/loading_screen.h index 36099fc..3bb8d4f 100644 --- a/source/loading_screen.h +++ b/source/loading_screen.h @@ -63,9 +63,6 @@ private: // Dibuja el efecto de carga en el borde void renderBorder(); - // Reconstruye la pantalla de carga - void recreateLoadingScreen(); - // Dibuja sobre la textura void fillTexture(); diff --git a/source/logo.cpp b/source/logo.cpp index 6d24df5..988a4f8 100644 --- a/source/logo.cpp +++ b/source/logo.cpp @@ -35,25 +35,18 @@ Logo::Logo() { jailgames_sprite_.push_back(std::make_shared(jailgames_texture_, 0, i, jailgames_texture_->getWidth(), 1)); jailgames_sprite_.back()->setClip(0, i, jailgames_texture_->getWidth(), 1); - if (i % 2 == 0) - { - jailgames_sprite_[i]->setX(256 + (i * 3)); - } - else - { - jailgames_sprite_[i]->setX(-181 - (i * 3)); - } - jailgames_sprite_[i]->setY(83 + i); + jailgames_sprite_.at(i)->setX((i % 2 == 0) ? (256 + (i * 3)) : (-181 - (i * 3))); + jailgames_sprite_.at(i)->setY(83 + i); } // Inicializa variables options.section.section = Section::LOGO; // Inicializa el vector de colores - const std::vector vColors = {"black", "blue", "red", "magenta", "green", "cyan", "yellow", "bright_white"}; - for (auto v : vColors) + const std::vector COLORS = {"black", "blue", "red", "magenta", "green", "cyan", "yellow", "bright_white"}; + for (const auto &color : COLORS) { - color_.push_back(stringToColor(options.video.palette, v)); + color_.push_back(stringToColor(options.video.palette, color)); } // Cambia el color del borde @@ -83,24 +76,24 @@ void Logo::updateJAILGAMES() { for (int i = 1; i < (int)jailgames_sprite_.size(); ++i) { - const int speed = 8; - const int dest = 37; - if (jailgames_sprite_[i]->getX() != 37) + constexpr int SPEED = 8; + constexpr int DEST = 37; + if (jailgames_sprite_.at(i)->getX() != 37) { if (i % 2 == 0) { - jailgames_sprite_[i]->incX(-speed); - if (jailgames_sprite_[i]->getX() < dest) + jailgames_sprite_.at(i)->incX(-SPEED); + if (jailgames_sprite_.at(i)->getX() < DEST) { - jailgames_sprite_[i]->setX(dest); + jailgames_sprite_.at(i)->setX(DEST); } } else { - jailgames_sprite_[i]->incX(speed); - if (jailgames_sprite_[i]->getX() > dest) + jailgames_sprite_.at(i)->incX(SPEED); + if (jailgames_sprite_.at(i)->getX() > DEST) { - jailgames_sprite_[i]->setX(dest); + jailgames_sprite_.at(i)->setX(DEST); } } } @@ -111,89 +104,89 @@ void Logo::updateJAILGAMES() // Gestiona el color de las texturas void Logo::updateTextureColors() { - const int ini = 70; - const int inc = 4; + constexpr int INI = 70; + constexpr int INC = 4; - if (counter_ == ini + inc * 0) + if (counter_ == INI + INC * 0) { - since_1998_texture_->setColor(color_[0].r, color_[0].g, color_[0].b); + since_1998_texture_->setColor(color_.at(0).r, color_.at(0).g, color_.at(0).b); } - else if (counter_ == ini + inc * 1) + else if (counter_ == INI + INC * 1) { - since_1998_texture_->setColor(color_[1].r, color_[1].g, color_[1].b); + since_1998_texture_->setColor(color_.at(1).r, color_.at(1).g, color_.at(1).b); } - else if (counter_ == ini + inc * 2) + else if (counter_ == INI + INC * 2) { - since_1998_texture_->setColor(color_[2].r, color_[2].g, color_[2].b); + since_1998_texture_->setColor(color_.at(2).r, color_.at(2).g, color_.at(2).b); } - else if (counter_ == ini + inc * 3) + else if (counter_ == INI + INC * 3) { - since_1998_texture_->setColor(color_[3].r, color_[3].g, color_[3].b); + since_1998_texture_->setColor(color_.at(3).r, color_.at(3).g, color_.at(3).b); } - else if (counter_ == ini + inc * 4) + else if (counter_ == INI + INC * 4) { - since_1998_texture_->setColor(color_[4].r, color_[4].g, color_[4].b); + since_1998_texture_->setColor(color_.at(4).r, color_.at(4).g, color_.at(4).b); } - else if (counter_ == ini + inc * 5) + else if (counter_ == INI + INC * 5) { - since_1998_texture_->setColor(color_[5].r, color_[5].g, color_[5].b); + since_1998_texture_->setColor(color_.at(5).r, color_.at(5).g, color_.at(5).b); } - else if (counter_ == ini + inc * 6) + else if (counter_ == INI + INC * 6) { - since_1998_texture_->setColor(color_[6].r, color_[6].g, color_[6].b); + since_1998_texture_->setColor(color_.at(6).r, color_.at(6).g, color_.at(6).b); } - else if (counter_ == ini + inc * 7) + else if (counter_ == INI + INC * 7) { - since_1998_texture_->setColor(color_[7].r, color_[7].g, color_[7].b); + since_1998_texture_->setColor(color_.at(7).r, color_.at(7).g, color_.at(7).b); } - else if (counter_ == INIT_FADE_ + inc * 0) + else if (counter_ == INIT_FADE_ + INC * 0) { - jailgames_texture_->setColor(color_[6].r, color_[6].g, color_[6].b); - since_1998_texture_->setColor(color_[6].r, color_[6].g, color_[6].b); + jailgames_texture_->setColor(color_.at(6).r, color_.at(6).g, color_.at(6).b); + since_1998_texture_->setColor(color_.at(6).r, color_.at(6).g, color_.at(6).b); } - else if (counter_ == INIT_FADE_ + inc * 1) + else if (counter_ == INIT_FADE_ + INC * 1) { - jailgames_texture_->setColor(color_[5].r, color_[5].g, color_[5].b); - since_1998_texture_->setColor(color_[5].r, color_[5].g, color_[5].b); + jailgames_texture_->setColor(color_.at(5).r, color_.at(5).g, color_.at(5).b); + since_1998_texture_->setColor(color_.at(5).r, color_.at(5).g, color_.at(5).b); } - else if (counter_ == INIT_FADE_ + inc * 2) + else if (counter_ == INIT_FADE_ + INC * 2) { - jailgames_texture_->setColor(color_[4].r, color_[4].g, color_[4].b); - since_1998_texture_->setColor(color_[4].r, color_[4].g, color_[4].b); + jailgames_texture_->setColor(color_.at(4).r, color_.at(4).g, color_.at(4).b); + since_1998_texture_->setColor(color_.at(4).r, color_.at(4).g, color_.at(4).b); } - else if (counter_ == INIT_FADE_ + inc * 3) + else if (counter_ == INIT_FADE_ + INC * 3) { - jailgames_texture_->setColor(color_[3].r, color_[3].g, color_[3].b); - since_1998_texture_->setColor(color_[3].r, color_[3].g, color_[3].b); + jailgames_texture_->setColor(color_.at(3).r, color_.at(3).g, color_.at(3).b); + since_1998_texture_->setColor(color_.at(3).r, color_.at(3).g, color_.at(3).b); } - else if (counter_ == INIT_FADE_ + inc * 4) + else if (counter_ == INIT_FADE_ + INC * 4) { - jailgames_texture_->setColor(color_[2].r, color_[2].g, color_[2].b); - since_1998_texture_->setColor(color_[2].r, color_[2].g, color_[2].b); + jailgames_texture_->setColor(color_.at(2).r, color_.at(2).g, color_.at(2).b); + since_1998_texture_->setColor(color_.at(2).r, color_.at(2).g, color_.at(2).b); } - else if (counter_ == INIT_FADE_ + inc * 5) + else if (counter_ == INIT_FADE_ + INC * 5) { - jailgames_texture_->setColor(color_[1].r, color_[1].g, color_[1].b); - since_1998_texture_->setColor(color_[1].r, color_[1].g, color_[1].b); + jailgames_texture_->setColor(color_.at(1).r, color_.at(1).g, color_.at(1).b); + since_1998_texture_->setColor(color_.at(1).r, color_.at(1).g, color_.at(1).b); } - else if (counter_ == INIT_FADE_ + inc * 6) + else if (counter_ == INIT_FADE_ + INC * 6) { - jailgames_texture_->setColor(color_[0].r, color_[0].g, color_[0].b); - since_1998_texture_->setColor(color_[0].r, color_[0].g, color_[0].b); + jailgames_texture_->setColor(color_.at(0).r, color_.at(0).g, color_.at(0).b); + since_1998_texture_->setColor(color_.at(0).r, color_.at(0).g, color_.at(0).b); } } diff --git a/source/options.cpp b/source/options.cpp index 4ab1e5d..0922f8e 100644 --- a/source/options.cpp +++ b/source/options.cpp @@ -39,9 +39,8 @@ bool loadOptionsFromFile(const std::string &file_path) options.version = ""; // Variables para manejar el fichero - std::string line; std::ifstream file(file_path); - + // Si el fichero se puede abrir if (file.good()) { @@ -50,6 +49,7 @@ bool loadOptionsFromFile(const std::string &file_path) { std::cout << "Reading file config.txt\n"; } + std::string line; while (std::getline(file, line)) { // Elimina espacios en blanco iniciales y finales diff --git a/source/options.h b/source/options.h index 0fbe3d0..b9e190f 100644 --- a/source/options.h +++ b/source/options.h @@ -212,7 +212,7 @@ struct OptionsStats worst_nightmare("") {} // Constructor - OptionsStats(int r, int i, std::string wn) + OptionsStats(int r, int i, const std::string wn) : rooms(r), items(i), worst_nightmare(wn) {} diff --git a/source/player.cpp b/source/player.cpp index 2f3a6bb..0bb390b 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -16,7 +16,7 @@ #include "screen.h" // Constructor -Player::Player(PlayerData player) +Player::Player(const PlayerData &player) : renderer_(Screen::get()->getRenderer()), input_(Input::get()), asset_(Asset::get()), diff --git a/source/player.h b/source/player.h index 2ec4d79..6d0e31b 100644 --- a/source/player.h +++ b/source/player.h @@ -168,7 +168,7 @@ public: public: // Constructor - Player(PlayerData player); + explicit Player(const PlayerData &player); // Destructor ~Player() = default; @@ -210,8 +210,5 @@ public: bool isAlive() { return is_alive_; } // Pone el jugador en modo pausa - void pause() { is_paused_ = true; } - - // Quita el modo pausa del jugador - void resume() { is_paused_ = false; } + void setPaused(bool value) { is_paused_ = value; } }; \ No newline at end of file diff --git a/source/room.cpp b/source/room.cpp index b58d34c..c724510 100644 --- a/source/room.cpp +++ b/source/room.cpp @@ -23,12 +23,12 @@ std::vector loadRoomTileFile(const std::string &file_path, bool verbose) { std::vector tileMapFile; const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1); - std::string line; std::ifstream file(file_path); // El fichero se puede abrir if (file.good()) { + std::string line; // Procesa el fichero linea a linea while (std::getline(file, line)) { // Lee el fichero linea a linea @@ -81,12 +81,12 @@ RoomData loadRoomFile(const std::string &file_path, bool verbose) const std::string fileName = file_path.substr(file_path.find_last_of("\\/") + 1); room.number = fileName.substr(0, fileName.find_last_of(".")); - std::string line; std::ifstream file(file_path); // El fichero se puede abrir if (file.good()) { + std::string line; // Procesa el fichero linea a linea while (std::getline(file, line)) { @@ -398,13 +398,14 @@ bool setItem(ItemData *item, const std::string &key, const std::string &value) } // Constructor -Room::Room(std::shared_ptr room, std::shared_ptr data) +Room::Room(const std::string &room_path, std::shared_ptr data) : screen_(Screen::get()), renderer_(Screen::get()->getRenderer()), asset_(Asset::get()), debug_(Debug::get()), data_(data) { + auto room = Resource::get()->getRoom(room_path); number_ = room->number; name_ = room->name; bg_color_ = room->bg_color; @@ -419,11 +420,11 @@ Room::Room(std::shared_ptr room, std::shared_ptr data) tile_map_file_ = room->tile_map_file; auto_surface_direction_ = room->auto_surface_direction; tile_map_ = Resource::get()->getTileMap(room->tile_map_file); - texture_ = (options.video.palette == Palette::ZXSPECTRUM) ? Resource::get()->getTexture(room->tile_set_file) : Resource::get()->getTexture(room->tile_set_file); + texture_ = Resource::get()->getTexture(room->tile_set_file); // Inicializa variables tile_set_width_ = texture_->getWidth() / TILE_SIZE_; - paused_ = false; + is_paused_ = false; counter_ = 0; // Crea los enemigos @@ -674,7 +675,7 @@ void Room::renderItems() // Actualiza las variables y objetos de la habitación void Room::update() { - if (paused_) + if (is_paused_) { // Si está en modo pausa no se actualiza nada return; } @@ -846,7 +847,7 @@ void Room::reLoadPalette() screen_->setBorderColor(stringToColor(options.video.palette, border_color_)); // Cambia la textura - //texture_ = (options.video.palette == Palette::ZXSPECTRUM) ? Resource::get()->getTexture(room->tile_set_file) : Resource::get()->getTexture(room->tile_set_file); + // texture_ = (options.video.palette == Palette::ZXSPECTRUM) ? Resource::get()->getTexture(room->tile_set_file) : Resource::get()->getTexture(room->tile_set_file); // Pone la nueva textura a los tiles animados for (auto tile : animated_tiles_) @@ -926,20 +927,19 @@ void Room::setBottomSurfaces() if ((int)tile.size() > 1) { int i = 0; - int lastOne = 0; do { h_line_t line; line.x1 = (tile[i] % MAP_WIDTH_) * TILE_SIZE_; line.y = ((tile[i] / MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; - lastOne = i; + int last_one = i; i++; if (i <= (int)tile.size() - 1) { while (tile[i] == tile[i - 1] + 1) { - lastOne = i; + last_one = i; if (i == (int)tile.size() - 1) { break; @@ -948,7 +948,7 @@ void Room::setBottomSurfaces() } } - line.x2 = ((tile[lastOne] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; + line.x2 = ((tile[last_one] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; bottom_surfaces_.push_back(line); if (i <= (int)tile.size() - 1) { @@ -989,20 +989,19 @@ void Room::setTopSurfaces() if ((int)tile.size() > 1) { int i = 0; - int lastOne = 0; do { h_line_t line; line.x1 = (tile[i] % MAP_WIDTH_) * TILE_SIZE_; line.y = (tile[i] / MAP_WIDTH_) * TILE_SIZE_; - lastOne = i; + int last_one = i; i++; if (i <= (int)tile.size() - 1) { while (tile[i] == tile[i - 1] + 1) { - lastOne = i; + last_one = i; if (i == (int)tile.size() - 1) { break; @@ -1011,7 +1010,7 @@ void Room::setTopSurfaces() } } - line.x2 = ((tile[lastOne] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; + line.x2 = ((tile[last_one] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; top_surfaces_.push_back(line); if (i <= (int)tile.size() - 1) { @@ -1224,23 +1223,22 @@ void Room::setAutoSurfaces() } // Recorre el vector de tiles buscando tiles consecutivos para localizar las superficies - int i = 0; - int lastOne = 0; if ((int)tile.size() > 0) { + int i = 0; do { h_line_t line; line.x1 = (tile[i] % MAP_WIDTH_) * TILE_SIZE_; line.y = (tile[i] / MAP_WIDTH_) * TILE_SIZE_; - lastOne = i; + int last_one = i; i++; if (i <= (int)tile.size() - 1) { while (tile[i] == tile[i - 1] + 1) { - lastOne = i; + last_one = i; if (i == (int)tile.size() - 1) { break; @@ -1249,7 +1247,7 @@ void Room::setAutoSurfaces() } } - line.x2 = ((tile[lastOne] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; + line.x2 = ((tile[last_one] % MAP_WIDTH_) * TILE_SIZE_) + TILE_SIZE_ - 1; auto_surfaces_.push_back(line); if (i <= (int)tile.size() - 1) { @@ -1474,18 +1472,6 @@ bool Room::checkRightSlopes(SDL_Point *p) return false; } -// Pone el mapa en modo pausa -void Room::pause() -{ - paused_ = true; -} - -// Quita el modo pausa del mapa -void Room::resume() -{ - paused_ = false; -} - // Obten la direccion de las superficies automaticas int Room::getAutoSurfaceDirection() { diff --git a/source/room.h b/source/room.h index e751745..c54f730 100644 --- a/source/room.h +++ b/source/room.h @@ -111,7 +111,7 @@ private: std::vector left_slopes_; // Lista con todas las rampas que suben hacia la izquierda std::vector right_slopes_; // Lista con todas las rampas que suben hacia la derecha int counter_; // Contador para lo que haga falta - bool paused_; // Indica si el mapa esta en modo pausa + bool is_paused_; // Indica si el mapa esta en modo pausa std::vector animated_tiles_; // Vector con los indices de tiles animados std::vector auto_surfaces_; // Lista con las superficies automaticas de la habitación int tile_set_width_; // Ancho del tileset en tiles @@ -157,7 +157,7 @@ private: public: // Constructor - Room(std::shared_ptr room, std::shared_ptr data); + Room(const std::string &room_path, std::shared_ptr data); // Destructor ~Room(); @@ -241,10 +241,7 @@ public: bool checkRightSlopes(SDL_Point *p); // Pone el mapa en modo pausa - void pause(); - - // Quita el modo pausa del mapa - void resume(); + void setPaused(bool value) { is_paused_ = value; }; // Obten la direccion de las superficies automaticas int getAutoSurfaceDirection(); diff --git a/source/room_tracker.cpp b/source/room_tracker.cpp index e0822e8..b26c65f 100644 --- a/source/room_tracker.cpp +++ b/source/room_tracker.cpp @@ -1,20 +1,9 @@ #include "room_tracker.h" -// Constructor -RoomTracker::RoomTracker() -{ -} - -// Destructor -RoomTracker::~RoomTracker() -{ - list.clear(); -} - // Comprueba si la habitación ya ha sido visitada -bool RoomTracker::hasBeenVisited(std::string name) +bool RoomTracker::hasBeenVisited(const std::string &name) { - for (auto l : list) + for (const auto &l : list) { if (l == name) { @@ -26,7 +15,7 @@ bool RoomTracker::hasBeenVisited(std::string name) } // Añade la habitación a la lista -bool RoomTracker::addRoom(std::string name) +bool RoomTracker::addRoom(const std::string &name) { // Comprueba si la habitación ya ha sido visitada if (!hasBeenVisited(name)) diff --git a/source/room_tracker.h b/source/room_tracker.h index 4d7b83a..b73dedc 100644 --- a/source/room_tracker.h +++ b/source/room_tracker.h @@ -10,15 +10,15 @@ private: std::vector list; // Lista con las habitaciones visitadas // Comprueba si la habitación ya ha sido visitada - bool hasBeenVisited(std::string name); + bool hasBeenVisited(const std::string &name); public: // Constructor - RoomTracker(); + RoomTracker() = default; // Destructor - ~RoomTracker(); + ~RoomTracker() = default; // Añade la habitación a la lista - bool addRoom(std::string name); + bool addRoom(const std::string &name); }; diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 0612253..185768c 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -122,17 +122,26 @@ void Scoreboard::reLoadPalette() } // Pone el marcador en modo pausa -void Scoreboard::pause() +void Scoreboard::setPaused(bool value) { - is_paused_ = true; - paused_time_ = SDL_GetTicks(); -} + if (is_paused_ == value) + { + // Evita ejecutar lógica si el estado no cambia + return; + } -// Quita el modo pausa del marcador -void Scoreboard::resume() -{ - is_paused_ = false; - paused_time_elapsed_ += SDL_GetTicks() - paused_time_; + is_paused_ = value; + + if (is_paused_) + { + // Guarda el tiempo actual al pausar + paused_time_ = SDL_GetTicks(); + } + else + { + // Calcula el tiempo pausado acumulado al reanudar + paused_time_elapsed_ += SDL_GetTicks() - paused_time_; + } } // Actualiza el color de la cantidad de items recogidos diff --git a/source/scoreboard.h b/source/scoreboard.h index 715a20c..1d9ffbe 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -14,17 +14,21 @@ class Texture; struct ScoreboardData { - int items; // Lleva la cuenta de los objetos recogidos - int lives; // Lleva la cuenta de ls vidas restantes del jugador - int rooms; // Lleva la cuenta de las habitaciones visitadas - bool music; // Indica si ha de sonar la musica durante el juego - Color color; // Color para escribir el texto del marcador - Uint32 ini_clock; // Tiempo inicial para calcular el tiempo transcurrido - bool jail_is_open; // Indica si se puede entrar a la Jail + int items; // Lleva la cuenta de los objetos recogidos + int lives; // Lleva la cuenta de las vidas restantes del jugador + int rooms; // Lleva la cuenta de las habitaciones visitadas + bool music; // Indica si ha de sonar la música durante el juego + Color color; // Color para escribir el texto del marcador + Uint32 ini_clock; // Tiempo inicial para calcular el tiempo transcurrido + bool jail_is_open; // Indica si se puede entrar a la Jail - // Constructor - ScoreboardData() - : items(0), lives(3), rooms(0), music(true), color({0, 0, 0}), ini_clock(0), jail_is_open(false) {} + // Constructor por defecto + ScoreboardData() + : items(0), lives(0), rooms(0), music(true), color({0, 0, 0}), ini_clock(0), jail_is_open(false) {} + + // Constructor parametrizado + ScoreboardData(int items, int lives, int rooms, bool music, Color color, Uint32 ini_clock, bool jail_is_open) + : items(items), lives(lives), rooms(rooms), music(music), color(color), ini_clock(ini_clock), jail_is_open(jail_is_open) {} }; class Scoreboard @@ -70,7 +74,7 @@ private: public: // Constructor - Scoreboard(std::shared_ptr data); + explicit Scoreboard(std::shared_ptr data); // Destructor ~Scoreboard(); @@ -88,10 +92,7 @@ public: void reLoadPalette(); // Pone el marcador en modo pausa - void pause(); - - // Quita el modo pausa del marcador - void resume(); + void setPaused(bool value); // Devuelve la cantidad de minutos de juego transcurridos int getMinutes(); diff --git a/source/title.cpp b/source/title.cpp index 03801ba..86cfa64 100644 --- a/source/title.cpp +++ b/source/title.cpp @@ -421,7 +421,7 @@ void Title::createCheevosTexture() // Escribe la lista de logros en la textura const std::string CHEEVOS_OWNER = "ACHIEVEMENTS"; - const std::string CHEEVOS_LIST_CAPTION = CHEEVOS_OWNER + " (" + std::to_string(Cheevos::get()->unlocked()) + " / " + std::to_string(Cheevos::get()->count()) + ")"; + const std::string CHEEVOS_LIST_CAPTION = CHEEVOS_OWNER + " (" + std::to_string(Cheevos::get()->unlocked()) + " / " + std::to_string(Cheevos::get()->size()) + ")"; int pos = 2; info_text_->writeDX(TEXT_CENTER | TEXT_COLOR, cheevos_texture_->getWidth() / 2, pos, CHEEVOS_LIST_CAPTION, 1, stringToColor(options.video.palette, "bright_green")); pos += info_text_->getCharacterSize();