diff --git a/source/asset.h b/source/asset.h index 07eb5ea..0923435 100644 --- a/source/asset.h +++ b/source/asset.h @@ -22,7 +22,7 @@ enum class AssetType : int class Asset { private: - // [SINGLETON] Objeto asset privado para Don Melitón + // [SINGLETON] Objeto asset privado static Asset *asset_; // Estructura para definir un item diff --git a/source/audio.cpp b/source/audio.cpp new file mode 100644 index 0000000..9796282 --- /dev/null +++ b/source/audio.cpp @@ -0,0 +1,129 @@ +#include "audio.h" +#include "jail_audio.h" +#include "options.h" +#include "resource.h" +#include + +// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado +Audio *Audio::audio_ = nullptr; + +// [SINGLETON] Crearemos el objeto asset con esta función estática +void Audio::init() +{ + Audio::audio_ = new Audio(); +} + +// [SINGLETON] Destruiremos el objeto asset con esta función estática +void Audio::destroy() +{ + delete Audio::audio_; +} + +// [SINGLETON] Con este método obtenemos el objeto asset y podemos trabajar con él +Audio *Audio::get() +{ + return Audio::audio_; +} + +// Constructor +Audio::Audio() +{ + // Inicializa SDL + if (!SDL_Init(SDL_INIT_AUDIO)) + { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_AUDIO could not initialize! SDL Error: %s", SDL_GetError()); + } + else + { + SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "\n** SDL_AUDIO: INITIALIZING\n"); + + JA_Init(48000, SDL_AUDIO_S16LE, 2); + enable(options.audio.enabled); + setMusicVolume(options.audio.music.volume); + setSoundVolume(options.audio.sound.volume); + + SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "** SDL_AUDIO: INITIALIZATION COMPLETE\n"); + } +} + +// Destructor +Audio::~Audio() +{ + JA_Quit(); +} + +// Reproduce la música +void Audio::playMusic(const std::string &name, const int loop) +{ + if (enabled_ && music_enabled_) + { + JA_PlayMusic(Resource::get()->getMusic(name), loop); + } +} + +// Pausa la música +void Audio::pauseMusic() +{ + if (enabled_ && music_enabled_) + { + JA_PauseMusic(); + } +} + +// Detiene la música +void Audio::stopMusic() +{ + if (enabled_ && music_enabled_) + { + JA_StopMusic(); + } +} + +// Reproduce un sonido +void Audio::playSound(const std::string &name) +{ + if (enabled_ && sound_enabled_) + { + JA_PlaySound(Resource::get()->getSound(name)); + } +} + +// Detiene todos los sonidos +void Audio::stopAllSounds() +{ + if (enabled_ && sound_enabled_) + { + JA_StopChannel(-1); + } +} + +// Realiza un fundido de salida de la música +void Audio::fadeOutMusic(int milliseconds) +{ + if (enabled_ && music_enabled_) + { + JA_FadeOutMusic(milliseconds); + } +} + +// Establece el volumen de los sonidos +void Audio::setSoundVolume(int volume) +{ + if (enabled_ && sound_enabled_) + { + volume = std::clamp(volume, 0, 100); + const int COVERTED_VOLUME = static_cast((volume / 100.0) * 128); + JA_SetSoundVolume(COVERTED_VOLUME); + } +} + +// Establece el volumen de la música +void Audio::setMusicVolume(int volume) +{ + if (enabled_ && music_enabled_) + { + volume = std::clamp(volume, 0, 100); + const int COVERTED_VOLUME = static_cast((volume / 100.0) * 128); + JA_SetMusicVolume(COVERTED_VOLUME); + } +} \ No newline at end of file diff --git a/source/audio.h b/source/audio.h new file mode 100644 index 0000000..4982eb6 --- /dev/null +++ b/source/audio.h @@ -0,0 +1,63 @@ +#pragma once + +#include +#include "audio.h" + +class Audio +{ +private: + // [SINGLETON] Objeto audio privado + static Audio *audio_; + + // Constructor + Audio(); // Constructor privado para el patrón Singleton + + // Destructor + ~Audio(); // Destructor privado para el patrón Singleton + + // Variables + bool enabled_ = true; // Indica si el audio está habilitado + bool sound_enabled_ = true; // Indica si los sonidos están habilitados + bool music_enabled_ = true; // Indica si la música está habilitada + +public: + // [SINGLETON] Crearemos el objeto con esta función estática + static void init(); // Inicializa el objeto Singleton + + // [SINGLETON] Destruiremos el objeto con esta función estática + static void destroy(); // Destruye el objeto Singleton + + // [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él + static Audio *get(); // Devuelve la instancia del Singleton + + void playMusic(const std::string &name, const int loop = -1); // Reproduce la música + void pauseMusic(); // Pausa la música + void stopMusic(); // Detiene la música + + void playSound(const std::string &name); // Reproduce un sonido + void stopAllSounds(); // Detiene todos los sonidos + + void fadeOutMusic(int milliseconds); // Realiza un fundido de salida de la música + + // Audio + void enable() { enabled_ = true; } // Habilita el audio + void disable() { enabled_ = false; } // Deshabilita el audio + void enable(bool value) { enabled_ = value; } // Habilita o deshabilita el audio + void toggleEnabled() { enabled_ = !enabled_; } // Alterna el estado del audio + + // Sound + void enableSound() { sound_enabled_ = true; } // Habilita los sonidos + void disableSound() { sound_enabled_ = false; } // Deshabilita los sonidos + void enableSound(bool value) { sound_enabled_ = value; } // Habilita o deshabilita los sonidos + void toggleSound() { sound_enabled_ = !sound_enabled_; } // Alterna el estado de los sonidos + + // Music + void enableMusic() { music_enabled_ = true; } // Habilita la música + void disableMusic() { music_enabled_ = false; } // Deshabilita la música + void enableMusic(bool value) { music_enabled_ = value; } // Habilita o deshabilita la música + void toggleMusic() { music_enabled_ = !music_enabled_; } // Alterna el estado de la música + + // Volume + void setSoundVolume(int volume); // Establece el volumen de los sonidos + void setMusicVolume(int volume); // Establece el volumen de la música +}; \ No newline at end of file diff --git a/source/balloon.cpp b/source/balloon.cpp index 3143c8f..12e98b0 100644 --- a/source/balloon.cpp +++ b/source/balloon.cpp @@ -6,7 +6,7 @@ #include "sprite.h" // Para Sprite #include "texture.h" // Para Texture #include "resource.h" -#include "jail_audio.h" +#include "audio.h" // Constructor Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel_x, float speed, Uint16 creation_timer, SDL_FRect play_area, std::shared_ptr texture, const std::vector &animation) @@ -414,6 +414,6 @@ void Balloon::playSound() { if (sound_enabled_) { - JA_PlaySound(Resource::get()->getSound(sound_)); + Audio::get()->playSound(sound_); } } \ No newline at end of file diff --git a/source/balloon_manager.cpp b/source/balloon_manager.cpp index 43642d1..889d306 100644 --- a/source/balloon_manager.cpp +++ b/source/balloon_manager.cpp @@ -5,7 +5,7 @@ #include "balloon.h" // Para Balloon, BALLOON_SCORE, BALLOON_VELX... #include "balloon_formations.h" // Para BalloonFormationParams, BalloonForma... #include "explosions.h" // Para Explosions -#include "jail_audio.h" // Para JA_PlaySound +#include "audio.h" // Para JA_PlaySound #include "param.h" // Para Param, ParamGame, param #include "resource.h" // Para Resource #include "screen.h" // Para Screen @@ -320,7 +320,7 @@ int BalloonManager::destroyAllBalloons() } balloon_deploy_counter_ = 300; - JA_PlaySound(Resource::get()->getSound("power_ball_explosion.wav")); + Audio::get()->playSound("power_ball_explosion.wav"); Screen::get()->flash(FLASH_COLOR, 3); Screen::get()->shake(); diff --git a/source/credits.cpp b/source/credits.cpp index b488033..aefbaf8 100644 --- a/source/credits.cpp +++ b/source/credits.cpp @@ -14,7 +14,7 @@ #include "global_events.h" // Para check #include "global_inputs.h" // Para check, update #include "input.h" // Para Input, INPUT_ALLOW_REPEAT -#include "jail_audio.h" // Para JA_GetMusicState, JA_SetMusicVolume +#include "audio.h" // Para JA_GetMusicState, JA_SetMusicVolume #include "lang.h" // Para getText #include "param.h" // Para Param, ParamGame, param #include "player.h" // Para Player, PlayerState @@ -71,7 +71,7 @@ Credits::~Credits() SDL_DestroyTexture(text_texture_); SDL_DestroyTexture(canvas_); resetVolume(); - JA_StopMusic(); + Audio::get()->stopMusic(); } // Bucle principal @@ -438,7 +438,7 @@ void Credits::updateBlackRects() { // Si los rectangulos izquierdo y derecho han llegado al centro setVolume(0); - JA_StopMusic(); + Audio::get()->stopMusic(); if (counter_pre_fade_ == 400) { fade_out_->activate(); @@ -472,10 +472,7 @@ void Credits::updateAllFades() fade_in_->update(); if (fade_in_->hasEnded()) { - if (JA_GetMusicState() == JA_MUSIC_INVALID || JA_GetMusicState() == JA_MUSIC_STOPPED) - { - JA_PlayMusic(Resource::get()->getMusic("credits.ogg")); - } + Audio::get()->playMusic("credits.ogg"); } fade_out_->update(); @@ -489,14 +486,14 @@ void Credits::updateAllFades() void Credits::setVolume(int amount) { options.audio.music.volume = std::clamp(amount, 0, 100); - JA_SetMusicVolume(to_JA_volume(options.audio.music.volume)); + Audio::get()->setMusicVolume(options.audio.music.volume); } // Reestablece el nivel de volumen void Credits::resetVolume() { options.audio.music.volume = initial_volume_; - JA_SetMusicVolume(to_JA_volume(options.audio.music.volume)); + Audio::get()->setMusicVolume(options.audio.music.volume); } // Cambia el color del fondo diff --git a/source/director.cpp b/source/director.cpp index 8f7bb6e..9f5f315 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -18,13 +18,13 @@ #include // Para operator+, allocator, char_traits #include // Para vector #include "asset.h" // Para Asset, AssetType +#include "audio.h" // Para Audio #include "credits.h" // Para Credits #include "game.h" // Para Game, GAME_MODE_DEMO_OFF, GAME_MOD... #include "hiscore_table.h" // Para HiScoreTable #include "input.h" // Para Input, InputAction #include "instructions.h" // Para Instructions #include "intro.h" // Para Intro -#include "jail_audio.h" // Para JA_SetMusicVolume, JA_SetSoundVolume #include "lang.h" // Para Code, loadFromFile #include "logo.h" // Para Logo #include "manage_hiscore_table.h" // Para ManageHiScoreTable @@ -93,7 +93,7 @@ void Director::init() // Inicializa y crea el resto de objetos lang::loadFromFile(getLangFile(static_cast(options.game.language))); Screen::init(); - initJailAudio(); + Audio::init(); Resource::init(); Input::init(Asset::get()->get("gamecontrollerdb.txt")); bindInputs(); @@ -110,14 +110,13 @@ void Director::close() { saveOptionsFile(Asset::get()->get("config.txt")); - Asset::destroy(); - Resource::destroy(); - Input::destroy(); - Screen::destroy(); - Notifier::destroy(); OnScreenHelp::destroy(); - - JA_Quit(); + Notifier::destroy(); + Input::destroy(); + Resource::destroy(); + Audio::destroy(); + Screen::destroy(); + Asset::destroy(); SDL_Quit(); @@ -257,34 +256,6 @@ void Director::bindInputs() } } -// Inicializa JailAudio -void Director::initJailAudio() -{ - // Inicializa SDL - if (!SDL_Init(SDL_INIT_AUDIO)) - { - SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_AUDIO could not initialize! SDL Error: %s", SDL_GetError()); - } - else - { - SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "\n** SDL_AUDIO: INITIALIZING\n"); - - JA_Init(48000, SDL_AUDIO_S16LE, 2); - if (options.audio.enabled) - { - JA_SetMusicVolume(to_JA_volume(options.audio.music.volume)); - JA_SetSoundVolume(to_JA_volume(options.audio.sound.volume)); - } - else - { - JA_SetMusicVolume(0); - JA_SetSoundVolume(0); - } - - SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "** SDL_AUDIO: INITIALIZATION COMPLETE\n"); - } -} - // Crea el indice de ficheros void Director::setFileList() { @@ -632,8 +603,8 @@ void Director::runDemoGame() // Ejecuta la sección init void Director::runInit() { - JA_StopMusic(); - JA_StopChannel(-1); + Audio::get()->stopMusic(); + Audio::get()->stopAllSounds(); if (section::options == section::Options::RELOAD || true) { Resource::get()->reload(); diff --git a/source/director.h b/source/director.h index 3b9cbfa..89994d9 100644 --- a/source/director.h +++ b/source/director.h @@ -13,9 +13,6 @@ private: std::string executable_path_; // Path del ejecutable std::string system_folder_; // Carpeta del sistema donde guardar datos - // Inicializa jail_audio - void initJailAudio(); - // Asigna los botones y teclas al objeto Input void bindInputs(); diff --git a/source/game.cpp b/source/game.cpp index 6b0af6f..08b249b 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -18,8 +18,7 @@ #include "global_inputs.h" // Para check, update #include "input.h" // Para InputAction, Input, INPUT_DO_NOT_A... #include "item.h" // Para Item, ItemType -#include "jail_audio.h" // Para JA_PlaySound, JA_GetMusicState -#include "lang.h" // Para getText +#include "audio.h" // Para Audio::icStateplaynclude "lang.h" // Para getText #include "manage_hiscore_table.h" // Para ManageHiScoreTable, HiScoreEntry #include "notifier.h" // Para Notifier #include "param.h" // Para Param, param, ParamGame, ParamFade @@ -34,11 +33,13 @@ #include "tabe.h" // Para Tabe, TabeState #include "text.h" // Para Text #include "texture.h" // Para Texture +#include "lang.h" // Constructor Game::Game(int player_id, int current_stage, bool demo) : renderer_(Screen::get()->getRenderer()), screen_(Screen::get()), + audio_(Audio::get()), asset_(Asset::get()), input_(Input::get()), background_(std::make_unique()), @@ -99,19 +100,18 @@ Game::Game(int player_id, int current_stage, bool demo) Game::~Game() { - // MODO DEMO + // [Modo DEMO] Vuelve a activar los sonidos if (demo_.enabled) { - // Habilita los sonidos - JA_EnableSound(true); + audio_->enableSound(); } - // MODO JUEGO else { - // Guarda las puntuaciones en un fichero + // [Modo JUEGO] Guarda puntuaciones y transita a modo título auto manager = std::make_unique(options.game.hi_score_table); manager->saveToFile(asset_->get("score.bin")); section::attract_mode = section::AttractMode::TITLE_TO_DEMO; + audio_->stopMusic(); } #ifdef RECORDING @@ -203,7 +203,7 @@ void Game::updateHiScore() if (hi_score_achieved_ == false) { hi_score_achieved_ = true; - JA_PlaySound(Resource::get()->getSound("hi_score_achieved.wav")); + audio_->playSound("hi_score_achieved.wav"); } } } @@ -261,7 +261,7 @@ void Game::updateStage() // Cambio de fase Stage::power = Stage::get(Stage::number).power_to_complete - Stage::power; ++Stage::number; - JA_PlaySound(Resource::get()->getSound("stage_change.wav")); + audio_->playSound("stage_change.wav"); balloon_manager_->resetBalloonSpeed(); screen_->flash(FLASH_COLOR, 3); screen_->shake(); @@ -313,7 +313,7 @@ void Game::updateGameStateGameOver() if (game_over_counter_ == GAME_OVER_COUNTER_) { createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_text_game_over")); - JA_FadeOutMusic(1000); + audio_->fadeOutMusic(1000); balloon_manager_->setSounds(true); } @@ -329,8 +329,8 @@ void Game::updateGameStateGameOver() { if (options.audio.enabled) { - const float vol = static_cast(64 * (100 - fade_out_->getValue())) / 100.0f; - JA_SetSoundVolume(to_JA_volume(static_cast(vol))); + const float VOL = static_cast(64 * (100 - fade_out_->getValue())) / 100.0f; + audio_->setSoundVolume(static_cast(VOL)); } } @@ -349,8 +349,8 @@ void Game::updateGameStateGameOver() section::options = section::Options::HI_SCORE_AFTER_PLAYING; if (options.audio.enabled) { - JA_StopChannel(-1); - JA_SetSoundVolume(to_JA_volume(options.audio.sound.volume)); + audio_->stopAllSounds(); + audio_->setSoundVolume(options.audio.sound.volume); } } } @@ -483,7 +483,7 @@ void Game::checkPlayerItemCollision(std::shared_ptr &player) player->addScore(1000); const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(0)->getWidth()) / 2; createItemText(x, game_text_textures_.at(0)); - JA_PlaySound(Resource::get()->getSound("item_pickup.wav")); + audio_->playSound("item_pickup.wav"); break; } case ItemType::GAVINA: @@ -491,7 +491,7 @@ void Game::checkPlayerItemCollision(std::shared_ptr &player) player->addScore(2500); const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(1)->getWidth()) / 2; createItemText(x, game_text_textures_.at(1)); - JA_PlaySound(Resource::get()->getSound("item_pickup.wav")); + audio_->playSound("item_pickup.wav"); break; } case ItemType::PACMAR: @@ -499,7 +499,7 @@ void Game::checkPlayerItemCollision(std::shared_ptr &player) player->addScore(5000); const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(2)->getWidth()) / 2; createItemText(x, game_text_textures_.at(2)); - JA_PlaySound(Resource::get()->getSound("item_pickup.wav")); + audio_->playSound("item_pickup.wav"); break; } case ItemType::DEBIAN: @@ -507,7 +507,7 @@ void Game::checkPlayerItemCollision(std::shared_ptr &player) player->addScore(100000); const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(6)->getWidth()) / 2; createItemText(x, game_text_textures_.at(6)); - JA_PlaySound(Resource::get()->getSound("debian_pickup.wav")); + audio_->playSound("debian_pickup.wav"); break; } case ItemType::CLOCK: @@ -515,7 +515,7 @@ void Game::checkPlayerItemCollision(std::shared_ptr &player) enableTimeStopItem(); const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(5)->getWidth()) / 2; createItemText(x, game_text_textures_.at(5)); - JA_PlaySound(Resource::get()->getSound("item_pickup.wav")); + audio_->playSound("item_pickup.wav"); break; } case ItemType::COFFEE: @@ -532,7 +532,7 @@ void Game::checkPlayerItemCollision(std::shared_ptr &player) const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(4)->getWidth()) / 2; createItemText(x, game_text_textures_.at(4)); } - JA_PlaySound(Resource::get()->getSound("voice_coffee.wav")); + audio_->playSound("voice_coffee.wav"); break; } case ItemType::COFFEE_MACHINE: @@ -541,7 +541,7 @@ void Game::checkPlayerItemCollision(std::shared_ptr &player) coffee_machine_enabled_ = false; const auto x = item->getPosX() + (item->getWidth() - game_text_textures_.at(3)->getWidth()) / 2; createItemText(x, game_text_textures_.at(3)); - JA_PlaySound(Resource::get()->getSound("voice_power_up.wav")); + audio_->playSound("voice_power_up.wav"); break; } default: @@ -570,20 +570,15 @@ void Game::checkBulletCollision() if (tabe_->tryToGetBonus()) { createItem(ItemType::DEBIAN, pos.x, pos.y); - JA_PlaySound(Resource::get()->getSound("debian_drop.wav")); + audio_->playSound("debian_drop.wav"); } else { if (rand() % 3 == 0) { createItem(ItemType::COFFEE, pos.x, pos.y); - // JA_PlaySound(Resource::get()->getSound("item_drop.wav")); } - else - { - // JA_PlaySound(Resource::get()->getSound("tabe_hit.wav")); - } - JA_PlaySound(Resource::get()->getSound("tabe_hit.wav")); + audio_->playSound("tabe_hit.wav"); } break; } @@ -605,7 +600,7 @@ void Game::checkBulletCollision() if (dropped_item != ItemType::COFFEE_MACHINE) { createItem(dropped_item, balloon->getPosX(), balloon->getPosY()); - JA_PlaySound(Resource::get()->getSound("item_drop.wav")); + audio_->playSound("item_drop.wav"); } else { @@ -627,7 +622,7 @@ void Game::checkBulletCollision() updateHiScore(); // Sonido de explosión - JA_PlaySound(Resource::get()->getSound("balloon.wav")); + audio_->playSound("balloon.wav"); // Deshabilita la bala bullet->disable(); @@ -683,7 +678,7 @@ void Game::updateItems() item->update(); if (item->isOnFloor()) { - JA_PlaySound(Resource::get()->getSound("title.wav")); + audio_->playSound("title.wav"); screen_->shake(); } } @@ -910,16 +905,16 @@ void Game::killPlayer(std::shared_ptr &player) // Lo pierde player->removeExtraHit(); throwCoffee(player->getPosX() + (player->getWidth() / 2), player->getPosY() + (player->getHeight() / 2)); - JA_PlaySound(Resource::get()->getSound("coffee_out.wav")); + audio_->playSound("coffee_out.wav"); screen_->shake(); } else { // Si no tiene cafes, muere balloon_manager_->stopAllBalloons(); - JA_PlaySound(Resource::get()->getSound("player_collision.wav")); + audio_->playSound("player_collision.wav"); screen_->shake(); - JA_PlaySound(Resource::get()->getSound("voice_no.wav")); + audio_->playSound("voice_no.wav"); player->setPlayingState(PlayerState::DYING); if (allPlayersAreNotPlaying()) { @@ -939,7 +934,7 @@ void Game::updateTimeStopped() { if (time_stopped_counter_ % 30 == 0) { - JA_PlaySound(Resource::get()->getSound("clock.wav")); + audio_->playSound("clock.wav"); } } else @@ -947,12 +942,12 @@ void Game::updateTimeStopped() if (time_stopped_counter_ % 30 == 0) { balloon_manager_->normalColorsToAllBalloons(); - JA_PlaySound(Resource::get()->getSound("clock.wav")); + audio_->playSound("clock.wav"); } else if (time_stopped_counter_ % 30 == 15) { balloon_manager_->reverseColorsToAllBalloons(); - JA_PlaySound(Resource::get()->getSound("clock.wav")); + audio_->playSound("clock.wav"); } } } @@ -1106,9 +1101,6 @@ void Game::run() checkEvents(); // Tiene que ir antes del render render(); } - - // Vuelve a dejar el sonido como estaba - (demo_.enabled) ? JA_EnableSound(options.audio.sound.enabled) : JA_StopMusic(); } // Inicializa las variables que contienen puntos de ruta para mover objetos @@ -1438,7 +1430,7 @@ void Game::handleFireInput(const std::shared_ptr &player, BulletType bul player->setInput(bulletType == BulletType::UP ? InputAction::FIRE_CENTER : bulletType == BulletType::LEFT ? InputAction::FIRE_LEFT : InputAction::FIRE_RIGHT); createBullet(player->getPosX() + (player->getWidth() / 2) - 6, player->getPosY() + (player->getHeight() / 2), bulletType, player->isPowerUp(), player->getId()); - JA_PlaySound(Resource::get()->getSound("bullet.wav")); + audio_->playSound("bullet.wav"); // Establece un tiempo de espera para el próximo disparo. const int cooldown = player->isPowerUp() ? 5 : options.game.autofire ? 10 @@ -1602,18 +1594,18 @@ void Game::initDemo(int player_id) // Aleatoriza la asignación del fichero con los datos del modo demostracion { - const auto demo1 = rand() % 2; - const auto demo2 = (demo1 == 0) ? 1 : 0; - demo_.data.emplace_back(Resource::get()->getDemoData(demo1)); - demo_.data.emplace_back(Resource::get()->getDemoData(demo2)); + const auto DEMO1 = rand() % 2; + const auto DEMO2 = (DEMO1 == 0) ? 1 : 0; + demo_.data.emplace_back(Resource::get()->getDemoData(DEMO1)); + demo_.data.emplace_back(Resource::get()->getDemoData(DEMO2)); } // Selecciona una pantalla al azar { - constexpr auto demos = 3; - const auto demo = rand() % demos; - const int stages[demos] = {0, 3, 5}; - Stage::number = stages[demo]; + constexpr auto NUM_DEMOS = 3; + const auto DEMO = rand() % NUM_DEMOS; + const int STAGES[NUM_DEMOS] = {0, 3, 5}; + Stage::number = STAGES[DEMO]; } // Actualiza el numero de globos explotados según la fase del modo demostración @@ -1625,8 +1617,8 @@ void Game::initDemo(int player_id) // Activa o no al otro jugador if (rand() % 3 != 0) { - const auto other_player_id = player_id == 1 ? 2 : 1; - auto other_player = getPlayer(other_player_id); + const auto OTHER_PLAYER_ID = player_id == 1 ? 2 : 1; + auto other_player = getPlayer(OTHER_PLAYER_ID); other_player->setPlayingState(PlayerState::PLAYING); } @@ -1640,7 +1632,7 @@ void Game::initDemo(int player_id) } // Deshabilita los sonidos - JA_EnableSound(false); + audio_->disableSound(); // Configura los marcadores scoreboard_->setMode(SCOREBOARD_LEFT_PANEL, ScoreboardMode::DEMO); @@ -1739,32 +1731,10 @@ void Game::initPlayers(int player_id) player->setInvulnerable(false); } -// Pausa la música -void Game::pauseMusic() -{ - if (JA_GetMusicState() == JA_MUSIC_PLAYING && !demo_.enabled) - { - JA_PauseMusic(); - } -} - -// Reanuda la música -void Game::resumeMusic() -{ - if (JA_GetMusicState() == JA_MUSIC_PAUSED && !demo_.enabled) - { - JA_ResumeMusic(); - } -} - // Hace sonar la música void Game::playMusic() { - // Si la música no está sonando - if (JA_GetMusicState() == JA_MUSIC_INVALID || JA_GetMusicState() == JA_MUSIC_STOPPED) - { - JA_PlayMusic(Resource::get()->getMusic("playing.ogg")); - } + audio_->playMusic("playing.ogg"); } // Detiene la música @@ -1772,7 +1742,7 @@ void Game::stopMusic() { if (!demo_.enabled) { - JA_StopMusic(); + audio_->stopMusic(); } } @@ -1856,7 +1826,7 @@ void Game::updateGameStateEnteringPlayer() { setState(GameState::SHOWING_GET_READY_MESSAGE); createMessage({paths_.at(0), paths_.at(1)}, Resource::get()->getTexture("game_text_get_ready")); - JA_PlaySound(Resource::get()->getSound("voice_get_ready.wav")); + audio_->playSound("voice_get_ready.wav"); } } } @@ -1909,7 +1879,7 @@ void Game::updateGameStatePlaying() checkAndUpdateBalloonSpeed(); checkState(); cleanVectors(); - playMusic(); + //playMusic(); } // Vacía los vectores de elementos deshabilitados diff --git a/source/game.h b/source/game.h index 86d6939..964b53a 100644 --- a/source/game.h +++ b/source/game.h @@ -10,22 +10,23 @@ #include "options.h" // Para GameOptions, Options, options #include "player.h" // Para Player #include "utils.h" // Para Demo -class Asset; // lines 14-14 -class Background; // lines 15-15 -class BalloonManager; // lines 16-16 -class Bullet; // lines 18-18 -class Fade; // lines 19-19 -class Input; // lines 20-20 -class Item; // lines 21-21 -class PathSprite; // lines 22-22 -class Scoreboard; // lines 23-23 -class Screen; // lines 24-24 -class SmartSprite; // lines 25-25 -class Tabe; // lines 17-17 -class Texture; // lines 26-26 -enum class BulletType : Uint8; // lines 27-27 -enum class ItemType; // lines 28-28 -struct Path; // lines 29-29 +class Audio; +class Asset; // lines 14-14 +class Background; // lines 15-15 +class BalloonManager; // lines 16-16 +class Bullet; // lines 18-18 +class Fade; // lines 19-19 +class Input; // lines 20-20 +class Item; // lines 21-21 +class PathSprite; // lines 22-22 +class Scoreboard; // lines 23-23 +class Screen; // lines 24-24 +class SmartSprite; // lines 25-25 +class Tabe; // lines 17-17 +class Texture; // lines 26-26 +enum class BulletType : Uint8; // lines 27-27 +enum class ItemType; // lines 28-28 +struct Path; // lines 29-29 // Modo demo constexpr bool GAME_MODE_DEMO_OFF = false; @@ -122,6 +123,7 @@ private: // Objetos y punteros SDL_Renderer *renderer_; // El renderizador de la ventana Screen *screen_; // Objeto encargado de dibujar en pantalla + Audio *audio_; // Objeto encargado de gestionar el audio Asset *asset_; // Objeto que gestiona todos los ficheros de recursos Input *input_; // Manejador de entrada Scoreboard *scoreboard_; // Objeto para dibujar el marcador @@ -371,12 +373,6 @@ private: // Inicializa los jugadores void initPlayers(int player_id); - // Pausa la música - void pauseMusic(); - - // Reanuda la música - void resumeMusic(); - // Hace sonar la música void playMusic(); diff --git a/source/game_logo.cpp b/source/game_logo.cpp index 40d1a1e..ebf0fce 100644 --- a/source/game_logo.cpp +++ b/source/game_logo.cpp @@ -2,7 +2,7 @@ #include // Para SDL_FlipMode #include // Para max #include "animated_sprite.h" // Para AnimatedSprite -#include "jail_audio.h" // Para JA_PlaySound +#include "audio.h" // Para JA_PlaySound #include "param.h" // Para Param, param, ParamGame, ParamTitle #include "resource.h" // Para Resource #include "screen.h" // Para Screen @@ -123,7 +123,7 @@ void GameLogo::update() coffee_crisis_status_ = Status::SHAKING; // Reproduce el efecto sonoro - JA_PlaySound(Resource::get()->getSound("title.wav")); + Audio::get()->playSound("title.wav"); Screen::get()->flash(Color(0xFF, 0xFF, 0xFF), FLASH_LENGHT, FLASH_DELAY); Screen::get()->shake(); } @@ -187,7 +187,7 @@ void GameLogo::update() zoom_ = 1.0f; arcade_edition_sprite_->setZoom(zoom_); shake_.init(1, 2, 8, arcade_edition_sprite_->getX()); - JA_PlaySound(Resource::get()->getSound("title.wav")); + Audio::get()->playSound("title.wav"); Screen::get()->flash(Color(0xFF, 0xFF, 0xFF), FLASH_LENGHT, FLASH_DELAY); Screen::get()->shake(); } diff --git a/source/global_inputs.cpp b/source/global_inputs.cpp index 254c158..7c754b3 100644 --- a/source/global_inputs.cpp +++ b/source/global_inputs.cpp @@ -4,7 +4,7 @@ #include // Para vector #include "asset.h" // Para Asset #include "input.h" // Para Input, InputAction, InputDeviceToUse -#include "jail_audio.h" // Para JA_SetMusicVolume, JA_SetSoundVolume +#include "audio.h" // Para JA_SetMusicVolume, JA_SetSoundVolume #include "lang.h" // Para getText, Code, getNextLangCode, loadFro... #include "notifier.h" // Para Notifier #include "on_screen_help.h" // Para OnScreenHelp @@ -61,16 +61,7 @@ namespace globalInputs void toggleAudio() { options.audio.enabled = !options.audio.enabled; - if (options.audio.enabled) - { - JA_SetMusicVolume(to_JA_volume(options.audio.music.volume)); - JA_SetSoundVolume(to_JA_volume(options.audio.sound.volume)); - } - else - { - JA_SetMusicVolume(0); - JA_SetSoundVolume(0); - } + Audio::get()->enable(options.audio.enabled); Notifier::get()->show({"Audio " + boolToOnOff(options.audio.enabled)}); } @@ -161,7 +152,7 @@ namespace globalInputs switch (section::name) { case section::Name::INTRO: - JA_StopMusic(); + Audio::get()->stopMusic(); /* Continua en el case de abajo */ case section::Name::LOGO: case section::Name::HI_SCORE_TABLE: diff --git a/source/hiscore_table.cpp b/source/hiscore_table.cpp index 38d8d83..78b4d94 100644 --- a/source/hiscore_table.cpp +++ b/source/hiscore_table.cpp @@ -12,7 +12,7 @@ #include "fade.h" // Para Fade, FadeMode, FadeType #include "global_events.h" // Para check #include "global_inputs.h" // Para check, update -#include "jail_audio.h" // Para JA_GetMusicState, JA_Music_state +#include "audio.h" // Para JA_GetMusicState, JA_Music_state #include "lang.h" // Para getText #include "manage_hiscore_table.h" // Para HiScoreEntry #include "options.h" // Para GameOptions, Options, options @@ -62,9 +62,6 @@ void HiScoreTable::update() // Actualiza el contador de ticks ticks_ = SDL_GetTicks(); - // Mantiene la música sonando - updateMusic(); - // Actualiza las posiciones de los sprites de texto updateSprites(); @@ -154,6 +151,7 @@ void HiScoreTable::checkInput() // Bucle para la pantalla de instrucciones void HiScoreTable::run() { + Audio::get()->playMusic("title.ogg"); while (section::name == section::Name::HI_SCORE_TABLE) { checkInput(); @@ -417,19 +415,10 @@ void HiScoreTable::glowEntryNames() } } -// Gestiona la musica -void HiScoreTable::updateMusic() -{ - if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED)) - { - JA_PlayMusic(Resource::get()->getMusic("title.ogg")); - } -} - // Gestiona el contador void HiScoreTable::updateCounter() { - counter_++; + ++counter_; if (counter_ == 150) { diff --git a/source/hiscore_table.h b/source/hiscore_table.h index eb572dd..ce74a9e 100644 --- a/source/hiscore_table.h +++ b/source/hiscore_table.h @@ -91,9 +91,6 @@ private: // Hace brillar los nombres de la tabla de records void glowEntryNames(); - // Gestiona la musica - void updateMusic(); - // Gestiona el contador void updateCounter(); diff --git a/source/instructions.cpp b/source/instructions.cpp index e524787..ab31172 100644 --- a/source/instructions.cpp +++ b/source/instructions.cpp @@ -9,7 +9,7 @@ #include "fade.h" // Para Fade, FadeMode, FadeType #include "global_events.h" // Para check #include "global_inputs.h" // Para check, update -#include "jail_audio.h" // Para JA_GetMusicState, JA_Music_state +#include "audio.h" // Para JA_GetMusicState, JA_Music_state #include "lang.h" // Para getText #include "param.h" // Para Param, param, ParamGame, ParamFade #include "resource.h" // Para Resource @@ -206,9 +206,6 @@ void Instructions::update() // Actualiza el contador de ticks ticks_ = SDL_GetTicks(); - // Mantiene la música sonando - updateMusic(); - // Actualiza el objeto screen Screen::get()->update(); @@ -278,6 +275,7 @@ void Instructions::checkInput() // Bucle para la pantalla de instrucciones void Instructions::run() { + Audio::get()->playMusic("title.ogg"); while (section::name == section::Name::INSTRUCTIONS) { checkInput(); @@ -344,15 +342,6 @@ void Instructions::renderLines(SDL_Renderer *renderer, SDL_Texture *texture, con } } -// Gestiona la musica -void Instructions::updateMusic() -{ - if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED)) - { - JA_PlayMusic(Resource::get()->getMusic("title.ogg")); - } -} - // Gestiona la textura con los graficos void Instructions::updateBackbuffer() { diff --git a/source/instructions.h b/source/instructions.h index 6504e94..0788ee4 100644 --- a/source/instructions.h +++ b/source/instructions.h @@ -96,9 +96,6 @@ private: // Método para renderizar las líneas void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector &lines); - // Gestiona la musica - void updateMusic(); - // Gestiona la textura con los graficos void updateBackbuffer(); diff --git a/source/intro.cpp b/source/intro.cpp index 3c50a64..36eaba0 100644 --- a/source/intro.cpp +++ b/source/intro.cpp @@ -11,7 +11,7 @@ #include // Para move #include "global_events.h" // Para check #include "global_inputs.h" // Para check, update -#include "jail_audio.h" // Para JA_PlayMusic, JA_StopMusic +#include "audio.h" // Para JA_PlayMusic, JA_StopMusic #include "lang.h" // Para getText #include "param.h" // Para Param, ParamGame, param #include "path_sprite.h" // Para PathSprite, PathType @@ -284,7 +284,7 @@ void Intro::render() // Bucle principal void Intro::run() { - JA_PlayMusic(Resource::get()->getMusic("intro.ogg"), 0); + Audio::get()->playMusic("intro.ogg", 0); while (section::name == section::Name::INTRO) { checkInput(); @@ -516,7 +516,7 @@ void Intro::updatePostState() // Finaliza la intro después de 1 segundo if (ELAPSED_TIME >= 1000) { - JA_StopMusic(); + Audio::get()->stopMusic(); section::name = section::Name::TITLE; section::options = section::Options::TITLE_1; } diff --git a/source/jail_audio.cpp b/source/jail_audio.cpp index af6fdb0..ca387fc 100644 --- a/source/jail_audio.cpp +++ b/source/jail_audio.cpp @@ -237,7 +237,6 @@ void JA_PlayMusic(JA_Music_t *music, const int loop) SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume); if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) printf("[ERROR] SDL_BindAudioStream failed!\n"); - // SDL_ResumeAudioStreamDevice(current_music->stream); } void JA_PauseMusic() diff --git a/source/logo.cpp b/source/logo.cpp index 8e3d413..fd84f40 100644 --- a/source/logo.cpp +++ b/source/logo.cpp @@ -4,7 +4,7 @@ #include // Para move #include "global_events.h" // Para check #include "global_inputs.h" // Para check, update -#include "jail_audio.h" // Para JA_FadeOutMusic, JA_PlaySound, JA_StopC... +#include "audio.h" // Para JA_FadeOutMusic, JA_PlaySound, JA_StopC... #include "param.h" // Para Param, ParamGame, param #include "resource.h" // Para Resource #include "screen.h" // Para Screen @@ -60,7 +60,7 @@ Logo::~Logo() { jail_texture_->setColor(255, 255, 255); since_texture_->setColor(255, 255, 255); - JA_StopChannel(-1); + Audio::get()->stopAllSounds(); } // Comprueba el manejador de eventos @@ -84,7 +84,7 @@ void Logo::updateJAILGAMES() { if (counter_ == 30) { - JA_PlaySound(Resource::get()->getSound("logo.wav")); + Audio::get()->playSound("logo.wav"); } if (counter_ > 30) @@ -184,9 +184,7 @@ void Logo::render() // Bucle para el logo del juego void Logo::run() { - // Detiene la música - JA_FadeOutMusic(300); - + Audio::get()->fadeOutMusic(300); while (section::name == section::Name::LOGO) { checkInput(); diff --git a/source/notifier.cpp b/source/notifier.cpp index 0a80ad6..e64f023 100644 --- a/source/notifier.cpp +++ b/source/notifier.cpp @@ -4,12 +4,12 @@ #include // Para string #include #include -#include "jail_audio.h" // Para JA_DeleteSound, JA_LoadSound, JA_Pla... -#include "param.h" // Para Param, param, ParamNotification, Par... -#include "screen.h" // Para Screen -#include "sprite.h" // Para Sprite -#include "text.h" // Para Text -#include "texture.h" // Para Texture +#include "audio.h" // Para JA_DeleteSound, JA_LoadSound, JA_Pla... +#include "param.h" // Para Param, param, ParamNotification, Par... +#include "screen.h" // Para Screen +#include "sprite.h" // Para Sprite +#include "text.h" // Para Text +#include "texture.h" // Para Texture #include "resource.h" // [SINGLETON] @@ -76,7 +76,7 @@ void Notifier::update() if (notifications_[i].state == NotificationStatus::RISING) { // Reproduce el sonido de la notificación - JA_PlaySound(Resource::get()->getSound("notify.wav")); + Audio::get()->playSound("notify.wav"); } } } diff --git a/source/on_screen_help.h b/source/on_screen_help.h index 0487435..879ae9b 100644 --- a/source/on_screen_help.h +++ b/source/on_screen_help.h @@ -18,7 +18,7 @@ enum class OnScreenHelpStatus class OnScreenHelp { private: - // [SINGLETON] Objeto screen privado para Don Melitón + // [SINGLETON] Objeto screen privado static OnScreenHelp *onScreenHelp; SDL_Texture *texture; // Textura donde dibujar diff --git a/source/options.cpp b/source/options.cpp index f96eaef..bce59fb 100644 --- a/source/options.cpp +++ b/source/options.cpp @@ -325,13 +325,6 @@ bool setOptions(const std::string &var, const std::string &value) return success; } -// Convierte valores de 0 a 100 en valores de 0 a 128 -int to_JA_volume(int vol) -{ - vol = vol * 1.28f; - return std::clamp(vol, 0, 128); -} - // Asigna el teclado al jugador void setKeyboardToPlayer(int player_id) { diff --git a/source/options.h b/source/options.h index 5de35bc..4dbd321 100644 --- a/source/options.h +++ b/source/options.h @@ -118,9 +118,6 @@ bool loadOptionsFile(std::string file_path); // Guarda el fichero de configuración bool saveOptionsFile(std::string file_path); -// Convierte valores de 0 a 100 en valores de 0 a 128 -int to_JA_volume(int vol); - // Asigna el teclado al jugador void setKeyboardToPlayer(int player_id); diff --git a/source/player.cpp b/source/player.cpp index 736eb4d..2630d02 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -6,7 +6,7 @@ #include // Para array #include "animated_sprite.h" // Para AnimatedSprite #include "input.h" // Para InputAction -#include "jail_audio.h" // Para JA_PlaySound +#include "audio.h" // Para JA_PlaySound #include "param.h" // Para Param, ParamGame, param #include "resource.h" // Para Resource #include "scoreboard.h" // Para Scoreboard, ScoreboardMode @@ -221,7 +221,7 @@ void Player::move() ++step_counter_; if (step_counter_ % 10 == 0) { - JA_PlaySound(Resource::get()->getSound("walk.wav")); + Audio::get()->playSound("walk.wav"); } switch (id_) @@ -252,7 +252,7 @@ void Player::move() ++step_counter_; if (step_counter_ % 10 == 0) { - JA_PlaySound(Resource::get()->getSound("walk.wav")); + Audio::get()->playSound("walk.wav"); } switch (id_) @@ -752,7 +752,7 @@ void Player::decContinueCounter() } else { - JA_PlaySound(Resource::get()->getSound("continue_clock.wav")); + Audio::get()->playSound("continue_clock.wav"); } } @@ -798,5 +798,5 @@ void Player::shiftSprite() void Player::playRandomBubbleSound() { const std::vector sounds = {"bubble1.wav", "bubble2.wav", "bubble3.wav", "bubble4.wav"}; - JA_PlaySound(Resource::get()->getSound(sounds.at(rand() % sounds.size()))); + Audio::get()->playSound(sounds.at(rand() % sounds.size())); } \ No newline at end of file diff --git a/source/resource.cpp b/source/resource.cpp index 1bc09da..b90efa1 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -3,7 +3,7 @@ #include // Para find_if #include // Para runtime_error #include "asset.h" // Para Asset, AssetType -#include "jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_LoadMusic +#include "jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_LoadMusic #include "lang.h" // Para getText #include "screen.h" // Para Screen #include "text.h" // Para Text, loadTextFile diff --git a/source/resource.h b/source/resource.h index 8741586..4bb706f 100644 --- a/source/resource.h +++ b/source/resource.h @@ -79,7 +79,7 @@ struct ResourceAnimation class Resource { private: - // [SINGLETON] Objeto resource privado para Don Melitón + // [SINGLETON] Objeto resource privado static Resource *resource_; std::vector sounds_; // Vector con los sonidos diff --git a/source/scoreboard.h b/source/scoreboard.h index f776edb..ff2f245 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -45,7 +45,7 @@ struct Panel class Scoreboard { private: - // [SINGLETON] Objeto scoreboard privado para Don Melitón + // [SINGLETON] Objeto scoreboard privado static Scoreboard *scoreboard_; // Objetos y punteros diff --git a/source/tabe.cpp b/source/tabe.cpp index e587dc6..8f4331a 100644 --- a/source/tabe.cpp +++ b/source/tabe.cpp @@ -3,7 +3,7 @@ #include // Para SDL_FlipMode #include // Para rand, abs #include // Para max -#include "jail_audio.h" // Para JA_PlaySound +#include "audio.h" // Para JA_PlaySound #include "param.h" // Para Param, ParamGame, param #include "resource.h" // Para Resource #include "utils.h" // Para Zone @@ -131,7 +131,7 @@ void Tabe::setRandomFlyPath(TabeDirection direction, int lenght) direction_ = direction; fly_distance_ = lenght; waiting_counter_ = 5 + rand() % 15; - JA_PlaySound(Resource::get()->getSound("tabe.wav")); + Audio::get()->playSound("tabe.wav"); constexpr float SPEED = 2.0f; diff --git a/source/title.cpp b/source/title.cpp index ba168cc..46f4b38 100644 --- a/source/title.cpp +++ b/source/title.cpp @@ -10,7 +10,7 @@ #include "game_logo.h" // Para GameLogo #include "global_inputs.h" // Para check, update #include "input.h" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_R... -#include "jail_audio.h" // Para JA_GetMusicState, JA_FadeOutMusic, JA_... +#include "audio.h" // Para JA_GetMusicState, JA_FadeOutMusic, JA_... #include "lang.h" // Para getText #include "global_events.h" // Para handleEvent #include "notifier.h" // Para Notifier @@ -55,7 +55,7 @@ Title::Title() Title::~Title() { Resource::get()->getTexture("smb2.gif")->setPalette(0); - JA_StopChannel(-1); + Audio::get()->stopAllSounds(); } // Actualiza las variables del objeto @@ -203,8 +203,8 @@ void Title::checkInput() { if ((state_ == TitleState::LOGO_FINISHED || ALLOW_TITLE_ANIMATION_SKIP) && !fade_->isEnabled()) { - JA_PlaySound(Resource::get()->getSound("game_start.wav")); - JA_FadeOutMusic(1500); + Audio::get()->playSound("game_start.wav"); + Audio::get()->fadeOutMusic(1500); switch (CONTROLLER.player_id) { case 1: @@ -325,7 +325,7 @@ void Title::updateFade() // Se ha pulsado para jugar section::name = section::Name::GAME; section::options = selection_; - JA_StopMusic(); + Audio::get()->stopMusic(); } } } @@ -342,6 +342,7 @@ void Title::updateState() if (game_logo_->hasFinished()) { state_ = TitleState::LOGO_FINISHED; + Audio::get()->playMusic("title.ogg"); } break; } @@ -350,12 +351,6 @@ void Title::updateState() // El contador solo sube si no estamos definiendo botones counter_ = define_buttons_->isEnabled() ? 0 : counter_ + 1; - // Reproduce la música - if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED)) - { - JA_PlayMusic(Resource::get()->getMusic("title.ogg")); - } - // Actualiza el logo con el título del juego game_logo_->update();