From f786cb777633d034740893bcbb7b18a068cb9694 Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Fri, 1 Nov 2024 13:05:11 +0100 Subject: [PATCH] Implementat el final del joc --- data/gfx/player/player.ani | 2 +- source/game.cpp | 226 ++++++++++++++------------ source/game.h | 21 ++- source/param.cpp | 1 + source/player.cpp | 320 ++++++++++++++----------------------- source/player.h | 113 ++++++------- source/scoreboard.cpp | 106 +++++------- source/scoreboard.h | 3 +- 8 files changed, 349 insertions(+), 443 deletions(-) diff --git a/data/gfx/player/player.ani b/data/gfx/player/player.ani index 3ed8cfa..1fe6fe5 100644 --- a/data/gfx/player/player.ani +++ b/data/gfx/player/player.ani @@ -79,7 +79,7 @@ frames=32,33,34,35 [/animation] [animation] -name=celeb +name=celebration speed=10 loop=-1 frames=36,36,36,36,36,36,37,38,39,40,40,40,40,40,40,39,39,39,40,40,40,39,39,39,38,37,36,36,36 diff --git a/source/game.cpp b/source/game.cpp index 4e08cd1..fb2fe38 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -85,6 +85,14 @@ Game::Game(int player_id, int current_stage, bool demo) initPaths(); setTotalPower(); +#ifdef DEBUG + // Si se empieza en una fase que no es la primera + for (int i = 0; i < current_stage_; ++i) + { + balloons_popped_ += balloon_formations_->getStage(i).power_to_complete; + } +#endif + // Crea los primeros globos y el mensaje de inicio if (!demo_.enabled) { @@ -320,68 +328,41 @@ void Game::renderPlayers() // Comprueba si hay cambio de fase y actualiza las variables void Game::updateStage() { - if (current_power_ >= balloon_formations_->getStage(current_stage_).power_to_complete) + if (state_ == GameState::PLAYING) { - // Cambio de fase - ++current_stage_; - current_power_ = 0; - JA_PlaySound(Resource::get()->getSound("stage_change.wav")); - balloon_speed_ = default_balloon_speed_; - setBalloonSpeed(balloon_speed_); - screen_->flash(flash_color, 100); - screen_->shake(); - - // Ha llegado al final el juego - if (status_ == GameStatus::PLAYING && current_stage_ == 10) + if (current_power_ >= balloon_formations_->getStage(current_stage_).power_to_complete) { - status_ = GameStatus::COMPLETED; - stopMusic(); - current_stage_ = 9; // Deja el valor dentro de los limites - destroyAllBalloons(); // Destruye a todos los globos - destroyAllItems(); // Destruye todos los items - current_power_ = 0; // Vuelve a dejar el poder a cero, por lo que hubiera podido subir al destruir todos los globos + // Cambio de fase + ++current_stage_; + current_power_ = 0; + JA_PlaySound(Resource::get()->getSound("stage_change.wav")); + balloon_speed_ = default_balloon_speed_; + setBalloonSpeed(balloon_speed_); + screen_->flash(flash_color, 100); + screen_->shake(); - for (auto &player : players_) - if (player->isPlaying()) - { - player->addScore(1000000); - player->setStatusPlaying(player->IsEligibleForHighScore() ? PlayerStatus::ENTERING_NAME_GAME_COMPLETED : PlayerStatus::GAME_COMPLETED); - } + // Escribe el texto por pantalla + if (current_stage_ < 10) + { + const auto stage_number = balloon_formations_->getStage(current_stage_).number; + std::vector paths = {paths_.at(2), paths_.at(3)}; + if (stage_number == 10) + createMessage(paths, Resource::get()->getTexture("last_stage")); else { - player->setStatusPlaying(PlayerStatus::GAME_OVER); + auto text = std::make_unique(Resource::get()->getTexture("04b_25.png"), Resource::get()->getTextFile("04b_25.txt")); + const std::string caption = std::to_string(10 - current_stage_) + lang::getText(38); + createMessage(paths, text->writeToTexture(caption, 2, -2)); } - - updateHiScore(); - } - - // Escribe el texto por pantalla - if (status_ == GameStatus::PLAYING) - { - const auto stage_number = balloon_formations_->getStage(current_stage_).number; - std::vector paths = {paths_.at(2), paths_.at(3)}; - if (stage_number == 10) - createMessage(paths, Resource::get()->getTexture("last_stage")); - else - { - auto text = std::make_unique(Resource::get()->getTexture("04b_25.png"), Resource::get()->getTextFile("04b_25.txt")); - const std::string caption = std::to_string(10 - current_stage_) + lang::getText(38); - createMessage(paths, text->writeToTexture(caption, 2, -2)); } } - else - { - createMessage({paths_.at(4), paths_.at(5)}, Resource::get()->getTexture("congratulations")); - createMessage({paths_.at(6), paths_.at(7)}, Resource::get()->getTexture("1000000_points")); - } } } // Actualiza el estado de fin de la partida -void Game::updateGameOver() +void Game::updateGameOverState() { - // Si todos estan en estado de Game Over y no hay mensajes por pantalla - if (allPlayersAreGameOver() && path_sprites_.empty()) + if (state_ == GameState::GAME_OVER) { if (game_over_counter_ > 0) { @@ -411,6 +392,71 @@ void Game::updateGameOver() } } +// Gestiona eventos para el estado del final del juego +void Game::updateCompletedState() +{ + if (state_ == GameState::COMPLETED) + { + // Para la música y elimina todos los globos e items + if (game_completed_counter_ == 0) + { + stopMusic(); + current_stage_ = 9; // Deja el valor dentro de los limites + destroyAllBalloons(); // Destruye a todos los globos + destroyAllItems(); // Destruye todos los items + current_power_ = 0; // Vuelve a dejar el poder a cero, por lo que hubiera podido subir al destruir todos los globos + } + + // Comienza las celebraciones + // Muestra el mensaje de felicitación y da los puntos a los jugadores + if (game_completed_counter_ == 200) + { + createMessage({paths_.at(4), paths_.at(5)}, Resource::get()->getTexture("congratulations")); + createMessage({paths_.at(6), paths_.at(7)}, Resource::get()->getTexture("1000000_points")); + + for (auto &player : players_) + if (player->isPlaying()) + { + player->addScore(1000000); + player->setPlayingState(PlayerState::CELEBRATING); + } + else + { + player->setPlayingState(PlayerState::GAME_OVER); + } + + updateHiScore(); + } + + // Termina las celebraciones + if (game_completed_counter_ == 500) + { + for (auto &player : players_) + if (player->isCelebrating()) + { + player->setPlayingState(player->IsEligibleForHighScore() ? PlayerState::ENTERING_NAME_GAME_COMPLETED : PlayerState::GAME_COMPLETED); + } + } + + // Incrementa el contador al final + ++game_completed_counter_; + } +} + +// Comprueba el estado del juego +void Game::checkState() +{ + if (state_ != GameState::COMPLETED && current_stage_ == 10) + { + state_ = GameState::COMPLETED; + } + + if (state_ != GameState::GAME_OVER && allPlayersAreGameOver()) + { + state_ = GameState::GAME_OVER; + } +} + // Actualiza los globos void Game::updateBalloons() { @@ -1036,7 +1082,7 @@ void Game::killPlayer(std::shared_ptr &player) JA_PlaySound(Resource::get()->getSound("player_collision.wav")); screen_->shake(); JA_PlaySound(Resource::get()->getSound("coffeeout.wav")); - player->setStatusPlaying(PlayerStatus::DYING); + player->setPlayingState(PlayerState::DYING); allPlayersAreNotPlaying() ? stopMusic() : resumeMusic(); } } @@ -1096,8 +1142,7 @@ void Game::update() #ifdef RECORDING updateRecording(); #endif - updateNormalGame(); - updateCompletedGame(); + updateGame(); checkMusicStatus(); screen_->update(); @@ -1109,7 +1154,7 @@ void Game::update() void Game::updateBackground() { // Si el juego está completado, se reduce la velocidad de las nubes - if (status_ == GameStatus::COMPLETED) + if (state_ == GameState::COMPLETED) balloons_popped_ = (balloons_popped_ > 400) ? (balloons_popped_ - 25) : 200; // Calcula la velocidad en función de los globos explotados y el total de globos a explotar para acabar el juego @@ -1212,7 +1257,7 @@ void Game::checkMusicStatus() if (JA_GetMusicState() == JA_MUSIC_INVALID || JA_GetMusicState() == JA_MUSIC_STOPPED) // Si se ha completado el juego o los jugadores han terminado, detiene la música - status_ == GameStatus::COMPLETED || allPlayersAreGameOver() ? JA_StopMusic() : JA_PlayMusic(Resource::get()->getMusic("playing.ogg")); + state_ == GameState::COMPLETED || allPlayersAreGameOver() ? JA_StopMusic() : JA_PlayMusic(Resource::get()->getMusic("playing.ogg")); } // Bucle para el juego @@ -1432,7 +1477,7 @@ void Game::checkEvents() } case SDLK_8: { - players_.at(0)->setStatusPlaying(PlayerStatus::GAME_COMPLETED); + players_.at(0)->setPlayingState(PlayerState::GAME_COMPLETED); } default: break; @@ -1502,7 +1547,7 @@ void Game::checkAndUpdatePlayerStatus(int activePlayerIndex, int inactivePlayerI { if (players_[activePlayerIndex]->isGameOver() && !players_[inactivePlayerIndex]->isGameOver() && !players_[inactivePlayerIndex]->isWaiting()) { - players_[activePlayerIndex]->setStatusPlaying(PlayerStatus::WAITING); + players_[activePlayerIndex]->setPlayingState(PlayerState::WAITING); } } @@ -1520,7 +1565,7 @@ void Game::checkPlayersStatusPlaying() // Entonces los pone en estado de Game Over for (auto &player : players_) { - player->setStatusPlaying(PlayerStatus::GAME_OVER); + player->setPlayingState(PlayerState::GAME_OVER); } } @@ -1742,7 +1787,7 @@ void Game::handlePlayerContinue(const std::shared_ptr &player) const auto controllerIndex = player->getController(); if (input_->checkInput(InputType::START, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].device_type, options.controller[controllerIndex].index)) { - player->setStatusPlaying(PlayerStatus::PLAYING); + player->setPlayingState(PlayerState::PLAYING); } // Disminuye el contador de continuación si se presiona cualquier botón de disparo. @@ -1766,8 +1811,8 @@ void Game::handleNameInput(const std::shared_ptr &player) { player->setInput(InputType::START); addScoreToScoreBoard(player->getRecordName(), player->getScore()); - const auto status = player->getStatusPlaying(); - player->setStatusPlaying(status == PlayerStatus::ENTERING_NAME ? PlayerStatus::CONTINUE : PlayerStatus::GAME_COMPLETED); + const auto status = player->getPlayingState(); + player->setPlayingState(status == PlayerState::ENTERING_NAME ? PlayerState::CONTINUE : PlayerState::GAME_COMPLETED); } else { @@ -1796,8 +1841,8 @@ void Game::handleNameInput(const std::shared_ptr &player) { player->setInput(InputType::START); addScoreToScoreBoard(player->getRecordName(), player->getScore()); - const auto status = player->getStatusPlaying(); - player->setStatusPlaying(status == PlayerStatus::ENTERING_NAME ? PlayerStatus::CONTINUE : PlayerStatus::GAME_COMPLETED); + const auto status = player->getPlayingState(); + player->setPlayingState(status == PlayerState::ENTERING_NAME ? PlayerState::CONTINUE : PlayerState::GAME_COMPLETED); } } @@ -1820,8 +1865,7 @@ void Game::initDemo(int player_id) current_stage_ = stages[demo]; } - // Actualiza el numero de globos explotados según la fase del modo - // demostración + // Actualiza el numero de globos explotados según la fase del modo demostración for (int i = 0; i < current_stage_; ++i) { balloons_popped_ += balloon_formations_->getStage(i).power_to_complete; @@ -1832,7 +1876,7 @@ void Game::initDemo(int player_id) { const auto other_player_id = player_id == 1 ? 2 : 1; auto other_player = getPlayer(other_player_id); - other_player->setStatusPlaying(PlayerStatus::PLAYING); + other_player->setPlayingState(PlayerState::PLAYING); } // Asigna cafes a los jugadores @@ -1939,7 +1983,7 @@ void Game::initPlayers(int player_id) // Activa el jugador que coincide con el "player_id" auto player = getPlayer(player_id); - player->setStatusPlaying(PlayerStatus::PLAYING); + player->setPlayingState(PlayerState::PLAYING); player->setInvulnerable(false); } @@ -2023,15 +2067,15 @@ void Game::updateRecording() #endif // Actualiza las variables durante el transcurso normal del juego -void Game::updateNormalGame() +void Game::updateGame() { - if (status_ == GameStatus::PLAYING && !paused_) + if (!paused_) { #ifdef DEBUG - if (auto_pop_balloons_) + if (auto_pop_balloons_ && state_ == GameState::PLAYING) { - balloons_popped_++; - increaseStageCurrentPower(1); + balloons_popped_ += 5; + increaseStageCurrentPower(5); } #endif fade_->update(); @@ -2044,7 +2088,8 @@ void Game::updateNormalGame() moveBullets(); updateItems(); updateStage(); - updateGameOver(); + updateGameOverState(); + updateCompletedState(); updateSmartSprites(); updatePathSprites(); updateTimeStopped(); @@ -2053,36 +2098,17 @@ void Game::updateNormalGame() checkBulletBalloonCollision(); updateMenace(); checkAndUpdateBalloonSpeed(); - freeBullets(); - freeBalloons(); - freeItems(); - freeSmartSprites(); - freePathSprites(); + checkState(); + cleanVectors(); } } -// Actualiza las variables durante el transcurso normal del juego -void Game::updateCompletedGame() +// Vacía los vectores de elementos deshabilitados +void Game::cleanVectors() { - if (status_ == GameStatus::COMPLETED && !paused_) - { - fade_->update(); - updatePlayers(); - checkPlayersStatusPlaying(); - updateScoreboard(); - updateBackground(); - updateBalloons(); - explosions_->update(); - moveBullets(); - updateItems(); - updateGameOver(); - updateSmartSprites(); - updatePathSprites(); - checkBulletBalloonCollision(); - freeBullets(); - freeBalloons(); - freeItems(); - freeSmartSprites(); - freePathSprites(); - } + freeBullets(); + freeBalloons(); + freeItems(); + freeSmartSprites(); + freePathSprites(); } \ No newline at end of file diff --git a/source/game.h b/source/game.h index dcac823..f5a533c 100644 --- a/source/game.h +++ b/source/game.h @@ -65,10 +65,11 @@ class Game { private: // Enum - enum class GameStatus + enum class GameState { PLAYING, COMPLETED, + GAME_OVER, }; // Contadores @@ -180,7 +181,7 @@ private: int power_ball_counter_ = 0; // Contador de formaciones enemigas entre la aparicion de una PowerBall y otra int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases - GameStatus status_ = GameStatus::PLAYING; // Estado + GameState state_ = GameState::PLAYING; // Estado #ifdef DEBUG bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados #endif @@ -216,7 +217,7 @@ private: void updateStage(); // Actualiza el estado de fin de la partida - void updateGameOver(); + void updateGameOverState(); // Actualiza los globos void updateBalloons(); @@ -350,9 +351,6 @@ private: // Inicializa las variables que contienen puntos de ruta para mover objetos void initPaths(); - // Pinta diferentes mensajes en la pantalla - void renderMessages(); - // Habilita el efecto del item de detener el tiempo void enableTimeStopItem(); @@ -471,11 +469,20 @@ private: void updateRecording(); #endif // Actualiza las variables durante el transcurso normal del juego - void updateNormalGame(); + void updateGame(); // Actualiza las variables durante el transcurso del final del juego void updateCompletedGame(); + // Gestiona eventos para el estado del final del juego + void updateCompletedState(); + + // Comprueba el estado del juego + void checkState(); + + // Vacía los vectores de elementos deshabilitados + void cleanVectors(); + public: // Constructor Game(int playerID, int current_stage, bool demo); diff --git a/source/param.cpp b/source/param.cpp index 4b98408..23fd92d 100644 --- a/source/param.cpp +++ b/source/param.cpp @@ -23,6 +23,7 @@ void initParam() param.game.item_size = 20; param.game.game_area.rect = {0, 0, param.game.width, param.game.height}; param.game.play_area.rect = {0, 0, param.game.width, 216}; + param.game.enter_name_seconds = 30; precalculateZones(); // SCOREBOARD diff --git a/source/player.cpp b/source/player.cpp index 93b961e..51196e2 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -39,9 +39,9 @@ void Player::init() // Inicializa variables de estado pos_x_ = default_pos_x_; pos_y_ = default_pos_y_; - status_walking_ = PlayerStatus::WALKING_STOP; - status_firing_ = PlayerStatus::FIRING_NONE; - status_playing_ = PlayerStatus::WAITING; + walking_state_ = PlayerState::WALKING_STOP; + firing_state_ = PlayerState::FIRING_NONE; + playing_state_ = PlayerState::WAITING; invulnerable_ = true; invulnerable_counter_ = INVULNERABLE_COUNTER_; power_up_ = false; @@ -70,19 +70,15 @@ void Player::init() // Actua en consecuencia de la entrada recibida void Player::setInput(InputType input) { - switch (status_playing_) + switch (playing_state_) { - case PlayerStatus::PLAYING: + case PlayerState::PLAYING: { setInputPlaying(input); break; } - case PlayerStatus::ENTERING_NAME: - { - setInputEnteringName(input); - break; - } - case PlayerStatus::ENTERING_NAME_GAME_COMPLETED: + case PlayerState::ENTERING_NAME: + case PlayerState::ENTERING_NAME_GAME_COMPLETED: { setInputEnteringName(input); break; @@ -100,34 +96,34 @@ void Player::setInputPlaying(InputType input) case InputType::LEFT: { vel_x_ = -BASE_SPEED_; - setWalkingStatus(PlayerStatus::WALKING_LEFT); + setWalkingState(PlayerState::WALKING_LEFT); break; } case InputType::RIGHT: { vel_x_ = BASE_SPEED_; - setWalkingStatus(PlayerStatus::WALKING_RIGHT); + setWalkingState(PlayerState::WALKING_RIGHT); break; } case InputType::FIRE_CENTER: { - setFiringStatus(PlayerStatus::FIRING_UP); + setFiringState(PlayerState::FIRING_UP); break; } case InputType::FIRE_LEFT: { - setFiringStatus(PlayerStatus::FIRING_LEFT); + setFiringState(PlayerState::FIRING_LEFT); break; } case InputType::FIRE_RIGHT: { - setFiringStatus(PlayerStatus::FIRING_RIGHT); + setFiringState(PlayerState::FIRING_RIGHT); break; } default: { vel_x_ = 0; - setWalkingStatus(PlayerStatus::WALKING_STOP); + setWalkingState(PlayerState::WALKING_STOP); break; } } @@ -162,9 +158,9 @@ void Player::setInputEnteringName(InputType input) // Mueve el jugador a la posición y animación que le corresponde void Player::move() { - switch (status_playing_) + switch (playing_state_) { - case PlayerStatus::PLAYING: + case PlayerState::PLAYING: { // Mueve el jugador a derecha o izquierda pos_x_ += vel_x_; @@ -177,7 +173,7 @@ void Player::move() shiftSprite(); break; } - case PlayerStatus::DYING: + case PlayerState::DYING: { // Si el cadaver abandona el area de juego por los laterales lo hace rebotar if ((player_sprite_->getPosX() < param.game.play_area.rect.x) || (player_sprite_->getPosX() + WIDTH_ > play_area_.w)) @@ -185,10 +181,10 @@ void Player::move() // Si el cadaver abandona el area de juego por abajo if (player_sprite_->getPosY() > param.game.play_area.rect.h) - setStatusPlaying(PlayerStatus::DIED); + setPlayingState(PlayerState::DIED); break; } - case PlayerStatus::GAME_COMPLETED: + case PlayerState::GAME_COMPLETED: { switch (id_) { @@ -208,7 +204,7 @@ void Player::move() shiftSprite(); if (pos_x_ == min_x || pos_x_ == max_x) - setStatusPlaying(PlayerStatus::GAME_OVER); + setPlayingState(PlayerState::GAME_OVER); break; } default: @@ -227,28 +223,22 @@ void Player::render() player_sprite_->render(); } -// Establece el estado del jugador cuando camina -void Player::setWalkingStatus(PlayerStatus status) { status_walking_ = status; } - -// Establece el estado del jugador cuando dispara -void Player::setFiringStatus(PlayerStatus status) { status_firing_ = status; } - // Establece la animación correspondiente al estado void Player::setAnimation() { // Crea cadenas de texto para componer el nombre de la animación - const std::string a_walking = status_walking_ == PlayerStatus::WALKING_STOP ? "stand" : "walk"; - const std::string a_firing = status_firing_ == PlayerStatus::FIRING_UP ? "centershoot" : "sideshoot"; - const std::string a_cooling = status_firing_ == PlayerStatus::COOLING_UP ? "centershoot" : "sideshoot"; + const std::string a_walking = walking_state_ == PlayerState::WALKING_STOP ? "stand" : "walk"; + const std::string a_firing = firing_state_ == PlayerState::FIRING_UP ? "centershoot" : "sideshoot"; + const std::string a_cooling = firing_state_ == PlayerState::COOLING_UP ? "centershoot" : "sideshoot"; - const SDL_RendererFlip flip_walk = status_walking_ == PlayerStatus::WALKING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; - const SDL_RendererFlip flip_fire = status_firing_ == PlayerStatus::FIRING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; - const SDL_RendererFlip flip_cooling = status_firing_ == PlayerStatus::COOLING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; + const SDL_RendererFlip flip_walk = walking_state_ == PlayerState::WALKING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; + const SDL_RendererFlip flip_fire = firing_state_ == PlayerState::FIRING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; + const SDL_RendererFlip flip_cooling = firing_state_ == PlayerState::COOLING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; // Establece la animación a partir de las cadenas if (isPlaying() || isEnteringNameGameCompleted() || isGameCompleted()) { - if (status_firing_ == PlayerStatus::FIRING_NONE) + if (firing_state_ == PlayerState::FIRING_NONE) { // No esta disparando player_sprite_->setCurrentAnimation(a_walking); player_sprite_->setFlip(flip_walk); @@ -266,34 +256,20 @@ void Player::setAnimation() player_sprite_->setFlip(a_firing == "centershoot" ? flip_walk : flip_fire); } } - else + else if (isDying() || hasDied()) { player_sprite_->setCurrentAnimation("death"); } + else if (isCelebrating()) + { + player_sprite_->setCurrentAnimation("celebration"); + } // Actualiza las animaciones de los sprites player_sprite_->update(); // Hace avanzar las animaciones y mueve el cadaver del jugador power_sprite_->update(); } -// Obtiene el valor de la variable -int Player::getPosX() const { return static_cast(pos_x_); } - -// Obtiene el valor de la variable -int Player::getPosY() const { return pos_y_; } - -// Obtiene el valor de la variable -int Player::getWidth() const { return WIDTH_; } - -// Obtiene el valor de la variable -int Player::getHeight() const { return HEIGHT_; } - -// Indica si el jugador puede disparar -bool Player::canFire() const { return cooldown_ > 0 ? false : true; } - -// Establece el valor de la variable -void Player::setFireCooldown(int time) { cooldown_ = time; } - // Actualiza el valor de la variable void Player::updateCooldown() { @@ -306,16 +282,16 @@ void Player::updateCooldown() if (!isCooling()) { cooling_status_counter_ = 40; - switch (status_firing_) + switch (firing_state_) { - case PlayerStatus::FIRING_LEFT: - status_firing_ = PlayerStatus::COOLING_LEFT; + case PlayerState::FIRING_LEFT: + firing_state_ = PlayerState::COOLING_LEFT; break; - case PlayerStatus::FIRING_RIGHT: - status_firing_ = PlayerStatus::COOLING_RIGHT; + case PlayerState::FIRING_RIGHT: + firing_state_ = PlayerState::COOLING_RIGHT; break; - case PlayerStatus::FIRING_UP: - status_firing_ = PlayerStatus::COOLING_UP; + case PlayerState::FIRING_UP: + firing_state_ = PlayerState::COOLING_UP; break; default: break; @@ -327,7 +303,7 @@ void Player::updateCooldown() } else { - setFiringStatus(PlayerStatus::FIRING_NONE); + setFiringState(PlayerState::FIRING_NONE); } } } @@ -346,12 +322,6 @@ void Player::update() updateScoreboard(); } -// Obtiene la puntuación del jugador -int Player::getScore() const { return score_; } - -// Asigna un valor a la puntuación del jugador -void Player::setScore(int score) { score_ = score; } - // Incrementa la puntuación del jugador void Player::addScore(int score) { @@ -361,50 +331,18 @@ void Player::addScore(int score) } } -// Indica si el jugador está jugando -bool Player::isPlaying() const { return status_playing_ == PlayerStatus::PLAYING; } - -// Indica si el jugador está continuando -bool Player::isContinue() const { return status_playing_ == PlayerStatus::CONTINUE; } - -// Indica si el jugador está esperando -bool Player::isWaiting() const { return status_playing_ == PlayerStatus::WAITING; } - -// Indica si el jugador está introduciendo su nombre -bool Player::isEnteringName() const { return status_playing_ == PlayerStatus::ENTERING_NAME; } - -// Indica si el jugador está muriendose -bool Player::isDying() const { return status_playing_ == PlayerStatus::DYING; } - -// Indica si el jugador ha terminado de morir -bool Player::hasDied() const { return status_playing_ == PlayerStatus::DIED; } - -// Indica si el jugador ya ha terminado de jugar -bool Player::isGameOver() const { return status_playing_ == PlayerStatus::GAME_OVER; } - -// Indica si el jugador está introduciendo su nombre una vez ha completado el juego -bool Player::isEnteringNameGameCompleted() const { return status_playing_ == PlayerStatus::ENTERING_NAME_GAME_COMPLETED; } - -// Indica si el jugador ha completado el juego -bool Player::isGameCompleted() const { return status_playing_ == PlayerStatus::GAME_COMPLETED; } - // Actualiza el panel del marcador void Player::updateScoreboard() { - switch (status_playing_) + switch (playing_state_) { - case PlayerStatus::CONTINUE: + case PlayerState::CONTINUE: { Scoreboard::get()->setContinue(getScoreBoardPanel(), getContinueCounter()); break; } - case PlayerStatus::ENTERING_NAME: - { - Scoreboard::get()->setRecordName(getScoreBoardPanel(), getRecordName()); - Scoreboard::get()->setSelectorPos(getScoreBoardPanel(), getRecordNamePos()); - break; - } - case PlayerStatus::ENTERING_NAME_GAME_COMPLETED: + case PlayerState::ENTERING_NAME: + case PlayerState::ENTERING_NAME_GAME_COMPLETED: { Scoreboard::get()->setRecordName(getScoreBoardPanel(), getRecordName()); Scoreboard::get()->setSelectorPos(getScoreBoardPanel(), getRecordNamePos()); @@ -425,20 +363,20 @@ void Player::setScoreboardMode(ScoreboardMode mode) } // Establece el estado del jugador en el juego -void Player::setStatusPlaying(PlayerStatus value) +void Player::setPlayingState(PlayerState state) { - status_playing_ = value; + playing_state_ = state; - switch (status_playing_) + switch (playing_state_) { - case PlayerStatus::PLAYING: + case PlayerState::PLAYING: { init(); - status_playing_ = PlayerStatus::PLAYING; + playing_state_ = PlayerState::PLAYING; setScoreboardMode(ScoreboardMode::SCORE); break; } - case PlayerStatus::CONTINUE: + case PlayerState::CONTINUE: { // Inicializa el contador de continuar continue_ticks_ = SDL_GetTicks(); @@ -447,17 +385,17 @@ void Player::setStatusPlaying(PlayerStatus value) setScoreboardMode(ScoreboardMode::CONTINUE); break; } - case PlayerStatus::WAITING: + case PlayerState::WAITING: { setScoreboardMode(ScoreboardMode::WAITING); break; } - case PlayerStatus::ENTERING_NAME: + case PlayerState::ENTERING_NAME: { setScoreboardMode(ScoreboardMode::ENTER_NAME); break; } - case PlayerStatus::DYING: + case PlayerState::DYING: { // Activa la animación de morir player_sprite_->setAccelY(0.2f); @@ -465,27 +403,32 @@ void Player::setStatusPlaying(PlayerStatus value) rand() % 2 == 0 ? player_sprite_->setVelX(3.3f) : player_sprite_->setVelX(-3.3f); break; } - case PlayerStatus::DIED: + case PlayerState::DIED: { - const auto nextPlayerStatus = IsEligibleForHighScore() ? PlayerStatus::ENTERING_NAME : PlayerStatus::CONTINUE; - demo_ ? setStatusPlaying(PlayerStatus::WAITING) : setStatusPlaying(nextPlayerStatus); + const auto nextPlayerStatus = IsEligibleForHighScore() ? PlayerState::ENTERING_NAME : PlayerState::CONTINUE; + demo_ ? setPlayingState(PlayerState::WAITING) : setPlayingState(nextPlayerStatus); break; } - case PlayerStatus::GAME_OVER: + case PlayerState::GAME_OVER: { setScoreboardMode(ScoreboardMode::GAME_OVER); break; } - case PlayerStatus::ENTERING_NAME_GAME_COMPLETED: + case PlayerState::CELEBRATING: { - setWalkingStatus(PlayerStatus::WALKING_STOP); - setFiringStatus(PlayerStatus::FIRING_NONE); + setScoreboardMode(ScoreboardMode::SCORE); + break; + } + case PlayerState::ENTERING_NAME_GAME_COMPLETED: + { + setWalkingState(PlayerState::WALKING_STOP); + setFiringState(PlayerState::FIRING_NONE); setScoreboardMode(ScoreboardMode::ENTER_NAME); break; } - case PlayerStatus::GAME_COMPLETED: + case PlayerState::GAME_COMPLETED: { - setScoreboardMode(ScoreboardMode::GAME_OVER); + setScoreboardMode(ScoreboardMode::GAME_COMPLETED); break; } default: @@ -493,15 +436,6 @@ void Player::setStatusPlaying(PlayerStatus value) } } -// Obtiene el estado del jugador en el juego -PlayerStatus Player::getStatusPlaying() const { return status_playing_; } - -// Obtiene el valor de la variable -float Player::getScoreMultiplier() const { return score_multiplier_; } - -// Establece el valor de la variable -void Player::setScoreMultiplier(float value) { score_multiplier_ = value; } - // Aumenta el valor de la variable hasta un máximo void Player::incScoreMultiplier() { @@ -516,9 +450,6 @@ void Player::decScoreMultiplier() score_multiplier_ = std::max(score_multiplier_, 1.0f); } -// Obtiene el valor de la variable -bool Player::isInvulnerable() const { return invulnerable_; } - // Establece el valor del estado void Player::setInvulnerable(bool value) { @@ -526,12 +457,6 @@ void Player::setInvulnerable(bool value) invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER_ : 0; } -// Obtiene el valor de la variable -int Player::getInvulnerableCounter() const { return invulnerable_counter_; } - -// Establece el valor de la variable -void Player::setInvulnerableCounter(int value) { invulnerable_counter_ = value; } - // Monitoriza el estado void Player::updateInvulnerable() { @@ -550,9 +475,6 @@ void Player::updateInvulnerable() } } -// Obtiene el valor de la variable -bool Player::isPowerUp() const { return power_up_; } - // Establece el valor de la variable void Player::setPowerUp() { @@ -560,12 +482,6 @@ void Player::setPowerUp() power_up_counter_ = POWERUP_COUNTER_; } -// Obtiene el valor de la variable -int Player::getPowerUpCounter() const { return power_up_counter_; } - -// Establece el valor de la variable -void Player::setPowerUpCounter(int value) { power_up_counter_ = value; } - // Actualiza el valor de la variable void Player::updatePowerUp() { @@ -576,9 +492,6 @@ void Player::updatePowerUp() } } -// Obtiene el valor de la variable -bool Player::hasExtraHit() const { return extra_hit_; } - // Concede un toque extra al jugador void Player::giveExtraHit() { @@ -603,12 +516,6 @@ void Player::removeExtraHit() extra_hit_ = coffees_ == 0 ? false : true; } -// Devuelve el número de cafes actuales -int Player::getCoffees() const { return coffees_; } - -// Obtiene el circulo de colisión -Circle &Player::getCollider() { return collider_; } - // Actualiza el circulo de colisión a la posición del jugador void Player::shiftColliders() { @@ -623,13 +530,10 @@ void Player::setPlayerTextures(const std::vector> &text power_sprite_->setTexture(texture[1]); } -// Obtiene el valor de la variable -int Player::getContinueCounter() const { return continue_counter_; } - // Actualiza el contador de continue void Player::updateContinueCounter() { - if (status_playing_ == PlayerStatus::CONTINUE) + if (playing_state_ == PlayerState::CONTINUE) { constexpr int TICKS_SPEED = 1000; if (SDL_GetTicks() - continue_ticks_ > TICKS_SPEED) @@ -642,7 +546,7 @@ void Player::updateContinueCounter() // Actualiza el contador de entrar nombre void Player::updateEnterNameCounter() { - if (status_playing_ == PlayerStatus::ENTERING_NAME || status_playing_ == PlayerStatus::ENTERING_NAME_GAME_COMPLETED) + if (playing_state_ == PlayerState::ENTERING_NAME || playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED) { constexpr int TICKS_SPEED = 1000; if (SDL_GetTicks() - enter_name_ticks_ > TICKS_SPEED) @@ -652,12 +556,6 @@ void Player::updateEnterNameCounter() } } -// Le asigna un panel en el marcador al jugador -void Player::setScoreBoardPanel(int panel) { scoreboard_panel_ = panel; } - -// Obtiene el valor de la variable -int Player::getScoreBoardPanel() const { return scoreboard_panel_; } - // Decrementa el contador de continuar void Player::decContinueCounter() { @@ -665,7 +563,7 @@ void Player::decContinueCounter() --continue_counter_; if (continue_counter_ < 0) { - setStatusPlaying(PlayerStatus::GAME_OVER); + setPlayingState(PlayerState::GAME_OVER); } } @@ -677,23 +575,14 @@ void Player::decEnterNameCounter() if (enter_name_counter_ < 0) { enter_name_counter_ = param.game.enter_name_seconds; - setStatusPlaying(PlayerStatus::CONTINUE); + if (playing_state_ == PlayerState::ENTERING_NAME) + setPlayingState(PlayerState::CONTINUE); + else + setPlayingState(PlayerState::GAME_COMPLETED); } } -// Establece el nombre del jugador -void Player::setName(const std::string &name) { name_ = name; } - -// Establece el nombre del jugador para la tabla de mejores puntuaciones -void Player::setRecordName(const std::string &record_name) { record_name_ = record_name.substr(0, 8); } - -// Obtiene el nombre del jugador -std::string Player::getName() const { return name_; } - -// Obtiene el nombre del jugador para la tabla de mejores puntuaciones -std::string Player::getRecordName() const { return record_name_; } - -// Obtiene la posici´´on que se está editando del nombre del jugador para la tabla de mejores puntuaciones +// Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones int Player::getRecordNamePos() const { if (enter_name_) @@ -702,21 +591,6 @@ int Player::getRecordNamePos() const return 0; } -// Establece el mando que usará para ser controlado -void Player::setController(int index) { controller_index_ = index; } - -// Obtiene el mando que usa para ser controlado -int Player::getController() const { return controller_index_; } - -// Obtiene el "id" del jugador -int Player::getId() const { return id_; } - -// Indica si el jugador se puede dibujar -bool Player::isRenderable() const { return isPlaying() || isDying() || isEnteringNameGameCompleted() || isGameCompleted(); } - -// Comprueba si la puntuación entra en la tabla de mejores puntuaciones -bool Player::IsEligibleForHighScore() { return score_ > options.game.hi_score_table.back().score; } - // Recoloca los sprites void Player::shiftSprite() { @@ -725,4 +599,48 @@ void Player::shiftSprite() power_sprite_->setPosX(getPosX() - power_up_desp_x_); } -bool Player::isCooling() { return status_firing_ == PlayerStatus::COOLING_LEFT || status_firing_ == PlayerStatus::COOLING_UP || status_firing_ == PlayerStatus::COOLING_RIGHT; } \ No newline at end of file +int Player::getScore() const { return score_; } +void Player::setScore(int score) { score_ = score; } +PlayerState Player::getPlayingState() const { return playing_state_; } +float Player::getScoreMultiplier() const { return score_multiplier_; } +void Player::setScoreMultiplier(float value) { score_multiplier_ = value; } +bool Player::isInvulnerable() const { return invulnerable_; } +int Player::getInvulnerableCounter() const { return invulnerable_counter_; } +void Player::setInvulnerableCounter(int value) { invulnerable_counter_ = value; } +bool Player::isPowerUp() const { return power_up_; } +int Player::getPowerUpCounter() const { return power_up_counter_; } +void Player::setPowerUpCounter(int value) { power_up_counter_ = value; } +bool Player::hasExtraHit() const { return extra_hit_; } +void Player::setScoreBoardPanel(int panel) { scoreboard_panel_ = panel; } +int Player::getScoreBoardPanel() const { return scoreboard_panel_; } +int Player::getCoffees() const { return coffees_; } +Circle &Player::getCollider() { return collider_; } +int Player::getContinueCounter() const { return continue_counter_; } +void Player::setName(const std::string &name) { name_ = name; } +void Player::setRecordName(const std::string &record_name) { record_name_ = record_name.substr(0, 8); } +std::string Player::getName() const { return name_; } +std::string Player::getRecordName() const { return record_name_; } +void Player::setController(int index) { controller_index_ = index; } +int Player::getController() const { return controller_index_; } +int Player::getId() const { return id_; } +bool Player::isRenderable() const { return isPlaying() || isDying() || isCelebrating() || isEnteringNameGameCompleted() || isGameCompleted(); } +bool Player::IsEligibleForHighScore() { return score_ > options.game.hi_score_table.back().score; } +bool Player::isCooling() { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; } +int Player::getPosX() const { return static_cast(pos_x_); } +int Player::getPosY() const { return pos_y_; } +int Player::getWidth() const { return WIDTH_; } +int Player::getHeight() const { return HEIGHT_; } +bool Player::canFire() const { return cooldown_ > 0 ? false : true; } +void Player::setFireCooldown(int time) { cooldown_ = time; } +void Player::setWalkingState(PlayerState state) { walking_state_ = state; } +void Player::setFiringState(PlayerState state) { firing_state_ = state; } +bool Player::isPlaying() const { return playing_state_ == PlayerState::PLAYING; } +bool Player::isContinue() const { return playing_state_ == PlayerState::CONTINUE; } +bool Player::isWaiting() const { return playing_state_ == PlayerState::WAITING; } +bool Player::isEnteringName() const { return playing_state_ == PlayerState::ENTERING_NAME; } +bool Player::isDying() const { return playing_state_ == PlayerState::DYING; } +bool Player::hasDied() const { return playing_state_ == PlayerState::DIED; } +bool Player::isGameOver() const { return playing_state_ == PlayerState::GAME_OVER; } +bool Player::isEnteringNameGameCompleted() const { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; } +bool Player::isGameCompleted() const { return playing_state_ == PlayerState::GAME_COMPLETED; } +bool Player::isCelebrating() const { return playing_state_ == PlayerState::CELEBRATING; } \ No newline at end of file diff --git a/source/player.h b/source/player.h index a0496f5..a821891 100644 --- a/source/player.h +++ b/source/player.h @@ -14,7 +14,7 @@ enum class InputType : int; // lines 13-13 enum class ScoreboardMode; // lines 14-14 // Estados del jugador -enum class PlayerStatus +enum class PlayerState { WALKING_LEFT, WALKING_RIGHT, @@ -29,15 +29,16 @@ enum class PlayerStatus COOLING_LEFT, COOLING_RIGHT, - PLAYING, - CONTINUE, - WAITING, - ENTERING_NAME, - DYING, - DIED, - GAME_OVER, - ENTERING_NAME_GAME_COMPLETED, - GAME_COMPLETED, + PLAYING, // Está jugando + CONTINUE, // Está con la cuenta atras para continuar + WAITING, // No está jugando pero puede entrar a jugar + ENTERING_NAME, // Introduciendo nombre + DYING, // El cadaver está volando por ahi + DIED, // El cadaver ha desaparecido por el fondo + GAME_OVER, // No está jugando y no puede entrar a jugar + CELEBRATING, // Poniendo pose de victoria + ENTERING_NAME_GAME_COMPLETED, // Poniendo nombre en el tramo final del juego + GAME_COMPLETED, // Moviendose fuera de la pantalla }; // Clase Player @@ -57,38 +58,38 @@ private: std::unique_ptr enter_name_; // Clase utilizada para introducir el nombre // Variables - int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2 - SDL_Rect play_area_; // Rectangulo con la zona de juego - float pos_x_ = 0.0f; // Posicion en el eje X - int pos_y_ = 0; // Posicion en el eje Y - float default_pos_x_; // Posición inicial para el jugador - int default_pos_y_; // Posición inicial para el jugador - float vel_x_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje X - int vel_y_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje Y - int cooldown_ = 0; // Contador durante el cual no puede disparar - int cooling_status_counter_ = 0; // Contador para la animación del estado cooling - int score_ = 0; // Puntos del jugador - float score_multiplier_ = 1.0f; // Multiplicador de puntos - PlayerStatus status_walking_ = PlayerStatus::WALKING_STOP; // Estado del jugador al moverse - PlayerStatus status_firing_ = PlayerStatus::FIRING_NONE; // Estado del jugador al disparar - PlayerStatus status_playing_ = PlayerStatus::WAITING; // Estado del jugador en el juego - bool invulnerable_ = true; // Indica si el jugador es invulnerable - int invulnerable_counter_ = INVULNERABLE_COUNTER_; // Contador para la invulnerabilidad - bool extra_hit_ = false; // Indica si el jugador tiene un toque extra - int coffees_ = 0; // Indica cuantos cafes lleva acumulados - bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp - int power_up_counter_ = POWERUP_COUNTER_; // Temporizador para el modo PowerUp - int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador - Circle collider_ = Circle(0, 0, 9); // Circulo de colisión del jugador - int continue_counter_ = 10; // Contador para poder continuar - Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo - int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador - std::string name_; // Nombre del jugador - std::string record_name_; // Nombre del jugador para la tabla de mejores puntuaciones - int controller_index_ = 0; // Indice del array de mandos que utilizará para moverse - bool demo_; // Para que el jugador sepa si está en el modo demostración - int enter_name_counter_; // Contador para poner nombre - Uint32 enter_name_ticks_ = 0; // Variable para poder cambiar el contador de poner nombre en función del tiempo + int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2 + SDL_Rect play_area_; // Rectangulo con la zona de juego + float pos_x_ = 0.0f; // Posicion en el eje X + int pos_y_ = 0; // Posicion en el eje Y + float default_pos_x_; // Posición inicial para el jugador + int default_pos_y_; // Posición inicial para el jugador + float vel_x_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje X + int vel_y_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje Y + int cooldown_ = 0; // Contador durante el cual no puede disparar + int cooling_status_counter_ = 0; // Contador para la animación del estado cooling + int score_ = 0; // Puntos del jugador + float score_multiplier_ = 1.0f; // Multiplicador de puntos + PlayerState walking_state_ = PlayerState::WALKING_STOP; // Estado del jugador al moverse + PlayerState firing_state_ = PlayerState::FIRING_NONE; // Estado del jugador al disparar + PlayerState playing_state_ = PlayerState::WAITING; // Estado del jugador en el juego + bool invulnerable_ = true; // Indica si el jugador es invulnerable + int invulnerable_counter_ = INVULNERABLE_COUNTER_; // Contador para la invulnerabilidad + bool extra_hit_ = false; // Indica si el jugador tiene un toque extra + int coffees_ = 0; // Indica cuantos cafes lleva acumulados + bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp + int power_up_counter_ = POWERUP_COUNTER_; // Temporizador para el modo PowerUp + int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador + Circle collider_ = Circle(0, 0, 9); // Circulo de colisión del jugador + int continue_counter_ = 10; // Contador para poder continuar + Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo + int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador + std::string name_; // Nombre del jugador + std::string record_name_; // Nombre del jugador para la tabla de mejores puntuaciones + int controller_index_ = 0; // Indice del array de mandos que utilizará para moverse + bool demo_; // Para que el jugador sepa si está en el modo demostración + int enter_name_counter_; // Contador para poner nombre + Uint32 enter_name_ticks_ = 0; // Variable para poder cambiar el contador de poner nombre en función del tiempo // Actualiza el circulo de colisión a la posición del jugador void shiftColliders(); @@ -117,6 +118,7 @@ private: // Cambia el modo del marcador void setScoreboardMode(ScoreboardMode mode); + // Se encuentra en alguno de los estados "COOLING" bool isCooling(); public: @@ -151,10 +153,10 @@ public: void move(); // Establece el estado del jugador - void setWalkingStatus(PlayerStatus status); + void setWalkingState(PlayerState state); // Establece el estado del jugador - void setFiringStatus(PlayerStatus status); + void setFiringState(PlayerState state); // Establece la animación correspondiente al estado void setAnimation(); @@ -189,38 +191,23 @@ public: // Incrementa la puntuación del jugador void addScore(int score); - // Indica si el jugador está jugando + // Indica si el jugador se encuentra en ese estado bool isPlaying() const; - - // Indica si el jugador está continuando bool isContinue() const; - - // Indica si el jugador está esperando bool isWaiting() const; - - // Indica si el jugador está introduciendo su nombre bool isEnteringName() const; - - // Indica si el jugador está muriendose bool isDying() const; - - // Indica si el jugador ha terminado de morir bool hasDied() const; - - // Indica si el jugador ya ha terminado de jugar bool isGameOver() const; - - // Indica si el jugador está introduciendo su nombre una vez ha completado el juego bool isEnteringNameGameCompleted() const; - - // Indica si el jugador ha completado el juego bool isGameCompleted() const; + bool isCelebrating() const; // Establece el estado del jugador en el juego - void setStatusPlaying(PlayerStatus value); + void setPlayingState(PlayerState state); // Obtiene el estado del jugador en el juego - PlayerStatus getStatusPlaying() const; + PlayerState getPlayingState() const; // Obtiene el valor de la variable float getScoreMultiplier() const; diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 0459bce..e49b925 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -118,77 +118,28 @@ void Scoreboard::render() SDL_RenderCopy(renderer_, background_, nullptr, &rect_); } -// Establece el valor de la variable -void Scoreboard::setName(int panel_, const std::string &name_) -{ - this->name_[panel_] = name_; -} +void Scoreboard::setName(int panel, const std::string &name) { name_[panel] = name; } +void Scoreboard::setRecordName(int panel, const std::string &record_name) { record_name_[panel] = record_name; } +void Scoreboard::setSelectorPos(int panel, int pos) { selector_pos_[panel] = pos; } +void Scoreboard::setScore(int panel, int score) { score_[panel] = score; } +void Scoreboard::setMult(int panel, float mult) { mult_[panel] = mult; } +void Scoreboard::setContinue(int panel, int continue_counter) { continue_counter_[panel] = continue_counter; } +void Scoreboard::setStage(int stage) { stage_ = stage; } +void Scoreboard::setHiScore(int hi_score) { hi_score_ = hi_score; } +void Scoreboard::setPower(float power) { power_ = power; } +void Scoreboard::setHiScoreName(const std::string &name) { hi_score_name_ = name; } // Establece el valor de la variable -void Scoreboard::setRecordName(int panel_, const std::string &record_name_) +void Scoreboard::setColor(Color color) { - this->record_name_[panel_] = record_name_; -} - -// Establece el valor de la variable -void Scoreboard::setSelectorPos(int panel_, int pos) -{ - selector_pos_[panel_] = pos; -} - -// Establece el valor de la variable -void Scoreboard::setScore(int panel_, int score_) -{ - this->score_[panel_] = score_; -} - -// Establece el valor de la variable -void Scoreboard::setMult(int panel_, float mult_) -{ - this->mult_[panel_] = mult_; -} - -// Establece el valor de la variable -void Scoreboard::setContinue(int panel_, int value) -{ - continue_counter_[panel_] = value; -} - -// Establece el valor de la variable -void Scoreboard::setStage(int stage_) -{ - this->stage_ = stage_; -} - -// Establece el valor de la variable -void Scoreboard::setHiScore(int hi_score_) -{ - this->hi_score_ = hi_score_; -} - -// Establece el valor de la variable -void Scoreboard::setPower(float power_) -{ - this->power_ = power_; -} - -// Establece el valor de la variable -void Scoreboard::setHiScoreName(const std::string &name_) -{ - hi_score_name_ = name_; -} - -// Establece el valor de la variable -void Scoreboard::setColor(Color color_) -{ - this->color_ = color_; + color_ = color; fillBackgroundTexture(); } // Establece el valor de la variable -void Scoreboard::setPos(SDL_Rect rect_) +void Scoreboard::setPos(SDL_Rect rect) { - this->rect_ = rect_; + rect_ = rect; // Recalcula las anclas de los elementos recalculateAnchors(); @@ -207,10 +158,10 @@ void Scoreboard::setPos(SDL_Rect rect_) void Scoreboard::fillPanelTextures() { // Guarda a donde apunta actualmente el renderizador - SDL_Texture *temp = SDL_GetRenderTarget(renderer_); + auto temp = SDL_GetRenderTarget(renderer_); // Genera el contenidoi de cada panel_ - for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i) + for (size_t i = 0; i < SCOREBOARD_MAX_PANELS; ++i) { // Cambia el destino del renderizador SDL_SetRenderTarget(renderer_, panel_texture_[i]); @@ -314,8 +265,9 @@ void Scoreboard::fillPanelTextures() text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y, lang::getText(106)); SDL_Rect rect = {enter_name_pos_.x, enter_name_pos_.y, 5, 7}; SDL_SetRenderDrawColor(renderer_, 0xFF, 0xFF, 0xEB, 255); - for (int j = 0; j < (int)record_name_[i].size(); ++j) + for (size_t j = 0; j < record_name_[i].size(); ++j) { + /* if (j == selector_pos_[i]) { // La letra seleccionada se pinta de forma intermitente if (counter_ % 3 > 0) @@ -329,11 +281,28 @@ void Scoreboard::fillPanelTextures() SDL_RenderDrawLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h); text_scoreboard_->write(rect.x, rect.y, record_name_[i].substr(j, 1)); } + */ + if (j != selector_pos_[i] || counter_ % 3 == 0) + { + SDL_RenderDrawLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h); + text_scoreboard_->write(rect.x, rect.y, record_name_[i].substr(j, 1)); + } rect.x += 7; } break; } + case ScoreboardMode::GAME_COMPLETED: + { + // GAME OVER + text_scoreboard_->writeCentered(slot4_1_.x, slot4_1_.y + 4, lang::getText(102)); + // SCORE + if (counter_ % 10 < 8) + { + text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y - 2, lang::getText(120)); + text_scoreboard_->writeCentered(slot4_4_.x, slot4_4_.y - 2, updateScoreText(score_[i])); + } + } default: break; } @@ -416,10 +385,7 @@ void Scoreboard::recalculateAnchors() } // Establece el modo del marcador -void Scoreboard::setMode(int index, ScoreboardMode mode) -{ - panel_[index].mode = mode; -} +void Scoreboard::setMode(int index, ScoreboardMode mode) { panel_[index].mode = mode; } // Crea la textura de fondo void Scoreboard::createBackgroundTexture() diff --git a/source/scoreboard.h b/source/scoreboard.h index ddd52dc..163d2c5 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -28,6 +28,7 @@ enum class ScoreboardMode : int GAME_OVER, DEMO, ENTER_NAME, + GAME_COMPLETED, NUM_MODES, }; @@ -58,7 +59,7 @@ private: // Variables std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nom de cada jugador std::string record_name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre introducido para la tabla de records - int selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre + size_t selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre int score_[SCOREBOARD_MAX_PANELS] = {}; // Puntuación de los jugadores float mult_[SCOREBOARD_MAX_PANELS] = {}; // Multiplicador de los jugadores int continue_counter_[SCOREBOARD_MAX_PANELS] = {}; // Tiempo para continuar de los jugadores