Quitadas todas las variables globales y transformadas en punteros

This commit is contained in:
2022-10-20 18:24:12 +02:00
parent 596bf2c4a5
commit b4e76a4c7d
25 changed files with 848 additions and 781 deletions

View File

@@ -1,30 +1,30 @@
#include "background.h" #include "background.h"
//Constructor // Constructor
Background::Background() Background::Background()
{ {
init(0, 0, 0, 0, NULL); init(0, 0, 0, 0, NULL);
} }
//Inicializador // Inicializador
void Background::init(int x, int y, int w, int h, LTexture *texture) void Background::init(int x, int y, int w, int h, LTexture *texture)
{ {
//Establece el alto y el ancho del sprite del fondo // Establece el alto y el ancho del sprite del fondo
mSprite.setWidth(w); mSprite.setWidth(w);
mSprite.setHeight(h); mSprite.setHeight(h);
//Establece la posición X,Y del sprite del fondo // Establece la posición X,Y del sprite del fondo
mSprite.setPosX(x); mSprite.setPosX(x);
mSprite.setPosY(y); mSprite.setPosY(y);
//Establece la textura donde están los gráficos para el sprite del fondo // Establece la textura donde están los gráficos para el sprite del fondo
mSprite.setTexture(*texture); mSprite.setTexture(*texture);
//Establece el rectangulo de donde coger la imagen // Establece el rectangulo de donde coger la imagen
mSprite.setSpriteClip(0, 0, mSprite.getWidth(), mSprite.getHeight()); mSprite.setSpriteClip(0, 0, mSprite.getWidth(), mSprite.getHeight());
} }
//Pinta el fondo en la pantalla // Pinta el fondo en la pantalla
void Background::render() void Background::render()
{ {
mSprite.render(); mSprite.render();

View File

@@ -5,21 +5,21 @@
#ifndef BACKGROUND_H #ifndef BACKGROUND_H
#define BACKGROUND_H #define BACKGROUND_H
//Clase para el fondo de pantalla del juego // Clase para el fondo de pantalla del juego
class Background class Background
{ {
public: public:
//Constructor // Constructor
Background(); Background();
//Inicializador // Inicializador
void init(int x, int y, int w, int h, LTexture *texture); void init(int x, int y, int w, int h, LTexture *texture);
//Pinta el fondo en la pantalla // Pinta el fondo en la pantalla
void render(); void render();
private: private:
//Variables // Variables
Sprite mSprite; Sprite mSprite;
}; };

View File

@@ -1,155 +1,171 @@
#include "balloon.h" #include "balloon.h"
//Constructor // Constructor
Balloon::Balloon() Balloon::Balloon(SDL_Renderer *gRenderer)
{ {
this->gRenderer = gRenderer;
gBalloonTexture = new LTexture(gRenderer);
// Carga los gráficos de los globos
if (!gBalloonTexture->loadFromFile("media/gfx/balloon.png"))
{
printf("Failed to load balloon texture!\n");
}
init(0, 0, NO_KIND, BALLON_VELX_POSITIVE, 0); init(0, 0, NO_KIND, BALLON_VELX_POSITIVE, 0);
} }
//Inicializador // Destructor
Balloon::~Balloon()
{
gBalloonTexture->free();
}
// Inicializador
void Balloon::init(int x, int y, Uint8 kind, float velx, Uint16 creationtimer) void Balloon::init(int x, int y, Uint8 kind, float velx, Uint16 creationtimer)
{ {
switch (kind) switch (kind)
{ {
case BALLOON_1: case BALLOON_1:
//Posición inicial // Posición inicial
mPosX = x; mPosX = x;
mPosY = y; mPosY = y;
//Alto y ancho del objeto // Alto y ancho del objeto
mWidth = 8; mWidth = 8;
mHeight = mWidth; mHeight = mWidth;
//Inicializa los valores de velocidad y gravedad // Inicializa los valores de velocidad y gravedad
mVelX = velx; mVelX = velx;
mVelY = 0; mVelY = 0;
mMaxVelY = 3; mMaxVelY = 3;
mGravity = 0.09; mGravity = 0.09;
mDefaultVelY = 3; mDefaultVelY = 3;
//Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
mScore = 50; mScore = 50;
//Rectangulo con la imagen del sprite // Rectangulo con la imagen del sprite
mSprite.setSpriteClip(37 + 21 + 13, 0, mWidth, mHeight); mSprite.setSpriteClip(37 + 21 + 13, 0, mWidth, mHeight);
break; break;
case BALLOON_2: case BALLOON_2:
//Posición inicial // Posición inicial
mPosX = x; mPosX = x;
mPosY = y; mPosY = y;
//Alto y ancho del objeto // Alto y ancho del objeto
mWidth = 13; mWidth = 13;
mHeight = mWidth; mHeight = mWidth;
//Inicializa los valores de velocidad y gravedad // Inicializa los valores de velocidad y gravedad
mVelX = velx; mVelX = velx;
mVelY = 0; mVelY = 0;
mMaxVelY = 3; mMaxVelY = 3;
mGravity = 0.10; mGravity = 0.10;
mDefaultVelY = 4; mDefaultVelY = 4;
//Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
mScore = 100; mScore = 100;
//Rectangulo con la imagen del sprite // Rectangulo con la imagen del sprite
mSprite.setSpriteClip(37 + 21, 0, mWidth, mHeight); mSprite.setSpriteClip(37 + 21, 0, mWidth, mHeight);
break; break;
case BALLOON_3: case BALLOON_3:
//Posición inicial // Posición inicial
mPosX = x; mPosX = x;
mPosY = y; mPosY = y;
//Alto y ancho del objeto // Alto y ancho del objeto
mWidth = 21; mWidth = 21;
mHeight = mWidth; mHeight = mWidth;
//Inicializa los valores de velocidad y gravedad // Inicializa los valores de velocidad y gravedad
mVelX = velx; mVelX = velx;
mVelY = 0; mVelY = 0;
mMaxVelY = 3; mMaxVelY = 3;
mGravity = 0.10; mGravity = 0.10;
mDefaultVelY = 4.5; mDefaultVelY = 4.5;
//Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
mScore = 200; mScore = 200;
//Rectangulo con la imagen del sprite // Rectangulo con la imagen del sprite
mSprite.setSpriteClip(37, 0, mWidth, mHeight); mSprite.setSpriteClip(37, 0, mWidth, mHeight);
break; break;
case BALLOON_4: case BALLOON_4:
//Posición inicial // Posición inicial
mPosX = x; mPosX = x;
mPosY = y; mPosY = y;
//Alto y ancho del objeto // Alto y ancho del objeto
mWidth = 37; mWidth = 37;
mHeight = mWidth; mHeight = mWidth;
//Inicializa los valores de velocidad y gravedad // Inicializa los valores de velocidad y gravedad
mVelX = velx; mVelX = velx;
mVelY = 0; mVelY = 0;
mMaxVelY = 3; mMaxVelY = 3;
mGravity = 0.10; mGravity = 0.10;
mDefaultVelY = 5; mDefaultVelY = 5;
//Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
mScore = 400; mScore = 400;
//Rectangulo con la imagen del sprite // Rectangulo con la imagen del sprite
mSprite.setSpriteClip(0, 0, mWidth, mHeight); mSprite.setSpriteClip(0, 0, mWidth, mHeight);
break; break;
default: default:
//Posición inicial // Posición inicial
mPosX = x; mPosX = x;
mPosY = y; mPosY = y;
//Alto y ancho del objeto // Alto y ancho del objeto
mWidth = 0; mWidth = 0;
mHeight = mWidth; mHeight = mWidth;
//Inicializa los valores de velocidad y gravedad // Inicializa los valores de velocidad y gravedad
mVelX = velx; mVelX = velx;
mVelY = 0; mVelY = 0;
mMaxVelY = 0; mMaxVelY = 0;
mGravity = 0; mGravity = 0;
mDefaultVelY = 0; mDefaultVelY = 0;
//Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
mScore = 0; mScore = 0;
//Rectangulo con la imagen del sprite // Rectangulo con la imagen del sprite
mSprite.setSpriteClip(0, 0, mWidth, mHeight); mSprite.setSpriteClip(0, 0, mWidth, mHeight);
break; break;
} }
//Textura con los gráficos del sprite // Textura con los gráficos del sprite
mSprite.setTexture(gBalloonTexture); mSprite.setTexture(*gBalloonTexture);
//Alto y ancho del sprite // Alto y ancho del sprite
mSprite.setWidth(mWidth); mSprite.setWidth(mWidth);
mSprite.setHeight(mHeight); mSprite.setHeight(mHeight);
//Posición X,Y del sprite // Posición X,Y del sprite
mSprite.setPosX(mPosX); mSprite.setPosX(mPosX);
mSprite.setPosY(mPosY); mSprite.setPosY(mPosY);
//Tamaño del circulo de colisión // Tamaño del circulo de colisión
mCollider.r = mWidth / 2; mCollider.r = mWidth / 2;
//Alinea el circulo de colisión con el objeto // Alinea el circulo de colisión con el objeto
shiftColliders(); shiftColliders();
//Inicializa variables // Inicializa variables
mStopped = true; mStopped = true;
mStoppedTimer = 0; mStoppedTimer = 0;
mBlinking = false; mBlinking = false;
@@ -158,11 +174,11 @@ void Balloon::init(int x, int y, Uint8 kind, float velx, Uint16 creationtimer)
mBeingCreated = true; mBeingCreated = true;
mCreationTimer = creationtimer; mCreationTimer = creationtimer;
//Tipo // Tipo
mKind = kind; mKind = kind;
} }
//Centra el globo en la posición X // Centra el globo en la posición X
void Balloon::allignTo(int x) void Balloon::allignTo(int x)
{ {
mPosX = x - (mWidth / 2); mPosX = x - (mWidth / 2);
@@ -176,15 +192,15 @@ void Balloon::allignTo(int x)
mPosX = PLAY_AREA_RIGHT - mWidth - 1; mPosX = PLAY_AREA_RIGHT - mWidth - 1;
} }
//Posición X,Y del sprite // Posición X,Y del sprite
mSprite.setPosX(getPosX()); mSprite.setPosX(getPosX());
mSprite.setPosY(getPosY()); mSprite.setPosY(getPosY());
//Alinea el circulo de colisión con el objeto // Alinea el circulo de colisión con el objeto
shiftColliders(); shiftColliders();
} }
//Pinta el globo en la pantalla // Pinta el globo en la pantalla
void Balloon::render() void Balloon::render()
{ {
if (mVisible) if (mVisible)
@@ -193,49 +209,49 @@ void Balloon::render()
} }
} }
//Actualiza la posición y estados del globo // Actualiza la posición y estados del globo
void Balloon::move() void Balloon::move()
{ {
//Comprobamos si se puede mover // Comprobamos si se puede mover
if (isStopped() == false) if (isStopped() == false)
{ {
//Lo movemos a izquierda o derecha // Lo movemos a izquierda o derecha
mPosX += mVelX; mPosX += mVelX;
//Si queda fuera de pantalla, corregimos su posición y cambiamos su sentido // Si queda fuera de pantalla, corregimos su posición y cambiamos su sentido
if ((mPosX < PLAY_AREA_LEFT) || (mPosX + mWidth > PLAY_AREA_RIGHT)) if ((mPosX < PLAY_AREA_LEFT) || (mPosX + mWidth > PLAY_AREA_RIGHT))
{ {
//Corregir posición // Corregir posición
mPosX -= mVelX; mPosX -= mVelX;
//Invertir sentido // Invertir sentido
mVelX = -mVelX; mVelX = -mVelX;
} }
//Mueve el globo hacia arriba o hacia abajo // Mueve el globo hacia arriba o hacia abajo
mPosY += int(mVelY); mPosY += int(mVelY);
//Si se sale por arriba // Si se sale por arriba
if (mPosY < PLAY_AREA_TOP) if (mPosY < PLAY_AREA_TOP)
{ {
//Corregimos // Corregimos
mPosY -= int(mVelY); mPosY -= int(mVelY);
//Invertimos sentido // Invertimos sentido
mVelY = -mVelY; mVelY = -mVelY;
} }
//Si el globo se sale por la parte inferior // Si el globo se sale por la parte inferior
if (mPosY + mHeight > PLAY_AREA_BOTTOM) if (mPosY + mHeight > PLAY_AREA_BOTTOM)
{ {
//Corregimos // Corregimos
mPosY -= int(mVelY); mPosY -= int(mVelY);
//Invertimos colocando una velocidad por defecto // Invertimos colocando una velocidad por defecto
mVelY = -mDefaultVelY; mVelY = -mDefaultVelY;
} }
//Aplica gravedad al objeto, sin pasarse de un limite establecido // Aplica gravedad al objeto, sin pasarse de un limite establecido
if (int(mVelY) > mMaxVelY) if (int(mVelY) > mMaxVelY)
{ {
mVelY = mMaxVelY; mVelY = mMaxVelY;
@@ -245,39 +261,39 @@ void Balloon::move()
mVelY += mGravity; mVelY += mGravity;
} }
//Actualiza la posición del sprite // Actualiza la posición del sprite
mSprite.setPosX(getPosX()); mSprite.setPosX(getPosX());
mSprite.setPosY(mPosY); mSprite.setPosY(mPosY);
//Actualiza la posición del circulo de colisión // Actualiza la posición del circulo de colisión
shiftColliders(); shiftColliders();
} }
//Si no se puede mover: // Si no se puede mover:
//Comprobar si se está creando // Comprobar si se está creando
else if (isBeingCreated() == true) else if (isBeingCreated() == true)
{ {
//Actualiza el valor de las variables // Actualiza el valor de las variables
setStop(true); setStop(true);
setInvulnerable(true); setInvulnerable(true);
//Todavia tiene tiempo en el contador // Todavia tiene tiempo en el contador
if (mCreationTimer > 0) if (mCreationTimer > 0)
{ {
//Desplaza lentamente el globo hacia abajo y hacia un lado // Desplaza lentamente el globo hacia abajo y hacia un lado
if (mCreationTimer % 10 == 0) if (mCreationTimer % 10 == 0)
{ {
++mPosY; ++mPosY;
mPosX += mVelX; mPosX += mVelX;
//Actualiza la posición del sprite // Actualiza la posición del sprite
mSprite.setPosX(getPosX()); mSprite.setPosX(getPosX());
mSprite.setPosY(mPosY); mSprite.setPosY(mPosY);
//Actualiza la posición del circulo de colisión // Actualiza la posición del circulo de colisión
shiftColliders(); shiftColliders();
} }
//Hace visible el globo de forma intermitente // Hace visible el globo de forma intermitente
if (mCreationTimer > 100) if (mCreationTimer > 100)
{ {
setVisible(mCreationTimer / 10 % 2 == 0); setVisible(mCreationTimer / 10 % 2 == 0);
@@ -289,7 +305,7 @@ void Balloon::move()
--mCreationTimer; --mCreationTimer;
} }
//El contador ha llegado a cero // El contador ha llegado a cero
else else
{ {
setBeingCreated(false); setBeingCreated(false);
@@ -298,14 +314,14 @@ void Balloon::move()
setInvulnerable(false); setInvulnerable(false);
} }
} }
//Comprobar si está detenido // Comprobar si está detenido
else if (isStopped() == true) else if (isStopped() == true)
{ {
//Si todavía está detenido, reduce el contador // Si todavía está detenido, reduce el contador
if (mStoppedTimer > 0) if (mStoppedTimer > 0)
{ {
--mStoppedTimer; --mStoppedTimer;
} //Si el contador ha llegado a cero, ya no está detenido } // Si el contador ha llegado a cero, ya no está detenido
else else
{ {
setStop(false); setStop(false);
@@ -313,13 +329,13 @@ void Balloon::move()
} }
} }
//Pone a cero todos los valores del globo // Pone a cero todos los valores del globo
void Balloon::erase() void Balloon::erase()
{ {
init(0, 0, NO_KIND, 0, 0); init(0, 0, NO_KIND, 0, 0);
} }
//Comprueba si el globo tiene algun tipo asignado // Comprueba si el globo tiene algun tipo asignado
bool Balloon::isActive() bool Balloon::isActive()
{ {
if (mKind == NO_KIND) if (mKind == NO_KIND)
@@ -332,136 +348,136 @@ bool Balloon::isActive()
} }
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
int Balloon::getPosX() int Balloon::getPosX()
{ {
return int(mPosX); return int(mPosX);
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
int Balloon::getPosY() int Balloon::getPosY()
{ {
return mPosY; return mPosY;
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
float Balloon::getVelY() float Balloon::getVelY()
{ {
return mVelY; return mVelY;
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
int Balloon::getWidth() int Balloon::getWidth()
{ {
return mWidth; return mWidth;
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
int Balloon::getHeight() int Balloon::getHeight()
{ {
return mHeight; return mHeight;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Balloon::setVelY(float velY) void Balloon::setVelY(float velY)
{ {
mVelY = velY; mVelY = velY;
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
int Balloon::getKind() int Balloon::getKind()
{ {
return mKind; return mKind;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Balloon::setStop(bool state) void Balloon::setStop(bool state)
{ {
mStopped = state; mStopped = state;
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
bool Balloon::isStopped() bool Balloon::isStopped()
{ {
return mStopped; return mStopped;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Balloon::setBlink(bool state) void Balloon::setBlink(bool state)
{ {
mBlinking = state; mBlinking = state;
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
bool Balloon::isBlinking() bool Balloon::isBlinking()
{ {
return mBlinking; return mBlinking;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Balloon::setVisible(bool state) void Balloon::setVisible(bool state)
{ {
mVisible = state; mVisible = state;
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
bool Balloon::isVisible() bool Balloon::isVisible()
{ {
return mVisible; return mVisible;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Balloon::setInvulnerable(bool state) void Balloon::setInvulnerable(bool state)
{ {
mInvulnerable = state; mInvulnerable = state;
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
bool Balloon::isInvulnerable() bool Balloon::isInvulnerable()
{ {
return mInvulnerable; return mInvulnerable;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Balloon::setBeingCreated(bool state) void Balloon::setBeingCreated(bool state)
{ {
mBeingCreated = state; mBeingCreated = state;
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
bool Balloon::isBeingCreated() bool Balloon::isBeingCreated()
{ {
return mBeingCreated; return mBeingCreated;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Balloon::setStoppedTimer(Uint16 time) void Balloon::setStoppedTimer(Uint16 time)
{ {
mStoppedTimer = time; mStoppedTimer = time;
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
Uint16 Balloon::getStoppedTimer() Uint16 Balloon::getStoppedTimer()
{ {
return mStoppedTimer; return mStoppedTimer;
} }
//Obtiene del valor de la variable // Obtiene del valor de la variable
Uint16 Balloon::getScore() Uint16 Balloon::getScore()
{ {
return mScore; return mScore;
} }
//Obtiene el circulo de colisión // Obtiene el circulo de colisión
Circle &Balloon::getCollider() Circle &Balloon::getCollider()
{ {
return mCollider; return mCollider;
} }
//Alinea el circulo de colisión con la posición del objeto globo // Alinea el circulo de colisión con la posición del objeto globo
void Balloon::shiftColliders() void Balloon::shiftColliders()
{ {
//Align collider to center of balloon // Align collider to center of balloon
mCollider.x = mPosX + mCollider.r; mCollider.x = mPosX + mCollider.r;
mCollider.y = mPosY + mCollider.r; mCollider.y = mPosY + mCollider.r;
} }

View File

@@ -3,149 +3,156 @@
#include "sprite.h" #include "sprite.h"
#include "const.h" #include "const.h"
#include "globals.h" #include "globals.h"
#include "globals2.h"
#ifndef BALLOON_H #ifndef BALLOON_H
#define BALLOON_H #define BALLOON_H
//Clase globo // Clase globo
class Balloon class Balloon
{ {
public: public:
//Constructor // Constructor
Balloon(); Balloon(SDL_Renderer *gRenderer);
//Inicializador // Destructor
~Balloon();
// Inicializador
void init(int x, int y, Uint8 kind, float velx, Uint16 creationtimer); void init(int x, int y, Uint8 kind, float velx, Uint16 creationtimer);
//Centra el globo en la posición X // Centra el globo en la posición X
void allignTo(int x); void allignTo(int x);
//Pinta el globo en la pantalla // Pinta el globo en la pantalla
void render(); void render();
//Actualiza la posición y estados del globo // Actualiza la posición y estados del globo
void move(); void move();
//Pone a cero todos los valores del globo // Pone a cero todos los valores del globo
void erase(); void erase();
//Comprueba si el globo tiene algun tipo asignado // Comprueba si el globo tiene algun tipo asignado
bool isActive(); bool isActive();
//Obtiene del valor de la variable // Obtiene del valor de la variable
int getPosX(); int getPosX();
//Obtiene del valor de la variable // Obtiene del valor de la variable
int getPosY(); int getPosY();
//Obtiene del valor de la variable // Obtiene del valor de la variable
float getVelY(); float getVelY();
//Obtiene del valor de la variable // Obtiene del valor de la variable
int getWidth(); int getWidth();
//Obtiene del valor de la variable // Obtiene del valor de la variable
int getHeight(); int getHeight();
//Establece el valor de la variable // Establece el valor de la variable
void setVelY(float velY); void setVelY(float velY);
//Obtiene del valor de la variable // Obtiene del valor de la variable
int getKind(); int getKind();
//Establece el valor de la variable // Establece el valor de la variable
void setStop(bool state); void setStop(bool state);
//Obtiene del valor de la variable // Obtiene del valor de la variable
bool isStopped(); bool isStopped();
//Establece el valor de la variable // Establece el valor de la variable
void setBlink(bool state); void setBlink(bool state);
//Obtiene del valor de la variable // Obtiene del valor de la variable
bool isBlinking(); bool isBlinking();
//Establece el valor de la variable // Establece el valor de la variable
void setVisible(bool state); void setVisible(bool state);
//Obtiene del valor de la variable // Obtiene del valor de la variable
bool isVisible(); bool isVisible();
//Establece el valor de la variable // Establece el valor de la variable
void setInvulnerable(bool state); void setInvulnerable(bool state);
//Obtiene del valor de la variable // Obtiene del valor de la variable
bool isInvulnerable(); bool isInvulnerable();
//Establece el valor de la variable // Establece el valor de la variable
void setBeingCreated(bool state); void setBeingCreated(bool state);
//Obtiene del valor de la variable // Obtiene del valor de la variable
bool isBeingCreated(); bool isBeingCreated();
//Establece el valor de la variable // Establece el valor de la variable
void setStoppedTimer(Uint16 time); void setStoppedTimer(Uint16 time);
//Obtiene del valor de la variable // Obtiene del valor de la variable
Uint16 getStoppedTimer(); Uint16 getStoppedTimer();
//Obtiene del valor de la variable // Obtiene del valor de la variable
Uint16 getScore(); Uint16 getScore();
//Obtiene el circulo de colisión // Obtiene el circulo de colisión
Circle &getCollider(); Circle &getCollider();
private: private:
//Posición X,Y del objeto globo // El renderizador de la ventana
SDL_Renderer *gRenderer;
LTexture *gBalloonTexture;
// Posición X,Y del objeto globo
float mPosX; float mPosX;
int mPosY; int mPosY;
//Alto y ancho del objeto globo // Alto y ancho del objeto globo
Uint8 mWidth; Uint8 mWidth;
Uint8 mHeight; Uint8 mHeight;
//Variables para controlar la velocidad del globo // Variables para controlar la velocidad del globo
float mVelX; float mVelX;
float mVelY; float mVelY;
float mGravity; float mGravity;
float mDefaultVelY; float mDefaultVelY;
int mMaxVelY; int mMaxVelY;
//Puntos que da el globo al ser destruido // Puntos que da el globo al ser destruido
Uint16 mScore; Uint16 mScore;
//Indica si el globo está parado // Indica si el globo está parado
bool mStopped; bool mStopped;
//Temporizador para controlar el estado "parado" // Temporizador para controlar el estado "parado"
Uint16 mStoppedTimer; Uint16 mStoppedTimer;
//Indica si el globo está intermitente // Indica si el globo está intermitente
bool mBlinking; bool mBlinking;
//Indica si el globo es visible // Indica si el globo es visible
bool mVisible; bool mVisible;
//Indica si el globo es invulnerable // Indica si el globo es invulnerable
bool mInvulnerable; bool mInvulnerable;
//Indica si el globo se está creando // Indica si el globo se está creando
bool mBeingCreated; bool mBeingCreated;
//Temporizador para controlar el estado "creandose" // Temporizador para controlar el estado "creandose"
Uint16 mCreationTimer; Uint16 mCreationTimer;
//Tipo de globo // Tipo de globo
Uint8 mKind; Uint8 mKind;
//Sprite del objeto globo // Sprite del objeto globo
Sprite mSprite; Sprite mSprite;
//Circulo de colisión del objeto // Circulo de colisión del objeto
Circle mCollider; Circle mCollider;
//Alinea el circulo de colisión con la posición del objeto globo // Alinea el circulo de colisión con la posición del objeto globo
void shiftColliders(); void shiftColliders();
}; };

View File

@@ -1,63 +1,79 @@
#include "bullet.h" #include "bullet.h"
//Constructor // Constructor
Bullet::Bullet() Bullet::Bullet(SDL_Renderer *gRenderer)
{ {
this->gRenderer = gRenderer;
gBulletTexture = new LTexture(gRenderer);
// Carga los gráficos de las balas
if (!gBulletTexture->loadFromFile("media/gfx/bullet.png"))
{
printf("Failed to load bullet texture!\n");
}
init(0, 0, NO_KIND); init(0, 0, NO_KIND);
} }
//Iniciador // Destructor
Bullet::~Bullet()
{
gBulletTexture->free();
}
// Iniciador
void Bullet::init(int x, int y, int kind) void Bullet::init(int x, int y, int kind)
{ {
//Posición inicial del objeto // Posición inicial del objeto
mPosX = x; mPosX = x;
mPosY = y; mPosY = y;
//Alto y ancho del objeto // Alto y ancho del objeto
mWidth = 8; mWidth = 8;
mHeight = mWidth; mHeight = mWidth;
//Velocidad inicial en el eje Y // Velocidad inicial en el eje Y
mVelY = -3; mVelY = -3;
//Tipo de bala // Tipo de bala
mKind = kind; mKind = kind;
//Textura con los gráficos del objeto // Textura con los gráficos del objeto
mSprite.setTexture(gBulletTexture); mSprite.setTexture(*gBulletTexture);
//Alto y ancho del sprite // Alto y ancho del sprite
mSprite.setWidth(mWidth); mSprite.setWidth(mWidth);
mSprite.setHeight(mHeight); mSprite.setHeight(mHeight);
//Posición inicial del sprite // Posición inicial del sprite
mSprite.setPosX(mPosX); mSprite.setPosX(mPosX);
mSprite.setPosY(mPosY); mSprite.setPosY(mPosY);
//Valores especificos según el tipo // Valores especificos según el tipo
switch (kind) switch (kind)
{ {
case BULLET_UP: case BULLET_UP:
//Establece la velocidad inicial // Establece la velocidad inicial
mVelX = 0; mVelX = 0;
//Rectangulo con los gráficos del objeto // Rectangulo con los gráficos del objeto
mSprite.setSpriteClip(0 * mWidth, 0, mSprite.getWidth(), mSprite.getHeight()); mSprite.setSpriteClip(0 * mWidth, 0, mSprite.getWidth(), mSprite.getHeight());
break; break;
case BULLET_LEFT: case BULLET_LEFT:
//Establece la velocidad inicial // Establece la velocidad inicial
mVelX = -2; mVelX = -2;
//Rectangulo con los gráficos del objeto // Rectangulo con los gráficos del objeto
mSprite.setSpriteClip(1 * mWidth, 0, mSprite.getWidth(), mSprite.getHeight()); mSprite.setSpriteClip(1 * mWidth, 0, mSprite.getWidth(), mSprite.getHeight());
break; break;
case BULLET_RIGHT: case BULLET_RIGHT:
//Establece la velocidad inicial // Establece la velocidad inicial
mVelX = 2; mVelX = 2;
//Rectangulo con los gráficos del objeto // Rectangulo con los gráficos del objeto
mSprite.setSpriteClip(2 * mWidth, 0, mSprite.getWidth(), mSprite.getHeight()); mSprite.setSpriteClip(2 * mWidth, 0, mSprite.getWidth(), mSprite.getHeight());
break; break;
@@ -65,69 +81,69 @@ void Bullet::init(int x, int y, int kind)
break; break;
} }
//Establece el tamaño del circulo de colisión // Establece el tamaño del circulo de colisión
mCollider.r = mWidth / 2; mCollider.r = mWidth / 2;
//Alinea el circulo de colisión con el objeto // Alinea el circulo de colisión con el objeto
shiftColliders(); shiftColliders();
} }
//Pinta el objeto en pantalla // Pinta el objeto en pantalla
void Bullet::render() void Bullet::render()
{ {
mSprite.render(); mSprite.render();
} }
//Actualiza la posición y estado del objeto en horizontal // Actualiza la posición y estado del objeto en horizontal
void Bullet::move() void Bullet::move()
{ {
//Mueve el objeto a su nueva posición // Mueve el objeto a su nueva posición
mPosX += mVelX; mPosX += mVelX;
//Si el objeto se sale del area de juego por los laterales // Si el objeto se sale del area de juego por los laterales
if ((mPosX < PLAY_AREA_LEFT) || (mPosX + mWidth > PLAY_AREA_RIGHT)) if ((mPosX < PLAY_AREA_LEFT) || (mPosX + mWidth > PLAY_AREA_RIGHT))
{ {
//Se deshabilita // Se deshabilita
mKind = NO_KIND; mKind = NO_KIND;
} }
//Mueve el objeto a su nueva posición en vertical // Mueve el objeto a su nueva posición en vertical
mPosY += int(mVelY); mPosY += int(mVelY);
//Si el objeto se sale del area de juego por la parte superior o inferior // Si el objeto se sale del area de juego por la parte superior o inferior
if ((mPosY < PLAY_AREA_TOP) || (mPosY + mHeight > PLAY_AREA_BOTTOM)) if ((mPosY < PLAY_AREA_TOP) || (mPosY + mHeight > PLAY_AREA_BOTTOM))
{ {
//Se deshabilita // Se deshabilita
mKind = NO_KIND; mKind = NO_KIND;
} }
//Actualiza la posición del sprite // Actualiza la posición del sprite
mSprite.setPosX(mPosX); mSprite.setPosX(mPosX);
mSprite.setPosY(mPosY); mSprite.setPosY(mPosY);
//Alinea el circulo de colisión con el objeto // Alinea el circulo de colisión con el objeto
shiftColliders(); shiftColliders();
} }
#ifdef TEST #ifdef TEST
void Bullet::testMove() void Bullet::testMove()
{ {
//Update sprite position // Update sprite position
mSprite.setPosX(mPosX); mSprite.setPosX(mPosX);
mSprite.setPosY(mPosY); mSprite.setPosY(mPosY);
//Update circle colliders // Update circle colliders
shiftColliders(); shiftColliders();
} }
#endif #endif
//Deshabilita el objeto // Deshabilita el objeto
void Bullet::erase() void Bullet::erase()
{ {
mKind = NO_KIND; mKind = NO_KIND;
} }
//Comprueba si el objeto está activo // Comprueba si el objeto está activo
bool Bullet::isActive() bool Bullet::isActive()
{ {
if (mKind == NO_KIND) if (mKind == NO_KIND)
@@ -140,49 +156,49 @@ bool Bullet::isActive()
} }
} }
//Obtiene el valor de la variable // Obtiene el valor de la variable
int Bullet::getPosX() int Bullet::getPosX()
{ {
return mPosX; return mPosX;
} }
//Obtiene el valor de la variable // Obtiene el valor de la variable
int Bullet::getPosY() int Bullet::getPosY()
{ {
return mPosY; return mPosY;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Bullet::setPosX(int x) void Bullet::setPosX(int x)
{ {
mPosX = x; mPosX = x;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Bullet::setPosY(int y) void Bullet::setPosY(int y)
{ {
mPosY = y; mPosY = y;
} }
//Obtiene el valor de la variable // Obtiene el valor de la variable
float Bullet::getVelY() float Bullet::getVelY()
{ {
return mVelY; return mVelY;
} }
//Obtiene el valor de la variable // Obtiene el valor de la variable
int Bullet::getKind() int Bullet::getKind()
{ {
return mKind; return mKind;
} }
//Obtiene el circulo de colisión // Obtiene el circulo de colisión
Circle &Bullet::getCollider() Circle &Bullet::getCollider()
{ {
return mCollider; return mCollider;
} }
//Alinea el circulo de colisión con el objeto // Alinea el circulo de colisión con el objeto
void Bullet::shiftColliders() void Bullet::shiftColliders()
{ {
mCollider.x = mPosX + mCollider.r; mCollider.x = mPosX + mCollider.r;

View File

@@ -3,79 +3,86 @@
#include "sprite.h" #include "sprite.h"
#include "const.h" #include "const.h"
#include "globals.h" #include "globals.h"
#include "globals2.h"
#ifndef BULLET_H #ifndef BULLET_H
#define BULLET_H #define BULLET_H
//Clase bala // Clase bala
class Bullet class Bullet
{ {
public: public:
//Constructor // Constructor
Bullet(); Bullet(SDL_Renderer *gRenderer);
//Iniciador // Destructor
~Bullet();
// Iniciador
void init(int x, int y, int kind); void init(int x, int y, int kind);
//Pinta el objeto en pantalla // Pinta el objeto en pantalla
void render(); void render();
//Actualiza la posición y estado del objeto // Actualiza la posición y estado del objeto
void move(); void move();
#ifdef TEST #ifdef TEST
void testMove(); void testMove();
#endif #endif
//Deshabilita el objeto // Deshabilita el objeto
void erase(); void erase();
//Comprueba si el objeto está activo // Comprueba si el objeto está activo
bool isActive(); bool isActive();
//Obtiene el valor de la variable // Obtiene el valor de la variable
int getPosX(); int getPosX();
//Obtiene el valor de la variable // Obtiene el valor de la variable
int getPosY(); int getPosY();
//Establece el valor de la variable // Establece el valor de la variable
void setPosX(int x); void setPosX(int x);
//Establece el valor de la variable // Establece el valor de la variable
void setPosY(int y); void setPosY(int y);
//Obtiene el valor de la variable // Obtiene el valor de la variable
float getVelY(); float getVelY();
//Obtiene el valor de la variable // Obtiene el valor de la variable
int getKind(); int getKind();
//Obtiene el circulo de colisión // Obtiene el circulo de colisión
Circle &getCollider(); Circle &getCollider();
private: private:
//Posición X/Y del objeto // El renderizador de la ventana
SDL_Renderer *gRenderer;
LTexture *gBulletTexture;
// Posición X/Y del objeto
int mPosX; int mPosX;
int mPosY; int mPosY;
//Alto y ancho el objeto // Alto y ancho el objeto
Uint8 mWidth; Uint8 mWidth;
Uint8 mHeight; Uint8 mHeight;
//Velocidad del objeto // Velocidad del objeto
int mVelX; int mVelX;
int mVelY; int mVelY;
//Tipo de objeto // Tipo de objeto
int mKind; int mKind;
//Sprite con los graficos y métodos de pintado // Sprite con los graficos y métodos de pintado
Sprite mSprite; Sprite mSprite;
//Balloon's collision circle // Balloon's collision circle
Circle mCollider; Circle mCollider;
//Alinea el circulo de colisión con el objeto // Alinea el circulo de colisión con el objeto
void shiftColliders(); void shiftColliders();
}; };

View File

@@ -3,18 +3,18 @@
#ifndef CONST_H #ifndef CONST_H
#define CONST_H #define CONST_H
//Tamaño de bloque // Tamaño de bloque
const int BLOCK = 8; const int BLOCK = 8;
//Tamaño de la pantalla real // Tamaño de la pantalla real
const int SCREEN_WIDTH = 256; const int SCREEN_WIDTH = 256;
const int SCREEN_HEIGHT = SCREEN_WIDTH * 3 / 4; const int SCREEN_HEIGHT = SCREEN_WIDTH * 3 / 4;
//Tamaño de la pantalla que se muestra // Tamaño de la pantalla que se muestra
const int VIEW_WIDTH = SCREEN_WIDTH * 3; const int VIEW_WIDTH = SCREEN_WIDTH * 3;
const int VIEW_HEIGHT = SCREEN_HEIGHT * 3; const int VIEW_HEIGHT = SCREEN_HEIGHT * 3;
//Zona de juego // Zona de juego
const int PLAY_AREA_TOP = (0 * BLOCK); const int PLAY_AREA_TOP = (0 * BLOCK);
const int PLAY_AREA_BOTTOM = SCREEN_HEIGHT - (4 * BLOCK); const int PLAY_AREA_BOTTOM = SCREEN_HEIGHT - (4 * BLOCK);
const int PLAY_AREA_LEFT = (0 * BLOCK); const int PLAY_AREA_LEFT = (0 * BLOCK);
@@ -22,39 +22,39 @@ const int PLAY_AREA_RIGHT = SCREEN_WIDTH - (0 * BLOCK);
const int PLAY_AREA_WIDTH = PLAY_AREA_RIGHT - PLAY_AREA_LEFT; const int PLAY_AREA_WIDTH = PLAY_AREA_RIGHT - PLAY_AREA_LEFT;
const int PLAY_AREA_HEIGHT = PLAY_AREA_BOTTOM - PLAY_AREA_TOP; const int PLAY_AREA_HEIGHT = PLAY_AREA_BOTTOM - PLAY_AREA_TOP;
//Color transparente para los sprites // Color transparente para los sprites
const int COLOR_KEY_R = 0xff; const int COLOR_KEY_R = 0xff;
const int COLOR_KEY_G = 0x00; const int COLOR_KEY_G = 0x00;
const int COLOR_KEY_B = 0xff; const int COLOR_KEY_B = 0xff;
//Opciones de menu // Opciones de menu
const int MENU_NO_OPTION = -1; const int MENU_NO_OPTION = -1;
const int MENU_OPTION_START = 0; const int MENU_OPTION_START = 0;
const int MENU_OPTION_QUIT = 1; const int MENU_OPTION_QUIT = 1;
const int MENU_OPTION_TOTAL = 2; const int MENU_OPTION_TOTAL = 2;
//Selector de menu // Selector de menu
const int MENU_SELECTOR_BLACK = (BLOCK * 0); const int MENU_SELECTOR_BLACK = (BLOCK * 0);
const int MENU_SELECTOR_WHITE = (BLOCK * 1); const int MENU_SELECTOR_WHITE = (BLOCK * 1);
//Tipos de fondos para el menu // Tipos de fondos para el menu
const int MENU_BACKGROUND_TRANSPARENT = 0; const int MENU_BACKGROUND_TRANSPARENT = 0;
const int MENU_BACKGROUND_SOLID = 1; const int MENU_BACKGROUND_SOLID = 1;
//Estados del jugador // Estados del jugador
const int PLAYER_STATE_STOPPED = 0; const int PLAYER_STATE_STOPPED = 0;
const int PLAYER_STATE_WALKING_LEFT = 1; const int PLAYER_STATE_WALKING_LEFT = 1;
const int PLAYER_STATE_WALKING_RIGHT = 2; const int PLAYER_STATE_WALKING_RIGHT = 2;
const int PLAYER_STATE_TOTAL = 3; const int PLAYER_STATE_TOTAL = 3;
//Estados del juego // Estados del juego
const int GAME_STATE_TITLE = 0; const int GAME_STATE_TITLE = 0;
const int GAME_STATE_PLAYING = 1; const int GAME_STATE_PLAYING = 1;
const int GAME_STATE_PAUSED = 2; const int GAME_STATE_PAUSED = 2;
const int GAME_STATE_QUIT = 3; const int GAME_STATE_QUIT = 3;
const int GAME_STATE_TOTAL = 4; const int GAME_STATE_TOTAL = 4;
//Anclajes para el marcador de puntos // Anclajes para el marcador de puntos
const int SCORE_WORD_X = (SCREEN_WIDTH / 4) - ((5 * BLOCK) / 2); const int SCORE_WORD_X = (SCREEN_WIDTH / 4) - ((5 * BLOCK) / 2);
const int SCORE_WORD_Y = SCREEN_HEIGHT - (3 * BLOCK) + 4; const int SCORE_WORD_Y = SCREEN_HEIGHT - (3 * BLOCK) + 4;
const int SCORE_NUMBER_X = (SCREEN_WIDTH / 4) - (3 * BLOCK); const int SCORE_NUMBER_X = (SCREEN_WIDTH / 4) - (3 * BLOCK);
@@ -64,25 +64,25 @@ const int HISCORE_WORD_Y = SCREEN_HEIGHT - (3 * BLOCK) + 4;
const int HISCORE_NUMBER_X = ((SCREEN_WIDTH / 4) * 3) - (3 * BLOCK); const int HISCORE_NUMBER_X = ((SCREEN_WIDTH / 4) * 3) - (3 * BLOCK);
const int HISCORE_NUMBER_Y = SCREEN_HEIGHT - (2 * BLOCK) + 4; const int HISCORE_NUMBER_Y = SCREEN_HEIGHT - (2 * BLOCK) + 4;
//Ningun tipo // Ningun tipo
const int NO_KIND = 0; const int NO_KIND = 0;
//Tipos de globo // Tipos de globo
const int BALLOON_1 = 1; const int BALLOON_1 = 1;
const int BALLOON_2 = 2; const int BALLOON_2 = 2;
const int BALLOON_3 = 3; const int BALLOON_3 = 3;
const int BALLOON_4 = 4; const int BALLOON_4 = 4;
//Velocidad del globo // Velocidad del globo
const float BALLON_VELX_POSITIVE = 0.7; const float BALLON_VELX_POSITIVE = 0.7;
const float BALLON_VELX_NEGATIVE = -0.7; const float BALLON_VELX_NEGATIVE = -0.7;
//Tipos de bala // Tipos de bala
const int BULLET_UP = 1; const int BULLET_UP = 1;
const int BULLET_LEFT = 2; const int BULLET_LEFT = 2;
const int BULLET_RIGHT = 3; const int BULLET_RIGHT = 3;
//Estados de entrada // Estados de entrada
const int NO_INPUT = 0; const int NO_INPUT = 0;
const int INPUT_UP = 1; const int INPUT_UP = 1;
const int INPUT_DOWN = 2; const int INPUT_DOWN = 2;
@@ -90,10 +90,10 @@ const int INPUT_LEFT = 3;
const int INPUT_RIGHT = 4; const int INPUT_RIGHT = 4;
const int INPUT_FIRE = 5; const int INPUT_FIRE = 5;
//Zona muerta del mando analógico // Zona muerta del mando analógico
const int JOYSTICK_DEAD_ZONE = 8000; const int JOYSTICK_DEAD_ZONE = 8000;
//Mapeo de bottones (8bitdo) // Mapeo de bottones (8bitdo)
const int BUTTON_A = 0; const int BUTTON_A = 0;
const int BUTTON_B = 1; const int BUTTON_B = 1;
const int BUTTON_X = 3; const int BUTTON_X = 3;

View File

@@ -27,8 +27,10 @@ bool checkCollision(Circle &a, Circle &b)
} }
// Constructor // Constructor
GameDirector::GameDirector() GameDirector::GameDirector(SDL_Renderer *gRenderer)
{ {
this->gRenderer = gRenderer;
init(); init();
} }
@@ -50,6 +52,34 @@ GameDirector::~GameDirector()
// Libera el mando // Libera el mando
SDL_JoystickClose(gGameController); SDL_JoystickClose(gGameController);
gGameController = NULL; gGameController = NULL;
// Libera texturas
gGameBackgroundTexture->free();
gTitleBackgroundTexture->free();
gWhiteFontTexture->free();
gBlackFontTexture->free();
gMiscTexture->free();
// Libera objetos
delete player;
delete menuPause;
delete menuTitle;
for (Uint8 i = 0; i < mMaxBalloons; i++)
{
if (balloon[i])
{
delete balloon[i];
}
}
for (int i = 0; i < mMaxBullets; i++)
{
if (bullet[i])
{
delete bullet[i];
}
}
} }
// Iniciador // Iniciador
@@ -83,6 +113,41 @@ void GameDirector::init()
printf("Failed to load bullet sound effect! SDL_mixer Error: %s\n", Mix_GetError()); printf("Failed to load bullet sound effect! SDL_mixer Error: %s\n", Mix_GetError());
} }
gGameBackgroundTexture = new LTexture(gRenderer);
// Carga los gráficos del fondo del juego
if (!gGameBackgroundTexture->loadFromFile("media/gfx/background.png"))
{
printf("Failed to load game background texture!\n");
}
gTitleBackgroundTexture = new LTexture(gRenderer);
// Carga los gráficos del fondo de la pantalla de titulo
if (!gTitleBackgroundTexture->loadFromFile("media/gfx/title.png"))
{
printf("Failed to load title texture!\n");
}
gMiscTexture = new LTexture(gRenderer);
// Carga varios gráficos para varios propósitos
if (!gMiscTexture->loadFromFile("media/gfx/misc.png"))
{
printf("Failed to load misc texture!\n");
}
gWhiteFontTexture = new LTexture(gRenderer);
// Carga los gráficos para el texto blanco
if (!gWhiteFontTexture->loadFromFile("media/gfx/white_font.png"))
{
printf("Failed to load white font texture!\n");
}
gBlackFontTexture = new LTexture(gRenderer);
// Carga los gráficos para el texto negro
if (!gBlackFontTexture->loadFromFile("media/gfx/black_font.png"))
{
printf("Failed to load black font texture!\n");
}
// Comprueba los mandos // Comprueba los mandos
if (SDL_NumJoysticks() < 1) if (SDL_NumJoysticks() < 1)
{ {
@@ -115,7 +180,8 @@ void GameDirector::init()
mGetReady = true; mGetReady = true;
// Objeto jugador // Objeto jugador
player.init(); player = new Player(gRenderer);
player->init();
// Establece a cero todos los valores del vector de objetos globo // Establece a cero todos los valores del vector de objetos globo
resetBalloons(); resetBalloons();
@@ -139,26 +205,28 @@ void GameDirector::init()
#endif #endif
// Los fondos // Los fondos
gameBackground.init(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - (0 * BLOCK), &gGameBackgroundTexture); gameBackground.init(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - (0 * BLOCK), gGameBackgroundTexture);
titleBackground.init(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, &gTitleBackgroundTexture); titleBackground.init(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, gTitleBackgroundTexture);
// Objetos texto, uno de cada color // Objetos texto, uno de cada color
whiteText.init(&gWhiteFontTexture); whiteText.init(gWhiteFontTexture);
blackText.init(&gBlackFontTexture); blackText.init(gBlackFontTexture);
// Inicializa el objeto con el menu del titulo // Inicializa el objeto con el menu del titulo
menuTitle.init(0, 16 * BLOCK, MENU_SELECTOR_WHITE, MENU_BACKGROUND_TRANSPARENT); menuTitle = new Menu(gRenderer);
menuTitle.addItem("START"); menuTitle->init(0, 16 * BLOCK, MENU_SELECTOR_WHITE, MENU_BACKGROUND_TRANSPARENT);
menuTitle.addItem("EXIT"); menuTitle->addItem("START");
menuTitle.setBackgroundColor(0, 0, 0, 255); menuTitle->addItem("EXIT");
menuTitle.centerMenuOnScreen(); menuTitle->setBackgroundColor(0, 0, 0, 255);
menuTitle->centerMenuOnScreen();
// Inicializa el objeto con el menu de pausa // Inicializa el objeto con el menu de pausa
menuPause.init(0, 12 * BLOCK, MENU_SELECTOR_WHITE, MENU_BACKGROUND_SOLID); menuPause = new Menu(gRenderer);
menuPause.addItem("CONTINUE"); menuPause->init(0, 12 * BLOCK, MENU_SELECTOR_WHITE, MENU_BACKGROUND_SOLID);
menuPause.addItem("EXIT TO TITLE"); menuPause->addItem("CONTINUE");
menuPause.setBackgroundColor(0x73, 0x27, 0x5c, 255); menuPause->addItem("EXIT TO TITLE");
menuPause.centerMenuOnScreen(); menuPause->setBackgroundColor(0x73, 0x27, 0x5c, 255);
menuPause->centerMenuOnScreen();
} }
// Hace una pausa de milisegundos // Hace una pausa de milisegundos
@@ -242,9 +310,9 @@ void GameDirector::moveBalloons()
{ {
for (Uint8 i = 0; i < mMaxBalloons; i++) for (Uint8 i = 0; i < mMaxBalloons; i++)
{ {
if (balloon[i].isActive()) if (balloon[i]->isActive())
{ {
balloon[i].move(); balloon[i]->move();
} }
} }
} }
@@ -254,9 +322,9 @@ void GameDirector::renderBalloons()
{ {
for (Uint8 i = 0; i < mMaxBalloons; i++) for (Uint8 i = 0; i < mMaxBalloons; i++)
{ {
if (balloon[i].isActive()) if (balloon[i]->isActive())
{ {
balloon[i].render(); balloon[i]->render();
} }
} }
} }
@@ -268,7 +336,7 @@ Uint8 GameDirector::getBallonFreeIndex()
for (Uint8 i = 0; i < mMaxBalloons; i++) for (Uint8 i = 0; i < mMaxBalloons; i++)
{ {
if (balloon[i].isActive() == false) if (balloon[i]->isActive() == false)
{ {
index = i; index = i;
break; break;
@@ -282,7 +350,8 @@ Uint8 GameDirector::getBallonFreeIndex()
Uint8 GameDirector::createNewBalloon(int x, int y, Uint8 kind, float velx, Uint16 creationtimer) Uint8 GameDirector::createNewBalloon(int x, int y, Uint8 kind, float velx, Uint16 creationtimer)
{ {
Uint8 index = getBallonFreeIndex(); Uint8 index = getBallonFreeIndex();
balloon[index].init(x, y, kind, velx, creationtimer); balloon[index] = new Balloon(gRenderer);
balloon[index]->init(x, y, kind, velx, creationtimer);
return index; return index;
} }
@@ -291,38 +360,38 @@ void GameDirector::resetBalloons()
{ {
for (Uint8 i = 0; i < mMaxBalloons; i++) for (Uint8 i = 0; i < mMaxBalloons; i++)
{ {
balloon[i].erase(); balloon[i]->erase();
} }
} }
// Explosiona un globo. Lo destruye y crea otros dos si es el caso // Explosiona un globo. Lo destruye y crea otros dos si es el caso
void GameDirector::popBalloon(Uint8 index) void GameDirector::popBalloon(Uint8 index)
{ {
if (balloon[index].isActive()) if (balloon[index]->isActive())
{ {
Uint8 kind = balloon[index].getKind(); Uint8 kind = balloon[index]->getKind();
Uint8 freeIndex = 0; Uint8 freeIndex = 0;
switch (kind) switch (kind)
{ {
// Si es del tipo más pequeño, simplemente elimina el globo // Si es del tipo más pequeño, simplemente elimina el globo
case BALLOON_1: case BALLOON_1:
balloon[index].erase(); balloon[index]->erase();
break; break;
// En cualquier otro caso, crea dos globos de un tipo inferior // En cualquier otro caso, crea dos globos de un tipo inferior
default: default:
freeIndex = getBallonFreeIndex(); freeIndex = getBallonFreeIndex();
balloon[freeIndex].init(0, balloon[index].getPosY(), balloon[index].getKind() - 1, BALLON_VELX_NEGATIVE, 0); balloon[freeIndex]->init(0, balloon[index]->getPosY(), balloon[index]->getKind() - 1, BALLON_VELX_NEGATIVE, 0);
balloon[freeIndex].allignTo(balloon[index].getPosX() + (balloon[index].getWidth() / 2)); balloon[freeIndex]->allignTo(balloon[index]->getPosX() + (balloon[index]->getWidth() / 2));
balloon[freeIndex].setVelY(-2.5); balloon[freeIndex]->setVelY(-2.5);
freeIndex = getBallonFreeIndex(); freeIndex = getBallonFreeIndex();
balloon[freeIndex].init(0, balloon[index].getPosY(), balloon[index].getKind() - 1, BALLON_VELX_POSITIVE, 0); balloon[freeIndex]->init(0, balloon[index]->getPosY(), balloon[index]->getKind() - 1, BALLON_VELX_POSITIVE, 0);
balloon[freeIndex].allignTo(balloon[index].getPosX() + (balloon[index].getWidth() / 2)); balloon[freeIndex]->allignTo(balloon[index]->getPosX() + (balloon[index]->getWidth() / 2));
balloon[freeIndex].setVelY(-2.5); balloon[freeIndex]->setVelY(-2.5);
// Elimina el globo // Elimina el globo
balloon[index].erase(); balloon[index]->erase();
break; break;
} }
} }
@@ -333,9 +402,9 @@ void GameDirector::stopAllBalloons()
{ {
for (Uint8 i = 0; i < mMaxBalloons; i++) for (Uint8 i = 0; i < mMaxBalloons; i++)
{ {
if (balloon[i].isActive()) if (balloon[i]->isActive())
{ {
balloon[i].setStop(true); balloon[i]->setStop(true);
} }
} }
} }
@@ -345,9 +414,9 @@ void GameDirector::startAllBalloons()
{ {
for (Uint8 i = 0; i < mMaxBalloons; i++) for (Uint8 i = 0; i < mMaxBalloons; i++)
{ {
if (balloon[i].isActive()) if (balloon[i]->isActive())
{ {
balloon[i].setStop(false); balloon[i]->setStop(false);
} }
} }
} }
@@ -358,7 +427,7 @@ Uint8 GameDirector::countBalloons()
Uint8 num = 0; Uint8 num = 0;
for (Uint8 i = 0; i < mMaxBalloons; i++) for (Uint8 i = 0; i < mMaxBalloons; i++)
{ {
if (balloon[i].isActive()) if (balloon[i]->isActive())
{ {
++num; ++num;
} }
@@ -372,9 +441,9 @@ bool GameDirector::checkPlayerBallonCollision()
bool result = false; bool result = false;
for (Uint8 i = 0; i < mMaxBalloons; i++) for (Uint8 i = 0; i < mMaxBalloons; i++)
{ {
if (balloon[i].isActive()) if (balloon[i]->isActive())
{ {
if (checkCollision(player.getCollider(), balloon[i].getCollider())) if (checkCollision(player->getCollider(), balloon[i]->getCollider()))
{ {
result = true; result = true;
break; break;
@@ -391,16 +460,16 @@ void GameDirector::processBulletBallonCollision()
{ {
for (Uint8 j = 0; j < mMaxBullets; j++) for (Uint8 j = 0; j < mMaxBullets; j++)
{ {
if (balloon[i].isActive() && !(balloon[i].isInvulnerable()) && bullet[j].isActive()) if (balloon[i]->isActive() && !(balloon[i]->isInvulnerable()) && bullet[j]->isActive())
{ {
if (checkCollision(balloon[i].getCollider(), bullet[j].getCollider())) if (checkCollision(balloon[i]->getCollider(), bullet[j]->getCollider()))
{ {
player.addScore(balloon[i].getScore()); player->addScore(balloon[i]->getScore());
setScore(player.getScore()); setScore(player->getScore());
updateHiScore(); updateHiScore();
popBalloon(i); popBalloon(i);
Mix_PlayChannel(-1, gPopBalloonFX, 0); Mix_PlayChannel(-1, gPopBalloonFX, 0);
bullet[j].erase(); bullet[j]->erase();
calculateMenaceLevel(); calculateMenaceLevel();
break; break;
} }
@@ -414,9 +483,9 @@ void GameDirector::moveBullets()
{ {
for (Uint8 i = 0; i < mMaxBullets; i++) for (Uint8 i = 0; i < mMaxBullets; i++)
{ {
if (bullet[i].isActive()) if (bullet[i]->isActive())
{ {
bullet[i].move(); bullet[i]->move();
} }
} }
} }
@@ -426,9 +495,9 @@ void GameDirector::renderBullets()
{ {
for (Uint8 i = 0; i < mMaxBullets; i++) for (Uint8 i = 0; i < mMaxBullets; i++)
{ {
if (bullet[i].isActive()) if (bullet[i]->isActive())
{ {
bullet[i].render(); bullet[i]->render();
} }
} }
} }
@@ -440,7 +509,7 @@ Uint8 GameDirector::getBulletFreeIndex()
for (int i = 0; i < mMaxBullets; i++) for (int i = 0; i < mMaxBullets; i++)
{ {
if (bullet[i].isActive() == false) if (bullet[i]->isActive() == false)
{ {
index = i; index = i;
break; break;
@@ -455,14 +524,16 @@ void GameDirector::resetBullets()
{ {
for (Uint8 i = 0; i < mMaxBullets; i++) for (Uint8 i = 0; i < mMaxBullets; i++)
{ {
bullet[i].init(0, 0, NO_KIND); bullet[i]->init(0, 0, NO_KIND);
} }
} }
// Crea un objeto bala // Crea un objeto bala
void GameDirector::createBullet(int x, int y, Uint8 kind) void GameDirector::createBullet(int x, int y, Uint8 kind)
{ {
bullet[getBulletFreeIndex()].init(x, y, kind); const int index = getBulletFreeIndex();
bullet[index] = new Bullet(gRenderer);
bullet[index]->init(x, y, kind);
} }
// Calcula y establece el valor de amenaza en funcion de los globos activos // Calcula y establece el valor de amenaza en funcion de los globos activos
@@ -471,7 +542,7 @@ void GameDirector::calculateMenaceLevel()
mMenaceLevel = 0; mMenaceLevel = 0;
for (Uint8 i = 0; i < mMaxBalloons; i++) for (Uint8 i = 0; i < mMaxBalloons; i++)
{ {
switch (balloon[i].getKind()) switch (balloon[i]->getKind())
{ {
case BALLOON_1: case BALLOON_1:
mMenaceLevel += 1; mMenaceLevel += 1;
@@ -514,7 +585,7 @@ void GameDirector::checkMenaceLevel()
Uint8 index = 0; Uint8 index = 0;
// Obtiene el centro del jugador en el eje X // Obtiene el centro del jugador en el eje X
int x = player.getPosX() + (player.getWidth() / 2); int x = player->getPosX() + (player->getWidth() / 2);
// Crea un globo sobre el jugador en dirección hacia el centro // Crea un globo sobre el jugador en dirección hacia el centro
if (x < (PLAY_AREA_WIDTH / 2)) if (x < (PLAY_AREA_WIDTH / 2))
@@ -525,7 +596,7 @@ void GameDirector::checkMenaceLevel()
{ {
index = createNewBalloon(0, PLAY_AREA_TOP + BLOCK - 37, BALLOON_4, BALLON_VELX_NEGATIVE, 400); index = createNewBalloon(0, PLAY_AREA_TOP + BLOCK - 37, BALLOON_4, BALLON_VELX_NEGATIVE, 400);
} }
balloon[index].allignTo(x); balloon[index]->allignTo(x);
// Recalcula el nivel de amenaza con el nuevo globo // Recalcula el nivel de amenaza con el nuevo globo
calculateMenaceLevel(); calculateMenaceLevel();
@@ -541,26 +612,26 @@ void GameDirector::checkGameInput()
// Si está pulsada la tecla izquierda o el mando hacia la izquierda // Si está pulsada la tecla izquierda o el mando hacia la izquierda
if ((keystates[SDL_SCANCODE_LEFT] != 0) || (SDL_JoystickGetAxis(gGameController, 0) < -JOYSTICK_DEAD_ZONE)) if ((keystates[SDL_SCANCODE_LEFT] != 0) || (SDL_JoystickGetAxis(gGameController, 0) < -JOYSTICK_DEAD_ZONE))
{ {
player.checkInput(INPUT_LEFT); player->checkInput(INPUT_LEFT);
} }
// Si está pulsada la tecla derecha o el mando hacia la derecha // Si está pulsada la tecla derecha o el mando hacia la derecha
else if ((keystates[SDL_SCANCODE_RIGHT] != 0) || (SDL_JoystickGetAxis(gGameController, 0) > JOYSTICK_DEAD_ZONE)) else if ((keystates[SDL_SCANCODE_RIGHT] != 0) || (SDL_JoystickGetAxis(gGameController, 0) > JOYSTICK_DEAD_ZONE))
{ {
player.checkInput(INPUT_RIGHT); player->checkInput(INPUT_RIGHT);
} }
// Ninguna de las dos direcciones pulsadas // Ninguna de las dos direcciones pulsadas
else else
{ {
player.checkInput(NO_INPUT); player->checkInput(NO_INPUT);
} }
// Comprobamos la tecla o el botón de disparo central // Comprobamos la tecla o el botón de disparo central
if ((SDL_JoystickGetButton(gGameController, BUTTON_X)) || (keystates[SDL_SCANCODE_W] != 0)) if ((SDL_JoystickGetButton(gGameController, BUTTON_X)) || (keystates[SDL_SCANCODE_W] != 0))
{ {
if (player.canFire()) if (player->canFire())
{ {
createBullet(player.getPosX() + (player.getWidth() / 2) - 4, player.getPosY(), BULLET_UP); createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY(), BULLET_UP);
player.setFireCooldown(10); player->setFireCooldown(10);
// Reproduce el sonido de disparo // Reproduce el sonido de disparo
Mix_PlayChannel(-1, gBulletFX, 0); Mix_PlayChannel(-1, gBulletFX, 0);
@@ -570,10 +641,10 @@ void GameDirector::checkGameInput()
// Comprobamos la tecla o el botón de disparo izquierdo // Comprobamos la tecla o el botón de disparo izquierdo
if ((SDL_JoystickGetButton(gGameController, BUTTON_Y)) || (keystates[SDL_SCANCODE_Q] != 0)) if ((SDL_JoystickGetButton(gGameController, BUTTON_Y)) || (keystates[SDL_SCANCODE_Q] != 0))
{ {
if (player.canFire()) if (player->canFire())
{ {
createBullet(player.getPosX() + (player.getWidth() / 2) - 4, player.getPosY(), BULLET_LEFT); createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY(), BULLET_LEFT);
player.setFireCooldown(10); player->setFireCooldown(10);
// Reproduce el sonido de disparo // Reproduce el sonido de disparo
Mix_PlayChannel(-1, gBulletFX, 0); Mix_PlayChannel(-1, gBulletFX, 0);
@@ -583,10 +654,10 @@ void GameDirector::checkGameInput()
// Comprobamos la tecla o el botón de disparo derecho // Comprobamos la tecla o el botón de disparo derecho
if ((SDL_JoystickGetButton(gGameController, BUTTON_A)) || (keystates[SDL_SCANCODE_E] != 0)) if ((SDL_JoystickGetButton(gGameController, BUTTON_A)) || (keystates[SDL_SCANCODE_E] != 0))
{ {
if (player.canFire()) if (player->canFire())
{ {
createBullet(player.getPosX() + (player.getWidth() / 2) - 4, player.getPosY(), BULLET_RIGHT); createBullet(player->getPosX() + (player->getWidth() / 2) - 4, player->getPosY(), BULLET_RIGHT);
player.setFireCooldown(10); player->setFireCooldown(10);
// Reproduce el sonido de disparo // Reproduce el sonido de disparo
Mix_PlayChannel(-1, gBulletFX, 0); Mix_PlayChannel(-1, gBulletFX, 0);
@@ -795,7 +866,7 @@ void GameDirector::renderGetReady()
if (mGetReady) if (mGetReady)
{ {
Sprite sprite; Sprite sprite;
sprite.setTexture(gMiscTexture); sprite.setTexture(*gMiscTexture);
sprite.setWidth(53); sprite.setWidth(53);
sprite.setHeight(10); sprite.setHeight(10);
sprite.setPosX((PLAY_AREA_WIDTH / 2) - (sprite.getWidth() / 2)); sprite.setPosX((PLAY_AREA_WIDTH / 2) - (sprite.getWidth() / 2));
@@ -837,27 +908,27 @@ void GameDirector::runTitle()
// Dibuja los objetos // Dibuja los objetos
titleBackground.render(); titleBackground.render();
menuTitle.render(whiteText); menuTitle->render(whiteText);
// Actualiza la pantalla // Actualiza la pantalla
SDL_RenderPresent(gRenderer); SDL_RenderPresent(gRenderer);
// Comprueba las entradas para el menu // Comprueba las entradas para el menu
checkMenuInput(&menuTitle); checkMenuInput(menuTitle);
// Comprueba si se ha seleccionado algún item del menú // Comprueba si se ha seleccionado algún item del menú
switch (menuTitle.getItemSelected()) switch (menuTitle->getItemSelected())
{ {
case 0: case 0:
setGameStatus(GAME_STATE_PLAYING); setGameStatus(GAME_STATE_PLAYING);
menuTitle.resetMenu(); menuTitle->resetMenu();
renderTransition(1); renderTransition(1);
Mix_HaltMusic(); Mix_HaltMusic();
SDL_Delay(1200); SDL_Delay(1200);
break; break;
case 1: case 1:
setGameStatus(GAME_STATE_QUIT); setGameStatus(GAME_STATE_QUIT);
menuTitle.resetMenu(); menuTitle->resetMenu();
renderTransition(1); renderTransition(1);
Mix_HaltMusic(); Mix_HaltMusic();
break; break;
@@ -938,7 +1009,7 @@ void GameDirector::runGame()
} }
// Actualiza el jugador // Actualiza el jugador
player.update(); player->update();
// Mueve los globos // Mueve los globos
moveBalloons(); moveBalloons();
@@ -979,9 +1050,9 @@ void GameDirector::runGame()
} }
#endif #endif
// whiteText.write(0, 0, std::to_string(mMenaceLevelThreshold)); // whiteText.write(0, 0, std::to_string(mMenaceLevelThreshold));
// whiteText.write(0, BLOCK, std::to_string(player.getPosX() + player.getWidth())); // whiteText.write(0, BLOCK, std::to_string(player->getPosX() + player->getWidth()));
renderBullets(); renderBullets();
player.render(); player->render();
renderScoreBoard(whiteText); renderScoreBoard(whiteText);
renderGetReady(); renderGetReady();
@@ -1006,26 +1077,26 @@ void GameDirector::runPausedGame()
gameBackground.render(); gameBackground.render();
renderBalloons(); renderBalloons();
renderBullets(); renderBullets();
player.render(); player->render();
renderScoreBoard(whiteText); renderScoreBoard(whiteText);
menuPause.render(whiteText); menuPause->render(whiteText);
// Limpia la pantalla // Limpia la pantalla
SDL_RenderPresent(gRenderer); SDL_RenderPresent(gRenderer);
// Comprueba las entradas para el menu // Comprueba las entradas para el menu
checkMenuInput(&menuPause); checkMenuInput(menuPause);
// Comprueba si se ha seleccionado algún item del menú // Comprueba si se ha seleccionado algún item del menú
switch (menuPause.getItemSelected()) switch (menuPause->getItemSelected())
{ {
case 0: case 0:
setGameStatus(GAME_STATE_PLAYING); setGameStatus(GAME_STATE_PLAYING);
menuPause.resetMenu(); menuPause->resetMenu();
break; break;
case 1: case 1:
setGameStatus(GAME_STATE_TITLE); setGameStatus(GAME_STATE_TITLE);
menuPause.resetMenu(); menuPause->resetMenu();
renderTransition(1); renderTransition(1);
init(); init();
break; break;

View File

@@ -18,7 +18,7 @@ class GameDirector
{ {
public: public:
// Constructor // Constructor
GameDirector(); GameDirector(SDL_Renderer *gRenderer);
// Destructor // Destructor
~GameDirector(); ~GameDirector();
@@ -129,6 +129,9 @@ public:
void runPausedGame(); void runPausedGame();
private: private:
// El renderizador de la ventana
SDL_Renderer *gRenderer = NULL;
// Objetos con la música del juego // Objetos con la música del juego
Mix_Music *gTitleMusic = NULL; Mix_Music *gTitleMusic = NULL;
Mix_Music *gPlayingMusic = NULL; Mix_Music *gPlayingMusic = NULL;
@@ -140,21 +143,28 @@ private:
// Manejador para el mando 1 // Manejador para el mando 1
SDL_Joystick *gGameController = NULL; SDL_Joystick *gGameController = NULL;
// Texturas
LTexture *gGameBackgroundTexture;
LTexture *gTitleBackgroundTexture;
LTexture *gWhiteFontTexture;
LTexture *gBlackFontTexture;
LTexture *gMiscTexture;
// Manejador de eventos // Manejador de eventos
SDL_Event eventHandler; SDL_Event eventHandler;
// El jugador // El jugador
Player player; Player *player;
// Vector con los objetos globo // Vector con los objetos globo
Balloon balloon[50]; Balloon *balloon[50];
#ifdef TEST #ifdef TEST
Balloon balloonTest; Balloon balloonTest;
Bullet bulletTest; Bullet bulletTest;
#endif #endif
// Vector con los objetos bala // Vector con los objetos bala
Bullet bullet[50]; Bullet *bullet[50];
// Fondo del juego // Fondo del juego
Background gameBackground; Background gameBackground;
@@ -169,10 +179,10 @@ private:
Text blackText; Text blackText;
// Menu de la pantalla de título // Menu de la pantalla de título
Menu menuTitle; Menu *menuTitle;
// Menú de la pantalla de pausa // Menú de la pantalla de pausa
Menu menuPause; Menu *menuPause;
// Indicador para el bucle principal // Indicador para el bucle principal
Uint8 mGameStatus; Uint8 mGameStatus;

View File

@@ -7,7 +7,7 @@
#ifndef GLOBALS_H #ifndef GLOBALS_H
#define GLOBALS_H #define GLOBALS_H
//Estructura para definir un circulo // Estructura para definir un circulo
struct Circle struct Circle
{ {
Uint16 x; Uint16 x;
@@ -15,9 +15,4 @@ struct Circle
Uint8 r; Uint8 r;
}; };
//El renderizador de la ventana
SDL_Renderer *gRenderer = NULL;
#endif #endif

View File

@@ -1,19 +0,0 @@
#pragma once
#include "ltexture.h"
#ifndef GLOBALS2_H
#define GLOBALS2_H
//Texturas con gráficos
LTexture gPlayerTexture;
LTexture gGameBackgroundTexture;
LTexture gTitleBackgroundTexture;
LTexture gWhiteFontTexture;
LTexture gBlackFontTexture;
LTexture gMenuTexture;
LTexture gBalloonTexture;
LTexture gBulletTexture;
LTexture gMiscTexture;
#endif

View File

@@ -1,8 +1,10 @@
#include "ltexture.h" #include "ltexture.h"
LTexture::LTexture() LTexture::LTexture(SDL_Renderer *gRenderer)
{ {
//Initialize this->gRenderer = gRenderer;
// Initialize
mTexture = NULL; mTexture = NULL;
mWidth = 0; mWidth = 0;
mHeight = 0; mHeight = 0;
@@ -10,19 +12,19 @@ LTexture::LTexture()
LTexture::~LTexture() LTexture::~LTexture()
{ {
//Deallocate // Deallocate
free(); free();
} }
bool LTexture::loadFromFile(std::string path) bool LTexture::loadFromFile(std::string path)
{ {
//Get rid of preexisting texture // Get rid of preexisting texture
free(); free();
//The final texture // The final texture
SDL_Texture *newTexture = NULL; SDL_Texture *newTexture = NULL;
//Load image at specified path // Load image at specified path
SDL_Surface *loadedSurface = IMG_Load(path.c_str()); SDL_Surface *loadedSurface = IMG_Load(path.c_str());
if (loadedSurface == NULL) if (loadedSurface == NULL)
{ {
@@ -30,10 +32,10 @@ bool LTexture::loadFromFile(std::string path)
} }
else else
{ {
//Color key image // Color key image
SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, COLOR_KEY_R, COLOR_KEY_G, COLOR_KEY_B)); SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, COLOR_KEY_R, COLOR_KEY_G, COLOR_KEY_B));
//Create texture from surface pixels // Create texture from surface pixels
newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface); newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);
if (newTexture == NULL) if (newTexture == NULL)
{ {
@@ -41,40 +43,40 @@ bool LTexture::loadFromFile(std::string path)
} }
else else
{ {
//Get image dimensions // Get image dimensions
mWidth = loadedSurface->w; mWidth = loadedSurface->w;
mHeight = loadedSurface->h; mHeight = loadedSurface->h;
} }
//Get rid of old loaded surface // Get rid of old loaded surface
SDL_FreeSurface(loadedSurface); SDL_FreeSurface(loadedSurface);
} }
//Return success // Return success
mTexture = newTexture; mTexture = newTexture;
return mTexture != NULL; return mTexture != NULL;
} }
bool LTexture::createBlank( int width, int height, SDL_TextureAccess access ) bool LTexture::createBlank(int width, int height, SDL_TextureAccess access)
{ {
//Create uninitialized texture // Create uninitialized texture
mTexture = SDL_CreateTexture( gRenderer, SDL_PIXELFORMAT_RGBA8888, access, width, height ); mTexture = SDL_CreateTexture(gRenderer, SDL_PIXELFORMAT_RGBA8888, access, width, height);
if( mTexture == NULL ) if (mTexture == NULL)
{ {
printf( "Unable to create blank texture! SDL Error: %s\n", SDL_GetError() ); printf("Unable to create blank texture! SDL Error: %s\n", SDL_GetError());
} }
else else
{ {
mWidth = width; mWidth = width;
mHeight = height; mHeight = height;
} }
return mTexture != NULL; return mTexture != NULL;
} }
void LTexture::free() void LTexture::free()
{ {
//Free texture if it exists // Free texture if it exists
if (mTexture != NULL) if (mTexture != NULL)
{ {
SDL_DestroyTexture(mTexture); SDL_DestroyTexture(mTexture);
@@ -86,42 +88,42 @@ void LTexture::free()
void LTexture::setColor(Uint8 red, Uint8 green, Uint8 blue) void LTexture::setColor(Uint8 red, Uint8 green, Uint8 blue)
{ {
//Modulate texture rgb // Modulate texture rgb
SDL_SetTextureColorMod(mTexture, red, green, blue); SDL_SetTextureColorMod(mTexture, red, green, blue);
} }
void LTexture::setBlendMode(SDL_BlendMode blending) void LTexture::setBlendMode(SDL_BlendMode blending)
{ {
//Set blending function // Set blending function
SDL_SetTextureBlendMode(mTexture, blending); SDL_SetTextureBlendMode(mTexture, blending);
} }
void LTexture::setAlpha(Uint8 alpha) void LTexture::setAlpha(Uint8 alpha)
{ {
//Modulate texture alpha // Modulate texture alpha
SDL_SetTextureAlphaMod(mTexture, alpha); SDL_SetTextureAlphaMod(mTexture, alpha);
} }
void LTexture::render(int x, int y, SDL_Rect *clip, double angle, SDL_Point *center, SDL_RendererFlip flip) void LTexture::render(int x, int y, SDL_Rect *clip, double angle, SDL_Point *center, SDL_RendererFlip flip)
{ {
//Set rendering space and render to screen // Set rendering space and render to screen
SDL_Rect renderQuad = {x, y, mWidth, mHeight}; SDL_Rect renderQuad = {x, y, mWidth, mHeight};
//Set clip rendering dimensions // Set clip rendering dimensions
if (clip != NULL) if (clip != NULL)
{ {
renderQuad.w = clip->w; renderQuad.w = clip->w;
renderQuad.h = clip->h; renderQuad.h = clip->h;
} }
//Render to screen // Render to screen
SDL_RenderCopyEx(gRenderer, mTexture, clip, &renderQuad, angle, center, flip); SDL_RenderCopyEx(gRenderer, mTexture, clip, &renderQuad, angle, center, flip);
} }
void LTexture::setAsRenderTarget() void LTexture::setAsRenderTarget()
{ {
//Make self render target // Make self render target
SDL_SetRenderTarget( gRenderer, mTexture ); SDL_SetRenderTarget(gRenderer, mTexture);
} }
int LTexture::getWidth() int LTexture::getWidth()

View File

@@ -8,61 +8,64 @@
#ifndef LTEXTURE_H #ifndef LTEXTURE_H
#define LTEXTURE_H #define LTEXTURE_H
//Texture wrapper class // Texture wrapper class
class LTexture class LTexture
{ {
public: public:
//Initializes variables // Initializes variables
LTexture(); LTexture(SDL_Renderer *gRenderer);
//Deallocates memory // Deallocates memory
~LTexture(); ~LTexture();
//Loads image at specified path // Loads image at specified path
bool loadFromFile( std::string path ); bool loadFromFile(std::string path);
//Creates blank texture // Creates blank texture
bool createBlank( int width, int height, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING ); bool createBlank(int width, int height, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING);
//Deallocates texture // Deallocates texture
void free(); void free();
//Set color modulation // Set color modulation
void setColor( Uint8 red, Uint8 green, Uint8 blue ); void setColor(Uint8 red, Uint8 green, Uint8 blue);
//Set blending // Set blending
void setBlendMode( SDL_BlendMode blending ); void setBlendMode(SDL_BlendMode blending);
//Set alpha modulation // Set alpha modulation
void setAlpha( Uint8 alpha ); void setAlpha(Uint8 alpha);
//Renders texture at given point
void render( int x, int y, SDL_Rect* clip = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE );
//Set self as render target // Renders texture at given point
void setAsRenderTarget(); void render(int x, int y, SDL_Rect *clip = NULL, double angle = 0.0, SDL_Point *center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE);
//Gets image dimensions // Set self as render target
int getWidth(); void setAsRenderTarget();
int getHeight();
//Pixel manipulators // Gets image dimensions
bool lockTexture(); int getWidth();
bool unlockTexture(); int getHeight();
void* getPixels();
void copyPixels( void* pixels );
int getPitch();
Uint32 getPixel32( unsigned int x, unsigned int y );
private: // Pixel manipulators
//The actual hardware texture bool lockTexture();
SDL_Texture* mTexture; bool unlockTexture();
void* mPixels; void *getPixels();
int mPitch; void copyPixels(void *pixels);
int getPitch();
Uint32 getPixel32(unsigned int x, unsigned int y);
//Image dimensions private:
int mWidth; // El renderizador de la ventana
int mHeight; SDL_Renderer *gRenderer = NULL;
// The actual hardware texture
SDL_Texture *mTexture;
void *mPixels;
int mPitch;
// Image dimensions
int mWidth;
int mHeight;
}; };
#endif #endif

View File

@@ -43,7 +43,6 @@ un tipo asociado diferente a NO_KIND
#include "const.h" #include "const.h"
#include "gamedirector.h" #include "gamedirector.h"
#include "globals.h" #include "globals.h"
#include "globals2.h"
#include "ltexture.h" #include "ltexture.h"
#include "menu.h" #include "menu.h"
#include "player.h" #include "player.h"
@@ -54,25 +53,28 @@ un tipo asociado diferente a NO_KIND
#include <stdio.h> #include <stdio.h>
#include <string> #include <string>
//La ventana donde dibujamos // La ventana donde dibujamos
SDL_Window *gWindow = NULL; SDL_Window *gWindow = NULL;
//Arranca SDL y crea la ventana // El renderizador de la ventana
SDL_Renderer *gRenderer = NULL;
// Arranca SDL y crea la ventana
bool init(); bool init();
//Carga todos los recursos // Carga todos los recursos
bool loadMedia(); bool loadMedia();
//Libera todos los recursos y cierra SDL // Libera todos los recursos y cierra SDL
void close(); void close();
//Arranca SDL y crea la ventana // Arranca SDL y crea la ventana
bool init() bool init()
{ {
//Indicador de inicialización // Indicador de inicialización
bool success = true; bool success = true;
//Inicializa SDL // Inicializa SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO) < 0) if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO) < 0)
{ {
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError()); printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
@@ -80,20 +82,20 @@ bool init()
} }
else else
{ {
//Establece el filtro de la textura a nearest // Establece el filtro de la textura a nearest
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0")) if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0"))
{ {
printf("Warning: Nearest texture filtering not enabled!"); printf("Warning: Nearest texture filtering not enabled!");
} }
//Inicializa SDL_mixer // Inicializa SDL_mixer
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
{ {
printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()); printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError());
success = false; success = false;
} }
//Crea la ventana // Crea la ventana
gWindow = SDL_CreateWindow("Super Popping (Like Loc) in Jailers World", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, VIEW_WIDTH, VIEW_HEIGHT, SDL_WINDOW_SHOWN); gWindow = SDL_CreateWindow("Super Popping (Like Loc) in Jailers World", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, VIEW_WIDTH, VIEW_HEIGHT, SDL_WINDOW_SHOWN);
if (gWindow == NULL) if (gWindow == NULL)
{ {
@@ -102,7 +104,7 @@ bool init()
} }
else else
{ {
//Crea un renderizador para la ventana con vsync // Crea un renderizador para la ventana con vsync
gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (gRenderer == NULL) if (gRenderer == NULL)
{ {
@@ -111,13 +113,13 @@ bool init()
} }
else else
{ {
//Inicializa el color de renderizado // Inicializa el color de renderizado
SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0x00, 0xFF); SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0x00, 0xFF);
//Establece el tamaño del buffer de renderizado // Establece el tamaño del buffer de renderizado
SDL_RenderSetLogicalSize(gRenderer, SCREEN_WIDTH, SCREEN_HEIGHT); SDL_RenderSetLogicalSize(gRenderer, SCREEN_WIDTH, SCREEN_HEIGHT);
//Inicializa el cargador de PNG // Inicializa el cargador de PNG
int imgFlags = IMG_INIT_PNG; int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags)) if (!(IMG_Init(imgFlags) & imgFlags))
{ {
@@ -131,105 +133,23 @@ bool init()
return success; return success;
} }
//Carga todos los recursos // Libera todos los recursos y cierra SDL
bool loadMedia()
{
//Indicador de éxito en la carga
bool success = true;
//Carga los gráficos del jugador
if (!gPlayerTexture.loadFromFile("media/gfx/player.png"))
{
printf("Failed to load player texture!\n");
success = false;
}
//Carga los gráficos de los globos
if (!gBalloonTexture.loadFromFile("media/gfx/balloon.png"))
{
printf("Failed to load balloon texture!\n");
success = false;
}
//Carga los gráficos de las balas
if (!gBulletTexture.loadFromFile("media/gfx/bullet.png"))
{
printf("Failed to load bullet texture!\n");
success = false;
}
//Carga los gráficos del fondo del juego
if (!gGameBackgroundTexture.loadFromFile("media/gfx/background.png"))
{
printf("Failed to load game background texture!\n");
success = false;
}
//Carga los gráficos del fondo de la pantalla de titulo
if (!gTitleBackgroundTexture.loadFromFile("media/gfx/title.png"))
{
printf("Failed to load title texture!\n");
success = false;
}
//Carga varios gráficos para varios propósitos
if (!gMiscTexture.loadFromFile("media/gfx/misc.png"))
{
printf("Failed to load misc texture!\n");
success = false;
}
//Carga los gráficos para el menu
if (!gMenuTexture.loadFromFile("media/gfx/menu.png"))
{
printf("Failed to load menu texture!\n");
success = false;
}
//Carga los gráficos para el texto blanco
if (!gWhiteFontTexture.loadFromFile("media/gfx/white_font.png"))
{
printf("Failed to load white font texture!\n");
success = false;
}
//Carga los gráficos para el texto negro
if (!gBlackFontTexture.loadFromFile("media/gfx/black_font.png"))
{
printf("Failed to load black font texture!\n");
success = false;
}
return success;
}
//Libera todos los recursos y cierra SDL
void close() void close()
{ {
//Libera todas las imagenes // Destruye la ventana
gPlayerTexture.free();
gGameBackgroundTexture.free();
gTitleBackgroundTexture.free();
gWhiteFontTexture.free();
gBlackFontTexture.free();
gMenuTexture.free();
gBalloonTexture.free();
gMiscTexture.free();
//Destruye la ventana
SDL_DestroyRenderer(gRenderer); SDL_DestroyRenderer(gRenderer);
SDL_DestroyWindow(gWindow); SDL_DestroyWindow(gWindow);
gWindow = NULL; gWindow = NULL;
gRenderer = NULL; gRenderer = NULL;
//Sal del subsistema SDL // Sal del subsistema SDL
IMG_Quit(); IMG_Quit();
SDL_Quit(); SDL_Quit();
} }
int main(int argc, char *args[]) int main(int argc, char *args[])
{ {
//Arranca SDL y crea la ventana // Arranca SDL y crea la ventana
if (!init()) if (!init())
{ {
printf("Failed to initialize!\n"); printf("Failed to initialize!\n");
@@ -237,24 +157,18 @@ int main(int argc, char *args[])
} }
else else
{ {
//Carga los recursos
if (!loadMedia())
{ {
printf("Failed to load media!\n"); // Crea el objeto gameDirector
} GameDirector gameDirector(gRenderer);
else
{
//Crea el objeto gameDirector
GameDirector gameDirector;
//Inicializa el objeto gameDirector // Inicializa el objeto gameDirector
gameDirector.init(); gameDirector.init();
#ifdef TEST #ifdef TEST
gameDirector.resetBalloons(); gameDirector.resetBalloons();
#endif #endif
//Mientras no se quiera salir del juego // Mientras no se quiera salir del juego
while (!(gameDirector.getGameStatus() == GAME_STATE_QUIT)) while (!(gameDirector.getGameStatus() == GAME_STATE_QUIT))
{ {
switch (gameDirector.getGameStatus()) switch (gameDirector.getGameStatus())
@@ -274,7 +188,7 @@ int main(int argc, char *args[])
} }
} }
//Libera todos los recursos y cierra SDL // Libera todos los recursos y cierra SDL
close(); close();
return 0; return 0;

View File

@@ -1,15 +1,30 @@
#include "menu.h" #include "menu.h"
//Constructor // Constructor
Menu::Menu() Menu::Menu(SDL_Renderer *gRenderer)
{ {
this->gRenderer = gRenderer;
gMenuTexture = new LTexture(gRenderer);
// Carga los gráficos para el menu
if (!gMenuTexture->loadFromFile("media/gfx/menu.png"))
{
printf("Failed to load menu texture!\n");
}
init(0, 0, 0, MENU_BACKGROUND_SOLID); init(0, 0, 0, MENU_BACKGROUND_SOLID);
} }
//Inicializador // Destructor
Menu::~Menu()
{
gMenuTexture->free();
}
// Inicializador
void Menu::init(int x, int y, int offset_sprite_selector, int backgroundType) void Menu::init(int x, int y, int offset_sprite_selector, int backgroundType)
{ {
//Inicia variables // Inicia variables
mSelectorIndex = 0; mSelectorIndex = 0;
mTotalItems = 0; mTotalItems = 0;
mItemSelected = MENU_NO_OPTION; mItemSelected = MENU_NO_OPTION;
@@ -24,15 +39,15 @@ void Menu::init(int x, int y, int offset_sprite_selector, int backgroundType)
mRectB = 0; mRectB = 0;
mBackgroundType = backgroundType; mBackgroundType = backgroundType;
//Sprite con los graficos del selector // Sprite con los graficos del selector
mSelectorSprite.setWidth(8); mSelectorSprite.setWidth(8);
mSelectorSprite.setHeight(8); mSelectorSprite.setHeight(8);
mSelectorSprite.setPosX(0); mSelectorSprite.setPosX(0);
mSelectorSprite.setPosY(0); mSelectorSprite.setPosY(0);
mSelectorSprite.setTexture(gMenuTexture); mSelectorSprite.setTexture(*gMenuTexture);
mSelectorSprite.setSpriteClip(offset_sprite_selector, 0, mSelectorSprite.getWidth(), mSelectorSprite.getHeight()); mSelectorSprite.setSpriteClip(offset_sprite_selector, 0, mSelectorSprite.getWidth(), mSelectorSprite.getHeight());
//Elementos del menu // Elementos del menu
for (Uint8 i = 0; i < 10; i++) for (Uint8 i = 0; i < 10; i++)
{ {
mMenuItem[i].label = ""; mMenuItem[i].label = "";
@@ -40,24 +55,24 @@ void Menu::init(int x, int y, int offset_sprite_selector, int backgroundType)
mMenuItem[i].y = mPosY + (i * (BLOCK + 2)); mMenuItem[i].y = mPosY + (i * (BLOCK + 2));
} }
//Mueve el grafico del selector al elemento seleccionado // Mueve el grafico del selector al elemento seleccionado
moveSelectorSprite(mSelectorIndex); moveSelectorSprite(mSelectorIndex);
} }
//Obtiene el valor de la variable // Obtiene el valor de la variable
Uint8 Menu::getItemSelected() Uint8 Menu::getItemSelected()
{ {
return mItemSelected; return mItemSelected;
}; };
//Mueve el grafico del selector al elemento seleccionado // Mueve el grafico del selector al elemento seleccionado
void Menu::moveSelectorSprite(int pos) void Menu::moveSelectorSprite(int pos)
{ {
mSelectorSprite.setPosX(mMenuItem[pos].x - (BLOCK * 1)); mSelectorSprite.setPosX(mMenuItem[pos].x - (BLOCK * 1));
mSelectorSprite.setPosY(mMenuItem[pos].y); mSelectorSprite.setPosY(mMenuItem[pos].y);
} }
//Deja el menu apuntando al primer elemento // Deja el menu apuntando al primer elemento
void Menu::resetMenu() void Menu::resetMenu()
{ {
mItemSelected = MENU_NO_OPTION; mItemSelected = MENU_NO_OPTION;
@@ -65,7 +80,7 @@ void Menu::resetMenu()
moveSelectorSprite(mSelectorIndex); moveSelectorSprite(mSelectorIndex);
}; };
//Deja el menu apuntando al siguiente elemento // Deja el menu apuntando al siguiente elemento
void Menu::increaseSelectorIndex() void Menu::increaseSelectorIndex()
{ {
if (mSelectorIndex < (mTotalItems - 1)) if (mSelectorIndex < (mTotalItems - 1))
@@ -74,7 +89,7 @@ void Menu::increaseSelectorIndex()
} }
}; };
//Deja el menu apuntando al elemento anterior // Deja el menu apuntando al elemento anterior
void Menu::decreaseSelectorIndex() void Menu::decreaseSelectorIndex()
{ {
if (mSelectorIndex > 0) if (mSelectorIndex > 0)
@@ -83,7 +98,7 @@ void Menu::decreaseSelectorIndex()
} }
}; };
//Comprueba la entrada (teclado, gamepad) y actua en consecuencia // Comprueba la entrada (teclado, gamepad) y actua en consecuencia
void Menu::checkInput(Uint8 input) void Menu::checkInput(Uint8 input)
{ {
switch (input) switch (input)
@@ -102,17 +117,17 @@ void Menu::checkInput(Uint8 input)
} }
} }
//Pinta el menu en pantalla // Pinta el menu en pantalla
void Menu::render(Text &text) void Menu::render(Text &text)
{ {
//Render color filled quad // Render color filled quad
if (mBackgroundType == MENU_BACKGROUND_SOLID) if (mBackgroundType == MENU_BACKGROUND_SOLID)
{ {
SDL_SetRenderDrawColor(gRenderer, mRectR, mRectG, mRectB, mRectA); SDL_SetRenderDrawColor(gRenderer, mRectR, mRectG, mRectB, mRectA);
SDL_RenderFillRect(gRenderer, &mRect); SDL_RenderFillRect(gRenderer, &mRect);
} }
//Render text // Render text
int i = 0; int i = 0;
mSelectorSprite.render(); mSelectorSprite.render();
for (i = 0; i < mTotalItems; i++) for (i = 0; i < mTotalItems; i++)
@@ -121,17 +136,17 @@ void Menu::render(Text &text)
} }
} }
//Establece el rectangulo de fondo del menu // Establece el rectangulo de fondo del menu
void Menu::setRectSize() void Menu::setRectSize()
{ {
int i = 0; int i = 0;
int maxLength = 0; int maxLength = 0;
//La altura se corresponde al numero de items mas un hueco arriba y otro abajo // La altura se corresponde al numero de items mas un hueco arriba y otro abajo
mRect.h = (mTotalItems + 2) * BLOCK; mRect.h = (mTotalItems + 2) * BLOCK;
//La anchura es la de la cadena mas larga mas tres bloques, uno por la derecha // La anchura es la de la cadena mas larga mas tres bloques, uno por la derecha
//y dos por la izquierda, uno de ellos para el selector // y dos por la izquierda, uno de ellos para el selector
for (i = 0; i < mTotalItems; i++) for (i = 0; i < mTotalItems; i++)
{ {
if ((int)mMenuItem[i].label.length() > maxLength) if ((int)mMenuItem[i].label.length() > maxLength)
@@ -145,13 +160,13 @@ void Menu::setRectSize()
mRect.y = mPosY - BLOCK; mRect.y = mPosY - BLOCK;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Menu::setTotalItems(int num) void Menu::setTotalItems(int num)
{ {
mTotalItems = num; mTotalItems = num;
} }
//Establece el color del rectangulo de fondo // Establece el color del rectangulo de fondo
void Menu::setBackgroundColor(int r, int g, int b, int alpha) void Menu::setBackgroundColor(int r, int g, int b, int alpha)
{ {
mRectR = r; mRectR = r;
@@ -160,30 +175,30 @@ void Menu::setBackgroundColor(int r, int g, int b, int alpha)
mRectA = alpha; mRectA = alpha;
} }
//Centra el menu en pantalla // Centra el menu en pantalla
void Menu::centerMenuOnScreen() void Menu::centerMenuOnScreen()
{ {
//Actualiza el rectangulo de fondo para recalcular las dimensiones // Actualiza el rectangulo de fondo para recalcular las dimensiones
setRectSize(); setRectSize();
//Establece la nueva posición centrada en funcion del ancho // Establece la nueva posición centrada en funcion del ancho
//de la pantalla y del ancho del rectangulo // de la pantalla y del ancho del rectangulo
mPosX = (SCREEN_WIDTH / 2) - (mRect.w / 2) + (BLOCK * 2); mPosX = (SCREEN_WIDTH / 2) - (mRect.w / 2) + (BLOCK * 2);
//Reposiciona los elementos del menu // Reposiciona los elementos del menu
for (Uint8 i = 0; i < 10; i++) for (Uint8 i = 0; i < 10; i++)
{ {
mMenuItem[i].x = mPosX; mMenuItem[i].x = mPosX;
} }
//Recalcula el rectangulo de fondo // Recalcula el rectangulo de fondo
setRectSize(); setRectSize();
//Recoloca el selector // Recoloca el selector
moveSelectorSprite(mSelectorIndex); moveSelectorSprite(mSelectorIndex);
} }
//Añade un item al menu // Añade un item al menu
void Menu::addItem(std::string text) void Menu::addItem(std::string text)
{ {
if (mTotalItems < 10) if (mTotalItems < 10)

View File

@@ -3,86 +3,93 @@
#include "sprite.h" #include "sprite.h"
#include "const.h" #include "const.h"
#include "globals.h" #include "globals.h"
#include "globals2.h"
#include "text.h" #include "text.h"
#ifndef MENU_H #ifndef MENU_H
#define MENU_H #define MENU_H
//Clase menu // Clase menu
class Menu class Menu
{ {
public: public:
//Constructor // Constructor
Menu(); Menu(SDL_Renderer *gRenderer);
//Inicializador // Destructor
~Menu();
// Inicializador
void init(int x, int y, int offset_sprite_selector, int backgroundType); void init(int x, int y, int offset_sprite_selector, int backgroundType);
//Obtiene el valor de la variable // Obtiene el valor de la variable
Uint8 getItemSelected(); Uint8 getItemSelected();
//Mueve el grafico del selector al elemento seleccionado // Mueve el grafico del selector al elemento seleccionado
void moveSelectorSprite(int pos); void moveSelectorSprite(int pos);
//Deja el menu apuntando al primer elemento // Deja el menu apuntando al primer elemento
void resetMenu(); void resetMenu();
//Deja el menu apuntando al siguiente elemento // Deja el menu apuntando al siguiente elemento
void increaseSelectorIndex(); void increaseSelectorIndex();
//Deja el menu apuntando al elemento anterior // Deja el menu apuntando al elemento anterior
void decreaseSelectorIndex(); void decreaseSelectorIndex();
//Comprueba la entrada (teclado, gamepad) y actua en consecuencia // Comprueba la entrada (teclado, gamepad) y actua en consecuencia
void checkInput(Uint8 input); void checkInput(Uint8 input);
//Pinta el menu en pantalla // Pinta el menu en pantalla
void render(Text &text); void render(Text &text);
//Establece el rectangulo de fondo del menu // Establece el rectangulo de fondo del menu
void setRectSize(); void setRectSize();
//Establece el valor de la variable // Establece el valor de la variable
void setTotalItems(int num); void setTotalItems(int num);
//Establece el color del rectangulo de fondo // Establece el color del rectangulo de fondo
void setBackgroundColor(int r, int g, int b, int alpha); void setBackgroundColor(int r, int g, int b, int alpha);
//Centra el menu en pantalla // Centra el menu en pantalla
void centerMenuOnScreen(); void centerMenuOnScreen();
//Añade un item al menu // Añade un item al menu
void addItem(std::string text); void addItem(std::string text);
private: private:
//Posicion X/Y del texto del primer elemento del menu // El renderizador de la ventana
SDL_Renderer *gRenderer;
LTexture *gMenuTexture;
// Posicion X/Y del texto del primer elemento del menu
int mPosX; int mPosX;
int mPosY; int mPosY;
//Elemento del menu que tiene el foco // Elemento del menu que tiene el foco
Uint8 mSelectorIndex; Uint8 mSelectorIndex;
//Numero de items del menu // Numero de items del menu
Uint8 mTotalItems; Uint8 mTotalItems;
//Item del menu que ha sido seleccionado // Item del menu que ha sido seleccionado
Uint8 mItemSelected; Uint8 mItemSelected;
//Tipo de fondo para el menu // Tipo de fondo para el menu
Uint8 mBackgroundType; Uint8 mBackgroundType;
//Sprite con los graficos del selector // Sprite con los graficos del selector
Sprite mSelectorSprite; Sprite mSelectorSprite;
//Rectangulo y colores para el fondo del menu // Rectangulo y colores para el fondo del menu
SDL_Rect mRect; SDL_Rect mRect;
Uint8 mRectR; //Rojo Uint8 mRectR; // Rojo
Uint8 mRectG; //Verde Uint8 mRectG; // Verde
Uint8 mRectB; //Azul Uint8 mRectB; // Azul
Uint8 mRectA; //Alfa o transparencia Uint8 mRectA; // Alfa o transparencia
//Estructura para cada elemento del menu // Estructura para cada elemento del menu
struct MenuItem struct MenuItem
{ {
std::string label; std::string label;

View File

@@ -1,75 +1,91 @@
#include "player.h" #include "player.h"
//Constructor // Constructor
Player::Player() Player::Player(SDL_Renderer *gRenderer)
{ {
this->gRenderer = gRenderer;
gPlayerTexture = new LTexture(gRenderer);
// Carga los gráficos del jugador
if (!gPlayerTexture->loadFromFile("media/gfx/player.png"))
{
printf("Failed to load player texture!\n");
}
init(); init();
} }
//Iniciador // Destructor
Player::~Player()
{
gPlayerTexture->free();
}
// Iniciador
void Player::init() void Player::init()
{ {
//Establece la altura y el ancho del jugador // Establece la altura y el ancho del jugador
mWidth = 3 * BLOCK; mWidth = 3 * BLOCK;
mHeight = 3 * BLOCK; mHeight = 3 * BLOCK;
//Establece la posición inicial del jugador // Establece la posición inicial del jugador
mPosX = PLAY_AREA_LEFT + (PLAY_AREA_WIDTH / 2) - (mWidth / 2); mPosX = PLAY_AREA_LEFT + (PLAY_AREA_WIDTH / 2) - (mWidth / 2);
mPosY = PLAY_AREA_BOTTOM - mHeight; mPosY = PLAY_AREA_BOTTOM - mHeight;
//Establece el tamaño del circulo de colisión // Establece el tamaño del circulo de colisión
mCollider.r = 7; mCollider.r = 7;
//Actualiza la posición del circulo de colisión // Actualiza la posición del circulo de colisión
shiftColliders(); shiftColliders();
//Establece la velocidad inicial // Establece la velocidad inicial
mVelX = 0; mVelX = 0;
mVelY = 0; mVelY = 0;
//Establece la velocidad base // Establece la velocidad base
mBaseSpeed = 1.5; mBaseSpeed = 1.5;
//Establece el numero inicial de vidas // Establece el numero inicial de vidas
mStartingLives = 3; mStartingLives = 3;
mLives = mStartingLives; mLives = mStartingLives;
//Establece la puntuación inicial // Establece la puntuación inicial
mScore = 0; mScore = 0;
//Inicia el contador // Inicia el contador
mCooldown = 10; mCooldown = 10;
//Inicia el sprite // Inicia el sprite
mSprite.init(); mSprite.init();
//Set width and height of the player sprite // Set width and height of the player sprite
mSprite.setWidth(mWidth); mSprite.setWidth(mWidth);
mSprite.setHeight(mHeight); mSprite.setHeight(mHeight);
//Set sprite position // Set sprite position
mSprite.setPosX(mPosX); mSprite.setPosX(mPosX);
mSprite.setPosY(mPosY); mSprite.setPosY(mPosY);
//Set sprite sheet // Set sprite sheet
mSprite.setTexture(gPlayerTexture); mSprite.setTexture(*gPlayerTexture);
//Set status // Set status
mStatus = PLAYER_STATE_STOPPED; mStatus = PLAYER_STATE_STOPPED;
//Initialize animation variables // Initialize animation variables
mSprite.setCurrentFrame(0); mSprite.setCurrentFrame(0);
mSprite.setAnimationCounter(0); mSprite.setAnimationCounter(0);
mSprite.setAnimationNumFrames(PLAYER_STATE_STOPPED, 1); mSprite.setAnimationNumFrames(PLAYER_STATE_STOPPED, 1);
mSprite.setAnimationNumFrames(PLAYER_STATE_WALKING_LEFT, 4); mSprite.setAnimationNumFrames(PLAYER_STATE_WALKING_LEFT, 4);
mSprite.setAnimationNumFrames(PLAYER_STATE_WALKING_RIGHT, 4); mSprite.setAnimationNumFrames(PLAYER_STATE_WALKING_RIGHT, 4);
mSprite.setAnimationSpeed(PLAYER_STATE_STOPPED, 10); mSprite.setAnimationSpeed(PLAYER_STATE_STOPPED, 10);
mSprite.setAnimationSpeed(PLAYER_STATE_WALKING_LEFT, 5); mSprite.setAnimationSpeed(PLAYER_STATE_WALKING_LEFT, 5);
mSprite.setAnimationSpeed(PLAYER_STATE_WALKING_RIGHT, 5); mSprite.setAnimationSpeed(PLAYER_STATE_WALKING_RIGHT, 5);
//Set animation clips // Set animation clips
mSprite.setAnimationFrames(PLAYER_STATE_WALKING_LEFT, 0, mSprite.getWidth() * 0, mSprite.getWidth() * 0, mSprite.getWidth(), mSprite.getHeight()); mSprite.setAnimationFrames(PLAYER_STATE_WALKING_LEFT, 0, mSprite.getWidth() * 0, mSprite.getWidth() * 0, mSprite.getWidth(), mSprite.getHeight());
mSprite.setAnimationFrames(PLAYER_STATE_WALKING_LEFT, 1, mSprite.getWidth() * 1, mSprite.getWidth() * 0, mSprite.getWidth(), mSprite.getHeight()); mSprite.setAnimationFrames(PLAYER_STATE_WALKING_LEFT, 1, mSprite.getWidth() * 1, mSprite.getWidth() * 0, mSprite.getWidth(), mSprite.getHeight());
mSprite.setAnimationFrames(PLAYER_STATE_WALKING_LEFT, 2, mSprite.getWidth() * 2, mSprite.getWidth() * 0, mSprite.getWidth(), mSprite.getHeight()); mSprite.setAnimationFrames(PLAYER_STATE_WALKING_LEFT, 2, mSprite.getWidth() * 2, mSprite.getWidth() * 0, mSprite.getWidth(), mSprite.getHeight());
@@ -80,11 +96,11 @@ void Player::init()
mSprite.setAnimationFrames(PLAYER_STATE_WALKING_RIGHT, 3, mSprite.getWidth() * 3, mSprite.getHeight() * 1, mSprite.getWidth(), mSprite.getHeight()); mSprite.setAnimationFrames(PLAYER_STATE_WALKING_RIGHT, 3, mSprite.getWidth() * 3, mSprite.getHeight() * 1, mSprite.getWidth(), mSprite.getHeight());
mSprite.setAnimationFrames(PLAYER_STATE_STOPPED, 0, mSprite.getWidth() * 0, mSprite.getHeight() * 2, mSprite.getWidth(), mSprite.getHeight()); mSprite.setAnimationFrames(PLAYER_STATE_STOPPED, 0, mSprite.getWidth() * 0, mSprite.getHeight() * 2, mSprite.getWidth(), mSprite.getHeight());
//Set window for sprite sheet // Set window for sprite sheet
mSprite.setSpriteClip(mSprite.getAnimationClip(PLAYER_STATE_STOPPED, 0)); mSprite.setSpriteClip(mSprite.getAnimationClip(PLAYER_STATE_STOPPED, 0));
} }
//Comprueba el teclado y actua en consecuencia // Comprueba el teclado y actua en consecuencia
void Player::checkInput(Uint8 input) void Player::checkInput(Uint8 input)
{ {
switch (input) switch (input)
@@ -94,56 +110,56 @@ void Player::checkInput(Uint8 input)
setStatus(PLAYER_STATE_WALKING_LEFT); setStatus(PLAYER_STATE_WALKING_LEFT);
break; break;
case INPUT_RIGHT: case INPUT_RIGHT:
mVelX = mBaseSpeed; mVelX = mBaseSpeed;
setStatus(PLAYER_STATE_WALKING_RIGHT); setStatus(PLAYER_STATE_WALKING_RIGHT);
break; break;
default: default:
mVelX = 0; mVelX = 0;
setStatus(PLAYER_STATE_STOPPED); setStatus(PLAYER_STATE_STOPPED);
break; break;
} }
} }
//Mueve el jugador a la posición y animación que le corresponde // Mueve el jugador a la posición y animación que le corresponde
void Player::move() void Player::move()
{ {
//Move the player left or right // Move the player left or right
mPosX += mVelX; mPosX += mVelX;
//If the player went too far to the left or right // If the player went too far to the left or right
if ((mPosX < PLAY_AREA_LEFT) || (mPosX + mWidth > PLAY_AREA_RIGHT)) if ((mPosX < PLAY_AREA_LEFT) || (mPosX + mWidth > PLAY_AREA_RIGHT))
{ {
//Move back // Move back
mPosX -= mVelX; mPosX -= mVelX;
} }
//Move the player up or down // Move the player up or down
mPosY += mVelY; mPosY += mVelY;
//If the player went too far up or down // If the player went too far up or down
if ((mPosY < PLAY_AREA_TOP) || (mPosY + mHeight > PLAY_AREA_BOTTOM)) if ((mPosY < PLAY_AREA_TOP) || (mPosY + mHeight > PLAY_AREA_BOTTOM))
{ {
//Move back // Move back
mPosY -= mVelY; mPosY -= mVelY;
} }
//Update sprite position // Update sprite position
mSprite.setPosX(getPosX()); mSprite.setPosX(getPosX());
mSprite.setPosY(mPosY); mSprite.setPosY(mPosY);
} }
//Pinta el jugador en pantalla // Pinta el jugador en pantalla
void Player::render() void Player::render()
{ {
mSprite.render(); mSprite.render();
} }
//Establece el estado del jugador // Establece el estado del jugador
void Player::setStatus(int status) void Player::setStatus(int status)
{ {
//Si cambiamos de estado, reiniciamos la animación // Si cambiamos de estado, reiniciamos la animación
if (mStatus != status) if (mStatus != status)
{ {
mStatus = status; mStatus = status;
@@ -151,40 +167,40 @@ void Player::setStatus(int status)
} }
} }
//Establece la animación correspondiente al estado // Establece la animación correspondiente al estado
void Player::setAnimation() void Player::setAnimation()
{ {
mSprite.animate(mStatus); mSprite.animate(mStatus);
} }
//Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getPosX() int Player::getPosX()
{ {
return int(mPosX); return int(mPosX);
} }
//Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getPosY() int Player::getPosY()
{ {
return mPosY; return mPosY;
} }
//Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getWidth() int Player::getWidth()
{ {
return mWidth; return mWidth;
} }
//Obtiene el valor de la variable // Obtiene el valor de la variable
int Player::getHeight() int Player::getHeight()
{ {
return mHeight; return mHeight;
} }
//Indica si el jugador puede disparar // Indica si el jugador puede disparar
bool Player::canFire() bool Player::canFire()
{ {
//Si el contador a llegado a cero, podemos disparar. En caso contrario decrementamos el contador // Si el contador a llegado a cero, podemos disparar. En caso contrario decrementamos el contador
if (mCooldown > 0) if (mCooldown > 0)
{ {
return false; return false;
@@ -195,13 +211,13 @@ bool Player::canFire()
} }
} }
//Establece el valor de la variable // Establece el valor de la variable
void Player::setFireCooldown(int time) void Player::setFireCooldown(int time)
{ {
mCooldown = time; mCooldown = time;
} }
//Actualiza el valor de la variable // Actualiza el valor de la variable
void Player::updateCooldown() void Player::updateCooldown()
{ {
if (mCooldown > 0) if (mCooldown > 0)
@@ -210,43 +226,43 @@ void Player::updateCooldown()
} }
} }
//Actualiza al jugador a su posicion, animación y controla los contadores // Actualiza al jugador a su posicion, animación y controla los contadores
void Player::update() void Player::update()
{ {
move(); move();
setAnimation(); setAnimation();
shiftColliders(); shiftColliders();
updateCooldown(); updateCooldown();
} }
//Obtiene la puntuación del jugador // Obtiene la puntuación del jugador
int Player::getScore() int Player::getScore()
{ {
return mScore; return mScore;
} }
//Establece la puntuación del jugador // Establece la puntuación del jugador
void Player::setScore(int score) void Player::setScore(int score)
{ {
mScore = score; mScore = score;
} }
//Añade a la puntuación del jugador // Añade a la puntuación del jugador
void Player::addScore(int score) void Player::addScore(int score)
{ {
mScore += score; mScore += score;
} }
//Obtiene el circulo de colisión // Obtiene el circulo de colisión
Circle &Player::getCollider() Circle &Player::getCollider()
{ {
return mCollider; return mCollider;
} }
//Actualiza el circulo de colisión a la posición del jugador // Actualiza el circulo de colisión a la posición del jugador
void Player::shiftColliders() void Player::shiftColliders()
{ {
//Align collider to center of player // Align collider to center of player
mCollider.x = mPosX + (mWidth / 2); mCollider.x = mPosX + (mWidth / 2);
mCollider.y = mPosY + (mHeight / 2); mCollider.y = mPosY + (mHeight / 2);
} }

View File

@@ -3,110 +3,117 @@
#include "spriteanimated.h" #include "spriteanimated.h"
#include "const.h" #include "const.h"
#include "globals.h" #include "globals.h"
#include "globals2.h"
#ifndef PLAYER_H #ifndef PLAYER_H
#define PLAYER_H #define PLAYER_H
//The player // The player
class Player class Player
{ {
public: public:
//Constructor // Constructor
Player(); Player(SDL_Renderer *gRenderer);
//Iniciador // DEstructor
~Player();
// Iniciador
void init(); void init();
//Comprueba la entrada (teclado, gamepad) y actua en consecuencia // Comprueba la entrada (teclado, gamepad) y actua en consecuencia
void checkInput(Uint8 input); void checkInput(Uint8 input);
//Mueve el jugador a la posición y animación que le corresponde // Mueve el jugador a la posición y animación que le corresponde
void move(); void move();
//Pinta el jugador en pantalla // Pinta el jugador en pantalla
void render(); void render();
//Establece el estado del jugador // Establece el estado del jugador
void setStatus(int status); void setStatus(int status);
//Establece la animación correspondiente al estado // Establece la animación correspondiente al estado
void setAnimation(); void setAnimation();
//Obtiene el valor de la variable // Obtiene el valor de la variable
int getPosX(); int getPosX();
//Obtiene el valor de la variable // Obtiene el valor de la variable
int getPosY(); int getPosY();
//Obtiene el valor de la variable // Obtiene el valor de la variable
int getWidth(); int getWidth();
//Obtiene el valor de la variable // Obtiene el valor de la variable
int getHeight(); int getHeight();
//Indica si el jugador puede disparar // Indica si el jugador puede disparar
bool canFire(); bool canFire();
//Establece el valor de la variable // Establece el valor de la variable
void setFireCooldown(int time); void setFireCooldown(int time);
//Actualiza el valor de la variable // Actualiza el valor de la variable
void updateCooldown(); void updateCooldown();
//Actualiza al jugador a su posicion, animación y controla los contadores // Actualiza al jugador a su posicion, animación y controla los contadores
void update(); void update();
//Obtiene la puntuación del jugador // Obtiene la puntuación del jugador
int getScore(); int getScore();
//Establece la puntuación del jugador // Establece la puntuación del jugador
void setScore(int score); void setScore(int score);
//Añade a la puntuación del jugador // Añade a la puntuación del jugador
void addScore(int score); void addScore(int score);
//Obtiene el circulo de colisión // Obtiene el circulo de colisión
Circle &getCollider(); Circle &getCollider();
private: private:
//Posición X, Y del jugador // El renderizador de la ventana
SDL_Renderer *gRenderer;
LTexture *gPlayerTexture;
// Posición X, Y del jugador
float mPosX; float mPosX;
int mPosY; int mPosY;
//Altura y anchura del jugador // Altura y anchura del jugador
Uint8 mWidth; Uint8 mWidth;
Uint8 mHeight; Uint8 mHeight;
//Velocidad X, Y del jugador // Velocidad X, Y del jugador
float mVelX; float mVelX;
int mVelY; int mVelY;
//Velocidad base del jugador // Velocidad base del jugador
float mBaseSpeed; float mBaseSpeed;
//Contador durante el cual no puede disparar // Contador durante el cual no puede disparar
int mCooldown; int mCooldown;
//Vidas actuales del jugador // Vidas actuales del jugador
Uint8 mLives; Uint8 mLives;
//Vidas iniciales del jugador // Vidas iniciales del jugador
Uint8 mStartingLives; Uint8 mStartingLives;
//Puntos del jugador // Puntos del jugador
int mScore; int mScore;
//Estado del jugador // Estado del jugador
Uint8 mStatus; Uint8 mStatus;
//Sprite para dibujar al jugador en pantalla // Sprite para dibujar al jugador en pantalla
SpriteAnimated mSprite; SpriteAnimated mSprite;
//Circulo de colisión del jugador // Circulo de colisión del jugador
Circle mCollider; Circle mCollider;
//Actualiza el circulo de colisión a la posición del jugador // Actualiza el circulo de colisión a la posición del jugador
void shiftColliders(); void shiftColliders();
}; };

View File

@@ -2,71 +2,71 @@
void Sprite::render() void Sprite::render()
{ {
//Muestra el sprite por pantalla // Muestra el sprite por pantalla
mTexture->render(mPosX, mPosY, &mSpriteClip); mTexture->render(mPosX, mPosY, &mSpriteClip);
} }
//Obten el valor de la variable // Obten el valor de la variable
int Sprite::getPosX() int Sprite::getPosX()
{ {
return mPosX; return mPosX;
} }
//Obten el valor de la variable // Obten el valor de la variable
int Sprite::getPosY() int Sprite::getPosY()
{ {
return mPosY; return mPosY;
} }
//Obten el valor de la variable // Obten el valor de la variable
int Sprite::getWidth() int Sprite::getWidth()
{ {
return mWidth; return mWidth;
} }
//Obten el valor de la variable // Obten el valor de la variable
int Sprite::getHeight() int Sprite::getHeight()
{ {
return mHeight; return mHeight;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Sprite::setPosX(int x) void Sprite::setPosX(int x)
{ {
mPosX = x; mPosX = x;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Sprite::setPosY(int y) void Sprite::setPosY(int y)
{ {
mPosY = y; mPosY = y;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Sprite::setWidth(int w) void Sprite::setWidth(int w)
{ {
mWidth = w; mWidth = w;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Sprite::setHeight(int h) void Sprite::setHeight(int h)
{ {
mHeight = h; mHeight = h;
} }
//Obten el valor de la variable // Obten el valor de la variable
SDL_Rect Sprite::getSpriteClip() SDL_Rect Sprite::getSpriteClip()
{ {
return mSpriteClip; return mSpriteClip;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Sprite::setSpriteClip(SDL_Rect rect) void Sprite::setSpriteClip(SDL_Rect rect)
{ {
mSpriteClip = rect; mSpriteClip = rect;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Sprite::setSpriteClip(int x, int y, int w, int h) void Sprite::setSpriteClip(int x, int y, int w, int h)
{ {
mSpriteClip.x = x; mSpriteClip.x = x;
@@ -75,13 +75,13 @@ void Sprite::setSpriteClip(int x, int y, int w, int h)
mSpriteClip.h = h; mSpriteClip.h = h;
} }
//Obten el valor de la variable // Obten el valor de la variable
LTexture* Sprite::getTexture() LTexture *Sprite::getTexture()
{ {
return mTexture; return mTexture;
} }
//Establece el valor de la variable // Establece el valor de la variable
void Sprite::setTexture(LTexture &texture) void Sprite::setTexture(LTexture &texture)
{ {
mTexture = &texture; mTexture = &texture;

View File

@@ -5,66 +5,65 @@
#ifndef SPRITE_H #ifndef SPRITE_H
#define SPRITE_H #define SPRITE_H
//Clase sprite // Clase sprite
class Sprite class Sprite
{ {
public: public:
//Muestra el sprite por pantalla // Muestra el sprite por pantalla
void render(); void render();
//Obten el valor de la variable // Obten el valor de la variable
int getPosX(); int getPosX();
//Obten el valor de la variable // Obten el valor de la variable
int getPosY(); int getPosY();
//Obten el valor de la variable // Obten el valor de la variable
int getWidth(); int getWidth();
//Obten el valor de la variable // Obten el valor de la variable
int getHeight(); int getHeight();
//Establece el valor de la variable // Establece el valor de la variable
void setPosX(int x); void setPosX(int x);
//Establece el valor de la variable // Establece el valor de la variable
void setPosY(int y); void setPosY(int y);
//Establece el valor de la variable // Establece el valor de la variable
void setWidth(int w); void setWidth(int w);
//Establece el valor de la variable // Establece el valor de la variable
void setHeight(int h); void setHeight(int h);
//Obten el valor de la variable // Obten el valor de la variable
SDL_Rect getSpriteClip(); SDL_Rect getSpriteClip();
//Establece el valor de la variable // Establece el valor de la variable
void setSpriteClip(SDL_Rect rect); void setSpriteClip(SDL_Rect rect);
//Establece el valor de la variable // Establece el valor de la variable
void setSpriteClip(int x, int y, int w, int h); void setSpriteClip(int x, int y, int w, int h);
//Obten el valor de la variable // Obten el valor de la variable
LTexture* getTexture(); LTexture *getTexture();
//Establece el valor de la variable // Establece el valor de la variable
void setTexture(LTexture &texture); void setTexture(LTexture &texture);
private: private:
//Posición X,Y donde dibujar el sprite // Posición X,Y donde dibujar el sprite
int mPosX; int mPosX;
int mPosY; int mPosY;
//Alto y ancho del sprite // Alto y ancho del sprite
Uint16 mWidth; Uint16 mWidth;
Uint16 mHeight; Uint16 mHeight;
//Textura donde estan todos los dibujos del sprite // Textura donde estan todos los dibujos del sprite
LTexture *mTexture; LTexture *mTexture;
//Rectangulo de la textura que se dibujará en pantalla // Rectangulo de la textura que se dibujará en pantalla
SDL_Rect mSpriteClip; SDL_Rect mSpriteClip;
}; };

View File

@@ -1,12 +1,12 @@
#include "spriteanimated.h" #include "spriteanimated.h"
//Constructor // Constructor
SpriteAnimated::SpriteAnimated() SpriteAnimated::SpriteAnimated()
{ {
init(); init();
} }
//Iniciador // Iniciador
void SpriteAnimated::init() void SpriteAnimated::init()
{ {
for (Uint8 i = 0; i < 20; i++) for (Uint8 i = 0; i < 20; i++)
@@ -25,41 +25,41 @@ void SpriteAnimated::init()
mAnimationCounter = 0; mAnimationCounter = 0;
} }
//Calcula el frame correspondiente a la animación // Calcula el frame correspondiente a la animación
void SpriteAnimated::animate(int index) void SpriteAnimated::animate(int index)
{ {
//Calculamos el frame actual a partir del contador // Calculamos el frame actual a partir del contador
mCurrentFrame = mAnimationCounter / mAnimation[index].speed; mCurrentFrame = mAnimationCounter / mAnimation[index].speed;
//Si alcanzamos el final de la animación, reiniciamos el contador de la animación // Si alcanzamos el final de la animación, reiniciamos el contador de la animación
if (mCurrentFrame >= mAnimation[index].numFrames) if (mCurrentFrame >= mAnimation[index].numFrames)
{ {
mAnimationCounter = 0; mAnimationCounter = 0;
} }
//En caso contrario // En caso contrario
else else
{ {
//Escogemos el frame correspondiente de la animación // Escogemos el frame correspondiente de la animación
setSpriteClip(mAnimation[index].frames[mCurrentFrame]); setSpriteClip(mAnimation[index].frames[mCurrentFrame]);
//Incrementamos el contador de la animacion // Incrementamos el contador de la animacion
++mAnimationCounter; ++mAnimationCounter;
} }
} }
//Establece el frame actual de la animación // Establece el frame actual de la animación
void SpriteAnimated::setCurrentFrame(Uint8 num) void SpriteAnimated::setCurrentFrame(Uint8 num)
{ {
mCurrentFrame = num; mCurrentFrame = num;
} }
//Establece el numero de frames de la animacion // Establece el numero de frames de la animacion
void SpriteAnimated::setAnimationCounter(Uint16 num) void SpriteAnimated::setAnimationCounter(Uint16 num)
{ {
mAnimationCounter = num; mAnimationCounter = num;
} }
//Establece el rectangulo para un frame de una animación // Establece el rectangulo para un frame de una animación
void SpriteAnimated::setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h) void SpriteAnimated::setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h)
{ {
mAnimation[index_animation].frames[index_frame].x = x; mAnimation[index_animation].frames[index_frame].x = x;
@@ -68,19 +68,19 @@ void SpriteAnimated::setAnimationFrames(Uint8 index_animation, Uint8 index_frame
mAnimation[index_animation].frames[index_frame].h = h; mAnimation[index_animation].frames[index_frame].h = h;
} }
//Establece la velocidad de una animación // Establece la velocidad de una animación
void SpriteAnimated::setAnimationSpeed(Uint8 index, Uint8 speed) void SpriteAnimated::setAnimationSpeed(Uint8 index, Uint8 speed)
{ {
mAnimation[index].speed = speed; mAnimation[index].speed = speed;
} }
//Establece el numero de frames de una animación // Establece el numero de frames de una animación
void SpriteAnimated::setAnimationNumFrames(Uint8 index, Uint8 num) void SpriteAnimated::setAnimationNumFrames(Uint8 index, Uint8 num)
{ {
mAnimation[index].numFrames = num; mAnimation[index].numFrames = num;
} }
//Devuelve el rectangulo de una animación y frame concreto // Devuelve el rectangulo de una animación y frame concreto
SDL_Rect SpriteAnimated::getAnimationClip(Uint8 index_animation, Uint8 index_frame) SDL_Rect SpriteAnimated::getAnimationClip(Uint8 index_animation, Uint8 index_frame)
{ {
return mAnimation[index_animation].frames[index_frame]; return mAnimation[index_animation].frames[index_frame];

View File

@@ -7,35 +7,35 @@
#ifndef SPRITEANIMATED_H #ifndef SPRITEANIMATED_H
#define SPRITEANIMATED_H #define SPRITEANIMATED_H
//Clase spriteAnimated // Clase spriteAnimated
class SpriteAnimated : public Sprite class SpriteAnimated : public Sprite
{ {
public: public:
//Constructor // Constructor
SpriteAnimated(); SpriteAnimated();
//Iniciador // Iniciador
void init(); void init();
//Calcula el frame correspondiente a la animación // Calcula el frame correspondiente a la animación
void animate(int index); void animate(int index);
//Establece el frame actual de la animación // Establece el frame actual de la animación
void setCurrentFrame(Uint8 num); void setCurrentFrame(Uint8 num);
//Establece el numero de frames de la animacion // Establece el numero de frames de la animacion
void setAnimationCounter(Uint16 num); void setAnimationCounter(Uint16 num);
//Establece el rectangulo para un frame de una animación // Establece el rectangulo para un frame de una animación
void setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h); void setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h);
//Establece la velocidad de una animación // Establece la velocidad de una animación
void setAnimationSpeed(Uint8 index, Uint8 speed); void setAnimationSpeed(Uint8 index, Uint8 speed);
//Establece el numero de frames de una animación // Establece el numero de frames de una animación
void setAnimationNumFrames(Uint8 index, Uint8 num); void setAnimationNumFrames(Uint8 index, Uint8 num);
//Devuelve el rectangulo de una animación y frame concreto // Devuelve el rectangulo de una animación y frame concreto
SDL_Rect getAnimationClip(Uint8 index_animation, Uint8 index_frame); SDL_Rect getAnimationClip(Uint8 index_animation, Uint8 index_frame);
private: private:
@@ -45,14 +45,14 @@ private:
Uint8 numFrames; Uint8 numFrames;
Uint8 speed; Uint8 speed;
}; };
//Vector con las diferentes animaciones y los diferentes frames de cada animación // Vector con las diferentes animaciones y los diferentes frames de cada animación
sAnimation mAnimation[20]; sAnimation mAnimation[20];
//Frame actual // Frame actual
Uint8 mCurrentFrame; Uint8 mCurrentFrame;
//Contador para las animaciones // Contador para las animaciones
Uint16 mAnimationCounter; Uint16 mAnimationCounter;
}; };

View File

@@ -1,15 +1,15 @@
#include "text.h" #include "text.h"
//Constructor // Constructor
Text::Text() Text::Text()
{ {
init(NULL); init(NULL);
} }
//Inicializador // Inicializador
void Text::init(LTexture *texture) void Text::init(LTexture *texture)
{ {
//Inicia los valores del sprite que dibuja las letras // Inicia los valores del sprite que dibuja las letras
mSprite.setWidth(8); mSprite.setWidth(8);
mSprite.setHeight(8); mSprite.setHeight(8);
mSprite.setPosX(0); mSprite.setPosX(0);
@@ -17,18 +17,18 @@ void Text::init(LTexture *texture)
mSprite.setTexture(*texture); mSprite.setTexture(*texture);
mSprite.setSpriteClip(8, 8, mSprite.getWidth(), mSprite.getHeight()); mSprite.setSpriteClip(8, 8, mSprite.getWidth(), mSprite.getHeight());
//Cadena con los caracteres ascii que se van a inicializar // Cadena con los caracteres ascii que se van a inicializar
std::string text = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-/().:#"; std::string text = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-/().:#";
Uint8 i; Uint8 i;
//Inicializa a cero el vector con las coordenadas // Inicializa a cero el vector con las coordenadas
for (i = 0; i < 255; ++i) for (i = 0; i < 255; ++i)
{ {
mOffset[i].x = 0; mOffset[i].x = 0;
mOffset[i].y = 0; mOffset[i].y = 0;
} }
//Establece las coordenadas para cada caracter ascii de la cadena // Establece las coordenadas para cada caracter ascii de la cadena
for (i = 0; i < text.length(); ++i) for (i = 0; i < text.length(); ++i)
{ {
mOffset[int(text[i])].x = (((int(text[i]) - 32) % 15) - 0) * BLOCK; mOffset[int(text[i])].x = (((int(text[i]) - 32) % 15) - 0) * BLOCK;
@@ -36,9 +36,10 @@ void Text::init(LTexture *texture)
} }
} }
//Escribe el texto en pantalla // Escribe el texto en pantalla
void Text::write(int x, int y, std::string text) void Text::write(int x, int y, std::string text)
{; {
;
for (Uint8 i = 0; i < text.length(); ++i) for (Uint8 i = 0; i < text.length(); ++i)
{ {
mSprite.setSpriteClip(mOffset[int(text[i])].x, mOffset[int(text[i])].y, 8, 8); mSprite.setSpriteClip(mOffset[int(text[i])].x, mOffset[int(text[i])].y, 8, 8);

View File

@@ -6,24 +6,24 @@
#ifndef TEXT_H #ifndef TEXT_H
#define TEXT_H #define TEXT_H
//Text class // Text class
class Text class Text
{ {
public: public:
//Constructor // Constructor
Text(); Text();
//Inicializador // Inicializador
void init(LTexture *texture); void init(LTexture *texture);
//Escribe el texto en pantalla // Escribe el texto en pantalla
void write(int x, int y, std::string text); void write(int x, int y, std::string text);
private: private:
//Objeto con los graficos para el texto // Objeto con los graficos para el texto
Sprite mSprite; Sprite mSprite;
//Coordenadas dentro del PNG para cada código ascii // Coordenadas dentro del PNG para cada código ascii
struct Offset struct Offset
{ {
int x; int x;

BIN
super_pang_clone_linux Normal file

Binary file not shown.