cmasmasizat el codi

This commit is contained in:
2025-03-24 13:28:54 +01:00
parent 4a2e5c27e2
commit e2e3b7c779
6 changed files with 75 additions and 111 deletions

View File

Before

Width:  |  Height:  |  Size: 128 B

After

Width:  |  Height:  |  Size: 128 B

View File

@@ -2,16 +2,13 @@
#include "defines.h"
// Constructor
Ball::Ball(float x, float vx, float vy, Color color, Texture *texture)
Ball::Ball(float x, float vx, float vy, Color color, std::shared_ptr<Texture> texture)
{
x_ = x;
y_ = 0.0f;
w_ = BALL_SIZE;
h_ = BALL_SIZE;
pos_ = {x, 0.0f, BALL_SIZE, BALL_SIZE};
vx_ = vx;
vy_ = vy;
sprite_ = new Sprite(texture);
sprite_->setPos({(int)x, (int)y_});
sprite_ = std::make_unique<Sprite>(texture);
sprite_->setPos({pos_.x, pos_.y});
sprite_->setSize(BALL_SIZE, BALL_SIZE);
sprite_->setClip({0, 0, BALL_SIZE, BALL_SIZE});
color_ = color;
@@ -21,15 +18,6 @@ Ball::Ball(float x, float vx, float vy, Color color, Texture *texture)
loss_ = ((rand() % 30) * 0.01f) + 0.6f;
}
// Destructor
Ball::~Ball()
{
if (sprite_)
{
delete sprite_;
}
}
// Actualiza la lógica de la clase
void Ball::update()
{
@@ -39,40 +27,40 @@ void Ball::update()
}
// Aplica la gravedad a la velocidad
if (!on_floor_ && (y_ - SCREEN_HEIGHT) < BALL_SIZE * 2)
if (!on_floor_ && (pos_.y - SCREEN_HEIGHT) < BALL_SIZE * 2)
{
vy_ += gravity_force_;
}
// Actualiza la posición en función de la velocidad
x_ += vx_;
y_ += vy_;
pos_.x += vx_;
pos_.y += vy_;
// Comprueba las colisiones con el lateral izquierdo
if (x_ < 0)
if (pos_.x < 0)
{
x_ = 0;
pos_.x = 0;
vx_ = -vx_;
}
// Comprueba las colisiones con el lateral derecho
if (x_ + w_ > SCREEN_WIDTH)
if (pos_.x + pos_.w > SCREEN_WIDTH)
{
x_ = SCREEN_WIDTH - w_;
pos_.x = SCREEN_WIDTH - pos_.w;
vx_ = -vx_;
}
// Comprueba las colisiones con la parte superior
if (y_ < 0)
if (pos_.y < 0)
{
y_ = 0;
pos_.y = 0;
vy_ = -vy_;
}
// Comprueba las colisiones con la parte inferior
if (y_ + h_ > SCREEN_HEIGHT)
if (pos_.y + pos_.h > SCREEN_HEIGHT)
{
y_ = SCREEN_HEIGHT - h_;
pos_.y = SCREEN_HEIGHT - pos_.h;
vy_ = -vy_ * loss_;
if (abs(vy_) < 0.1f)
{
@@ -93,7 +81,7 @@ void Ball::update()
}
// Actualiza la posición del sprite
sprite_->setPos({(int)x_, (int)y_});
sprite_->setPos({pos_.x, pos_.y});
}
// Pinta la clase

View File

@@ -1,5 +1,6 @@
#pragma once
#include <memory>
#include "sprite.h"
#include "texture.h"
#include "defines.h"
@@ -7,11 +8,8 @@
class Ball
{
private:
Sprite *sprite_; // Sprite para pintar la clase
float x_; // Posición x
float y_; // Posición y
int w_; // Ancho
int h_; // Alto
std::unique_ptr<Sprite> sprite_; // Sprite para pintar la clase
SDL_FRect pos_; // Posición y tamaño de la pelota
float vx_, vy_; // Velocidad
float gravity_force_; // Gravedad
Color color_; // Color de la pelota
@@ -21,10 +19,10 @@ private:
public:
// Constructor
Ball(float x, float vx, float vy, Color color, Texture *texture);
Ball(float x, float vx, float vy, Color color, std::shared_ptr<Texture> texture);
// Destructor
~Ball();
~Ball() = default;
// Actualiza la lógica de la clase
void update();

View File

@@ -5,31 +5,33 @@
#include "dbgtxt.h"
#include <iostream>
#include <vector>
#include <array>
#include <cstdlib>
#include <ctime>
#include <memory>
// Variables globales
SDL_Window *window = nullptr;
SDL_Renderer *renderer = nullptr;
Texture *texture = nullptr;
std::vector<Ball *> balls;
int test[8] = {1, 10, 100, 500, 1000, 10000, 50000, 100000};
std::shared_ptr<Texture> texture = nullptr;
std::vector<std::unique_ptr<Ball>> balls;
std::array<int, 8> test = {1, 10, 100, 500, 1000, 10000, 50000, 100000};
bool should_exit = false; // Controla si la aplicación debe cerrarse
Uint64 ticks = 0; // Tiempo en milisegundos para controlar la actualización
int scenario = 0; // Escenario actual basado en el número de bolas
std::string text = ""; // Texto a mostrar en pantalla
std::string text; // Texto a mostrar en pantalla
int text_pos = 0; // Posición del texto en la pantalla
bool show_text = true; // Determina si el texto se debe mostrar
Uint64 text_init_time = 0; // Temporizador para mostrar el texto
void deleteBalls(); // Declaración de una función para eliminar bolas
// Establece el texto en pantalla mostrando el número de bolas actuales
void setText()
{
const std::string TEXT2 = test[scenario] == 1 ? " PELOTA" : " PELOTAS";
text = std::to_string(test[scenario]) + TEXT2;
const int SIZE = text.size() * 8;
text_pos = SCREEN_WIDTH / 2 - SIZE / 2;
const std::string TEXT_NUMBER = test[scenario] == 1 ? " PELOTA" : " PELOTAS";
text = std::to_string(test[scenario]) + TEXT_NUMBER;
const int TEXT_SIZE = static_cast<int>(text.size() * 8);
text_pos = SCREEN_WIDTH / 2 - TEXT_SIZE / 2;
text_init_time = SDL_GetTicks();
show_text = true;
}
@@ -37,27 +39,26 @@ void setText()
// Inicializa las bolas según el escenario seleccionado
void initBalls(int value)
{
deleteBalls(); // Limpia las bolas actuales
for (int i = 0; i < test[value]; ++i)
balls.clear();
for (int i = 0; i < test.at(value); ++i)
{
const int SIGN = ((rand() % 2) * 2) - 1; // Genera un signo aleatorio (+ o -)
const float X = (rand() % (SCREEN_WIDTH / 2)) + (SCREEN_WIDTH / 4); // Posición inicial en X
const float VX = (((rand() % 20) + 10) * 0.1f) * SIGN; // Velocidad en X
const float VY = ((rand() % 60) - 30) * 0.1f; // Velocidad en Y
const Color COLOR = {(rand() % 192) + 32, (rand() % 192) + 32, (rand() % 192) + 32}; // Color aleatorio
Ball *b = new Ball(X, VX, VY, COLOR, texture);
balls.push_back(b); // Añadir la nueva bola al vector
balls.emplace_back(std::make_unique<Ball>(X, VX, VY, COLOR, texture));
}
setText(); // Actualizar el texto
setText(); // Actualiza el texto
}
// Aumenta la velocidad vertical de las bolas "hacia arriba"
void pushUpBalls()
{
for (auto ball : balls)
for (auto &ball : balls)
{
const int SIGN = ((rand() % 2) * 2) - 1;
const float VX = (((rand() % 20) + 10) * 0.1f) * SIGN;
const int SIGNO = ((rand() % 2) * 2) - 1;
const float VX = (((rand() % 20) + 10) * 0.1f) * SIGNO;
const float VY = ((rand() % 40) * 0.1f) + 5;
ball->modVel(VX, -VY); // Modifica la velocidad de la bola
}
@@ -66,38 +67,21 @@ void pushUpBalls()
// Cambia la gravedad de todas las bolas
void switchBallsGravity()
{
for (auto ball : balls)
{
if (ball)
for (auto &ball : balls)
{
ball->switchGravity();
}
}
}
// Elimina todas las bolas y libera memoria
void deleteBalls()
{
for (auto ball : balls)
{
if (ball)
{
delete ball;
ball = nullptr;
}
}
balls.clear(); // Limpia el vector
}
// Inicializa SDL y configura los componentes principales
bool init()
{
bool success = true; // Bandera de éxito
bool success = true;
// Inicializa SDL
if (!SDL_Init(SDL_INIT_VIDEO))
{
printf("¡SDL no se pudo inicializar! Error de SDL: %s\n", SDL_GetError());
std::cout << "¡SDL no se pudo inicializar! Error de SDL: " << SDL_GetError() << std::endl;
success = false;
}
else
@@ -106,7 +90,7 @@ bool init()
window = SDL_CreateWindow(WINDOW_CAPTION, SCREEN_WIDTH * WINDOW_SIZE, SCREEN_HEIGHT * WINDOW_SIZE, SDL_WINDOW_OPENGL);
if (window == nullptr)
{
printf("¡No se pudo crear la ventana! Error de SDL: %s\n", SDL_GetError());
std::cout << "¡No se pudo crear la ventana! Error de SDL: " << SDL_GetError() << std::endl;
success = false;
}
else
@@ -115,7 +99,7 @@ bool init()
renderer = SDL_CreateRenderer(window, nullptr);
if (renderer == nullptr)
{
printf("¡No se pudo crear el renderizador! Error de SDL: %s\n", SDL_GetError());
std::cout << "¡No se pudo crear el renderizador! Error de SDL: " << SDL_GetError() << std::endl;
success = false;
}
else
@@ -130,10 +114,10 @@ bool init()
}
// Inicializar otros componentes
texture = new Texture(renderer, "resources/pelota.png");
texture = std::make_shared<Texture>(renderer, "resources/ball.png");
ticks = SDL_GetTicks();
srand(time(nullptr));
dbg_init(renderer); // Inicializar herramientas de depuración
srand(static_cast<unsigned>(time(nullptr)));
dbg_init(renderer);
initBalls(scenario);
return success;
@@ -144,18 +128,7 @@ void close()
{
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
window = nullptr;
renderer = nullptr;
if (texture)
{
delete texture;
texture = nullptr;
}
deleteBalls(); // Liberar memoria de las bolas
SDL_Quit(); // Finalizar SDL
SDL_Quit();
}
// Verifica los eventos en la cola
@@ -239,7 +212,7 @@ void update()
{
ticks = SDL_GetTicks();
for (auto ball : balls)
for (auto &ball : balls)
{
ball->update();
}
@@ -257,7 +230,7 @@ void render()
SDL_SetRenderDrawColor(renderer, 32, 32, 32, 255);
SDL_RenderClear(renderer);
for (auto ball : balls)
for (auto &ball : balls)
{
ball->render();
}
@@ -273,7 +246,11 @@ void render()
// Función principal
int main(int argc, char *args[])
{
init();
if (!init())
{
std::cout << "Ocurrió un error durante la inicialización." << std::endl;
return 1;
}
while (!should_exit)
{

View File

@@ -1,13 +1,13 @@
#include "sprite.h"
// Constructor
Sprite::Sprite(Texture *texture)
Sprite::Sprite(std::shared_ptr<Texture> texture)
: texture_(texture),
pos_{0, 0, 0, 0},
clip_{0, 0, 0, 0} {}
pos_{0.0f, 0.0f, 0.0f, 0.0f},
clip_{0.0f, 0.0f, 0.0f, 0.0f} {}
// Establece la posición del sprite
void Sprite::setPos(SDL_Point pos)
void Sprite::setPos(SDL_FPoint pos)
{
pos_.x = pos.x;
pos_.y = pos.y;
@@ -26,7 +26,7 @@ void Sprite::setClip(SDL_FRect clip)
}
// Establece el tamaño del sprite
void Sprite::setSize(int w, int h)
void Sprite::setSize(float w, float h)
{
pos_.w = w;
pos_.h = h;

View File

@@ -1,24 +1,25 @@
#pragma once
#include <SDL3/SDL.h>
#include <memory>
#include "texture.h"
class Sprite
{
private:
Texture *texture_; // Textura con los gráficos del sprite
std::shared_ptr<Texture> texture_; // Textura con los gráficos del sprite
SDL_FRect pos_; // Posición y tamaño del sprite
SDL_FRect clip_; // Parte de la textura que se va a dibujar
public:
// Constructor
explicit Sprite(Texture *texture);
explicit Sprite(std::shared_ptr<Texture> texture);
// Destructor
~Sprite() = default;
// Establece la posición del sprite
void setPos(SDL_Point pos);
void setPos(SDL_FPoint pos);
// Pinta el sprite
void render();
@@ -27,7 +28,7 @@ public:
void setClip(SDL_FRect clip);
// Establece el tamaño del sprite
void setSize(int w, int h);
void setSize(float w, float h);
// Modulación de color
void setColor(int r, int g, int b);