working on class sections

This commit is contained in:
2021-04-17 23:46:14 +02:00
parent 2330820a15
commit e9ff516b1d
18 changed files with 329 additions and 6375 deletions

BIN
media/.DS_Store vendored

Binary file not shown.

View File

@@ -19,13 +19,13 @@ void AnimatedSprite::init(LTexture *texture, SDL_Renderer *renderer)
{
mRenderer = renderer;
mTexture = texture;
for (Uint8 i = 0; i < 20; i++)
for (int i = 0; i < 20; i++)
{
mAnimation[i].numFrames = 0;
mAnimation[i].speed = 0;
mAnimation[i].loop = true;
mAnimation[i].completed = false;
for (Uint8 j = 0; i < 20; i++)
for (int j = 0; i < 20; i++)
{
mAnimation[i].frames[j].x = 0;
mAnimation[i].frames[j].y = 0;

View File

@@ -53,13 +53,13 @@ void Balloon::init(float x, float y, Uint8 kind, float velx, float speed, Uint16
mMenace = 1;
// Establece los frames de cada animación
for (Uint8 i = 0; i < NUM_FRAMES_BALLON; i++)
for (int i = 0; i < NUM_FRAMES_BALLON; i++)
mSprite->setAnimationFrames(BALLOON_MOVING_ANIMATION, i, 50 + OFFSET_ORANGE_BALLOONS, 21 + (37 * i), getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
mSprite->setAnimationFrames(BALLOON_BORN_ANIMATION, i, 50 + OFFSET_BLUE_BALLOONS, 21 + (37 * i), getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_POP; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_POP; i++)
mSprite->setAnimationFrames(BALLOON_POP_ANIMATION, i, 50 + OFFSET_EXPLOSIONS, 21 + (37 * i), getWidth(), getHeight());
break;
@@ -87,13 +87,13 @@ void Balloon::init(float x, float y, Uint8 kind, float velx, float speed, Uint16
mMenace = 2;
// Establece los frames de cada animación
for (Uint8 i = 0; i < NUM_FRAMES_BALLON; i++)
for (int i = 0; i < NUM_FRAMES_BALLON; i++)
mSprite->setAnimationFrames(BALLOON_MOVING_ANIMATION, i, 37 + OFFSET_ORANGE_BALLOONS, 21 + (37 * i), getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
mSprite->setAnimationFrames(BALLOON_BORN_ANIMATION, i, 37 + OFFSET_BLUE_BALLOONS, 21 + (37 * i), getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_POP; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_POP; i++)
mSprite->setAnimationFrames(BALLOON_POP_ANIMATION, i, 37 + OFFSET_EXPLOSIONS, 21 + (37 * i), getWidth(), getHeight());
break;
@@ -121,13 +121,13 @@ void Balloon::init(float x, float y, Uint8 kind, float velx, float speed, Uint16
mMenace = 4;
// Establece los frames de cada animación
for (Uint8 i = 0; i < NUM_FRAMES_BALLON; i++)
for (int i = 0; i < NUM_FRAMES_BALLON; i++)
mSprite->setAnimationFrames(BALLOON_MOVING_ANIMATION, i, 37 + OFFSET_ORANGE_BALLOONS, 37 * i, getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
mSprite->setAnimationFrames(BALLOON_BORN_ANIMATION, i, 37 + OFFSET_BLUE_BALLOONS, 37 * i, getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_POP; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_POP; i++)
mSprite->setAnimationFrames(BALLOON_POP_ANIMATION, i, 37 + OFFSET_EXPLOSIONS, 37 * i, getWidth(), getHeight());
break;
@@ -155,13 +155,13 @@ void Balloon::init(float x, float y, Uint8 kind, float velx, float speed, Uint16
mMenace = 8;
// Establece los frames de cada animación
for (Uint8 i = 0; i < NUM_FRAMES_BALLON; i++)
for (int i = 0; i < NUM_FRAMES_BALLON; i++)
mSprite->setAnimationFrames(BALLOON_MOVING_ANIMATION, i, OFFSET_ORANGE_BALLOONS, 37 * i, getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
mSprite->setAnimationFrames(BALLOON_BORN_ANIMATION, i, OFFSET_BLUE_BALLOONS, 37 * i, getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_POP; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_POP; i++)
mSprite->setAnimationFrames(BALLOON_POP_ANIMATION, i, OFFSET_EXPLOSIONS, 37 * i, getWidth(), getHeight());
break;
@@ -189,13 +189,13 @@ void Balloon::init(float x, float y, Uint8 kind, float velx, float speed, Uint16
mMenace = 1;
// Establece los frames de cada animación
for (Uint8 i = 0; i < NUM_FRAMES_BALLON; i++)
for (int i = 0; i < NUM_FRAMES_BALLON; i++)
mSprite->setAnimationFrames(BALLOON_MOVING_ANIMATION, i, 50 + OFFSET_GREEN_BALLOONS, 21 + (37 * i), getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
mSprite->setAnimationFrames(BALLOON_BORN_ANIMATION, i, 50 + OFFSET_PURPLE_BALLOONS, 21 + (37 * i), getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_POP; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_POP; i++)
mSprite->setAnimationFrames(BALLOON_POP_ANIMATION, i, 50 + OFFSET_EXPLOSIONS, 21 + (37 * i), getWidth(), getHeight());
break;
@@ -223,13 +223,13 @@ void Balloon::init(float x, float y, Uint8 kind, float velx, float speed, Uint16
mMenace = 2;
// Establece los frames de cada animación
for (Uint8 i = 0; i < NUM_FRAMES_BALLON; i++)
for (int i = 0; i < NUM_FRAMES_BALLON; i++)
mSprite->setAnimationFrames(BALLOON_MOVING_ANIMATION, i, 37 + OFFSET_GREEN_BALLOONS, 21 + (37 * i), getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
mSprite->setAnimationFrames(BALLOON_BORN_ANIMATION, i, 37 + OFFSET_PURPLE_BALLOONS, 21 + (37 * i), getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_POP; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_POP; i++)
mSprite->setAnimationFrames(BALLOON_POP_ANIMATION, i, 37 + OFFSET_EXPLOSIONS, 21 + (37 * i), getWidth(), getHeight());
break;
@@ -257,13 +257,13 @@ void Balloon::init(float x, float y, Uint8 kind, float velx, float speed, Uint16
mMenace = 4;
// Establece los frames de cada animación
for (Uint8 i = 0; i < NUM_FRAMES_BALLON; i++)
for (int i = 0; i < NUM_FRAMES_BALLON; i++)
mSprite->setAnimationFrames(BALLOON_MOVING_ANIMATION, i, 37 + OFFSET_GREEN_BALLOONS, 37 * i, getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
mSprite->setAnimationFrames(BALLOON_BORN_ANIMATION, i, 37 + OFFSET_PURPLE_BALLOONS, 37 * i, getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_POP; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_POP; i++)
mSprite->setAnimationFrames(BALLOON_POP_ANIMATION, i, 37 + OFFSET_EXPLOSIONS, 37 * i, getWidth(), getHeight());
break;
@@ -291,13 +291,13 @@ void Balloon::init(float x, float y, Uint8 kind, float velx, float speed, Uint16
mMenace = 8;
// Establece los frames de cada animación
for (Uint8 i = 0; i < NUM_FRAMES_BALLON; i++)
for (int i = 0; i < NUM_FRAMES_BALLON; i++)
mSprite->setAnimationFrames(BALLOON_MOVING_ANIMATION, i, OFFSET_GREEN_BALLOONS, 37 * i, getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
mSprite->setAnimationFrames(BALLOON_BORN_ANIMATION, i, OFFSET_PURPLE_BALLOONS, 37 * i, getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_POP; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_POP; i++)
mSprite->setAnimationFrames(BALLOON_POP_ANIMATION, i, OFFSET_EXPLOSIONS, 37 * i, getWidth(), getHeight());
break;
@@ -325,13 +325,13 @@ void Balloon::init(float x, float y, Uint8 kind, float velx, float speed, Uint16
mMenace = 0;
// Establece los frames de cada animación
for (Uint8 i = 0; i < NUM_FRAMES_BALLON; i++)
for (int i = 0; i < NUM_FRAMES_BALLON; i++)
mSprite->setAnimationFrames(BALLOON_MOVING_ANIMATION, i, OFFSET_POWER_BALL, 37 * i, getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_BORN; i++)
mSprite->setAnimationFrames(BALLOON_BORN_ANIMATION, i, OFFSET_POWER_BALL, 37 * i, getWidth(), getHeight());
for (Uint8 i = 0; i < NUM_FRAMES_BALLON_POP; i++)
for (int i = 0; i < NUM_FRAMES_BALLON_POP; i++)
mSprite->setAnimationFrames(BALLOON_POP_ANIMATION, i, OFFSET_EXPLOSIONS, 37 * i, getWidth(), getHeight());
// Añade rotación al sprite

View File

@@ -1,5 +1,6 @@
#pragma once
#include "ifdefs.h"
#include "utils.h"
#include <string>
#ifndef CONST_H
@@ -140,6 +141,8 @@ const int SCREEN_THIRD_QUARTER_Y = (SCREEN_HEIGHT / 4) * 3;
#define PROG_SECTION_INTRO 1
#define PROG_SECTION_TITLE 2
#define PROG_SECTION_GAME 3
#define PROG_SECTION_INSTRUCTIONS 4
#define PROG_SECTION_QUIT 5
// Secciones del juego
#define GAME_SECTION_PLAY 0
@@ -150,11 +153,10 @@ const int SCREEN_THIRD_QUARTER_Y = (SCREEN_HEIGHT / 4) * 3;
#define TITLE_SECTION_1 0
#define TITLE_SECTION_2 1
#define TITLE_SECTION_3 2
#define TITLE_SECTION_INSTRUCTIONS 3
// Modos
#define MODE_AUTO 0
#define MODE_MANUAL 1
// Secciones de las instrucciones
#define INSTRUCTIONS_MODE_MANUAL 0
#define INSTRUCTIONS_MODE_AUTO 1
// Estados de cada elemento que pertenece a un evento
#define EVENT_WAITING 1
@@ -270,9 +272,8 @@ const int MULTIPLIER_NUMBER_Y = SCREEN_HEIGHT - (2 * BLOCK) + 2;
#define ITEM_POINTS_2_GAVINA 2
#define ITEM_POINTS_3_PACMAR 3
#define ITEM_CLOCK 4
#define ITEM_TNT 5
#define ITEM_COFFEE 6
#define ITEM_POWER_BALL 7
#define ITEM_COFFEE 5
#define ITEM_POWER_BALL 6
// Cantidad de objetos simultaneos
#define MAX_ITEMS 5
@@ -284,14 +285,8 @@ const int MULTIPLIER_NUMBER_Y = SCREEN_HEIGHT - (2 * BLOCK) + 2;
// Estados de entrada
#define NO_INPUT 0
#define INPUT_UP 1
#define INPUT_DOWN 2
#define INPUT_LEFT 3
#define INPUT_RIGHT 4
#define INPUT_ACCEPT 5
#define INPUT_CANCEL 6
#define INPUT_FIRE_UP 7
#define INPUT_FIRE_LEFT 8
#define INPUT_FIRE_LEFT 7
#define INPUT_FIRE_UP 8
#define INPUT_FIRE_RIGHT 9
#define INPUT_PAUSE 10
@@ -319,4 +314,10 @@ const int MULTIPLIER_NUMBER_Y = SCREEN_HEIGHT - (2 * BLOCK) + 2;
#define DEATH_COUNTER 350
#define SHAKE_COUNTER 10
// Colores
const color_t bgColor = {0x27, 0x27, 0x36};
const color_t noColor = {0xFF, 0xFF, 0xFF};
const color_t shdwTxtColor = {0x43, 0x43, 0x4F};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,679 +0,0 @@
#pragma once
#include "ifdefs.h"
#include "sprite.h"
#include "movingsprite.h"
#include "smartsprite.h"
#include "player.h"
#include "balloon.h"
#include "bullet.h"
#include "coffeedrop.h"
#include "item.h"
#include "text.h"
#include "text2.h"
#include "menu.h"
#include "const.h"
#include "jail_audio.h"
#include "utils.h"
#include <math.h>
#ifndef GAMEDIRECTOR_H
#define GAMEDIRECTOR_H
// GameDirector
class GameDirector
{
private:
SDL_Window *mWindow; // La ventana donde dibujamos
SDL_Renderer *mRenderer; // El renderizador de la ventana
SDL_Event *mEventHandler; // Manejador de eventos
SDL_Texture *mBackbuffer; // Textura para usar como backbuffer
SDL_Texture *mTitleSurface; // Textura para dibujar el fondo de la pantalla de título
SDL_Texture *mInstructionsSurface; // Textura donde dibujar las instrucciones
SDL_Joystick *mGameController; // Manejador para el mando 1
SDL_Haptic *mControllerHaptic; // Manejador para el mando con vibración
bool mGameControllerFound; // Variable para saber si hay un mando conectado
#ifndef UNUSED
CoffeeDrop *mCoffeeDrop[MAX_COFFEE_DROPS]; // Vector con todas ls gotas de café;
#endif
struct text_t
{
Text *white; // Texto blanco de 8x8
Text *whiteX2; // Texto blanco de 16x16
Text *black; // Texto negro de 8x8
Text *blackX2; // Texto negro de 16x16
Text *nokia; // Texto de anchura variable y 10px de alto
};
text_t mText; // Variable con todos los objetos de texto
struct menu_t
{
Menu *title; // Menu de la pantalla de título
Menu *pause; // Menú de la pantalla de pausa
Menu *gameOver; // Menú de la pantalla de game over
Menu *options; // Menú de la pantalla de opciones
Menu *active; // Menu activo (de momento para la pantalla del titulo)
bool keyPressed; // Variable para evitar la repetición de teclas en los menus
};
menu_t mMenu; // Variable con todos los objetos menus y sus variables
struct intro_t
{
SmartSprite *bitmap[INTRO_TOTAL_BITMAPS]; // Vector con los sprites inteligentes para los dibujos de la intro
Text2 *text[INTRO_TOTAL_TEXTS]; // Textos de la intro
Uint8 events[INTRO_TOTAL_EVENTS]; // Vector para coordinar los eventos de la intro
};
intro_t mIntro; // Contiene todas las variables de la sección 'Intro'
struct enemyInits_t
{
int x; // Posición en el eje X donde crear al enemigo
int y; // Posición en el eje Y donde crear al enemigo
float velX; // Velocidad inicial en el eje X
Uint8 kind; // Tipo de enemigo
Uint16 creationCounter; // Temporizador para la creación del enemigo
};
struct enemyFormation_t // Contiene la información de una formación enemiga
{
Uint8 numberOfEnemies; // Cantidad de enemigos que forman la formación
enemyInits_t init[50]; // Vector con todas las inicializaciones de los enemigos de la formación
};
enemyFormation_t mEnemyFormation[100]; // Vector con todas las formaciones enemigas
struct enemyPool_t
{
enemyFormation_t *set[10]; // Conjunto de formaciones enemigas
};
enemyPool_t mEnemyPool[10]; // Variable con los diferentes conjuntos de formaciones enemigas
struct stage_t // Contiene todas las variables relacionadas con una fase
{
enemyPool_t *enemyPool; // El conjunto de formaciones enemigas de la fase
Uint16 currentPower; // Cantidad actual de poder
Uint16 powerToComplete; // Cantidad de poder que se necesita para completar la fase
Uint8 maxMenace; // Umbral máximo de amenaza de la fase
Uint8 minMenace; // Umbral mínimo de amenaza de la fase
Uint8 number; // Numero de fase
};
struct effect_t
{
bool flash; // Indica si se ha de pintar la pantalla de blanco
bool shake; // Indica si se ha de agitar la pantalla
Uint8 shakeCounter; // Contador para medir el tiempo que dura el efecto
};
struct game_t
{
Uint32 score; // Puntuación actual
Uint32 hiScore; // Puntuación máxima
Uint8 section; // Seccion actual dentro del juego
bool hiScoreAchieved; // Indica si se ha superado la puntuación máxima
Uint8 currentStage; // Indica la fase actual
stage_t stage[10]; // Variable con los datos de cada pantalla
Uint8 stageBitmapCounter; // Contador para el tiempo visible del texto de Stage
float stageBitmapPath[STAGE_COUNTER]; // Vector con los puntos Y por donde se desplaza el texto
float getReadyBitmapPath[STAGE_COUNTER]; // Vector con los puntos X por donde se desplaza el texto
Uint16 deathCounter; // Contador para la animación de muerte del jugador
Uint8 deathIndex; // Indice del vector de smartsprites que contiene el sprite del jugador
Uint8 menaceCurrent; // Nivel de amenaza actual
Uint8 menaceThreshold; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el numero de globos
bool timeStopped; // Indica si el tiempo está detenido
Uint16 timeStoppedCounter; // Temporizador para llevar la cuenta del tiempo detenido
Uint8 remainingExplosions; // Cantidad de explosiones restantes
Uint16 remainingExplosionsCounter; // Temporizador para la cantidad de explosiones restantes
bool explosionTime; // Indica si las explosiones estan en marcha
Uint32 counter; // Contador para el juego
Uint32 scoreDataFile[TOTAL_SCORE_DATA]; // Datos del fichero de puntos
Sprite *getReadyBitmap; // Sprite para el texto de GetReady del principio de la partida
SmartSprite *_1000Bitmap; // Sprite con el texto 1.000
SmartSprite *_2500Bitmap; // Sprite con el texto 2.500
SmartSprite *_5000Bitmap; // Sprite con el texto 5.000
Sprite *background; // Sprite con los graficos frontales del fondo
Sprite *gradient; // Sprite con los graficos del degradado de color de fondo
SDL_Rect gradientRect[4]; // Vector con las coordenadas de los 4 gradientes
Uint16 balloonsPopped; // Lleva la cuenta de los globos explotados
MovingSprite *clouds1a; // Sprite para las nubes superiores
MovingSprite *clouds1b; // Sprite para las nubes superiores
MovingSprite *clouds2a; // Sprite para las nubes inferiores
MovingSprite *clouds2b; // Sprite para las nubes inferiores
Sprite *grass; // Sprite para la hierba
Sprite *scoreBoard; // Sprite para el fondo del marcador
Sprite *powerMeter; // Sprite para el medidor de poder de la fase
Player *player; // El jugador
Balloon *balloon[MAX_BALLOONS]; // Vector con los objetos globo
Bullet *bullet[MAX_BULLETS]; // Vector con los objetos bala
Item *item[MAX_ITEMS]; // Vector con los objetos item
SmartSprite *smartSprite[MAX_SMART_SPRITES]; // Vector para almacenar y gestionar SmartSprites
Uint8 lastEnemyDeploy; // Guarda cual ha sido la última formación desplegada para no repetir;
Uint8 enemyDeployCounter; // Cuando se lanza una formación, se le da un valor y no sale otra hasta que llegue a cero
float enemySpeed; // Velocidad a la que se mueven los enemigos
effect_t effect; // Variable para gestionar los efectos visuales
bool powerBallEabled; // Indica si hay una powerball ya activa
};
game_t mGame; // Variable con todas las variables usadas durante el juego
struct title_t
{
Uint16 counter; // Temporizador para la pantalla de titulo
Uint16 backgroundCounter; // Temporizador para el fondo de tiles de la pantalla de titulo
Uint8 backgroundMode; // Variable para almacenar el tipo de efecto que hará el fondo de la pantalla de titulo
bool menuVisible; // Indicador para saber si se muestra el menu del titulo o la frase intermitente
Sprite *tile; // Sprite para dibujar el fondo de pantalla del título
SDL_Rect backgroundWindow; // Ventana visible para la textura de fondo del titulo
Uint8 section; // Indicador para el bucle del titulo
Uint8 nextProgSection; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo
Uint8 events[TITLE_TOTAL_EVENTS]; // Vector para coordinar los eventos de la pantalla de titulo
Uint16 instructionsCounter; // Contador para las instrucciones
Uint8 instructionsMode; // Modo en el que se van a mostrar las instrucciones
SmartSprite *coffeeBitmap; // Sprite con la palabra COFFEE para la pantalla de titulo
SmartSprite *crisisBitmap; // Sprite con la palabra CRISIS para la pantalla de titulo
AnimatedSprite *dustBitmapL; // Sprite con la el polvo que aparece al colisionar el texto de la pantalla de titulo
AnimatedSprite *dustBitmapR; // Sprite con la el polvo que aparece al colisionar el texto de la pantalla de titulo
};
title_t mTitle; // Variable con todas las variables de la pantalla de titulo
struct demo_t
{
bool enabled; // Indica si está activo el modo demo
bool recording; // Indica si está activado el modo para grabar la demo
Uint16 counter; // Contador para el modo demo
demoKeys_t keys; // Variable con las pulsaciones de teclas del modo demo
demoKeys_t dataFile[TOTAL_DEMO_DATA]; // Datos del fichero con los movimientos para la demo
};
demo_t mDemo; // Variable con todas las variables relacionadas con el modo demo
struct options_t
{
Uint32 fullScreenMode; // Contiene el valor del modo de pantalla completa
Uint32 fullScreenModePrevious;
Uint8 windowSize; // Contiene el valor del tamaño de la ventana
Uint8 windowSizePrevious;
bool displayCoffeeDrops; // Indica si se han de mostar las gotas de cafe
};
options_t mOptions; // Variable con todas las variables de las opciones del programa
struct logo_t
{
Uint16 counter; // Contador
Sprite *sprite; // Sprite con la textura del logo
};
logo_t mLogo; // Variable con las variables para el logo
struct prog_t
{
bool quit; // Indica si hay que salir del programa
input_t keyboard; // Almacena los códigos de teclado correspondientes
input_t keyboardBuffer; // Buffer para teclas pulsadas
std::string executablePath; // Path del ejecutable
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint8 section; // Sección actual del programa;
Uint8 subsection; // Subseccion dentro de la sección;
Uint8 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
};
prog_t mProg; // Contiene todas las variables globales del programa
struct debug_t
{
bool enabled; // Indica si se va a mostrar la información de debug
Uint8 enemySet; // Escoge el set enemigo a generar
Uint8 gradR, gradG, gradB; // Colores RGB para modificar el color del gradiente de fondo
float hudW, hudH; // Multiplica el tamaño del hud de debug;
};
debug_t mDebug;
struct resourceBinFile_t
{
std::string file; // Ruta al fichero
};
resourceBinFile_t mBinFile[TOTAL_BINFILE]; // Todos los ficheros binarios
struct resourceSound_t
{
std::string file; // Ruta al fichero
JA_Sound sound; // Variable con el sonido
};
resourceSound_t mSound[TOTAL_SOUND]; // Todos los sonidos
struct resourceMusic_t
{
std::string file; // Ruta al fichero
JA_Music music; // Variable con la música
};
resourceMusic_t mMusic[TOTAL_MUSIC]; // Todas las músicas
struct resourceTexture_t
{
std::string file; // Ruta al fichero
LTexture *texture; // Variable con la textura
};
resourceTexture_t mTexture[TOTAL_TEXTURE]; // Todos los gráficos
public:
// Constructor
GameDirector(std::string path);
// Destructor
~GameDirector();
// Inicia las variables necesarias para arrancar el programa
void initProg();
// Carga los recursos necesarios para el programa
bool loadMediaProg();
// Libera las variables del programa
void quitProg();
// Inicializa jail_audio
void initJailAudio();
// Arranca SDL y crea la ventana
bool initSDL();
// Inicializa el vector con los valores del seno
void initSin();
// Inicializa las variables que contienen puntos de ruta para mover objetos
void initPaths();
// Inicializa las variables necesarias para la sección 'Logo'
void initLogo();
// Carga los recursos necesarios para la sección 'Logo'
bool loadMediaLogo();
// Libera las variables necesarias para la sección 'Logo'
void quitLogo();
// Inicializa las variables necesarias para la sección 'Intro'
void initIntro();
// Carga los recursos necesarios para la sección 'Intro'
bool loadMediaIntro();
// Libera las variables necesarias para la sección 'Intro'
void quitIntro();
// Inicializa las variables necesarias para la sección 'Title'
void initTitle(Uint8 subsection = TITLE_SECTION_1);
// Resetea las variables necesarias para la sección 'Title'
void resetTitle(Uint8 subsection = TITLE_SECTION_1);
// Carga los recursos necesarios para la sección 'Title'
bool loadMediaTitle();
// Libera las variables necesarias para la sección 'Title'
void quitTitle();
// Inicializa las variables necesarias para la sección 'Game'
void initGame();
// Inicializa las variables especificas de la sección 'Game' para empezar una nueva partida
void resetGame();
// Carga los recursos necesarios para la sección 'Game'
bool loadMediaGame();
// Libera las variables necesarias para la sección 'Game'
void quitGame();
// Crea el indice de ficheros
void setFileList();
// Comprueba que todos los ficheros existen
bool checkFileList();
// Carga el fichero de puntos
bool loadScoreFile();
// Carga el fichero de configuración
bool loadConfigFile();
// Carga el fichero de datos para la demo
bool loadDemoFile();
// Guarda el fichero de puntos
bool saveScoreFile();
// Guarda el fichero de configuración
bool saveConfigFile();
// Guarda el fichero de datos para la demo
bool saveDemoFile();
// Carga un archivo de imagen en una textura
bool loadTextureFromFile(LTexture *texture, std::string path, SDL_Renderer *renderer);
// Comprueba el valor de la variable 'quit'
bool exit();
// Establece el valor de la variable
void setExecutablePath(std::string path);
// Inicializa las formaciones enemigas
void initEnemyFormations();
// Inicializa los conjuntos de formaciones
void initEnemyPools();
// Inicializa las fases del juego
void initGameStages();
// Crea una formación de enemigos
void deployEnemyFormation();
// Aumenta el poder de la fase
void increaseStageCurrentPower(Uint8 power);
// Establece el valor de la variable
void setScore(Uint32 score);
// Establece el valor de la variable
void setHiScore(Uint32 score);
// Actualiza el valor de HiScore en caso necesario
void updateHiScore();
// Transforma un valor numérico en una cadena de 6 cifras
std::string updateScoreText(Uint32 num);
// Pinta el marcador en pantalla usando un objeto texto
void renderScoreBoard();
// Actualiza las variables del jugador
void updatePlayer();
// Actualiza las variables de la fase
void updateStage();
// Actualiza el estado de muerte
void updateDeath();
// Renderiza el fade final cuando se acaba la partida
void renderDeathFade();
// Actualiza los globos
void updateBalloons();
// Pinta en pantalla todos los globos activos
void renderBalloons();
// Devuelve el primer indice no activo del vector de globos
Uint8 getBalloonFreeIndex();
// Crea un globo nuevo en el vector de globos
Uint8 createNewBalloon(float x, int y, Uint8 kind, float velx, float speed, Uint16 stoppedcounter, LTexture *texture);
// Crea una PowerBall
void createPowerBall();
// Establece a cero todos los valores del vector de objetos globo
void resetBalloons();
// Establece la velocidad de los globos
void setBalloonSpeed(float speed);
// Incrementa la velocidad de los globos
void incBalloonSpeed();
// Decrementa la velocidad de los globos
void decBalloonSpeed();
// Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
void updateBalloonSpeed();
// Explosiona un globo. Lo destruye y crea otros dos si es el caso
void popBalloon(Uint8 index);
// Explosiona un globo. Lo destruye
void destroyBalloon(Uint8 index);
// Explosiona todos los globos
void popAllBalloons();
// Destruye todos los globos
void destroyAllBalloons();
// Detiene todos los globos
void stopAllBalloons(Uint16 time);
// Pone en marcha todos los globos
void startAllBalloons();
// Obtiene el numero de globos activos
Uint8 countBalloons();
// Comprueba la colisión entre el jugador y los globos activos
bool checkPlayerBalloonCollision();
// Comprueba la colisión entre el jugador y los items
void checkPlayerItemCollision();
// Comprueba la colisión entre las balas y los globos
void checkBulletBalloonCollision();
// Mueve las balas activas
void moveBullets();
// Pinta las balas activas
void renderBullets();
// Devuelve el primer indice no activo del vector de balas
Uint8 getBulletFreeIndex();
// Establece a cero todos los valores del vector de objetos bala
void resetBullets();
// Crea un objeto bala
void createBullet(int x, int y, Uint8 kind);
// Actualiza los items
void updateItems();
// Pinta los items activos
void renderItems();
// Devuelve el primer indice no activo del vector de items
Uint8 getItemFreeIndex();
// Establece a cero todos los valores del vector de objetos item
void resetItems();
// Devuelve un item en función del azar
Uint8 dropItem();
// Crea un objeto item
void createItem(int x, int y, Uint8 kind);
// Crea un objeto SmartSprite
void createItemScoreSprite(int x, int y, SmartSprite *sprite);
// Crea un objeto de bonus en función del azar
void dropBonus();
// Dibuja el efecto de flash
void renderFlashEffect();
// Actualiza el efecto de agitar la pantalla
void updateShakeEffect();
// Crea un SmartSprite para arrojar el item café al recibir un impacto
void throwCoffee(int x, int y);
// Crea un SmartSprite para arrojar al jugador al morir
void throwPlayer(int x, int y);
// Actualiza los SmartSprites
void updateSmartSprites();
// Pinta los SmartSprites activos
void renderSmartSprites();
// Devuelve el primer indice no activo del vector de SmartSprites
Uint8 getSmartSpriteFreeIndex();
// Establece a cero todos los valores del vector de objetos SmafrtSprite
void resetSmartSprites();
#ifndef UNUSED
// Deshabilita todas las gotas de café
void resetCoffeeDrops();
// Actualiza las gotas de cafe
void updateCoffeeDrops();
// Dibuja las gotas de cafe
void renderCoffeeDrops();
// Devuelve el primer indice libre del vector de CoffeeDrops
Uint8 getCoffeDropFreeIndex();
// Crea un numero de gotas de cafe
void createCoffeDrops(Uint8 num, int x, int y);
#endif
// Acciones a realizar cuando el jugador muere
void killPlayer();
// Obtiene el valor de la variable
Uint8 getSubsection();
// Calcula y establece el valor de amenaza en funcion de los globos activos
void setMenace();
// Obtiene el valor de la variable
Uint8 getMenace();
// Establece el valor de la variable
void setTimeStopped(bool value);
// Obtiene el valor de la variable
bool isTimeStopped();
// Establece el valor de la variable
void setTimeStoppedCounter(Uint16 value);
// Incrementa el valor de la variable
void incTimeStoppedCounter(Uint16 value);
// Actualiza la variable EnemyDeployCounter
void updateEnemyDeployCounter();
// Actualiza y comprueba el valor de la variable
void updateTimeStoppedCounter();
// Establece el valor de la variable
void setExplosionTime(bool value);
// Obtiene el valor de la variable
bool isExplosionTime();
// Establece el valor de la variable
void setRemainingExplosions(Uint8 value);
// Actualiza y comprueba el valor de la variable
void updateRemainingExplosionsCounter();
// Gestiona el nivel de amenaza
void old_updateMenace();
// Gestiona el nivel de amenaza
void updateMenace();
// Actualiza el campo de juego
void updatePlayField();
// Actualiza el fondo
void updateBackground();
// Dibuja el fondo
void renderBackground();
// Dibuja el campo de juego
void renderPlayField();
// Gestiona las entradas desde el mando de juego
bool checkGameController(Uint8 state);
// Gestiona la entrada durante el juego
void checkGameInput();
// Gestiona la entrada de teclado y mando durante el menu
void checkMenuInput(Menu *menu);
// Obtiene el valor de la variable
Uint8 getProgSection();
// Establece el valor de la variable
void setProgSection(Uint8 section, Uint8 subsection = 0);
// Pinta una transición en pantalla
void renderFade(Uint8 index);
// Pinta diferentes mensajes en la pantalla
void renderMessages();
// Habilita el efecto del item de detener el tiempo
void enableTimeStopItem();
// Deshabilita el efecto del item de detener el tiempo
void disableTimeStopItem();
// Cambia el valor de la variable de modo de pantalla completa
void changeFullScreenMode();
// Actualiza los elementos del menu de opciones
void updateOptionsMenu();
// Agita la pantalla
void shakeScreen();
// Agita la pantalla
void shakeScreen2();
// Bucle para el logo del juego
void runLogo();
// Bucle para la intro del juego
void runIntro();
// Bucle para el titulo del juego
void runTitle(Uint8 subsection = TITLE_SECTION_1);
// Bucle para el juego
void runGame();
// Bucle para el menu de pausa del juego
void runPausedGame();
// Bucle para la pantalla de instrucciones
void runInstructions(Uint8 mode);
// Bucle para la pantalla de game over
void runGameOverScreen();
// Activa el modo Demo
void enableDemoMode();
// Desactiva el modo Demo
void disableDemoMode();
// Intercambia el proximo estado del juego despues del titulo
void toogleTitleNextGS();
// Dibuja la informacion de debug en pantalla
void renderDebugInfo();
// Indica si se puede crear una powerball
bool canPowerBallBeCreated();
// Calcula el poder actual de los globos en pantalla
int calculateScreenPower();
};
#endif

View File

@@ -54,30 +54,32 @@ void Item::init(Uint8 value, float x, float y, LTexture *texture, SDL_Renderer *
mVelX = 0;
mVelY = 0;
break;
case ITEM_POINTS_1_DISK:
mSprite->setAnimationFrames(0, 0, 16 * 0, 16 * 0, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 16 * 0, 16 * 1, mWidth, mHeight);
break;
case ITEM_POINTS_2_GAVINA:
mSprite->setAnimationFrames(0, 0, 16 * 1, 16 * 0, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 16 * 1, 16 * 1, mWidth, mHeight);
break;
case ITEM_POINTS_3_PACMAR:
mSprite->setAnimationFrames(0, 0, 16 * 2, 16 * 0, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 16 * 2, 16 * 1, mWidth, mHeight);
break;
case ITEM_CLOCK:
mSprite->setAnimationFrames(0, 0, 16 * 3, 16 * 0, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 16 * 3, 16 * 1, mWidth, mHeight);
break;
case ITEM_TNT:
mSprite->setAnimationFrames(0, 0, 16 * 4, 16 * 0, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 16 * 4, 16 * 1, mWidth, mHeight);
break;
case ITEM_COFFEE:
mSprite->setAnimationFrames(0, 0, 16 * 5, 16 * 0, mWidth, mHeight);
mSprite->setAnimationFrames(0, 1, 16 * 5, 16 * 1, mWidth, mHeight);
break;
default:
break;
}
@@ -195,7 +197,7 @@ void Item::updateTimeToLive()
{
if (mTimeToLive > 0)
{
--mTimeToLive;
mTimeToLive--;
}
}
@@ -203,9 +205,7 @@ void Item::updateTimeToLive()
void Item::checkTimeToLive()
{
if (mTimeToLive == 0)
{
erase();
}
}
// Obtiene del valor de la variable

View File

@@ -17,11 +17,11 @@ A continuación tenemos las clases enfocadas a la lógica del juego, la clase pl
contiene la información del jugador, la clase balloon la de los enemigos y la
clase bullet para las balas que dispara el jugador. La clase background es
muy simple y sirve para pintar el fondo de la pantalla. Por ultimo, la clase
gamedirector es la que realiza toda la lógica y se encarga de hacer interactuar
mDirector es la que realiza toda la lógica y se encarga de hacer interactuar
al resto de objetos entre si.
El objeto gamedirector tiene tres estados: titulo, juego y pausa. Segun su estado
el bucle que recorre es distinto. En el bucle juego, el objeto gamedirector
El objeto mDirector tiene tres estados: titulo, juego y pausa. Segun su estado
el bucle que recorre es distinto. En el bucle juego, el objeto mDirector
tiene un objeto jugador, un vector con los objetos globo y un vector con los
objetos bala. Se encarga de comprobar las entradas de teclado o gamepad para
cerrar la aplicacion, saltar al estado de pausa y para mover al jugador. Recorre
@@ -36,10 +36,7 @@ En los vectores que contienen objetos, se considera activos los objetos que tien
un tipo asociado diferente a NO_KIND
*/
#include "ifdefs.h"
#include "const.h"
#include "gamedirector.h"
#include <time.h>
#include "director.h"
#include <stdio.h>
#include <string>
@@ -48,33 +45,16 @@ int main(int argc, char *args[])
// Inicia el generador de numeros aleatorios
srand(time(nullptr));
// Crea el objeto gameDirector
GameDirector *gameDirector = new GameDirector(args[0]);
// Crea el objeto mDirector
Director *mDirector = new Director(args[0]);
printf("Starting the game...\n\n");
// Mientras no se quiera salir del juego
while (!(gameDirector->exit()))
{
switch (gameDirector->getProgSection())
{
case PROG_SECTION_LOGO:
gameDirector->runLogo();
break;
case PROG_SECTION_INTRO:
gameDirector->runIntro();
break;
case PROG_SECTION_TITLE:
gameDirector->runTitle(gameDirector->getSubsection());
break;
case PROG_SECTION_GAME:
gameDirector->runGame();
break;
}
}
// Bucle principal
mDirector->run();
// Libera todos los recursos y cierra SDL
delete gameDirector;
gameDirector = nullptr;
delete mDirector;
mDirector = nullptr;
printf("Shutting down the game...\n");
return 0;

View File

@@ -4,20 +4,26 @@
#include "menu.h"
// Constructor
Menu::Menu()
Menu::Menu(SDL_Renderer *renderer, Text *text, Input *input, std::string *fileList)
{
init("", 0, 0, 0, nullptr, nullptr, nullptr);
mRenderer = renderer;
mText = text;
mInput = input;
mFileList = fileList;
}
Menu::~Menu()
{
mRenderer = nullptr;
mText = nullptr;
mInput = nullptr;
}
// Inicializador
void Menu::init(std::string name, int x, int y, int backgroundType, LTexture *texture, SDL_Renderer *renderer, Text *text)
void Menu::init(std::string name, int x, int y, int backgroundType)
{
loadMedia();
// Inicia variables
mName = name;
mSelector.index = 0;
@@ -42,8 +48,6 @@ void Menu::init(std::string name, int x, int y, int backgroundType, LTexture *te
mSelector.b = 0;
mSelector.a = 255;
mBackgroundType = backgroundType;
mText = text;
mRenderer = renderer;
mIsCentered = false;
mAreElementsCentered = false;
mCenter = x + ((SCREEN_WIDTH - x) / 2);
@@ -82,6 +86,20 @@ void Menu::init(std::string name, int x, int y, int backgroundType, LTexture *te
//moveSelectorSprite(mSelector.index);
}
// Carga los recursos necesarios para la sección 'Title'
bool Menu::loadMedia()
{
// Indicador de éxito en la carga
bool success = true;
// Sonidos
mSoundMove = JA_LoadSound(mFileList[17].c_str());
mSoundAccept = JA_LoadSound(mFileList[18].c_str());
mSoundCancel = JA_LoadSound(mFileList[16].c_str());
return success;
}
// Obtiene el nombre del menu
std::string Menu::getName()
{
@@ -91,7 +109,9 @@ std::string Menu::getName()
// Obtiene el valor de la variable
Uint8 Menu::getItemSelected()
{
return mItemSelected;
const int temp = mItemSelected;
mItemSelected = MENU_NO_OPTION;
return temp;
}
// Mueve el grafico del selector al elemento seleccionado
@@ -159,7 +179,7 @@ Uint16 Menu::getWidestItem()
Uint16 result = 0;
// Obtenemos la anchura del item mas ancho
for (Uint8 i = 0; i < mTotalItems; i++)
for (int i = 0; i < mTotalItems; i++)
{
if (mItem[i].w > result)
{
@@ -232,30 +252,6 @@ bool Menu::decreaseSelectorIndex()
return success;
}
// Comprueba la entrada (teclado, gamepad) y actua en consecuencia
bool Menu::checkInput(Uint8 input)
{
bool success = false;
switch (input)
{
case INPUT_UP:
success = decreaseSelectorIndex();
//moveSelectorSprite(mSelector.index);
break;
case INPUT_DOWN:
success = increaseSelectorIndex();
//moveSelectorSprite(mSelector.index);
break;
case INPUT_ACCEPT:
mItemSelected = mSelector.index;
break;
case INPUT_CANCEL:
mItemSelected = mDefaultActionWhenCancel;
break;
}
return success;
}
// Actualiza la logica del menu
void Menu::update()
{
@@ -280,11 +276,12 @@ void Menu::render()
//mSelectorSprite.render();
// Renderitza el text
for (Uint8 i = 0; i < mTotalItems; i++)
for (int i = 0; i < mTotalItems; i++)
{
if (i == mSelector.index)
{
mText->writeColored(mItem[i].x, mItem[i].y, mItem[i].label, mSelector.itemR, mSelector.itemG, mSelector.itemB);
const color_t color = {mSelector.itemR, mSelector.itemG, mSelector.itemB};
mText->writeColored(mItem[i].x, mItem[i].y, mItem[i].label, color);
}
else
{
@@ -378,7 +375,7 @@ void Menu::centerMenu(int value)
mPosX = (value) - (mWidestItem / 2);
// Reposiciona los elementos del menu
for (Uint8 i = 0; i < 10; i++)
for (int i = 0; i < 10; i++)
{
mItem[i].x = mPosX;
}
@@ -397,7 +394,7 @@ void Menu::centerMenuElements()
{
mAreElementsCentered = true;
for (Uint8 i = 0; i < mTotalItems; i++)
for (int i = 0; i < mTotalItems; i++)
{
//mItem[i].x = (mCenter - ((mText->lenght(mItem[i].label, 0)) / 2));
mItem[i].x = (mCenter - (mItem[i].w / 2));
@@ -453,3 +450,31 @@ void Menu::setDefaultActionWhenCancel(Uint8 item)
{
mDefaultActionWhenCancel = item;
}
// Gestiona la entrada de teclado y mando durante el menu
void Menu::checkInput()
{
if (mInput->checkInput(INPUT_UP, REPEAT_FALSE))
{
if (decreaseSelectorIndex())
JA_PlaySound(mSoundMove);
}
if (mInput->checkInput(INPUT_DOWN, REPEAT_FALSE))
{
if (increaseSelectorIndex())
JA_PlaySound(mSoundMove);
}
if (mInput->checkInput(INPUT_ACCEPT, REPEAT_FALSE))
{
mItemSelected = mSelector.index;
JA_PlaySound(mSoundAccept);
}
if (mInput->checkInput(INPUT_CANCEL, REPEAT_FALSE))
{
mItemSelected = mDefaultActionWhenCancel;
JA_PlaySound(mSoundCancel);
}
}

View File

@@ -1,6 +1,8 @@
#pragma once
#include "sprite.h"
#include "text.h"
#include "input.h"
#include "jail_audio.h"
#ifndef MENU_H
#define MENU_H
@@ -8,65 +10,73 @@
// Clase menu
class Menu
{
public:
// Constructor
Menu();
// Destructor
~Menu();
// Inicializador
void init(std::string name, int x, int y, int backgroundType, LTexture *texture, SDL_Renderer *renderer, Text *text);
// Obtiene el nombre del menu
std::string getName();
// Obtiene el valor de la variable
Uint8 getItemSelected();
// Deja el menu apuntando al primer elemento
void reset();
// Deja el menu sin elemento seleccionado
void deselectItem();
// Comprueba la entrada (teclado, gamepad) y actua en consecuencia
bool checkInput(Uint8 input);
// Actualiza la logica del menu
void update();
// Pinta el menu en pantalla
void render();
// Establece el color del rectangulo de fondo
void setBackgroundColor(int r, int g, int b, int alpha);
// Establece el color del rectangulo del selector
void setSelectorColor(int r, int g, int b, int alpha);
// Establece el color del texto del selector
void setSelectorTextColor(int r, int g, int b);
// Centra el menu respecto a un punto
void centerMenu(int value);
// Centra los elementos del menu
void centerMenuElements();
// Añade un item al menu
void addItem(std::string text, const Uint8 hPaddingUp = 0, const Uint8 hPaddingDown = 0);
// Cambia el texto de un item
void setItemCaption(Uint8 index, std::string text);
// Establece el indice del item que se usará por defecto al cancelar el menu
void setDefaultActionWhenCancel(Uint8 item);
// Coloca el selector en una posición específica
void setSelectorPos(Uint8 index);
private:
int mPosX; // Posición en el eje X de la primera letra del primer elemento
int mPosY; // Posición en el eje Y de la primera letra del primer elemento
std::string mName; // Nombre del menu
Uint8 mTotalItems; // Numero total de items del menu
int mItemSelected; // Índice del item del menu que ha sido seleccionado
Uint8 mDefaultActionWhenCancel; // Indice del item del menu que se selecciona cuando se cancela el menu
Uint8 mVerticalPadding; // Espacio de separacion entre items
Uint8 mBackgroundType; // Tipo de fondo para el menu
Sprite *mSelectorSprite; // Sprite con los graficos del selector
Text *mText; // Texto para poder escribir los items del menu
SDL_Renderer *mRenderer; // Puntero al renderizador de la ventana
std::string *mFileList; // Lista de ficheros
bool mIsCentered; // Variable para saber si el menu debe estar centrado respecto a un punto
int mCenter; // Centro del menu
bool mAreElementsCentered; // Variable para saber si los elementos van centrados
Uint16 mWidestItem; // Anchura del elemento más ancho
JA_Sound mSoundAccept; // Sonido al aceptar o elegir una opción del menu
JA_Sound mSoundCancel; // Sonido al cancelar el menu
JA_Sound mSoundMove; // Sonido al mover el selector
Input *mInput; // Gestor de eventos de entrada de teclado o gamepad
struct rectangle
{
SDL_Rect rect; // Rectangulo
Uint8 r; // Rojo
Uint8 g; // Verde
Uint8 b; // Azul
Uint8 a; // Transparencia
};
rectangle mRectBG; // Rectangulo de fondo del menu
struct item
{
std::string label; // Texto
int x; // Posición en el eje X de la primera letra del elemento
int y; // Posición en el eje Y de la primera letra del elemento
Uint8 w; // Ancho del elemento
Uint8 h; // Alto del elemento
Uint8 hPaddingUp; // Espaciado sobre el elemento
Uint8 hPaddingDown; // Espaciado bajo el elemento
};
item mItem[10]; // Estructura para cada elemento del menu
struct selector
{
double origin; // Coordenada de origen
double target; // Coordenada de destino
double y; // Coordenada actual
Uint8 numJumps; // Numero de pasos preestablecido para llegar al destino
double despY; // Cantidad de pixeles que se desplaza el selector en cada salto: (target - origin) / numJumps
bool moving; // Indica si el selector está avanzando hacia el destino
Uint8 index; // Elemento del menu que tiene el foco
SDL_Rect rect; // Rectangulo del selector
Uint8 r; // Cantidad de color rojo para el rectangulo del selector
Uint8 g; // Cantidad de color verde para el rectangulo del selector
Uint8 b; // Cantidad de color azul para el rectangulo del selector
Uint8 a; // Cantidad de transparencia para el rectangulo del selector
Uint8 itemR; // Cantidad de color rojo para el texto del elemento seleccionado
Uint8 itemG; // Cantidad de color verde para el texto del elemento seleccionado
Uint8 itemB; // Cantidad de color azul para el texto del elemento seleccionado
};
selector mSelector; // Variables para pintar el selector del menu
// Carga los recursos necesarios para la sección 'Title'
bool loadMedia();
// Establece el valor de la variable
void setTotalItems(int num);
@@ -97,94 +107,66 @@ private:
// Obtiene la anchura del elemento más ancho del menu
Uint16 getWidestItem();
// Posicion X/Y del texto del primer elemento del menu
int mPosX; // En esta posición se pinta la primera letra del primer elemento
int mPosY;
// Gestiona la entrada de teclado y mando durante el menu
void checkMenuInput(Menu *menu);
// Nombre del menu
std::string mName;
public:
// Constructor
Menu(SDL_Renderer *renderer, Text *text, Input *input, std::string *fileList);
// Numero de items del menu
Uint8 mTotalItems;
// Destructor
~Menu();
// Item del menu que ha sido seleccionado
Uint8 mItemSelected;
// Inicializador
void init(std::string name, int x, int y, int backgroundType);
// Item del menu seleccionado cuando se cancela el menu
Uint8 mDefaultActionWhenCancel;
// Obtiene el nombre del menu
std::string getName();
// Espacio de separacion entre items
Uint8 mVerticalPadding;
// Obtiene el valor de la variable
Uint8 getItemSelected();
// Tipo de fondo para el menu
Uint8 mBackgroundType;
// Deja el menu apuntando al primer elemento
void reset();
// Sprite con los graficos del selector
//Sprite mSelectorSprite;
// Deja el menu sin elemento seleccionado
void deselectItem();
struct rectangle
{
SDL_Rect rect;
Uint8 r; // Rojo
Uint8 g; // Verde
Uint8 b; // Azul
Uint8 a; // Transparencia
};
// Gestiona la entrada de teclado y mando durante el menu
void checkInput();
rectangle mRectBG; // Rectangulo de fondo del menu
// Actualiza la logica del menu
void update();
// Estructura para cada elemento del menu
struct item
{
std::string label;
int x;
int y;
Uint8 w;
Uint8 h;
Uint8 hPaddingUp;
Uint8 hPaddingDown;
};
// Pinta el menu en pantalla
void render();
item mItem[10];
// Establece el color del rectangulo de fondo
void setBackgroundColor(int r, int g, int b, int alpha);
// Texto para poder escribir los items del menu
Text *mText;
// Establece el color del rectangulo del selector
void setSelectorColor(int r, int g, int b, int alpha);
// Puntero al renderizador de la ventana
SDL_Renderer *mRenderer;
// Establece el color del texto del selector
void setSelectorTextColor(int r, int g, int b);
// Variable para saber si el menu debe estar centrado respecto a un punto
bool mIsCentered;
// Centra el menu respecto a un punto
void centerMenu(int value);
// Centro del menu
int mCenter;
// Centra los elementos del menu
void centerMenuElements();
// Variable para saber si los elementos van centrados
bool mAreElementsCentered;
// Añade un item al menu
void addItem(std::string text, const Uint8 hPaddingUp = 0, const Uint8 hPaddingDown = 0);
// Anchura del elemento más ancho
Uint16 mWidestItem;
// Cambia el texto de un item
void setItemCaption(Uint8 index, std::string text);
struct selector
{
double origin; // Coordenada de origen
double target; // Coordenada de destino
double y; // Coordenada actual
Uint8 numJumps; // Numero de pasos preestablecido para llegar al destino
double despY; // (target - origin) / numJumps
bool moving; // Indica si el selector está avanzando hacia el destino
Uint8 index; // Elemento del menu que tiene el foco
SDL_Rect rect;
Uint8 r; // Rojo
Uint8 g; // Verde
Uint8 b; // Azul
Uint8 a; // Transparencia
Uint8 itemR; // Rojo
Uint8 itemG; // Verde
Uint8 itemB; // Azul
};
// Establece el indice del item que se usará por defecto al cancelar el menu
void setDefaultActionWhenCancel(Uint8 item);
selector mSelector;
// Coloca el selector en una posición específica
void setSelectorPos(Uint8 index);
};
#endif

View File

@@ -281,7 +281,7 @@ void Player::setFiringStatus(Uint8 status)
void Player::setAnimation()
{
// Actualiza los frames de la animación en función del número de cafes
for (Uint8 i = 0; i < 4; i++)
for (int i = 0; i < 4; i++)
{
mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_LEFT, i, mWidth * i, mHeight * (0 + (6 * mCoffees)), mWidth, mHeight);
mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_LEFT, i, mWidth * i, mHeight * (1 + (6 * mCoffees)), mWidth, mHeight);

View File

@@ -1,5 +1,6 @@
#pragma once
#include "utils.h"
#include "input.h"
#include "animatedsprite.h"
#ifndef PLAYER_H

View File

@@ -2,10 +2,11 @@
#include "text.h"
// Constructor
Text::Text()
Text::Text(LTexture *texture, SDL_Renderer *renderer)
{
mSprite = new Sprite();
init(nullptr, nullptr, 0, 0);
mSprite->setTexture(texture);
mSprite->setRenderer(renderer);
}
// Destructor
@@ -15,7 +16,7 @@ Text::~Text()
}
// Inicializador
void Text::init(LTexture *texture, SDL_Renderer *renderer, Uint8 type, Uint8 size)
void Text::init(Uint8 type, Uint8 size)
{
// Inicializa variables
mType = type;
@@ -26,15 +27,13 @@ void Text::init(LTexture *texture, SDL_Renderer *renderer, Uint8 type, Uint8 siz
mSprite->setHeight(size);
mSprite->setPosX(0);
mSprite->setPosY(0);
mSprite->setTexture(texture);
mSprite->setRenderer(renderer);
mSprite->setSpriteClip(0, 0, mSprite->getWidth(), mSprite->getHeight());
// Cadena con los caracteres ascii que se van a inicializar
std::string text = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ{\\[]]^_`abcdefghijklmnopqrstuvwxyz";
const std::string text = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ{\\[]]^_`abcdefghijklmnopqrstuvwxyz";
// Inicializa a cero el vector con las coordenadas
for (Uint8 i = 0; i < 255; i++)
for (int i = 0; i < 255; i++)
{
mOffset[i].x = 0;
mOffset[i].y = 0;
@@ -42,14 +41,12 @@ void Text::init(LTexture *texture, SDL_Renderer *renderer, Uint8 type, Uint8 siz
}
// Establece las coordenadas para cada caracter ascii de la cadena y su ancho
for (Uint8 i = 0; i < text.length(); ++i)
for (int i = 0; i < text.length(); ++i)
{
mOffset[int(text[i])].x = ((int(text[i]) - 32) % 15) * mSprite->getWidth();
mOffset[int(text[i])].y = ((int(text[i]) - 32) / 15) * mSprite->getHeight();
if (type == TEXT_FIXED)
{
mOffset[int(text[i])].w = size;
}
}
// Establece el ancho de cada caracter
@@ -133,25 +130,15 @@ void Text::init(LTexture *texture, SDL_Renderer *renderer, Uint8 type, Uint8 siz
}
}
// Escribe el texto en pantalla
void Text::write(int x, int y, std::string text)
// Escribe texto en pantalla
void Text::write(int x, int y, std::string text, int kerning, Uint8 lenght)
{
Uint16 shift = 0;
for (Uint8 i = 0; i < text.length(); ++i)
{
mSprite->setSpriteClip(mOffset[int(text[i])].x, mOffset[int(text[i])].y, mSprite->getWidth(), mSprite->getHeight());
mSprite->setPosX(x + shift);
mSprite->setPosY(y);
mSprite->render();
shift += (mOffset[int(text[i])].w);
}
}
// Escribe el texto en pantalla con kerning
void Text::write(int x, int y, std::string text, int kerning)
{
Uint16 shift = 0;
for (Uint8 i = 0; i < text.length(); ++i)
if (lenght == 0)
lenght = text.length();
for (int i = 0; i < lenght; ++i)
{
mSprite->setSpriteClip(mOffset[int(text[i])].x, mOffset[int(text[i])].y, mSprite->getWidth(), mSprite->getHeight());
mSprite->setPosX(x + shift);
@@ -161,88 +148,57 @@ void Text::write(int x, int y, std::string text, int kerning)
}
}
// Escribe una cantidad determinada de caracteres del texto en pantalla
void Text::write(int x, int y, std::string text, int kerning, Uint8 lenght)
{
Uint16 shift = 0;
for (Uint8 i = 0; i < lenght; ++i)
{
if (text[i] == '*')
{
shift = 0;
y += mSize;
}
else
{
mSprite->setSpriteClip(mOffset[int(text[i])].x, mOffset[int(text[i])].y, mSprite->getWidth(), mSprite->getHeight());
mSprite->setPosX(x + shift);
mSprite->setPosY(y);
mSprite->render();
shift += (mOffset[int(text[i])].w + kerning);
}
}
}
// Escribe el texto con colores
void Text::writeColored(int x, int y, std::string text, Uint8 R, Uint8 G, Uint8 B)
void Text::writeColored(int x, int y, std::string text, color_t color, int kerning, Uint8 lenght)
{
mSprite->getTexture()->setColor(R, G, B);
write(x, y, text);
mSprite->getTexture()->setColor(color.r, color.g, color.b);
write(x, y, text, kerning, lenght);
mSprite->getTexture()->setColor(255, 255, 255);
}
// Escribe el texto con sombra
void Text::writeShadowed(int x, int y, std::string text, Uint8 R, Uint8 G, Uint8 B)
void Text::writeShadowed(int x, int y, std::string text, color_t color, Uint8 shadowDistance, int kerning, Uint8 lenght)
{
mSprite->getTexture()->setColor(R, G, B);
write(x+1, y+1, text);
mSprite->getTexture()->setColor(color.r, color.g, color.b);
write(x + shadowDistance, y + shadowDistance, text, kerning, lenght);
mSprite->getTexture()->setColor(255, 255, 255);
write(x, y, text);
write(x, y, text, kerning, lenght);
}
// Escribe el texto centrado en un punto x y con kerning
void Text::writeCentered(int x, int y, std::string text, int kerning)
// Escribe el texto centrado en un punto x
void Text::writeCentered(int x, int y, std::string text, int kerning, Uint8 lenght)
{
// Uint16 lenght = Text::lenght(text, kerning);
x = x - (Text::lenght(text, kerning) / 2);
Uint16 shift = 0;
for (Uint8 i = 0; i < text.length(); ++i)
{
mSprite->setSpriteClip(mOffset[int(text[i])].x, mOffset[int(text[i])].y, mSprite->getWidth(), mSprite->getHeight());
mSprite->setPosX(x + shift);
mSprite->setPosY(y);
mSprite->render();
shift += (mOffset[int(text[i])].w + kerning);
}
x -= (Text::lenght(text, kerning) / 2);
write(x, y, text, kerning, lenght);
}
// Escribe el texto centrado en un punto x y con kerning
void Text::writeCenteredAndColored(int x, int y, std::string text, int kerning, Uint8 R, Uint8 G, Uint8 B)
// Escribe texto con extras
void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, color_t textColor, Uint8 shadowDistance, color_t shadowColor, Uint8 lenght)
{
mSprite->getTexture()->setColor(R, G, B);
const bool centered = ((flags & TXT_CENTER) == TXT_CENTER);
const bool shadowed = ((flags & TXT_SHADOW) == TXT_SHADOW);
const bool colored = ((flags & TXT_COLOR) == TXT_COLOR);
x = x - (Text::lenght(text, kerning) / 2);
Uint16 shift = 0;
for (Uint8 i = 0; i < text.length(); ++i)
{
mSprite->setSpriteClip(mOffset[int(text[i])].x, mOffset[int(text[i])].y, mSprite->getWidth(), mSprite->getHeight());
mSprite->setPosX(x + shift);
mSprite->setPosY(y);
mSprite->render();
shift += (mOffset[int(text[i])].w + kerning);
}
if (centered)
x -= (Text::lenght(text, kerning) / 2);
mSprite->getTexture()->setColor(255, 255, 255);
if (shadowed)
writeColored(x + shadowDistance, y + shadowDistance, text, shadowColor, kerning, lenght);
if (colored)
writeColored(x, y, text, textColor, kerning, lenght);
else
write(x, y, text, kerning, lenght);
}
// Obtiene la longitud en pixels de una cadena
Uint16 Text::lenght(std::string text, int kerning)
{
Uint16 shift = 0;
for (Uint8 i = 0; i < text.length(); ++i)
{
for (int i = 0; i < text.length(); ++i)
shift += (mOffset[int(text[i])].w + kerning);
}
return shift;
}

View File

@@ -1,9 +1,14 @@
#pragma once
#include "sprite.h"
#include "utils.h"
#ifndef TEXT_H
#define TEXT_H
#define TXT_COLOR 1
#define TXT_SHADOW 2
#define TXT_CENTER 4
// Clase texto. Pinta texto en pantalla a partir de un bitmap
class Text
{
@@ -23,30 +28,28 @@ private:
public:
// Constructor
Text();
Text(LTexture *texture, SDL_Renderer *renderer);
// Destructor
~Text();
// Inicializador
void init(LTexture *texture, SDL_Renderer *renderer, Uint8 type, Uint8 size);
void init(Uint8 type, Uint8 size);
// Escribe el texto en pantalla
void write(int x, int y, std::string text);
void write(int x, int y, std::string text, int kerning);
void write(int x, int y, std::string text, int kerning, Uint8 lenght);
void write(int x, int y, std::string text, int kerning = 0, Uint8 lenght = 0);
// Escribe el texto con colores
void writeColored(int x, int y, std::string text, Uint8 R, Uint8 G, Uint8 B);
void writeColored(int x, int y, std::string text, color_t color, int kerning = 0, Uint8 lenght = 0);
// Escribe el texto con sombra
void writeShadowed(int x, int y, std::string text, Uint8 R, Uint8 G, Uint8 B);
void writeShadowed(int x, int y, std::string text, color_t color, Uint8 shadowDistance = 1, int kerning = 0, Uint8 lenght = 0);
// Escribe el texto centrado en un punto x y con kerning
void writeCentered(int x, int y, std::string text, int kerning = 0);
void writeCentered(int x, int y, std::string text, int kerning = 0, Uint8 lenght = 0);
// Escribe el texto centrado en un punto x y con kerning
void writeCenteredAndColored(int x, int y, std::string text, int kerning = 0, Uint8 R = 255, Uint8 G = 255, Uint8 B = 255);
// Escribe texto con extras
void writeDX(Uint8 flags, int x, int y, std::string text, int kerning = 0, color_t textColor = {255, 255, 255}, Uint8 shadowDistance = 1, color_t shadowColor = {0, 0, 0}, Uint8 lenght = 0);
// Obtiene la longitud en pixels de una cadena
Uint16 lenght(std::string text, int kerning);

View File

@@ -2,21 +2,19 @@
#include "text2.h"
// Constructor
Text2::Text2()
Text2::Text2(LTexture *texture, SDL_Renderer *renderer) : Text(texture, renderer)
{
init(nullptr, nullptr, 0, 0);
}
// Destructor
Text2::~Text2()
{
init(nullptr, nullptr, 0, 0);
}
// Inicializador
void Text2::init(LTexture *texture, SDL_Renderer *renderer, Uint8 type, Uint8 size)
void Text2::init(Uint8 type, Uint8 size)
{
Text::init(texture, renderer, type, size);
Text::init(type, size);
mPosX = 0;
mPosY = 0;
mKerning = 0;

View File

@@ -10,13 +10,13 @@ class Text2 : public Text
{
public:
// Constructor
Text2();
Text2(LTexture *texture, SDL_Renderer *renderer);
// Destructor
~Text2();
// Inicializador
void init(LTexture *texture, SDL_Renderer *renderer, Uint8 type, Uint8 size);
void init(Uint8 type, Uint8 size);
// Establece el valor de la variable
void setPosX(int value);

View File

@@ -109,4 +109,16 @@ bool checkCollision(SDL_Rect &a, SDL_Rect &b)
//If none of the sides from A are outside B
return true;
}
// Carga un archivo de imagen en una textura
bool loadTextureFromFile(LTexture *texture, std::string path, SDL_Renderer *renderer)
{
bool success = true;
if (!texture->loadFromFile(path, renderer))
{
printf("Failed to load %s texture!\n", path.c_str());
success = false;
}
return success;
}

View File

@@ -1,5 +1,6 @@
#pragma once
#include "ifdefs.h"
#include "ltexture.h"
#ifndef UTILS_H
#define UTILS_H
@@ -12,20 +13,19 @@ struct circle_t
Uint8 r;
};
// Estructura para definir todas las entradas que aceptará el programa
struct input_t
// Estructura para definir un color
struct color_t
{
Uint8 up;
Uint8 down;
Uint8 left;
Uint8 right;
Uint8 escape;
Uint8 pause;
Uint8 fire;
Uint8 fireLeft;
Uint8 fireRight;
Uint8 accept;
Uint8 cancel;
Uint8 r;
Uint8 g;
Uint8 b;
};
// Estructura para saber la seccion y subseccion del programa
struct section_t
{
Uint8 name;
Uint8 subsection;
};
// Estructura para mapear el teclado usado en la demo
@@ -39,6 +39,15 @@ struct demoKeys_t
Uint8 fireRight;
};
// Estructura con todas las opciones de configuración del programa
struct options_t
{
Uint32 fullScreenMode; // Contiene el valor del modo de pantalla completa
Uint32 fullScreenModePrevious; // Usado por si se cancelan los cambios en el menu de opciones
Uint8 windowSize; // Contiene el valor del tamaño de la ventana
Uint8 windowSizePrevious; // Usado por si se cancelan los cambios en el menu de opciones
};
// Calcula el cuadrado de la distancia entre dos puntos
double distanceSquared(int x1, int y1, int x2, int y2);
@@ -51,4 +60,7 @@ bool checkCollision(circle_t &a, SDL_Rect &b);
// Detector de colisiones entre un dos rectangulos
bool checkCollision(SDL_Rect a, SDL_Rect b);
// Carga un archivo de imagen en una textura
bool loadTextureFromFile(LTexture *texture, std::string path, SDL_Renderer *renderer);
#endif