novetat: canvi de color de les bales quan queda poc powerUp

This commit is contained in:
2025-09-26 14:13:52 +02:00
parent 35f4bf690c
commit 0c670fd344
6 changed files with 257 additions and 219 deletions

View File

@@ -4,28 +4,29 @@
#include <string> // Para char_traits, basic_string, operator+, string
#include "param.h" // Para Param, ParamGame, param
#include "player.h" // Para Player::Id
#include "resource.h" // Para Resource
// Constructor
Bullet::Bullet(float x, float y, BulletType bullet_type, bool powered, Player::Id owner)
Bullet::Bullet(float x, float y, Type type, Color color, int owner)
: sprite_(std::make_unique<AnimatedSprite>(Resource::get()->getTexture("bullet.png"), Resource::get()->getAnimation("bullet.ani"))),
bullet_type_(bullet_type),
type_(type),
owner_(owner),
pos_x_(x),
pos_y_(y) {
vel_x_ = calculateVelocity(bullet_type_);
sprite_->setCurrentAnimation(buildAnimationString(bullet_type_, powered));
vel_x_ = calculateVelocity(type_);
sprite_->setCurrentAnimation(buildAnimationString(type_, color));
collider_.r = WIDTH / 2;
shiftColliders();
}
// Calcula la velocidad horizontal de la bala basada en su tipo
auto Bullet::calculateVelocity(BulletType bullet_type) -> float {
switch (bullet_type) {
case BulletType::LEFT:
auto Bullet::calculateVelocity(Type type) -> float {
switch (type) {
case Type::LEFT:
return VEL_X_LEFT;
case BulletType::RIGHT:
case Type::RIGHT:
return VEL_X_RIGHT;
default:
return VEL_X_CENTER;
@@ -33,17 +34,17 @@ auto Bullet::calculateVelocity(BulletType bullet_type) -> float {
}
// Construye el string de animación basado en el tipo de bala y si está potenciada
auto Bullet::buildAnimationString(BulletType bullet_type, bool powered) -> std::string {
std::string animation_string = powered ? "powered_" : "normal_";
auto Bullet::buildAnimationString(Type type, Color color) -> std::string {
std::string animation_string = color == Color::GREEN ? "powered_" : "normal_";
switch (bullet_type) {
case BulletType::UP:
switch (type) {
case Type::UP:
animation_string += "up";
break;
case BulletType::LEFT:
case Type::LEFT:
animation_string += "left";
break;
case BulletType::RIGHT:
case Type::RIGHT:
animation_string += "right";
break;
default:
@@ -53,49 +54,48 @@ auto Bullet::buildAnimationString(BulletType bullet_type, bool powered) -> std::
return animation_string;
}
// Implementación de render (llama al render del sprite_)
// Implementación de render
void Bullet::render() {
if (bullet_type_ != BulletType::NONE) {
if (type_ != Type::NONE) {
sprite_->render();
}
}
// Actualiza el estado del objeto (time-based)
auto Bullet::update(float deltaTime) -> BulletMoveStatus {
// Actualiza el estado del objeto
auto Bullet::update(float deltaTime) -> MoveStatus {
sprite_->update(deltaTime);
return move(deltaTime);
}
// Implementación del movimiento usando BulletMoveStatus (time-based)
auto Bullet::move(float deltaTime) -> BulletMoveStatus {
// DeltaTime puro: velocidad (pixels/segundo) * tiempo (segundos)
// Implementación del movimiento usando MoveStatus
auto Bullet::move(float deltaTime) -> MoveStatus {
pos_x_ += vel_x_ * deltaTime;
if (pos_x_ < param.game.play_area.rect.x - WIDTH || pos_x_ > param.game.play_area.rect.w) {
disable();
return BulletMoveStatus::OUT;
return MoveStatus::OUT;
}
pos_y_ += VEL_Y * deltaTime;
if (pos_y_ < param.game.play_area.rect.y - HEIGHT) {
disable();
return BulletMoveStatus::OUT;
return MoveStatus::OUT;
}
shiftSprite();
shiftColliders();
return BulletMoveStatus::OK;
return MoveStatus::OK;
}
auto Bullet::isEnabled() const -> bool {
return bullet_type_ != BulletType::NONE;
return type_ != Type::NONE;
}
void Bullet::disable() {
bullet_type_ = BulletType::NONE;
type_ = Type::NONE;
}
auto Bullet::getOwner() const -> Player::Id {
auto Bullet::getOwner() const -> int {
return owner_;
}

View File

@@ -6,22 +6,8 @@
#include <string> // Para string
#include "animated_sprite.h" // Para AnimatedSprite
#include "player.h" // Para Player
#include "utils.h" // Para Circle
// --- Enums ---
enum class BulletType : Uint8 {
UP, // Bala hacia arriba
LEFT, // Bala hacia la izquierda
RIGHT, // Bala hacia la derecha
NONE // Sin bala
};
enum class BulletMoveStatus : Uint8 {
OK = 0, // Movimiento normal
OUT = 1 // Fuera de los límites
};
// --- Clase Bullet: representa una bala del jugador ---
class Bullet {
public:
@@ -29,18 +15,36 @@ class Bullet {
static constexpr float WIDTH = 12.0F; // Anchura de la bala
static constexpr float HEIGHT = 12.0F; // Altura de la bala
// --- Enums ---
enum class Type : Uint8 {
UP, // Bala hacia arriba
LEFT, // Bala hacia la izquierda
RIGHT, // Bala hacia la derecha
NONE // Sin bala
};
enum class MoveStatus : Uint8 {
OK = 0, // Movimiento normal
OUT = 1 // Fuera de los límites
};
enum class Color : Uint8 {
YELLOW,
GREEN
};
// --- Constructor y destructor ---
Bullet(float x, float y, BulletType bullet_type, bool powered, Player::Id owner); // Constructor principal
Bullet(float x, float y, Type type, Color color, int owner); // Constructor principal
~Bullet() = default; // Destructor
// --- Métodos principales ---
void render(); // Dibuja la bala en pantalla
auto update(float deltaTime) -> BulletMoveStatus; // Actualiza el estado del objeto (time-based)
auto update(float deltaTime) -> MoveStatus; // Actualiza el estado del objeto (time-based)
void disable(); // Desactiva la bala
// --- Getters ---
[[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está activa
[[nodiscard]] auto getOwner() const -> Player::Id; // Devuelve el identificador del dueño
[[nodiscard]] auto getOwner() const -> int; // Devuelve el identificador del dueño
auto getCollider() -> Circle&; // Devuelve el círculo de colisión
private:
@@ -55,8 +59,8 @@ class Bullet {
// --- Variables de estado ---
Circle collider_; // Círculo de colisión
BulletType bullet_type_; // Tipo de bala
Player::Id owner_; // Identificador del dueño
Type type_; // Tipo de bala
int owner_; // Identificador del jugador
float pos_x_; // Posición en el eje X
float pos_y_; // Posición en el eje Y
float vel_x_; // Velocidad en el eje X
@@ -64,7 +68,7 @@ class Bullet {
// --- Métodos internos ---
void shiftColliders(); // Ajusta el círculo de colisión
void shiftSprite(); // Ajusta el sprite
auto move(float deltaTime) -> BulletMoveStatus; // Mueve la bala y devuelve su estado (time-based)
static auto calculateVelocity(BulletType bullet_type) -> float; // Calcula la velocidad horizontal de la bala
static auto buildAnimationString(BulletType bullet_type, bool powered) -> std::string; // Construye el string de animación
auto move(float deltaTime) -> MoveStatus; // Mueve la bala y devuelve su estado (time-based)
static auto calculateVelocity(Type type) -> float; // Calcula la velocidad horizontal de la bala
static auto buildAnimationString(Type type, Color color) -> std::string; // Construye el string de animación
};

View File

@@ -396,24 +396,8 @@ void Player::updateStepCounter(float deltaTime) {
// Pinta el jugador en pantalla
void Player::render() {
if (power_up_ && isPlaying()) {
// Convertir lógica de parpadeo a deltaTime en segundos
const float TOTAL_POWERUP_TIME_S = static_cast<float>(POWERUP_COUNTER) / 60.0f; // Total time in seconds
const float QUARTER_TIME_S = TOTAL_POWERUP_TIME_S / 4.0f; // 25% del tiempo total
if (power_up_time_accumulator_ > QUARTER_TIME_S) {
// En los primeros 75% del tiempo, siempre visible
if (power_sprite_visible_ && isPlaying()) {
power_sprite_->render();
} else {
// En el último 25%, parpadea cada 20 frames (≈0.333s)
constexpr float BLINK_PERIOD_S = 20.0f / 60.0f; // 20 frames in seconds
constexpr float VISIBLE_PROPORTION = 4.0f / 20.0f; // 4 frames visible de 20 total
float cycle_position = fmod(power_up_time_accumulator_, BLINK_PERIOD_S) / BLINK_PERIOD_S;
if (cycle_position >= VISIBLE_PROPORTION) {
power_sprite_->render();
}
}
}
if (isRenderable()) {
@@ -774,6 +758,9 @@ void Player::setPowerUp() {
power_up_ = true;
power_up_counter_ = POWERUP_COUNTER;
power_up_time_accumulator_ = static_cast<float>(POWERUP_COUNTER) / 60.0f; // Convert frames to seconds
power_sprite_visible_ = true; // Inicialmente visible cuando se activa el power-up
in_power_up_ending_phase_ = false; // Empezar en fase normal
bullet_color_toggle_ = false; // Resetear toggle
}
// Actualiza el valor de la variable (time-based)
@@ -784,8 +771,37 @@ void Player::updatePowerUp(float deltaTime) {
power_up_ = power_up_time_accumulator_ > 0;
if (!power_up_) {
power_up_time_accumulator_ = 0;
power_sprite_visible_ = false;
in_power_up_ending_phase_ = false;
bullet_color_toggle_ = false;
bullet_color_ = Bullet::Color::YELLOW;
} else {
// Calcular visibilidad del power sprite
const float TOTAL_POWERUP_TIME_S = static_cast<float>(POWERUP_COUNTER) / 60.0f;
const float QUARTER_TIME_S = TOTAL_POWERUP_TIME_S / 4.0f;
if (power_up_time_accumulator_ > QUARTER_TIME_S) {
// En los primeros 75% del tiempo, siempre visible
power_sprite_visible_ = true;
in_power_up_ending_phase_ = false;
bullet_color_ = Bullet::Color::GREEN;
} else {
// En el último 25%, parpadea cada 20 frames (≈0.333s)
constexpr float BLINK_PERIOD_S = 20.0f / 60.0f;
constexpr float VISIBLE_PROPORTION = 4.0f / 20.0f;
float cycle_position = fmod(power_up_time_accumulator_, BLINK_PERIOD_S) / BLINK_PERIOD_S;
power_sprite_visible_ = cycle_position >= VISIBLE_PROPORTION;
in_power_up_ending_phase_ = true; // Activar modo alternancia de colores de balas
bullet_color_ = power_sprite_visible_ ? Bullet::Color::GREEN : Bullet::Color::YELLOW;
}
}
} else {
power_sprite_visible_ = false;
in_power_up_ending_phase_ = false;
bullet_color_toggle_ = false;
bullet_color_ = Bullet::Color::YELLOW;
}
}
}
@@ -919,6 +935,17 @@ auto Player::isRenderable() const -> bool {
return !isTitleHidden();
};
// Devuelve el color para la próxima bala (alterna si está en modo toggle)
auto Player::getNextBulletColor() -> Bullet::Color {
if (in_power_up_ending_phase_) {
// En fase final: alternar entre verde y amarillo
bullet_color_toggle_ = !bullet_color_toggle_;
return bullet_color_toggle_ ? Bullet::Color::GREEN : Bullet::Color::YELLOW;
}
// Modo normal: sin power-up = amarillo, con power-up = verde
return bullet_color_;
}
// Añade una puntuación a la tabla de records
void Player::addScoreToScoreBoard() const {
if (hi_score_table_ == nullptr) {

View File

@@ -8,6 +8,7 @@
#include <vector> // Para vector
#include "animated_sprite.h" // Para AnimatedSprite
#include "bullet.h" // Para Bullet
#include "enter_name.h" // Para EnterName
#include "input.h" // Para Input
#include "manage_hiscore_table.h" // Para Table
@@ -185,6 +186,9 @@ class Player {
[[nodiscard]] auto getName() const -> const std::string& { return name_; }
[[nodiscard]] auto get1CC() const -> bool { return game_completed_ && credits_used_ <= 1; }
[[nodiscard]] auto getEnterNamePositionOverflow() const -> bool { return enter_name_ ? enter_name_->getPositionOverflow() : false; }
[[nodiscard]] auto getBulletColor() const -> Bullet::Color { return bullet_color_; }
[[nodiscard]] auto isInBulletColorToggleMode() const -> bool { return in_power_up_ending_phase_; }
auto getNextBulletColor() -> Bullet::Color; // Devuelve el color para la próxima bala (alterna si está en modo toggle)
// Setters inline
void setController(int index) { controller_index_ = index; }
@@ -246,6 +250,7 @@ class Player {
State walking_state_ = State::WALKING_STOP; // Estado del jugador al moverse
State firing_state_ = State::FIRING_NONE; // Estado del jugador al disparar
State playing_state_ = State::WAITING; // Estado del jugador en el juego
Bullet::Color bullet_color_ = Bullet::Color::YELLOW; // Color de la bala del jugador
float pos_x_ = 0.0F; // Posición en el eje X
float default_pos_x_; // Posición inicial para el jugador
@@ -283,7 +288,6 @@ class Player {
float aiming_duration_ = 0.0f; // Duración del estado AIMING
float recoiling_duration_ = 0.0f; // Duración del estado RECOILING
int invulnerable_counter_ = INVULNERABLE_COUNTER; // Contador para la invulnerabilidad
int score_ = 0; // Puntos del jugador
int coffees_ = 0; // Indica cuántos cafés lleva acumulados
@@ -300,6 +304,9 @@ class Player {
bool invulnerable_ = true; // Indica si el jugador es invulnerable
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
bool power_sprite_visible_ = false; // Indica si el sprite de power-up debe ser visible
bool in_power_up_ending_phase_ = false; // Indica si está en la fase final del power-up (alternando colores)
bool bullet_color_toggle_ = false; // Para alternar entre verde y amarillo en fase final
bool demo_ = false; // Para que el jugador sepa si está en el modo demostración
bool game_completed_ = false; // Indica si ha completado el juego
bool uses_keyboard_ = false; // Indica si usa el teclado como dispositivo de control

View File

@@ -15,7 +15,7 @@
#include "background.h" // Para Background
#include "balloon.h" // Para Balloon
#include "balloon_manager.h" // Para BalloonManager
#include "bullet.h" // Para Bullet, BulletType, BulletMoveStatus
#include "bullet.h" // Para Bullet, Bullet::Type, BulletMoveStatus
#include "color.h" // Para Color, Colors::FLASH
#include "difficulty.h" // Para Code
#include "fade.h" // Para Fade, FadeType, FadeMode
@@ -564,7 +564,7 @@ auto Game::checkBulletBalloonCollision(const std::shared_ptr<Bullet> &bullet) ->
// Procesa el impacto en un globo
void Game::processBalloonHit(const std::shared_ptr<Bullet> &bullet, const std::shared_ptr<Balloon> &balloon) {
auto player = getPlayer(bullet->getOwner());
auto player = getPlayer(static_cast<Player::Id>(bullet->getOwner()));
handleItemDrop(balloon, player);
handleBalloonDestruction(balloon, player);
@@ -602,8 +602,8 @@ void Game::handleBalloonDestruction(std::shared_ptr<Balloon> balloon, const std:
// Mueve las balas activas
void Game::updateBullets(float deltaTime) {
for (auto &bullet : bullets_) {
if (bullet->update(deltaTime) == BulletMoveStatus::OUT) {
getPlayer(bullet->getOwner())->decScoreMultiplier();
if (bullet->update(deltaTime) == Bullet::MoveStatus::OUT) {
getPlayer(static_cast<Player::Id>(bullet->getOwner()))->decScoreMultiplier();
}
}
}
@@ -616,8 +616,8 @@ void Game::renderBullets() {
}
// Crea un objeto bala
void Game::createBullet(int x, int y, BulletType kind, bool powered_up, Player::Id owner) {
bullets_.emplace_back(std::make_shared<Bullet>(x, y, kind, powered_up, owner));
void Game::createBullet(int x, int y, Bullet::Type type, Bullet::Color color, int owner) {
bullets_.emplace_back(std::make_shared<Bullet>(x, y, type, color, owner));
}
// Vacia el vector de balas
@@ -1305,30 +1305,30 @@ void Game::demoHandlePlayerInput(const std::shared_ptr<Player> &player, int inde
}
if (demo_data.fire == 1) {
handleFireInput(player, BulletType::UP);
handleFireInput(player, Bullet::Type::UP);
} else if (demo_data.fire_left == 1) {
handleFireInput(player, BulletType::LEFT);
handleFireInput(player, Bullet::Type::LEFT);
} else if (demo_data.fire_right == 1) {
handleFireInput(player, BulletType::RIGHT);
handleFireInput(player, Bullet::Type::RIGHT);
}
}
// Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos.
void Game::handleFireInput(const std::shared_ptr<Player> &player, BulletType bullet_type) {
void Game::handleFireInput(const std::shared_ptr<Player> &player, Bullet::Type type) {
if (player->canFire()) {
SDL_Point bullet = {0, 0};
switch (bullet_type) {
case BulletType::UP:
switch (type) {
case Bullet::Type::UP:
player->setInput(Input::Action::FIRE_CENTER);
bullet.x = 2 + player->getPosX() + (Player::WIDTH - Bullet::WIDTH) / 2;
bullet.y = player->getPosY() - (Bullet::HEIGHT / 2);
break;
case BulletType::LEFT:
case Bullet::Type::LEFT:
player->setInput(Input::Action::FIRE_LEFT);
bullet.x = player->getPosX() - (Bullet::WIDTH / 2);
bullet.y = player->getPosY();
break;
case BulletType::RIGHT:
case Bullet::Type::RIGHT:
player->setInput(Input::Action::FIRE_RIGHT);
bullet.x = player->getPosX() + Player::WIDTH - (Bullet::WIDTH / 2);
bullet.y = player->getPosY();
@@ -1336,7 +1336,7 @@ void Game::handleFireInput(const std::shared_ptr<Player> &player, BulletType bul
default:
break;
}
createBullet(bullet.x, bullet.y, bullet_type, player->isPowerUp(), player->getId());
createBullet(bullet.x, bullet.y, type, player->getNextBulletColor(), static_cast<int>(player->getId()));
playSound("bullet.wav");
// Establece un tiempo de espera para el próximo disparo.
@@ -1402,7 +1402,7 @@ void Game::handleFireInputs(const std::shared_ptr<Player> &player, bool autofire
}
if (input_->checkAction(Input::Action::FIRE_CENTER, autofire, player->getUsesKeyboard(), player->getGamepad())) {
handleFireInput(player, BulletType::UP);
handleFireInput(player, Bullet::Type::UP);
#ifdef RECORDING
demo_.keys.fire = 1;
#endif
@@ -1410,7 +1410,7 @@ void Game::handleFireInputs(const std::shared_ptr<Player> &player, bool autofire
}
if (input_->checkAction(Input::Action::FIRE_LEFT, autofire, player->getUsesKeyboard(), player->getGamepad())) {
handleFireInput(player, BulletType::LEFT);
handleFireInput(player, Bullet::Type::LEFT);
#ifdef RECORDING
demo_.keys.fire_left = 1;
#endif
@@ -1418,7 +1418,7 @@ void Game::handleFireInputs(const std::shared_ptr<Player> &player, bool autofire
}
if (input_->checkAction(Input::Action::FIRE_RIGHT, autofire, player->getUsesKeyboard(), player->getGamepad())) {
handleFireInput(player, BulletType::RIGHT);
handleFireInput(player, Bullet::Type::RIGHT);
#ifdef RECORDING
demo_.keys.fire_right = 1;
#endif

View File

@@ -6,6 +6,7 @@
#include <string> // Para string
#include <vector> // Para vector
#include "bullet.h" // Para Bullet
#include "hit.h" // Para Hit
#include "item.h" // Para Item, ItemType
#include "manage_hiscore_table.h" // Para HiScoreEntry
@@ -27,7 +28,6 @@ class Scoreboard;
class Screen;
class Tabe;
class Texture;
enum class BulletType : Uint8;
namespace Difficulty {
enum class Code;
@@ -214,7 +214,7 @@ class Game {
// --- Entrada de jugadores normales ---
void handlePlayersInput(); // Gestiona entrada de todos los jugadores
void handleNormalPlayerInput(const std::shared_ptr<Player>& player); // Procesa entrada de un jugador específico
void handleFireInput(const std::shared_ptr<Player> &player, BulletType bullet_type); // Gestiona disparo de jugador
void handleFireInput(const std::shared_ptr<Player>& player, Bullet::Type type); // Gestiona disparo de jugador
void handleFireInputs(const std::shared_ptr<Player>& player, bool autofire); // Procesa disparos automáticos
void handlePlayerContinueInput(const std::shared_ptr<Player>& player); // Permite continuar al jugador
void handlePlayerWaitingInput(const std::shared_ptr<Player>& player); // Permite (re)entrar al jugador
@@ -228,7 +228,7 @@ class Game {
// --- Sistema de balas y proyectiles ---
void updateBullets(float deltaTime); // Actualiza posición y estado de todas las balas (time-based)
void renderBullets(); // Renderiza todas las balas activas
void createBullet(int x, int y, BulletType kind, bool powered_up, Player::Id owner); // Crea una nueva bala
void createBullet(int x, int y, Bullet::Type kind, Bullet::Color color, int owner); // Crea una nueva bala
void checkBulletCollision(); // Verifica colisiones de todas las balas
void freeBullets(); // Libera memoria del vector de balas