Compare commits

...

2 Commits

Author SHA1 Message Date
c9a29e26dd revisant la seccio game: bales, items e inici 2025-09-24 11:37:23 +02:00
2977869ab5 revisat tabe.cpp, item.cpp i game.cpp 2025-09-24 09:37:23 +02:00
12 changed files with 257 additions and 110 deletions

View File

@@ -10,7 +10,7 @@ frames=0,1,2,3
[animation]
name=stand
speed=0.0167
speed=0.167
loop=0
frames=4,5,6,7
[/animation]
@@ -101,14 +101,14 @@ frames=37
[animation]
name=rolling
speed=0.0167
speed=0.167
loop=0
frames=38,39,40,41
[/animation]
[animation]
name=celebration
speed=0.0167
speed=0.167
loop=-1
frames=42,42,42,42,42,42,43,44,45,46,46,46,46,46,46,45,45,45,46,46,46,45,45,45,44,43,42,42,42
[/animation]

136
game_cpp_repair_plan.md Normal file
View File

@@ -0,0 +1,136 @@
# Plan de Reparación: game.cpp - Limpieza DeltaTime
## Estado Actual
`calculateDeltaTime()` convertido a segundos
✅ Constantes de tiempo convertidas de `_MS` a `_S`
✅ Eliminados hardcoded `1000.0f / 60.0f`
`throwCoffee()` velocidades convertidas a pixels/segundo
✅ Frame-based counter en `updateGameStateShowingGetReadyMessage()` convertido a timer con flag
## Problemas Detectados Pendientes
### ✅ COMPLETADO
1. **Valores hardcoded frame-based (60, 16.67, 1000/60)** - Solo quedan las conversiones correctas
2. **SmartSprite setFinishedDelay() calls** - Correcto (0.0F está bien)
3. **Velocidades y aceleraciones** - Todas convertidas correctamente
4. **Timer variables** - Todas usan deltaTime correctamente
### ❌ PENDIENTES DE REPARAR
#### ✅ **SOLUCIONADO: Balas no se mueven**
- **Síntoma**: Las balas se crean pero no avanzan en pantalla
- **Causa encontrada**: Velocidades en `bullet.h` seguían en pixels/ms pero `calculateDeltaTime()` ahora devuelve segundos
- **Solución aplicada**:
- `VEL_Y = -0.18F``VEL_Y = -180.0F` (pixels/segundo)
- `VEL_X_LEFT = -0.12F``VEL_X_LEFT = -120.0F` (pixels/segundo)
- `VEL_X_RIGHT = 0.12F``VEL_X_RIGHT = 120.0F` (pixels/segundo)
- Actualizado comentario en `bullet.cpp`: "pixels/ms" → "pixels/segundo"
#### ✅ **SOLUCIONADO: Contadores frame-based (++ o -- operations)**
- **Problema**: `demo_.counter++` en líneas 1665, 1691
- **Ubicación**: `updateDemo()` y `updateRecording()`
- **Contexto**: `demo_.counter` indexa un vector con datos de teclas por frame (ej: 2000 frames = 2000 entradas)
- **Solución aplicada**: Acumulador de tiempo que se incrementa cada 16.67ms (1/60 segundos)
- **Implementación**:
```cpp
// updateDemo()
static float demo_frame_timer = 0.0f;
demo_frame_timer += calculateDeltaTime();
if (demo_frame_timer >= 0.01667f && demo_.counter < TOTAL_DEMO_DATA) {
demo_.counter++;
demo_frame_timer -= 0.01667f; // Mantener precisión acumulada
}
// updateRecording()
static float recording_frame_timer = 0.0f;
recording_frame_timer += calculateDeltaTime();
if (recording_frame_timer >= 0.01667f && demo_.counter < TOTAL_DEMO_DATA) {
demo_.counter++;
recording_frame_timer -= 0.01667f; // Mantener precisión acumulada
}
```
#### 6. **Fade duration values (milisegundos vs segundos)**
- **Problema 1**: `fade_out_->setPostDuration(500);` línea 234
- **Problema 2**: `fade_out_->setPostDuration(param.fade.post_duration_ms);` líneas 89, 1671
- **Solución**: Verificar si `param.fade.post_duration_ms` debe ser convertido a segundos
### NUEVOS PROBLEMAS A AÑADIR
#### 7. **Verificar param.fade estructura**
- Revisar si `param.fade.post_duration_ms` debe ser convertido a segundos
- Verificar todas las propiedades de `param.fade` relacionadas con tiempo
#### 8. **Revisar constantes TOTAL_DEMO_DATA**
- **Problema**: `TOTAL_DEMO_DATA - 200` en línea 1669
- **Detalle**: 200 frames hardcoded, debería ser tiempo en segundos
#### 9. **Buscar más magic numbers relacionados con tiempo**
- Buscar números como 100, 150, 200, 500 que puedan ser frames
- Verificar contexto de cada uno
#### 10. **Revisar setRotateSpeed() values**
- **Problema**: `setRotateSpeed(10)` línea 797
- **Verificar**: Si debe ser convertido de rotaciones/frame a rotaciones/segundo
#### ✅ **VERIFICADO: SDL_Delay() calls**
- **Problema**: `SDL_Delay(param.game.hit_stop_ms);` línea 847
- **Ubicación**: `handlePlayerCollision()`
- **Contexto**: Pausa el juego al recibir daño (hitStop effect)
- **Resultado**: `param.game.hit_stop_ms` está configurado explícitamente en milisegundos en archivos .txt
- **Conclusión**: Correcto, `SDL_Delay()` espera milisegundos y `hit_stop_ms` ya está en milisegundos
#### ✅ **VERIFICADO: Cooldown de disparos en frames**
- **Problema**: `handleFireInput()` líneas 1312-1314
- **Detalle**: `POWERUP_COOLDOWN = 5`, `AUTOFIRE_COOLDOWN = 10`, `NORMAL_COOLDOWN = 7`
- **Contexto**: Son frames de cooldown, se pasan a `player->startFiringSystem(cant_fire_counter)`
- **Resultado**: `startFiringSystem()` convierte internamente frames a segundos con: `fire_cooldown_timer_ = static_cast<float>(cooldown_frames) / 60.0f;`
- **Conclusión**: No necesita cambios, la conversión ya está implementada correctamente
#### 12. **Revisar paths y PathSprite durations**
- **Problema**: En `initPaths()` líneas 1024, 1025, 1036, 1037, 1049, 1050, 1062, 1063
- **Detalle**: `createPath(..., 80, ...), 20);` - Los números 80 y 20 son frames
- **Ejemplo**: `paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 20);`
- **Investigar**: Si createPath espera segundos o milisegundos
- **Conversión**: 80 frames = 80/60 = 1.33s, 20 frames = 20/60 = 0.33s
- **Verificar**: Documentación de createPath() y PathSprite para unidades correctas
## Herramientas de Búsqueda Útiles
```bash
# Buscar magic numbers de tiempo
rg "\b(100|150|200|250|300|400|500|1000)\b" --context=2
# Buscar más frame-based operations
rg "setRotateSpeed|SDL_Delay|createPath.*[0-9]+"
# Buscar estructuras param que mencionen tiempo
rg "param\..*\.(duration|time|delay|ms|frames)"
# Buscar comentarios con "frame" or "60fps"
rg "(frame|60fps|milliseconds)" --ignore-case
```
## Prioridad de Reparación
### ✅ COMPLETADAS
1.**CRÍTICA**: Las balas no se desplazan - **SOLUCIONADO**: Velocidades convertidas de pixels/ms a pixels/segundo
2.**ALTA**: demo_.counter system - **SOLUCIONADO**: Implementados acumuladores de tiempo
3.**ALTA**: Fade durations hardcoded - **SOLUCIONADO**: Convertidos a segundos
4.**ALTA**: initPaths() frame values - **SOLUCIONADO**: Convertidos a segundos
5.**MEDIA**: Cooldown de disparos - **VERIFICADO**: Ya convierte internamente frames a segundos
6.**BAJA**: SDL_Delay investigation - **VERIFICADO**: Correcto, usa milisegundos
### ❌ PENDIENTES
7. **MEDIA**: param.fade.post_duration_ms verification (líneas 89, 1671)
8. **MEDIA**: TOTAL_DEMO_DATA - 200 magic number (línea 1669) - Nota: No necesita cambios, lógica correcta
9. **BAJA**: setRotateSpeed verification (línea 797)
10. **BAJA**: Comprehensive magic number search
## Notas Importantes
- **TODOS los contadores deben ser crecientes** (0 → constante_tope)
- **SOLO SEGUNDOS** en todo el codebase, NO frames ni milisegundos simultáneos
- **Documentar conversiones** con comentarios explicativos
- **Crear constantes** para valores repetidos
- **Evitar números mágicos** sin contexto

View File

@@ -68,7 +68,7 @@ auto Bullet::update(float deltaTime) -> BulletMoveStatus {
// Implementación del movimiento usando BulletMoveStatus (time-based)
auto Bullet::move(float deltaTime) -> BulletMoveStatus {
// DeltaTime puro: velocidad (pixels/ms) * tiempo (ms)
// DeltaTime puro: velocidad (pixels/segundo) * tiempo (segundos)
pos_x_ += vel_x_ * deltaTime;
if (pos_x_ < param.game.play_area.rect.x - WIDTH || pos_x_ > param.game.play_area.rect.w) {
disable();

View File

@@ -45,10 +45,10 @@ class Bullet {
private:
// --- Constantes ---
static constexpr float VEL_Y = -0.18F; // Velocidad vertical (pixels/ms)
static constexpr float VEL_X_LEFT = -0.12F; // Velocidad izquierda (pixels/ms)
static constexpr float VEL_X_RIGHT = 0.12F; // Velocidad derecha (pixels/ms)
static constexpr float VEL_X_CENTER = 0.0F; // Velocidad central
static constexpr float VEL_Y = -180.0F; // Velocidad vertical (pixels/segundo) - era -0.18F pixels/ms
static constexpr float VEL_X_LEFT = -120.0F; // Velocidad izquierda (pixels/segundo) - era -0.12F pixels/ms
static constexpr float VEL_X_RIGHT = 120.0F; // Velocidad derecha (pixels/segundo) - era 0.12F pixels/ms
static constexpr float VEL_X_CENTER = 0.0F; // Velocidad central
// --- Objetos y punteros ---
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos

View File

@@ -42,7 +42,7 @@ Director::Director(int argc, std::span<char *> argv) {
Section::name = Section::Name::GAME;
Section::options = Section::Options::GAME_PLAY_1P;
#elif _DEBUG
Section::name = Section::Name::TITLE;
Section::name = Section::Name::GAME;
Section::options = Section::Options::GAME_PLAY_1P;
#else // NORMAL GAME
Section::name = Section::Name::LOGO;

View File

@@ -67,16 +67,16 @@ void Item::alignTo(int x) {
void Item::render() {
if (enabled_) {
// Muestra normalmente hasta los últimos ~3.3 segundos (200 frames)
constexpr float BLINK_START_MS = LIFETIME_DURATION_MS - (200.0f * (1000.0f / 60.0f));
// Muestra normalmente hasta los últimos ~3.3 segundos
constexpr float BLINK_START_S = LIFETIME_DURATION_S - 3.33f;
if (lifetime_timer_ < BLINK_START_MS) {
if (lifetime_timer_ < BLINK_START_S) {
sprite_->render();
} else {
// Efecto de parpadeo en los últimos segundos (cada ~333ms o 20 frames)
constexpr float BLINK_INTERVAL_MS = 20.0f * (1000.0f / 60.0f);
const float phase = fmod(lifetime_timer_, BLINK_INTERVAL_MS);
const float half_interval = BLINK_INTERVAL_MS / 2.0f;
// Efecto de parpadeo en los últimos segundos (cada ~0.33 segundos)
constexpr float BLINK_INTERVAL_S = 0.33f;
const float phase = fmod(lifetime_timer_, BLINK_INTERVAL_S);
const float half_interval = BLINK_INTERVAL_S / 2.0f;
if (phase < half_interval) {
sprite_->render();
@@ -88,11 +88,11 @@ void Item::render() {
void Item::move(float deltaTime) {
floor_collision_ = false;
// Calcula la nueva posición usando deltaTime puro (velocidad en pixels/ms)
// Calcula la nueva posición usando deltaTime (velocidad en pixels/segundo)
pos_x_ += vel_x_ * deltaTime;
pos_y_ += vel_y_ * deltaTime;
// Aplica las aceleraciones a la velocidad usando deltaTime puro (aceleración en pixels/ms²)
// Aplica las aceleraciones a la velocidad usando deltaTime (aceleración en pixels/segundo²)
vel_x_ += accel_x_ * deltaTime;
vel_y_ += accel_y_ * deltaTime;
@@ -162,7 +162,7 @@ void Item::update(float deltaTime) {
void Item::updateTimeToLive(float deltaTime) {
lifetime_timer_ += deltaTime;
if (lifetime_timer_ >= LIFETIME_DURATION_MS) {
if (lifetime_timer_ >= LIFETIME_DURATION_S) {
disable();
}
}

View File

@@ -29,21 +29,21 @@ class Item {
// --- Constantes ---
static constexpr int COFFEE_MACHINE_WIDTH = 30; // Anchura de la máquina de café
static constexpr int COFFEE_MACHINE_HEIGHT = 39; // Altura de la máquina de café
static constexpr float LIFETIME_DURATION_MS = 10000.0f; // Duración de vida del ítem (600 frames a 60fps)
static constexpr float LIFETIME_DURATION_S = 10.0f; // Duración de vida del ítem en segundos
// Velocidades base (pixels/ms) - Coffee Machine
static constexpr float COFFEE_MACHINE_VEL_X_FACTOR = 0.03F; // Factor para velocidad X de máquina de café
static constexpr float COFFEE_MACHINE_VEL_Y = -0.006F; // Velocidad Y inicial de máquina de café
static constexpr float COFFEE_MACHINE_ACCEL_Y = 0.00036F; // Aceleración Y de máquina de café (pixels/ms²)
// Velocidades base (pixels/segundo) - Coffee Machine
static constexpr float COFFEE_MACHINE_VEL_X_FACTOR = 30.0F; // Factor para velocidad X de máquina de café (0.5*60fps)
static constexpr float COFFEE_MACHINE_VEL_Y = -6.0F; // Velocidad Y inicial de máquina de café (-0.1*60fps)
static constexpr float COFFEE_MACHINE_ACCEL_Y = 360.0F; // Aceleración Y de máquina de café (0.1*60²fps = 360 pixels/segundo²)
// Velocidades base (pixels/ms) - Items normales (del plan: vel_x: ±1.0F→±0.06F, vel_y: -4.0F→-0.24F, accel_y: 0.2F→0.012F)
static constexpr float ITEM_VEL_X_BASE = 0.06F; // Velocidad X base para items (1.0F/16.67)
static constexpr float ITEM_VEL_X_STEP = 0.02F; // Incremento de velocidad X (0.33F/16.67)
static constexpr float ITEM_VEL_Y = -0.24F; // Velocidad Y inicial de items (-4.0F/16.67)
static constexpr float ITEM_ACCEL_Y = 0.00072F; // Aceleración Y de items (pixels/ms²) - 0.2F * (60/1000)²
// Velocidades base (pixels/segundo) - Items normales
static constexpr float ITEM_VEL_X_BASE = 60.0F; // Velocidad X base para items (1.0F*60fps)
static constexpr float ITEM_VEL_X_STEP = 20.0F; // Incremento de velocidad X (0.33F*60fps)
static constexpr float ITEM_VEL_Y = -240.0F; // Velocidad Y inicial de items (-4.0F*60fps)
static constexpr float ITEM_ACCEL_Y = 720.0F; // Aceleración Y de items (0.2*60²fps = 720 pixels/segundo²)
// Constantes de física de rebote
static constexpr float BOUNCE_VEL_THRESHOLD = 0.06F; // Umbral de velocidad para parar (1.0F/16.67)
static constexpr float BOUNCE_VEL_THRESHOLD = 60.0F; // Umbral de velocidad para parar (1.0F*60fps)
static constexpr float COFFEE_BOUNCE_DAMPING = -0.20F; // Factor de rebote Y para máquina de café
static constexpr float ITEM_BOUNCE_DAMPING = -0.5F; // Factor de rebote Y para items normales
static constexpr float HORIZONTAL_DAMPING = 0.75F; // Factor de amortiguación horizontal
@@ -84,7 +84,7 @@ class Item {
float accel_y_; // Aceleración en el eje Y
int width_; // Ancho del objeto
int height_; // Alto del objeto
float lifetime_timer_ = 0.0f; // Acumulador de tiempo de vida del ítem (milisegundos)
float lifetime_timer_ = 0.0f; // Acumulador de tiempo de vida del ítem (segundos)
bool floor_collision_ = false; // Indica si el objeto colisiona con el suelo
bool enabled_ = true; // Indica si el objeto está habilitado

View File

@@ -159,18 +159,18 @@ void Player::move(float deltaTime) {
handleRollingMovement();
break;
case State::TITLE_ANIMATION:
handleTitleAnimation();
handleTitleAnimation(deltaTime);
break;
case State::CONTINUE_TIME_OUT:
handleContinueTimeOut();
break;
case State::LEAVING_SCREEN:
updateStepCounter(deltaTime);
handleLeavingScreen();
handleLeavingScreen(deltaTime);
break;
case State::ENTERING_SCREEN:
updateStepCounter(deltaTime);
handleEnteringScreen();
handleEnteringScreen(deltaTime);
break;
case State::CREDITS:
handleCreditsMovement(deltaTime);
@@ -253,10 +253,10 @@ void Player::handleRollingBounce() {
playSound("jump.wav");
}
void Player::handleTitleAnimation() {
void Player::handleTitleAnimation(float deltaTime) {
setInputBasedOnPlayerId();
pos_x_ += vel_x_ * 2.0F;
pos_x_ += (vel_x_ * 2.0F) * deltaTime;
const float MIN_X = -WIDTH;
const float MAX_X = play_area_.w;
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
@@ -275,11 +275,11 @@ void Player::handleContinueTimeOut() {
}
}
void Player::handleLeavingScreen() {
void Player::handleLeavingScreen(float deltaTime) {
// updateStepCounter se llama desde move() con deltaTime
setInputBasedOnPlayerId();
pos_x_ += vel_x_;
pos_x_ += vel_x_ * deltaTime;
const float MIN_X = -WIDTH;
const float MAX_X = play_area_.w;
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
@@ -290,15 +290,15 @@ void Player::handleLeavingScreen() {
}
}
void Player::handleEnteringScreen() {
void Player::handleEnteringScreen(float deltaTime) {
// updateStepCounter se llama desde move() con deltaTime
switch (id_) {
case Id::PLAYER1:
handlePlayer1Entering();
handlePlayer1Entering(deltaTime);
break;
case Id::PLAYER2:
handlePlayer2Entering();
handlePlayer2Entering(deltaTime);
break;
default:
break;
@@ -307,18 +307,18 @@ void Player::handleEnteringScreen() {
shiftSprite();
}
void Player::handlePlayer1Entering() {
void Player::handlePlayer1Entering(float deltaTime) {
setInputPlaying(Input::Action::RIGHT);
pos_x_ += vel_x_;
pos_x_ += vel_x_ * deltaTime;
if (pos_x_ > default_pos_x_) {
pos_x_ = default_pos_x_;
setPlayingState(State::PLAYING);
}
}
void Player::handlePlayer2Entering() {
void Player::handlePlayer2Entering(float deltaTime) {
setInputPlaying(Input::Action::LEFT);
pos_x_ += vel_x_;
pos_x_ += vel_x_ * deltaTime;
if (pos_x_ < default_pos_x_) {
pos_x_ = default_pos_x_;
setPlayingState(State::PLAYING);
@@ -640,14 +640,14 @@ void Player::setPlayingState(State state) {
// Activa la animación de rodar dando botes
player_sprite_->setCurrentAnimation("rolling");
player_sprite_->setAnimationSpeed(4.0f / 60.0f); // 4 frames convertido a segundos
player_sprite_->setVelY(-6.6F); // Velocidad inicial
player_sprite_->setAccelY(0.2F); // Gravedad
player_sprite_->setVelY(-396.0F); // Velocidad inicial (6.6 * 60 = 396 pixels/s)
player_sprite_->setAccelY(12.0F); // Gravedad (0.2 * 60 = 12 pixels/s²)
player_sprite_->setPosY(pos_y_ - 2); // Para "sacarlo" del suelo, ya que está hundido un pixel para ocultar el outline de los pies
(rand() % 2 == 0) ? player_sprite_->setVelX(3.3F) : player_sprite_->setVelX(-3.3F);
(rand() % 2 == 0) ? player_sprite_->setVelX(198.0F) : player_sprite_->setVelX(-198.0F); // 3.3 * 60 = 198 pixels/s
break;
}
case State::TITLE_ANIMATION: {
// Activa la animación de rodar
// Activa la animación de caminar
player_sprite_->setCurrentAnimation("walk");
playSound("voice_credit_thankyou.wav");
break;
@@ -659,8 +659,8 @@ void Player::setPlayingState(State state) {
}
case State::CONTINUE_TIME_OUT: {
// Activa la animación de sacar al jugador de la zona de juego
player_sprite_->setAccelY(0.2F);
player_sprite_->setVelY(-4.0F);
player_sprite_->setAccelY(12.0F); // 0.2 * 60 = 12 pixels/s²
player_sprite_->setVelY(-240.0F); // -4.0 * 60 = -240 pixels/s
player_sprite_->setVelX(0.0F);
player_sprite_->setCurrentAnimation("rolling");
player_sprite_->setAnimationSpeed(5.0f / 60.0f); // 5 frames convertido a segundos

View File

@@ -346,12 +346,12 @@ class Player {
void handleRollingGroundCollision(); // Gestiona la interacción del objeto rodante con el suelo (rebotes, frenado, etc.)
void handleRollingStop(); // Detiene el movimiento del objeto rodante cuando se cumplen las condiciones necesarias
void handleRollingBounce(); // Aplica una lógica de rebote al colisionar con superficies durante el rodamiento
void handleTitleAnimation(); // Ejecuta la animación del título en pantalla (ej. entrada, parpadeo o desplazamiento)
void handleTitleAnimation(float deltaTime); // Ejecuta la animación del título en pantalla (ej. entrada, parpadeo o desplazamiento)
void handleContinueTimeOut(); // Gestiona el tiempo de espera en la pantalla de "Continuar" y decide si pasar a otro estado
void handleLeavingScreen(); // Lógica para salir de la pantalla actual (transición visual o cambio de escena)
void handleEnteringScreen(); // Lógica para entrar en una nueva pantalla, posiblemente con animación o retraso
void handlePlayer1Entering(); // Controla la animación o posición de entrada del Jugador 1 en pantalla
void handlePlayer2Entering(); // Controla la animación o posición de entrada del Jugador 2 en pantalla
void handleLeavingScreen(float deltaTime); // Lógica para salir de la pantalla actual (transición visual o cambio de escena)
void handleEnteringScreen(float deltaTime); // Lógica para entrar en una nueva pantalla, posiblemente con animación o retraso
void handlePlayer1Entering(float deltaTime); // Controla la animación o posición de entrada del Jugador 1 en pantalla
void handlePlayer2Entering(float deltaTime); // Controla la animación o posición de entrada del Jugador 2 en pantalla
void handleCreditsMovement(); // Movimiento general en la pantalla de créditos (frame-based)
void handleCreditsMovement(float deltaTime); // Movimiento general en la pantalla de créditos (time-based)
void handleCreditsRightMovement(); // Lógica específica para mover los créditos hacia la derecha

View File

@@ -79,7 +79,7 @@ Game::Game(Player::Id player_id, int current_stage, bool demo)
scoreboard_ = Scoreboard::get();
fade_in_->setColor(param.fade.color);
fade_in_->setPreDuration(demo_.enabled ? DEMO_FADE_PRE_DURATION_MS : 0);
fade_in_->setPreDuration(demo_.enabled ? static_cast<int>(DEMO_FADE_PRE_DURATION_S * 1000) : 0);
fade_in_->setPostDuration(0);
fade_in_->setType(Fade::Type::RANDOM_SQUARE2);
fade_in_->setMode(Fade::Mode::IN);
@@ -327,13 +327,13 @@ void Game::updateGameStateGameOver(float deltaTime) {
checkBulletCollision();
cleanVectors();
if (game_over_timer_ < GAME_OVER_DURATION_MS) {
if (game_over_timer_ < GAME_OVER_DURATION_S) {
handleGameOverEvents(); // Maneja eventos al inicio
game_over_timer_ += deltaTime; // Incremento time-based
constexpr float FADE_TRIGGER_MS = GAME_OVER_DURATION_MS - (150.0f * (1000.0f / 60.0f)); // 2500ms antes del final
if (game_over_timer_ >= FADE_TRIGGER_MS && !fade_out_->isEnabled()) {
constexpr float FADE_TRIGGER_S = GAME_OVER_DURATION_S - 2.5f; // 2.5 segundos antes del final
if (game_over_timer_ >= FADE_TRIGGER_S && !fade_out_->isEnabled()) {
fade_out_->activate();
}
}
@@ -783,10 +783,10 @@ void Game::throwCoffee(int x, int y) {
smart_sprites_.back()->setPosY(y - 8);
smart_sprites_.back()->setWidth(param.game.item_size);
smart_sprites_.back()->setHeight(param.game.item_size);
smart_sprites_.back()->setVelX(-1.0F + ((rand() % 5) * 0.5F));
smart_sprites_.back()->setVelY(-4.0F);
smart_sprites_.back()->setVelX((-1.0F + ((rand() % 5) * 0.5F)) * 60.0f); // Convertir a pixels/segundo
smart_sprites_.back()->setVelY(-4.0F * 60.0f); // Convertir a pixels/segundo
smart_sprites_.back()->setAccelX(0.0F);
smart_sprites_.back()->setAccelY(0.2F);
smart_sprites_.back()->setAccelY(0.2F * 60.0f); // Convertir a pixels/segundo²
smart_sprites_.back()->setDestX(x + (smart_sprites_.back()->getVelX() * 50));
smart_sprites_.back()->setDestY(param.game.height + 1);
smart_sprites_.back()->setEnabled(true);
@@ -859,23 +859,23 @@ void Game::handlePlayerCollision(std::shared_ptr<Player> &player, std::shared_pt
// Actualiza el estado del tiempo detenido
void Game::updateTimeStopped(float deltaTime) {
static constexpr float WARNING_THRESHOLD_MS = 2000.0f; // 120 frames a 60fps
static constexpr float CLOCK_SOUND_INTERVAL_MS = 500.0f; // 30 frames a 60fps
static constexpr float COLOR_FLASH_INTERVAL_MS = 250.0f; // 15 frames a 60fps
static constexpr float WARNING_THRESHOLD_S = 2.0f; // 120 frames a 60fps → segundos
static constexpr float CLOCK_SOUND_INTERVAL_S = 0.5f; // 30 frames a 60fps → segundos
static constexpr float COLOR_FLASH_INTERVAL_S = 0.25f; // 15 frames a 60fps → segundos
if (time_stopped_timer_ > 0) {
time_stopped_timer_ -= deltaTime;
// Fase de advertencia (últimos 2 segundos)
if (time_stopped_timer_ <= WARNING_THRESHOLD_MS) {
if (time_stopped_timer_ <= WARNING_THRESHOLD_S) {
static float last_sound_time = 0.0f;
last_sound_time += deltaTime;
if (last_sound_time >= CLOCK_SOUND_INTERVAL_MS) {
if (last_sound_time >= CLOCK_SOUND_INTERVAL_S) {
balloon_manager_->normalColorsToAllBalloons();
playSound("clock.wav");
last_sound_time = 0.0f;
} else if (last_sound_time >= COLOR_FLASH_INTERVAL_MS) {
} else if (last_sound_time >= COLOR_FLASH_INTERVAL_S) {
balloon_manager_->reverseColorsToAllBalloons();
playSound("clock.wav");
}
@@ -883,7 +883,7 @@ void Game::updateTimeStopped(float deltaTime) {
// Fase normal - solo sonido ocasional
static float sound_timer = 0.0f;
sound_timer += deltaTime;
if (sound_timer >= CLOCK_SOUND_INTERVAL_MS) {
if (sound_timer >= CLOCK_SOUND_INTERVAL_S) {
playSound("clock.wav");
sound_timer = 0.0f;
}
@@ -978,7 +978,7 @@ void Game::fillCanvas() {
void Game::enableTimeStopItem() {
balloon_manager_->stopAllBalloons();
balloon_manager_->reverseColorsToAllBalloons();
time_stopped_timer_ = TIME_STOPPED_DURATION_MS;
time_stopped_timer_ = TIME_STOPPED_DURATION_S;
}
// Deshabilita el efecto del item de detener el tiempo
@@ -988,12 +988,12 @@ void Game::disableTimeStopItem() {
balloon_manager_->normalColorsToAllBalloons();
}
// Calcula el deltatime
// Calcula el deltatime en segundos
auto Game::calculateDeltaTime() -> float {
const Uint64 current_time = SDL_GetTicks();
const float delta_time = static_cast<float>(current_time - last_time_);
const float delta_time_ms = static_cast<float>(current_time - last_time_);
last_time_ = current_time;
return delta_time;
return delta_time_ms / 1000.0f; // Convertir de milisegundos a segundos
}
// Bucle para el juego
@@ -1021,7 +1021,7 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - (W / 2);
const int X2 = param.game.play_area.rect.w;
const int Y = param.game.play_area.center_y;
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 20);
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 0.33f); // 20 frames → segundos
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
}
@@ -1033,7 +1033,7 @@ void Game::initPaths() {
const int Y1 = param.game.play_area.center_y - (H / 2);
const int Y2 = -H;
const int X = param.game.play_area.center_x;
paths_.emplace_back(createPath(Y0, Y1, PathType::VERTICAL, X, 80, easeOutQuint), 20);
paths_.emplace_back(createPath(Y0, Y1, PathType::VERTICAL, X, 80, easeOutQuint), 0.33f); // 20 frames → segundos
paths_.emplace_back(createPath(Y1, Y2, PathType::VERTICAL, X, 80, easeInQuint), 0);
}
@@ -1046,7 +1046,7 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - (W / 2);
const int X2 = param.game.play_area.rect.w;
const int Y = param.game.play_area.center_y - (H / 2) - 20;
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400);
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 6.67f); // 400 frames → segundos
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
}
@@ -1059,7 +1059,7 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - (W / 2);
const int X2 = -W;
const int Y = param.game.play_area.center_y + (H / 2) - 20;
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400);
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 6.67f); // 400 frames → segundos
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
}
}
@@ -1660,9 +1660,12 @@ void Game::updateDemo() {
fade_in_->update();
fade_out_->update();
// Incrementa el contador de la demo
if (demo_.counter < TOTAL_DEMO_DATA) {
// Incrementa el contador de la demo cada 1/60 segundos (16.67ms)
static float demo_frame_timer = 0.0f;
demo_frame_timer += calculateDeltaTime();
if (demo_frame_timer >= 0.01667f && demo_.counter < TOTAL_DEMO_DATA) {
demo_.counter++;
demo_frame_timer -= 0.01667f; // Mantener precisión acumulada
}
// Activa el fundido antes de acabar con los datos de la demo
@@ -1686,9 +1689,13 @@ void Game::updateRecording() {
// Solo mira y guarda el input en cada update
checkInput();
// Incrementa el contador de la demo
if (demo_.counter < TOTAL_DEMO_DATA)
// Incrementa el contador de la demo cada 1/60 segundos (16.67ms)
static float recording_frame_timer = 0.0f;
recording_frame_timer += calculateDeltaTime();
if (recording_frame_timer >= 0.01667f && demo_.counter < TOTAL_DEMO_DATA) {
demo_.counter++;
recording_frame_timer -= 0.01667f; // Mantener precisión acumulada
}
// Si se ha llenado el vector con datos, sale del programa
else {
@@ -1731,10 +1738,18 @@ void Game::updateGameStateShowingGetReadyMessage(float deltaTime) {
if (path_sprites_.empty()) {
setState(State::PLAYING);
}
if (counter_ == 100) {
playMusic();
// Reproducir música después de ~1.67 segundos (100 frames a 60fps)
static bool music_started = false;
static float music_timer = 0.0f;
if (!music_started) {
music_timer += deltaTime;
if (music_timer >= 1.67f) {
playMusic();
music_started = true;
setState(State::PLAYING);
}
}
++counter_;
}
// Actualiza las variables durante el transcurso normal del juego
@@ -1895,12 +1910,12 @@ void Game::onPauseStateChanged(bool is_paused) {
// Maneja eventos del juego completado usando flags para triggers únicos
void Game::handleGameCompletedEvents() {
constexpr float START_CELEBRATIONS_MS = 6667.0f; // 400 frames a 60fps
constexpr float END_CELEBRATIONS_MS = 11667.0f; // 700 frames a 60fps
constexpr float START_CELEBRATIONS_S = 6.667f; // 400 frames a 60fps → segundos
constexpr float END_CELEBRATIONS_S = 11.667f; // 700 frames a 60fps → segundos
// Inicio de celebraciones
static bool start_celebrations_triggered = false;
if (!start_celebrations_triggered && game_completed_timer_ >= START_CELEBRATIONS_MS) {
if (!start_celebrations_triggered && game_completed_timer_ >= START_CELEBRATIONS_S) {
createMessage({paths_.at(4), paths_.at(5)}, Resource::get()->getTexture("game_text_congratulations"));
createMessage({paths_.at(6), paths_.at(7)}, Resource::get()->getTexture("game_text_1000000_points"));
@@ -1919,7 +1934,7 @@ void Game::handleGameCompletedEvents() {
// Fin de celebraciones
static bool end_celebrations_triggered = false;
if (!end_celebrations_triggered && game_completed_timer_ >= END_CELEBRATIONS_MS) {
if (!end_celebrations_triggered && game_completed_timer_ >= END_CELEBRATIONS_S) {
for (auto &player : players_) {
if (player->isCelebrating()) {
player->setPlayingState(player->qualifiesForHighScore() ? Player::State::ENTERING_NAME_GAME_COMPLETED : Player::State::LEAVING_SCREEN);

View File

@@ -73,13 +73,13 @@ class Game {
GAME_OVER, // Fin del juego
};
// --- Constantes de tiempo (en milisegundos) ---
static constexpr float HELP_COUNTER_MS = 16667.0f; // Contador de ayuda (1000 frames a 60fps)
static constexpr float GAME_COMPLETED_START_FADE_MS = 8333.0f; // Inicio del fade al completar (500 frames)
static constexpr float GAME_COMPLETED_END_MS = 11667.0f; // Fin del juego completado (700 frames)
static constexpr float GAME_OVER_DURATION_MS = 5833.0f; // Duración game over (350 frames)
static constexpr float TIME_STOPPED_DURATION_MS = 6000.0f; // Duración del tiempo detenido (360 frames)
static constexpr int DEMO_FADE_PRE_DURATION_MS = 500; // Pre-duración del fade en modo demo
// --- Constantes de tiempo (en segundos) ---
static constexpr float HELP_COUNTER_S = 16.667f; // Contador de ayuda (1000 frames a 60fps → segundos)
static constexpr float GAME_COMPLETED_START_FADE_S = 8.333f; // Inicio del fade al completar (500 frames → segundos)
static constexpr float GAME_COMPLETED_END_S = 11.667f; // Fin del juego completado (700 frames → segundos)
static constexpr float GAME_OVER_DURATION_S = 5.833f; // Duración game over (350 frames → segundos)
static constexpr float TIME_STOPPED_DURATION_S = 6.0f; // Duración del tiempo detenido (360 frames → segundos)
static constexpr float DEMO_FADE_PRE_DURATION_S = 0.5f; // Pre-duración del fade en modo demo
static constexpr int ITEM_POINTS_1_DISK_ODDS = 10;
static constexpr int ITEM_POINTS_2_GAVINA_ODDS = 6;
static constexpr int ITEM_POINTS_3_PACMAR_ODDS = 3;
@@ -102,7 +102,7 @@ class Game {
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
Helper()
: counter(HELP_COUNTER_MS),
: counter(HELP_COUNTER_S * 1000), // Convertir a milisegundos para compatibilidad
item_disk_odds(ITEM_POINTS_1_DISK_ODDS),
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS),
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS),

View File

@@ -40,12 +40,10 @@ void Tabe::render() {
// Mueve el objeto (time-based)
void Tabe::move(float deltaTime) {
// Convertir deltaTime (milisegundos) a factor de frame (asumiendo 60fps)
float frameFactor = deltaTime / (1000.0f / 60.0f);
const int X = static_cast<int>(x_);
speed_ += accel_ * frameFactor;
x_ += speed_ * frameFactor;
speed_ += accel_ * deltaTime;
x_ += speed_ * deltaTime;
fly_distance_ -= std::abs(X - static_cast<int>(x_));
// Comprueba si sale por los bordes
@@ -80,7 +78,7 @@ void Tabe::move(float deltaTime) {
if (fly_distance_ <= 0) {
if (waiting_counter_ > 0) {
accel_ = speed_ = 0.0F;
waiting_counter_ -= frameFactor;
waiting_counter_ -= deltaTime;
if (waiting_counter_ < 0) waiting_counter_ = 0;
} else {
constexpr int CHOICES = 4;
@@ -132,22 +130,22 @@ void Tabe::enable() {
void Tabe::setRandomFlyPath(Direction direction, int length) {
direction_ = direction;
fly_distance_ = length;
waiting_counter_ = 5 + rand() % 15;
waiting_counter_ = 0.083f + (rand() % 15) * 0.0167f; // 5-20 frames converted to seconds (5/60 to 20/60)
Audio::get()->playSound("tabe.wav");
constexpr float SPEED = 2.0F;
constexpr float SPEED = 120.0f; // 2 pixels/frame * 60fps = 120 pixels/second
switch (direction) {
case Direction::TO_THE_LEFT: {
speed_ = -1.0F * SPEED;
accel_ = -1.0F * (1 + rand() % 10) / 30.0F;
accel_ = -1.0F * (1 + rand() % 10) * 2.0f; // Converted from frame-based to seconds
sprite_->setFlip(SDL_FLIP_NONE);
break;
}
case Direction::TO_THE_RIGHT: {
speed_ = SPEED;
accel_ = (1 + rand() % 10) / 30.0F;
accel_ = (1 + rand() % 10) * 2.0f; // Converted from frame-based to seconds
sprite_->setFlip(SDL_FLIP_HORIZONTAL);
break;
}
@@ -169,7 +167,7 @@ void Tabe::setState(State state) {
case State::HIT:
sprite_->setCurrentAnimation("hit");
hit_counter_ = 5;
hit_counter_ = 0.083f; // 5 frames converted to seconds (5/60)
++number_of_hits_;
break;
@@ -182,9 +180,7 @@ void Tabe::setState(State state) {
// Actualiza el estado (time-based)
void Tabe::updateState(float deltaTime) {
if (state_ == State::HIT) {
// Convertir deltaTime (milisegundos) a factor de frame (asumiendo 60fps)
float frameFactor = deltaTime / (1000.0f / 60.0f);
hit_counter_ -= frameFactor;
hit_counter_ -= deltaTime;
if (hit_counter_ <= 0) {
setState(State::FLY);
}