From 90706d5d0cd91346dd36d0c79dbe0978e4abb07d Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Wed, 14 Aug 2024 11:59:16 +0200 Subject: [PATCH] enmig del berenjenal d'afegir estats nous al jugador --- source/game.cpp | 70 ++++++++++++++++--------------- source/game.h | 20 ++++----- source/player.cpp | 102 +++++++++++++++++++++++++++++----------------- source/player.h | 35 ++++++++++------ 4 files changed, 129 insertions(+), 98 deletions(-) diff --git a/source/game.cpp b/source/game.cpp index 7353f82..3b09a1f 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -112,8 +112,8 @@ void Game::init(int playerID) Player *player2 = new Player((PLAY_AREA_CENTER_FIRST_QUARTER_X * ((1 * 2) + 1)) - 11, PLAY_AREA_BOTTOM - 30, playerTextures[1], playerAnimations); players.push_back(player2); - // Habilita el jugador seleccionado - players[playerID]->enable(true); + // Cambia el estado del jugador seleccionado + players[playerID]->setStatusPlaying(PLAYER_STATUS_PLAYING); // Como es el principio del juego, empieza sin inmunidad players[playerID]->setInvulnerable(false); @@ -148,11 +148,11 @@ void Game::init(int playerID) // Variables para el marcador scoreboard->setPos({param->scoreboard.x, param->scoreboard.y, param->scoreboard.w, param->scoreboard.h}); - if (!players[0]->isEnabled()) + if (players[0]->isWaiting()) { scoreboard->setMode(SCOREBOARD_LEFT_PANEL, SCOREBOARD_MODE_GAME_OVER); } - if (!players[1]->isEnabled()) + if (!players[1]->isWaiting()) { scoreboard->setMode(SCOREBOARD_RIGHT_PANEL, SCOREBOARD_MODE_GAME_OVER); } @@ -169,7 +169,7 @@ void Game::init(int playerID) menaceThreshold = 0; hiScoreAchieved = false; stageBitmapCounter = STAGE_COUNTER; - deathCounter = DEATH_COUNTER; + gameOverCounter = DEATH_COUNTER; timeStopped = false; timeStoppedCounter = 0; counter = 0; @@ -210,7 +210,7 @@ void Game::init(int playerID) if (rand() % 2 == 0) { const int otherPlayer = playerID == 1 ? 1 : 0; - players[otherPlayer]->enable(true); + players[otherPlayer]->setStatusPlaying(PLAYER_STATUS_PLAYING); } for (auto player : players) @@ -931,18 +931,18 @@ void Game::updatePlayers() { for (auto player : players) { - if (player->isEnabled()) + if (player->isPlaying()) { player->update(); // Comprueba la colisión entre el jugador y los globos if (checkPlayerBalloonCollision(player)) { - if (player->isAlive()) + if (player->isPlaying()) { killPlayer(player); - if (demo.enabled && allPlayersAreDead()) + if (demo.enabled && allPlayersAreWaiting()) { fade->setType(FADE_RANDOM_SQUARE); fade->activate(); @@ -961,7 +961,7 @@ void Game::renderPlayers() { for (auto player : players) { - if (player->isEnabled()) + if (!player->isWaiting()) { player->render(); #ifdef DEBUG @@ -991,7 +991,7 @@ void Game::updateStage() menaceCurrent = 255; // Sube el nivel de amenaza para que no cree mas globos for (auto player : players) { // Añade un millon de puntos a los jugadores que queden vivos - if (player->isAlive()) + if (player->isPlaying()) { player->addScore(1000000); } @@ -1023,17 +1023,17 @@ void Game::updateStage() } } -// Actualiza el estado de muerte -void Game::updateDeath() +// Actualiza el estado de fin de la partida +void Game::updateGameOver() { // Comprueba si todos los jugadores estan muertos - if (allPlayersAreDead()) + if (allPlayersAreWaiting()) { - if (deathCounter > 0) + if (gameOverCounter > 0) { - deathCounter--; + gameOverCounter--; - if ((deathCounter == 250) || (deathCounter == 200) || (deathCounter == 180) || (deathCounter == 120) || (deathCounter == 60)) + if ((gameOverCounter == 250) || (gameOverCounter == 200) || (gameOverCounter == 180) || (gameOverCounter == 120) || (gameOverCounter == 60)) { // Hace sonar aleatoriamente uno de los 4 sonidos de burbujas const int index = rand() % 4; @@ -1041,7 +1041,7 @@ void Game::updateDeath() JA_PlaySound(sound[index], 0); } - if (deathCounter == 150) + if (gameOverCounter == 150) { fade->activate(); } @@ -1049,7 +1049,6 @@ void Game::updateDeath() if (fade->hasEnded()) { - // section->subsection = SUBSECTION_GAME_GAMEOVER; section->name = SECTION_PROG_HI_SCORE_TABLE; } } @@ -1430,7 +1429,7 @@ bool Game::checkPlayerBalloonCollision(Player *player) // Comprueba la colisión entre el jugador y los items void Game::checkPlayerItemCollision(Player *player) { - if (!player->isAlive()) + if (!player->isPlaying()) { return; } @@ -1797,8 +1796,8 @@ void Game::renderSmartSprites() // Acciones a realizar cuando el jugador muere void Game::killPlayer(Player *player) { - if (!player->isEnabled() || player->isInvulnerable()) - { // Si no está habilitado o tiene inmunidad, no hace nada + if (!player->isPlaying() || player->isInvulnerable()) + { // Si no está jugando o tiene inmunidad, no hace nada return; } @@ -1820,10 +1819,10 @@ void Game::killPlayer(Player *player) JA_PlaySound(playerCollisionSound); screen->shake(); JA_PlaySound(coffeeOutSound); - player->setAlive(false); + demo.enabled ? player->setStatusPlaying(PLAYER_STATUS_WAITING) : player->setStatusPlaying(PLAYER_STATUS_CONTINUE); if (!demo.enabled) { // En el modo DEMO ni se para la musica ni se añade la puntuación a la tabla - allPlayersAreDead() ? JA_StopMusic() : JA_ResumeMusic(); + allPlayersAreWaiting() ? JA_StopMusic() : JA_ResumeMusic(); addScoreToScoreBoard("Sergio", player->getScore()); } } @@ -1990,7 +1989,7 @@ void Game::update() updateStage(); // Actualiza el estado de muerte - updateDeath(); + updateGameOver(); // Actualiza los SmartSprites updateSmartSprites(); @@ -2104,7 +2103,7 @@ void Game::render() #ifdef DEBUG //text->write(0, 0, "P1 ALIVE: " + boolToString(players[0]->isAlive())); //text->write(0, 10, "P2 ALIVE: " + boolToString(players[1]->isAlive())); - //text->write(0, 20, "ALL DEAD: " + boolToString(allPlayersAreDead())); + //text->write(0, 20, "ALL DEAD: " + boolToString(allPlayersAreWaiting())); #endif // Dibuja el fade @@ -2180,7 +2179,7 @@ void Game::checkInput() int i = 0; for (auto player : players) { - if (player->isAlive() && player->isEnabled()) + if (player->isPlaying()) { // Comprueba direcciones if (demo.dataFile[i][demo.counter].left == 1) @@ -2256,7 +2255,7 @@ void Game::checkInput() for (auto player : players) { const bool autofire = player->isPowerUp() || options->game.autofire; - if (player->isAlive() && player->isEnabled()) + if (player->isPlaying()) { // Input a la izquierda if (input->checkInput(input_left, ALLOW_REPEAT, options->controller[i].deviceType, options->controller[i].index)) @@ -2350,7 +2349,7 @@ void Game::checkInput() { if (input->checkInput(input_start, ALLOW_REPEAT, options->controller[i].deviceType, options->controller[i].index)) { - player->enable(true); + player->setStatusPlaying(PLAYER_STATUS_PLAYING); } i++; } @@ -2454,8 +2453,8 @@ void Game::checkMusicStatus() // Si la música no está sonando if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED)) { - // Si se ha completado el juego o los jugadores estan mujertos, detiene la música - gameCompleted || allPlayersAreDead() ? JA_StopMusic() : JA_PlayMusic(music); + // Si se ha completado el juego o los jugadores han terminado, detiene la música + gameCompleted || allPlayersAreWaiting() ? JA_StopMusic() : JA_PlayMusic(music); } } @@ -2629,14 +2628,13 @@ void Game::updateHelper() } } -// Comprueba si todos los jugadores han muerto -bool Game::allPlayersAreDead() +// Comprueba si todos los jugadores han terminado de jugar +bool Game::allPlayersAreWaiting() { - bool success = true; + bool success = false; for (auto player : players) { - // success &= (!player->isAlive() || !player->isEnabled()); - success &= !player->isAlive(); + success |= player->isWaiting(); } return success; diff --git a/source/game.h b/source/game.h index a5ff6a2..b7ae4c6 100644 --- a/source/game.h +++ b/source/game.h @@ -47,7 +47,7 @@ #define TIME_STOPPED_COUNTER 300 /* - Esta clase gestiona un estado del programa. Se encarga de toda la parte en la + Esta clase gestiona un estado del programa. Se encarga de toda la parte en la que se está jugando. Tiene: @@ -126,7 +126,7 @@ private: std::vector player2Textures; // Vector con las texturas del jugador std::vector> playerTextures; // Vector con todas las texturas de los jugadores; - Texture *gameTextTexture; // Textura para los sprites con textos + Texture *gameTextTexture; // Textura para los sprites con textos std::vector *> itemAnimations; // Vector con las animaciones de los items std::vector *> playerAnimations; // Vector con las animaciones del jugador @@ -173,7 +173,7 @@ private: int stageBitmapCounter; // Contador para el tiempo visible del texto de Stage float stageBitmapPath[STAGE_COUNTER]; // Vector con los puntos Y por donde se desplaza el texto float getReadyBitmapPath[STAGE_COUNTER]; // Vector con los puntos X por donde se desplaza el texto - int deathCounter; // Contador para la animación de muerte del jugador + int gameOverCounter; // Contador para el estado de fin de partida int menaceCurrent; // Nivel de amenaza actual int menaceThreshold; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el número de globos bool timeStopped; // Indica si el tiempo está detenido @@ -251,8 +251,8 @@ private: // Comprueba si hay cambio de fase y actualiza las variables void updateStage(); - // Actualiza el estado de muerte - void updateDeath(); + // Actualiza el estado de fin de la partida + void updateGameOver(); // Actualiza los globos void updateBalloons(); @@ -398,12 +398,6 @@ private: // Deshabilita el efecto del item de detener el tiempo void disableTimeStopItem(); - // Actualiza los elementos de la pantalla de game over - void updateGameOverScreen(); - - // Dibuja los elementos de la pantalla de game over - void renderGameOverScreen(); - // Indica si se puede crear una powerball bool canPowerBallBeCreated(); @@ -419,8 +413,8 @@ private: // Actualiza las variables de ayuda void updateHelper(); - // Comprueba si todos los jugadores han muerto - bool allPlayersAreDead(); + // Comprueba si todos los jugadores han terminado de jugar + bool allPlayersAreWaiting(); // Carga las animaciones void loadAnimations(std::string filePath, std::vector *buffer); diff --git a/source/player.cpp b/source/player.cpp index 4b56489..9f7db7f 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -18,7 +18,8 @@ Player::Player(float x, int y, std::vector texture, std::vectorsetPosY(y - (powerSprite->getHeight() - playerSprite->getHeight())); // Inicializa variables - enabled = false; + // enabled = false; + statusPlaying = PLAYER_STATUS_WAITING; init(); } @@ -35,7 +36,7 @@ void Player::init() // Inicializa variables de estado posX = defaultPosX; posY = defaultPosY; - alive = enabled; + statusPlaying = PLAYER_STATUS_PLAYING; statusWalking = PLAYER_STATUS_WALKING_STOP; statusFiring = PLAYER_STATUS_FIRING_NO; invulnerable = true; @@ -45,31 +46,17 @@ void Player::init() extraHit = false; coffees = 0; input = true; - - // Establece la altura y el ancho del jugador + continueTicks = 0; + continueCounter = 9; width = 30; height = 30; - - // Establece el tamaño del circulo de colisión collider.r = 9; - - // Actualiza la posición del circulo de colisión shiftColliders(); - - // Establece la velocidad inicial velX = 0; velY = 0; - - // Establece la velocidad base baseSpeed = 1.5; - - // Establece la puntuación inicial score = 0; - - // Establece el multiplicador de puntos inicial scoreMultiplier = 1.0f; - - // Inicia el contador para la cadencia de disparo cooldown = 10; // Establece la posición del sprite @@ -117,7 +104,7 @@ void Player::setInput(int input) // Mueve el jugador a la posición y animación que le corresponde void Player::move() { - if (isAlive()) + if (isPlaying()) { // Mueve el jugador a derecha o izquierda posX += velX; @@ -155,7 +142,7 @@ void Player::move() // Pinta el jugador en pantalla void Player::render() { - if (powerUp && alive) + if (powerUp && isPlaying()) { if (powerUpCounter > (PLAYER_POWERUP_COUNTER / 4) || powerUpCounter % 20 > 4) { @@ -197,7 +184,7 @@ void Player::setAnimation() const SDL_RendererFlip flipFire = statusFiring == PLAYER_STATUS_FIRING_RIGHT ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE; // Establece la animación a partir de las cadenas - if (alive) + if (isPlaying()) { if (statusFiring == PLAYER_STATUS_FIRING_NO) { // No esta disparando @@ -285,6 +272,7 @@ void Player::update() updateCooldown(); updatePowerUpCounter(); updateInvulnerable(); + updateContinueCounter(); } // Obtiene la puntuación del jugador @@ -302,29 +290,58 @@ void Player::setScore(Uint32 score) // Incrementa la puntuación del jugador void Player::addScore(Uint32 score) { - //if (enabled && alive) - if (alive) + if (isPlaying()) { this->score += score; } } -// Obtiene el valor de la variable -bool Player::isAlive() +// Indica si el jugador está jugando +bool Player::isPlaying() { - return alive; + return statusPlaying == PLAYER_STATUS_PLAYING; } -// Establece el valor de la variable -void Player::setAlive(bool value) +// Indica si el jugador está continuando +bool Player::isContinue() { - alive = value; + return statusPlaying == PLAYER_STATUS_CONTINUE; +} - if (!alive) +// Indica si el jugador está esperando +bool Player::isWaiting() +{ + return statusPlaying == PLAYER_STATUS_WAITING; +} + +// Establece el estado del jugador en el juego +void Player::setStatusPlaying(int value) +{ + statusPlaying = value; + + switch (statusPlaying) { + case PLAYER_STATUS_PLAYING: + init(); + break; + + case PLAYER_STATUS_CONTINUE: + // Activa la animación de morir playerSprite->setAccelY(0.2f); playerSprite->setVelY(-6.6f); rand() % 2 == 0 ? playerSprite->setVelX(3.3f) : playerSprite->setVelX(-3.3f); + + // Inicializa el contador de continuar + continueTicks = SDL_GetTicks(); + continueCounter = 9; + break; + + case PLAYER_STATUS_WAITING: + + break; + + default: + break; } } @@ -510,15 +527,26 @@ void Player::setPlayerTextures(std::vector texture) powerSprite->setTexture(texture[1]); } -// Activa o descativa el jugador -void Player::enable(bool value) +// Obtiene el valor de la variable +int Player::getContinueCounter() { - enabled = value; - init(); + return continueCounter; } -// Obtiene el valor de la variable -bool Player::isEnabled() +// Actualiza el contador de continue +void Player::updateContinueCounter() { - return enabled; + if (statusPlaying == PLAYER_STATUS_CONTINUE) + { + const Uint32 ticksSpeed = 1000; + + if (SDL_GetTicks() - continueTicks > ticksSpeed) + { + // Actualiza el contador de ticks + continueTicks = SDL_GetTicks(); + + // Decrementa el contador + continueCounter--; + } + } } \ No newline at end of file diff --git a/source/player.h b/source/player.h index 6a2a6ba..daa69a2 100644 --- a/source/player.h +++ b/source/player.h @@ -17,6 +17,10 @@ #define PLAYER_STATUS_FIRING_RIGHT 2 #define PLAYER_STATUS_FIRING_NO 3 +#define PLAYER_STATUS_PLAYING 0 +#define PLAYER_STATUS_CONTINUE 1 +#define PLAYER_STATUS_WAITING 2 + // Variables del jugador #define PLAYER_INVULNERABLE_COUNTER 200 #define PLAYER_POWERUP_COUNTER 1500 @@ -48,8 +52,9 @@ private: int score; // Puntos del jugador float scoreMultiplier; // Multiplicador de puntos - int statusWalking; // Estado del jugador - int statusFiring; // Estado del jugador + int statusWalking; // Estado del jugador al moverse + int statusFiring; // Estado del jugador al disparar + int statusPlaying; // Estado del jugador en el juego bool invulnerable; // Indica si el jugador es invulnerable int invulnerableCounter; // Contador para la invulnerabilidad @@ -60,8 +65,8 @@ private: int powerUpDespX; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador bool input; // Indica si puede recibir ordenes de entrada circle_t collider; // Circulo de colisión del jugador - bool alive; // Indica si el jugador está vivo - bool enabled; // Indica si el jugador está activo + int continueCounter; // Contador para poder continuar + Uint32 continueTicks; // Variable para poder cambiar el contador de continue en función del tiempo // Actualiza el circulo de colisión a la posición del jugador void shiftColliders(); @@ -69,6 +74,9 @@ private: // Monitoriza el estado void updateInvulnerable(); + // Actualiza el contador de continue + void updateContinueCounter(); + public: // Constructor Player(float x, int y, std::vector texture, std::vector *> animations); @@ -133,11 +141,17 @@ public: // Incrementa la puntuación del jugador void addScore(Uint32 score); - // Obtiene el valor de la variable - bool isAlive(); + // Indica si el jugador está jugando + bool isPlaying(); - // Establece el valor de la variable - void setAlive(bool value); + // Indica si el jugador está continuando + bool isContinue(); + + // Indica si el jugador está esperando + bool isWaiting(); + + // Establece el estado del jugador en el juego + void setStatusPlaying(int value); // Obtiene el valor de la variable float getScoreMultiplier(); @@ -202,9 +216,6 @@ public: // Obtiene el puntero a la textura con los gráficos de la animación de morir Texture *getDeadTexture(); - // Activa o descativa el jugador - void enable(bool value); - // Obtiene el valor de la variable - bool isEnabled(); + int getContinueCounter(); };