diff --git a/media/gfx/menu_animation.png b/media/gfx/menu_animation.png index 3f21152..2694a84 100644 Binary files a/media/gfx/menu_animation.png and b/media/gfx/menu_animation.png differ diff --git a/source/animatedsprite.h b/source/animatedsprite.h index 845167d..e417ac8 100644 --- a/source/animatedsprite.h +++ b/source/animatedsprite.h @@ -52,10 +52,10 @@ public: SDL_Rect getAnimationClip(Uint8 index, Uint8 frame); // Establece la animación actual - void AnimatedSprite::setCurrentAnimation(Uint8 index); + void setCurrentAnimation(Uint8 index); // Obtiene la animación actual - Uint8 AnimatedSprite::getCurrentAnimation(); + Uint8 getCurrentAnimation(); private: struct sAnimation diff --git a/source/const.h b/source/const.h index 509450c..bfa707c 100644 --- a/source/const.h +++ b/source/const.h @@ -5,7 +5,10 @@ #ifndef CONST_H #define CONST_H -const Uint8 GAME_SPEED = 24; //16 = normal-rapid, 24 = normal. Quan menor, m�s r�pid +// Textos +#define WINDOW_CAPTION "Volcano (@2016,2021 JailDesigner v0.5)" + +const Uint8 GAME_SPEED = 24; //16 = normal-rapido, 24 = normal. Cuanto mas pequeño, más rápido const Uint8 UP = 0; const Uint8 DOWN = 2; @@ -121,9 +124,6 @@ const Uint8 MENU_SECTION_ANIMATION = 2; const Uint8 ZONE_SURFACE = 0; const Uint8 ZONE_VOLCANO = 1; -const std::string WINDOW_TITLE = "Volcano v0005"; -const std::string BUILD = ".05"; - // Recursos const Uint8 FILE_MAP_VOLCANO = 0; const Uint8 FILE_CONFIG = 1; @@ -159,23 +159,21 @@ const Uint8 MUSIC_VOLCANO = 2; const Uint8 TOTAL_MUSIC = 3; -///////////////////////////////COFFEE CRISIS/////////////////// +///////////////////////////////COFFEE CRISIS////////////////////////////////////////////// + -// Textos -#define WINDOW_CAPTION "Coffee Crisis" -#define TEXT_COPYRIGHT "@2016,2021 JAILDESIGNER (V0.5)" // Tamaño de bloque const Uint8 BLOCK = 8; const Uint8 HALF_BLOCK = BLOCK / 2; // Tamaño de la pantalla real -const int SCREEN_WIDTH = 256; -const int SCREEN_HEIGHT = SCREEN_WIDTH * 3 / 4; // 192 +const int SCREEN_WIDTH = 320; +const int SCREEN_HEIGHT = SCREEN_WIDTH * 3 / 4; // 240 // Tamaño de la pantalla que se muestra -const int VIEW_WIDTH = SCREEN_WIDTH * 3; // 768 -const int VIEW_HEIGHT = SCREEN_HEIGHT * 3; // 576 +const int VIEW_WIDTH = SCREEN_WIDTH * 3; // 960 +const int VIEW_HEIGHT = SCREEN_HEIGHT * 3; // 720 // Cantidad de enteros a escribir en los ficheros de datos const Uint8 TOTAL_SCORE_DATA = 3; diff --git a/source/director.cpp b/source/director.cpp new file mode 100644 index 0000000..d6d8a8b --- /dev/null +++ b/source/director.cpp @@ -0,0 +1,685 @@ +#include "const.h" +#include "struct.h" +#include "director.h" +#include + +const Uint8 *keystates; + +// Constructor +Director::Director(std::string _path) +{ + // Crea todos los objetos del juego + initObjects(); + + // Inicializa todas las variables + init(_path); +} + +Director::~Director() +{ + // Borra todos los objetos del juego + deleteObjects(); + + // Destruye la ventana + SDL_DestroyRenderer(renderer); + SDL_DestroyTexture(backbuffer); + SDL_DestroyWindow(window); + backbuffer = nullptr; + renderer = nullptr; + window = nullptr; + + // Sal del subsistema SDL + SDL_Quit(); +} + +// Inicializa todas las variables +void Director::init(std::string _path) +{ + setPath(_path); + section = NONE; + gameControllerFound = false; + for (int i = 0; i < 360; i++) + sen[i] = sin(i * 3.14 / 180); + for (int i = 0; i < TOTAL_SCORE_DATA; i++) + scoreData[i] = 0; + + initOptions(); + quit = false; +} + +// Inicializa las variables de las opciones +void Director::initOptions() +{ + options.fullScreenMode = 0; + options.fullScreenModePrevious = 0; + options.windowSize = 0; + options.windowSizePrevious = 0; +} + +// Inicializa las variables del juego +void Director::initGame() +{ + // Variables + game.score = 0; + game.section = 0; + game.paused = false; + game.ticks = 0; + game.ticksSpeed = GAME_SPEED; + game.counter = 0; + + // Player + resource.texture[TEXTURE_PLAYER].texture = new LTexture(); + loadTextureFromFile(resource.texture[TEXTURE_PLAYER].texture, resource.texture[TEXTURE_PLAYER].file, renderer); + player = new Player(renderer, resource.texture[TEXTURE_PLAYER].texture); + + // Map + resource.texture[TEXTURE_ACTORS].texture = new LTexture(); + loadTextureFromFile(resource.texture[TEXTURE_ACTORS].texture, resource.texture[TEXTURE_ACTORS].file, renderer); + resource.texture[TEXTURE_BKG_SURFACE].texture = new LTexture(); + loadTextureFromFile(resource.texture[TEXTURE_BKG_SURFACE].texture, resource.texture[TEXTURE_BKG_SURFACE].file, renderer); + resource.texture[TEXTURE_TILES_VOLCANO].texture = new LTexture(); + loadTextureFromFile(resource.texture[TEXTURE_TILES_VOLCANO].texture, resource.texture[TEXTURE_TILES_VOLCANO].file, renderer); + map = new Map(renderer, resource.texture[TEXTURE_TILES_VOLCANO].texture, resource.texture[TEXTURE_ACTORS].texture, + resource.texture[TEXTURE_BKG_SURFACE].texture, resource.file[FILE_MAP_VOLCANO].file); +} + +// Limpia las variables del juego +void Director::quitGame() +{ + // Player + delete player; + player = nullptr; + delete resource.texture[TEXTURE_PLAYER].texture; + resource.texture[TEXTURE_PLAYER].texture = nullptr; + + // Map + delete map; + map = nullptr; + delete resource.texture[TEXTURE_TILES_VOLCANO].texture; + resource.texture[TEXTURE_TILES_VOLCANO].texture = nullptr; + delete resource.texture[TEXTURE_ACTORS].texture; + resource.texture[TEXTURE_ACTORS].texture = nullptr; + delete resource.texture[TEXTURE_BKG_SURFACE].texture; + resource.texture[TEXTURE_BKG_SURFACE].texture = nullptr; +} + +// Arranca SDL y crea la ventana +bool Director::initSDL() +{ + // Indicador de inicialización + bool success = true; + + // Inicializa SDL + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO | SDL_INIT_HAPTIC) < 0) + { + printf("SDL could not initialize!\nSDL Error: %s\n", SDL_GetError()); + success = false; + } + else + { + // Establece el filtro de la textura a nearest + if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0")) + { + printf("Warning: Nearest texture filtering not enabled!\n"); + } + + // Inicializa jail_audio + JA_Init(48000, AUDIO_S16, 2); + + // Comprueba si hay algun mando conectado + if (SDL_NumJoysticks() < 1) + { + printf("Warning: No joysticks connected!\n"); + gameControllerFound = false; + } + else + { + // Carga el mando + gameController = SDL_JoystickOpen(0); + gameControllerFound = true; + + if (gameController == NULL) + { + printf("Warning: Unable to open game controller!\nSDL Error: %s\n", SDL_GetError()); + gameControllerFound = false; + } + else + { + printf("%i joysticks were found.\n", SDL_NumJoysticks()); + std::cout << SDL_JoystickNumButtons(gameController) << " buttons\n"; + + //Get controller haptic device + controllerHaptic = SDL_HapticOpenFromJoystick(gameController); + if (controllerHaptic == NULL) + { + printf("Warning: Controller does not support haptics!\nSDL Error: %s\n", SDL_GetError()); + } + else + { + printf("Haptics detected\n"); + + //Get initialize rumble + if (SDL_HapticRumbleInit(controllerHaptic) < 0) + { + printf("Warning: Unable to initialize rumble!\nSDL Error: %s\n", SDL_GetError()); + } + } + } + } + + // Crea la ventana + window = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, VIEW_WIDTH, VIEW_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); + if (window == NULL) + { + printf("Window could not be created!\nSDL Error: %s\n", SDL_GetError()); + success = false; + } + else + { + // Crea un renderizador para la ventana con vsync + renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); + if (renderer == NULL) + { + printf("Renderer could not be created!\nSDL Error: %s\n", SDL_GetError()); + success = false; + } + else + { + // Inicializa el color de renderizado + SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF); + + // Establece el tamaño del buffer de renderizado + SDL_RenderSetLogicalSize(renderer, SCREEN_WIDTH, SCREEN_HEIGHT); + + // Establece el modo de mezcla + SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); + } + + // Crea un backbuffer para el renderizador + backbuffer = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT); + if (backbuffer == NULL) + { + printf("Backbuffer could not be created!\nSDL Error: %s\n", SDL_GetError()); + success = false; + } + } + } + + printf("\n"); + return success; +} + +// Crea los objetos del programa +void Director::initObjects() +{ + eventHandler = new SDL_Event(); + text.white = new Text(); +} + +// Borra los objetos del programa +void Director::deleteObjects() +{ + delete eventHandler; + delete text.white; + eventHandler = nullptr; + text.white = nullptr; +} + +// Crea el indice de ficheros de recursos +void Director::setResourceList() +{ + // Ficheros binarios + resource.file[FILE_MAP_VOLCANO].file = path + "/" + "../data/volcano.map"; + resource.file[FILE_CONFIG].file = path + "/" + "../data/config.bin"; + + // Texturas + resource.texture[TEXTURE_ACTORS].file = path + "/" + "../media/gfx/actors.png"; + resource.texture[TEXTURE_BKG_SURFACE].file = path + "/" + "../media/gfx/bkg_surface.png"; + resource.texture[TEXTURE_FILTER].file = path + "/" + "../media/gfx/filter.png"; + resource.texture[TEXTURE_HUD].file = path + "/" + "../media/gfx/hud.png"; + resource.texture[TEXTURE_MENU_ANIMATION].file = path + "/" + "../media/gfx/menu_animation.png"; + resource.texture[TEXTURE_MENU].file = path + "/" + "../media/gfx/menu.png"; + resource.texture[TEXTURE_PLAYER].file = path + "/" + "../media/gfx/player.png"; + resource.texture[TEXTURE_TILES_SURFACE].file = path + "/" + "../media/gfx/tiles_surface.png"; + resource.texture[TEXTURE_TILES_VOLCANO].file = path + "/" + "../media/gfx/tiles_volcano.png"; + for (Uint8 i = 0; i < TOTAL_TEXTURE; i++) + resource.texture[i].texture = nullptr; + + // Sonidos + resource.sound[SOUND_COIN].file = path + "/" + "../media/sound/sound_player_coin.wav"; + resource.sound[SOUND_DEATH].file = path + "/" + "../media/sound/sound_player_death.wav"; + resource.sound[SOUND_DROP_ENEMY].file = path + "/" + "../media/sound/sound_drop_enemy.wav"; + resource.sound[SOUND_DROP_SPLAT].file = path + "/" + "../media/sound/sound_drop_splat.wav"; + resource.sound[SOUND_JUMP].file = path + "/" + "../media/sound/sound_player_jump.wav"; + resource.sound[SOUND_MENU_LOGO].file = path + "/" + "../media/sound/sound_menu_logo.wav"; + resource.sound[SOUND_MENU_START].file = path + "/" + "../media/sound/sound_menu_start.wav"; + for (Uint8 i = 0; i < TOTAL_SOUND; i++) + resource.sound[i].sound = nullptr; + + // Musicas + resource.music[MUSIC_MENU].file = path + "/" + "../media/music/music_menu.ogg"; + resource.music[MUSIC_SURFACE].file = path + "/" + "../media/music/music_surface.ogg"; + resource.music[MUSIC_VOLCANO].file = path + "/" + "../media/music/music_volcano.ogg"; + for (Uint8 i = 0; i < TOTAL_TEXTURE; i++) + resource.music[i].music = nullptr; +} + +// Comprueba que todos los ficheros de recursos existen +bool Director::checkResourceList() +{ + bool success = true; + std::string p; + std::string filename; + SDL_RWops *file; + + // Comprueba los ficheros de musica + printf("\n>> MUSIC FILES\n"); + for (Uint8 i = 0; i < TOTAL_MUSIC; i++) + { + p = resource.music[i].file.c_str(); + filename = p.substr(p.find_last_of("\\/") + 1); + file = SDL_RWFromFile(p.c_str(), "r+b"); + if (file != NULL) + { + printf("Checking file %-20s [OK]\n", filename.c_str()); + } + else + { + success = false; + printf("Checking file %-20s [ERROR]\n", filename.c_str()); + } + SDL_RWclose(file); + } + + // Comprueba los ficheros de sonidos + printf("\n>> SOUND FILES\n"); + for (Uint8 i = 0; i < TOTAL_SOUND; i++) + { + p = resource.sound[i].file.c_str(); + filename = p.substr(p.find_last_of("\\/") + 1); + file = SDL_RWFromFile(p.c_str(), "r+b"); + if (file != NULL) + { + printf("Checking file %-20s [OK]\n", filename.c_str()); + } + else + { + success = false; + printf("Checking file %-20s [ERROR]\n", filename.c_str()); + } + SDL_RWclose(file); + } + + // Comprueba los ficheros con texturas + printf("\n>> TEXTURE FILES\n"); + for (Uint8 i = 0; i < TOTAL_TEXTURE; i++) + { + p = resource.texture[i].file.c_str(); + filename = p.substr(p.find_last_of("\\/") + 1); + file = SDL_RWFromFile(p.c_str(), "r+b"); + if (file != NULL) + { + printf("Checking file %-20s [OK]\n", filename.c_str()); + } + else + { + success = false; + printf("Checking file %-20s [ERROR]\n", filename.c_str()); + } + SDL_RWclose(file); + } + + // Resultado + if (success) + { + printf("\n** All files OK.\n\n"); + } + else + { + printf("\n** File is missing. Exiting.\n\n"); + } + return success; +} + +// Inicializa la variable con los ficheros de recursos +bool Director::initResourceList() +{ + setResourceList(); + return checkResourceList(); +} + +// Carga un archivo de imagen en una textura +bool Director::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; +} + +// Carga los recursos necesarios +bool Director::loadMedia(Uint8 section) +{ + // Indicador de éxito en la carga + bool success = true; + std::string p; + + switch (section) + { + case GAME_SECTION_INIT: + { + p = resource.file[FILE_CONFIG].file.c_str(); + std::string filename = p.substr(p.find_last_of("\\/") + 1); + filename = p.substr(p.find_last_of("\\/") + 1); + + // Abre el fichero con la configuracion de las opciones para leer en binario + SDL_RWops *file = SDL_RWFromFile(p.c_str(), "r+b"); + + // El fichero no existe + if (file == NULL) + { + printf("Warning: Unable to open %s file\n", filename.c_str()); + + // Crea el fichero para escribir + file = SDL_RWFromFile(p.c_str(), "w+b"); + if (file != NULL) + { + printf("New file (%s) created!\n", filename.c_str()); + + // Inicializa los datos + options.fullScreenMode = 0; + SDL_RWwrite(file, &options.fullScreenMode, sizeof(options.fullScreenMode), 1); + + options.windowSize = 3; + SDL_RWwrite(file, &options.windowSize, sizeof(options.windowSize), 1); + + // Cierra el fichero + SDL_RWclose(file); + } + else + { + printf("Error: Unable to create file %s\n", filename.c_str()); + success = false; + } + } + // El fichero existe + else + { + // Carga los datos + printf("Reading file %s\n", filename.c_str()); + SDL_RWread(file, &options.fullScreenMode, sizeof(options.fullScreenMode), 1); + SDL_SetWindowFullscreen(window, options.fullScreenMode); + SDL_RWread(file, &options.windowSize, sizeof(options.windowSize), 1); + SDL_SetWindowSize(window, SCREEN_WIDTH * options.windowSize, SCREEN_HEIGHT * options.windowSize); + + // Cierra el fichero + SDL_RWclose(file); + } + printf("\n"); + + // Texturas + + // Sonidos + + // Musicas + } + break; + + case GAME_SECTION_TITLE: + { + } + break; + + case GAME_SECTION_PLAYING: + { + } + break; + + case GAME_SECTION_GAME_OVER_SCREEN: + { + } + break; + + case GAME_SECTION_INTRO: + { + } + break; + + case GAME_SECTION_DEMO: + { + } + break; + + case GAME_SECTION_INSTRUCTIONS: + { + } + break; + + case GAME_SECTION_LOGO: + { + } + break; + + default: + { + } + break; + } + + return success; +} + +// Descrga los recursos necesarios +bool Director::unLoadMedia(Uint8 section) +{ + // Indicador de éxito en la carga + bool success = true; + std::string p; + + switch (section) + { + case GAME_SECTION_INIT: + { + p = resource.file[FILE_CONFIG].file; + std::string filename = p.substr(p.find_last_of("\\/") + 1); + + // Abre el fichero de puntuación para escribir + SDL_RWops *file = SDL_RWFromFile(p.c_str(), "w+b"); + + if (file != NULL) + { + // Guardamos los datos + SDL_RWwrite(file, &options.fullScreenMode, sizeof(Uint32), 1); + SDL_RWwrite(file, &options.windowSize, sizeof(Uint8), 1); + + printf("Writing file %s\n", filename.c_str()); + + // Cerramos el fichero + SDL_RWclose(file); + } + else + { + printf("Error: Unable to save %s file! %s\n", filename.c_str(), SDL_GetError()); + } + } + break; + + case GAME_SECTION_TITLE: + { + } + break; + + case GAME_SECTION_PLAYING: + { + } + break; + + case GAME_SECTION_GAME_OVER_SCREEN: + { + } + break; + + case GAME_SECTION_INTRO: + { + } + break; + + case GAME_SECTION_DEMO: + { + } + break; + + case GAME_SECTION_INSTRUCTIONS: + { + } + break; + + case GAME_SECTION_LOGO: + { + } + break; + + default: + { + } + break; + } + + return success; +} + +// Establece el valor de la variable +void Director::setPath(std::string _path) +{ + path = _path.substr(0, _path.find_last_of("\\/")); +} + +// Obtiene el valor de la variable +Uint8 Director::getGameSection() +{ + return game.section; +} + +// Establece el valor de la variable +void Director::changeGameSection(_section sectionPrevious, _section sectionNext) +{ + switch (sectionPrevious) + { + case GAME: + quitGame(); + + break; + + default: + break; + } + + switch (sectionNext) + { + case GAME: + initGame(); + + break; + + default: + break; + } + + game.section = sectionNext; +} + +// Cambia el valor de la variable de modo de pantalla completa +void Director::changeFullScreenMode() +{ + switch (options.fullScreenMode) + { + case 0: + options.fullScreenMode = SDL_WINDOW_FULLSCREEN; + break; + case SDL_WINDOW_FULLSCREEN: + options.fullScreenMode = SDL_WINDOW_FULLSCREEN_DESKTOP; + break; + case SDL_WINDOW_FULLSCREEN_DESKTOP: + options.fullScreenMode = 0; + break; + + default: + options.fullScreenMode = 0; + break; + } +} + +// Comprueba si hay que salir +bool Director::isRunning() +{ + return !quit; +} + +// Bucle para el logo del juego +void Director::runLogo() +{ +} + +// Bucle para la intro del juego +void Director::runIntro() +{ +} + +// Bucle para el titulo del juego +void Director::runTitle() +{ +} + +// Bucle para el juego +void Director::runGame() +{ + // Actualiza la lógica del juego + updateGame(); + + // Pinta la sección de juego + renderGame(); +} + +// Actualiza la lógica del juego +void Director::updateGame() +{ + // Comprueba que la diferencia de ticks sea mayor a la velocidad del juego + if (SDL_GetTicks() - game.ticks > game.ticksSpeed) + { + // Actualiza el contador de ticks + game.ticks = SDL_GetTicks(); + + // Comprueba los eventos que hay en la cola + while (SDL_PollEvent(eventHandler) != 0) + { + // Evento de salida de la aplicación + if (eventHandler->type == SDL_QUIT) + { + quit = true; + break; + } + } + + game.counter++; + map->update(); + player->update(); + } +} + +// Pinta la sección de juego +void Director::renderGame() +{ + // Limpia la pantalla + SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF); + SDL_RenderClear(renderer); + + // Dibuja los objetos + map->render(); + player->render(); + + // Muestra el backbuffer en pantalla + SDL_RenderPresent(renderer); +} \ No newline at end of file diff --git a/source/game.h b/source/director.h similarity index 53% rename from source/game.h rename to source/director.h index 3e4c22a..0da078b 100644 --- a/source/game.h +++ b/source/director.h @@ -4,6 +4,7 @@ #include "movingsprite.h" #include "smartsprite.h" #include "player.h" +#include "map.h" #include "text.h" #include "text2.h" #include "menu.h" @@ -15,92 +16,20 @@ #ifndef GAME_H #define GAME_H -// GameDirector -class Game +// director +class Director { -public: - // Constructor - Game(); - - // Destructor - ~Game(); - - // Iniciador - void init(); - - // Arranca SDL y crea la ventana - bool initSDL(); - - // Crea el indice de ficheros - void setFileList(); - - // Comprueba que todos los ficheros existen - bool checkFileList(); - - // Carga un archivo de imagen en una textura - bool loadTextureFromFile(LTexture *texture, std::string path, SDL_Renderer *renderer); - - // Carga los recursos necesarios - bool loadMedia(Uint8 section); - - // Descrga los recursos necesarios - bool unLoadMedia(Uint8 section); - - // Establece el valor de la variable - void setPath(std::string path); - - // Obtiene el valor de la variable - Uint8 getGameSection(); - - // Establece el valor de la variable - void setGameSection(Uint8 section); - - // Cambia el valor de la variable de modo de pantalla completa - void changeFullScreenMode(); - - // Bucle para el logo del juego - void runLogo(); - - // Bucle para la intro del juego - void runIntro(); - - // Bucle para el titulo del juego - void runTitle(); - - // Bucle para el juego - void runGame(); - private: - SDL_Window *mWindow; // La ventana de la aplicación - SDL_Renderer *mRenderer; // El renderizador donde se dibuja todo - SDL_Event *mEventHandler; // Manejador de eventos - - SDL_Texture *mBackbuffer; // Texturas - - SDL_Joystick *mGameController; // Manejador para el mando 1 - bool mGameControllerFound; // Indica si se ha encontrado algun mando conectado - SDL_Haptic *mControllerHaptic; // Manejador para la vibración del mando - - Uint32 mScoreData[TOTAL_SCORE_DATA]; // Datos del fichero de puntuación - - Player *mPlayer; // El jugador - - double mSen[360]; // Vector con los valores del seno para 360 grados - struct _text // Objetos de texto { Text *white; }; - _text mText; // Variable con los objetos texto - struct _menu // Objetos menu { Menu *title; // Menu de la pantalla de título }; - _menu mMenu; // Variable con los objetos menu - struct _options // Variables relacionadas con las opciones del juego { Uint32 fullScreenMode; // Guarda el valor elegido para el modo de pantalla completa @@ -117,37 +46,29 @@ private: Uint32 ticks; // Contador de ticks para ajustar la velocidad del juego Uint8 ticksSpeed; // Velocidad a la que se repite el bucle de juego Uint32 counter; // Contador para el juego - _options options; // Contiene todas las opciones del juego - std::string path; // Path donde está el ejecutable del juego }; - _game mGame; - // Recursos struct _resourceFile { std::string file; - bool loaded; }; struct _resourceSound { std::string file; - bool loaded; JA_Sound sound; }; struct _resourceMusic { std::string file; - bool loaded; JA_Music music; }; struct _resourceTexture { std::string file; - bool loaded; LTexture *texture; }; @@ -159,7 +80,112 @@ private: _resourceTexture texture[TOTAL_TEXTURE]; }; - _resource mResource; + SDL_Window *window; // La ventana de la aplicación + SDL_Renderer *renderer; // El renderizador donde se dibuja todo + SDL_Event *eventHandler; // Manejador de eventos + SDL_Texture *backbuffer; // Texturas + SDL_Joystick *gameController; // Manejador para el mando 1 + SDL_Haptic *controllerHaptic; // Manejador para la vibración del mando + + _game game; // Contiene las variables de la sección de juego + //_menu menu; // Variable con los objetos menu + _resource resource; // Contiene todos los objetos y variables asociados a recursos + _options options; // Contiene todas las opciones del programa + _text text; // Variable con los objetos texto + bool gameControllerFound; // Indica si se ha encontrado algun mando conectado + double sen[360]; // Vector con los valores del seno para 360 grados + Player *player; // El jugador + Map *map; // El mapa del juego + Uint32 scoreData[TOTAL_SCORE_DATA]; // Datos del fichero de puntuación + std::string path; // Path donde está el ejecutable del juego + enum _section // Lista con todas las secciones en las que se divide el programa + { + GAME, + TITLE, + QUIT, + NONE + }; + _section section; // Seccion actual del programa + bool quit; // Indica si hay que terminar el programa + +public: + // Constructor + Director(std::string _path); + + // Destructor + ~Director(); + + // Inicializa todas las variables + void init(std::string _path); + + // Inicializa las variables de las opciones + void initOptions(); + + // Inicializa las variables del juego + void initGame(); + + // Limpia las variables del juego + void quitGame(); + + // Arranca SDL y crea la ventana + bool initSDL(); + + // Crea los objetos del programa + void initObjects(); + + // Borra los objetos del programa + void deleteObjects(); + + // Establece el valor de la variable + void setPath(std::string _path); + + // Crea el indice de ficheros de recursos + void setResourceList(); + + // Comprueba que todos los ficheros de recursos existen + bool checkResourceList(); + + // Inicializa la variable con los ficheros de recursos + bool initResourceList(); + + // Carga un archivo de imagen en una textura + bool loadTextureFromFile(LTexture *texture, std::string path, SDL_Renderer *renderer); + + // Carga los recursos necesarios + bool loadMedia(Uint8 section); + + // Descrga los recursos necesarios + bool unLoadMedia(Uint8 section); + + // Obtiene el valor de la variable + Uint8 getGameSection(); + + // Establece el valor de la variable + void changeGameSection(_section sectionPrevious, _section sectionNext); + + // Cambia el valor de la variable de modo de pantalla completa + void changeFullScreenMode(); + + // Comprueba si hay que salir + bool isRunning(); + + // Bucle para el logo del juego + void runLogo(); + + // Bucle para la intro del juego + void runIntro(); + + // Bucle para el titulo del juego + void runTitle(); + + // Bucle para el juego + void runGame(); + + // Pinta la sección de juego + void renderGame(); + + // Actualiza la lógica del juego + void updateGame(); }; #endif diff --git a/source/game.cpp b/source/game.cpp deleted file mode 100644 index fec5a79..0000000 --- a/source/game.cpp +++ /dev/null @@ -1,500 +0,0 @@ -#include "const.h" -#include "struct.h" -#include "game.h" -#include - -const Uint8 *keystates; - -// Constructor -Game::Game() -{ -} - -Game::~Game() -{ -} - -// Iniciador -void Game::init() -{ -} - -// Arranca SDL y crea la ventana -bool Game::initSDL() -{ - // Indicador de inicialización - bool success = true; - - // Inicializa SDL - if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO | SDL_INIT_HAPTIC) < 0) - { - printf("SDL could not initialize!\nSDL Error: %s\n", SDL_GetError()); - success = false; - } - else - { - // Establece el filtro de la textura a nearest - if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0")) - { - printf("Warning: Nearest texture filtering not enabled!\n"); - } - - // Inicializa jail_audio - JA_Init(48000, AUDIO_S16, 2); - - // Comprueba si hay algun mando conectado - if (SDL_NumJoysticks() < 1) - { - printf("Warning: No joysticks connected!\n"); - mGameControllerFound = false; - } - else - { - // Carga el mando - mGameController = SDL_JoystickOpen(0); - mGameControllerFound = true; - - if (mGameController == NULL) - { - printf("Warning: Unable to open game controller!\nSDL Error: %s\n", SDL_GetError()); - mGameControllerFound = false; - } - else - { - printf("%i joysticks were found.\n", SDL_NumJoysticks()); - std::cout << SDL_JoystickNumButtons(mGameController) << " buttons\n"; - - //Get controller haptic device - mControllerHaptic = SDL_HapticOpenFromJoystick(mGameController); - if (mControllerHaptic == NULL) - { - printf("Warning: Controller does not support haptics!\nSDL Error: %s\n", SDL_GetError()); - } - else - { - printf("Haptics detected\n"); - - //Get initialize rumble - if (SDL_HapticRumbleInit(mControllerHaptic) < 0) - { - printf("Warning: Unable to initialize rumble!\nSDL Error: %s\n", SDL_GetError()); - } - } - } - } - - // Crea la ventana - mWindow = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, VIEW_WIDTH, VIEW_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); - if (mWindow == NULL) - { - printf("Window could not be created!\nSDL Error: %s\n", SDL_GetError()); - success = false; - } - else - { - // Crea un renderizador para la ventana con vsync - mRenderer = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); - if (mRenderer == NULL) - { - printf("Renderer could not be created!\nSDL Error: %s\n", SDL_GetError()); - success = false; - } - else - { - // Inicializa el color de renderizado - SDL_SetRenderDrawColor(mRenderer, 0x00, 0x00, 0x00, 0xFF); - - // Establece el tamaño del buffer de renderizado - SDL_RenderSetLogicalSize(mRenderer, SCREEN_WIDTH, SCREEN_HEIGHT); - - // Establece el modo de mezcla - SDL_SetRenderDrawBlendMode(mRenderer, SDL_BLENDMODE_BLEND); - } - - // Crea un backbuffer para el renderizador - mBackbuffer = SDL_CreateTexture(mRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT); - if (mBackbuffer == NULL) - { - printf("Backbuffer could not be created!\nSDL Error: %s\n", SDL_GetError()); - success = false; - } - } - } - - printf("\n"); - return success; -} - -// Crea el indice de ficheros -void Game::setFileList() -{ - // Ficheros binarios - mResource.file[FILE_MAP_VOLCANO].file = mGame.path + "/" + "../data/volcano.map"; - mResource.file[FILE_CONFIG].file = mGame.path + "/" + "../data/config.bin"; - - // Texturas - mResource.texture[TEXTURE_ACTORS].file = mGame.path + "/" + "../media/gfx/actors.png"; - mResource.texture[TEXTURE_BKG_SURFACE].file = mGame.path + "/" + "../media/gfx/bkg_surface.png"; - mResource.texture[TEXTURE_FILTER].file = mGame.path + "/" + "../media/gfx/filter.png"; - mResource.texture[TEXTURE_HUD].file = mGame.path + "/" + "../media/gfx/hud.png"; - mResource.texture[TEXTURE_MENU_ANIMATION].file = mGame.path + "/" + "../media/gfx/menu_animation.png"; - mResource.texture[TEXTURE_MENU].file = mGame.path + "/" + "../media/gfx/menu.png"; - mResource.texture[TEXTURE_PLAYER].file = mGame.path + "/" + "../media/gfx/player.png"; - mResource.texture[TEXTURE_TILES_SURFACE].file = mGame.path + "/" + "../media/gfx/tiles_surface.png"; - mResource.texture[TEXTURE_TILES_VOLCANO].file = mGame.path + "/" + "../media/gfx/tiles_volcano.png"; - - // Sonidos - mResource.sound[SOUND_COIN].file = mGame.path + "/" + "../media/sound/sound_player_coin.wav"; - mResource.sound[SOUND_DEATH].file = mGame.path + "/" + "../media/sound/sound_player_death.wav"; - mResource.sound[SOUND_DROP_ENEMY].file = mGame.path + "/" + "../media/sound/sound_drop_enemy.wav"; - mResource.sound[SOUND_DROP_SPLAT].file = mGame.path + "/" + "../media/sound/sound_drop_splat.wav"; - mResource.sound[SOUND_JUMP].file = mGame.path + "/" + "../media/sound/sound_player_jump.wav"; - mResource.sound[SOUND_MENU_LOGO].file = mGame.path + "/" + "../media/sound/sound_menu_logo.wav"; - mResource.sound[SOUND_MENU_START].file = mGame.path + "/" + "../media/sound/sound_menu_start.wav"; - - // Musicas - mResource.music[MUSIC_MENU].file = mGame.path + "/" + "../media/music/music_menu.ogg"; - mResource.music[MUSIC_SURFACE].file = mGame.path + "/" + "../media/music/music_surface.ogg"; - mResource.music[MUSIC_VOLCANO].file = mGame.path + "/" + "../media/music/music_volcano.ogg"; -} - -// Comprueba que todos los ficheros existen -bool Game::checkFileList() -{ - bool success = true; - std::string p; - std::string filename; - SDL_RWops *file; - - // Comprueba los ficheros de musica - printf("\n>> MUSIC FILES\n"); - for (Uint8 i = 0; i < TOTAL_MUSIC; i++) - { - p = mResource.music[i].file.c_str(); - filename = p.substr(p.find_last_of("\\/") + 1); - file = SDL_RWFromFile(p.c_str(), "r+b"); - if (file != NULL) - { - printf("Checking file %-20s [OK]\n", filename.c_str()); - } - else - { - success = false; - printf("Checking file %-20s [ERROR]\n", filename.c_str()); - } - SDL_RWclose(file); - } - - // Comprueba los ficheros de sonidos - printf("\n>> SOUND FILES\n"); - for (Uint8 i = 0; i < TOTAL_SOUND; i++) - { - p = mResource.sound[i].file.c_str(); - filename = p.substr(p.find_last_of("\\/") + 1); - file = SDL_RWFromFile(p.c_str(), "r+b"); - if (file != NULL) - { - printf("Checking file %-20s [OK]\n", filename.c_str()); - } - else - { - success = false; - printf("Checking file %-20s [ERROR]\n", filename.c_str()); - } - SDL_RWclose(file); - } - - // Comprueba los ficheros con texturas - printf("\n>> TEXTURE FILES\n"); - for (Uint8 i = 0; i < TOTAL_TEXTURE; i++) - { - p = mResource.texture[i].file.c_str(); - filename = p.substr(p.find_last_of("\\/") + 1); - file = SDL_RWFromFile(p.c_str(), "r+b"); - if (file != NULL) - { - printf("Checking file %-20s [OK]\n", filename.c_str()); - } - else - { - success = false; - printf("Checking file %-20s [ERROR]\n", filename.c_str()); - } - SDL_RWclose(file); - } - - // Resultado - if (success) - { - printf("\n** All files OK.\n\n"); - } - else - { - printf("\n** File is missing. Exiting.\n\n"); - } - return success; -} - -// Carga un archivo de imagen en una textura -bool Game::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; -} - -// Carga los recursos necesarios -bool Game::loadMedia(Uint8 section) -{ - // Indicador de éxito en la carga - bool success = true; - std::string path = mGame.path + "/"; - std::string p; - - switch (section) - { - case GAME_SECTION_INIT: - { - p = mResource.file[FILE_CONFIG].file.c_str(); - std::string filename = p.substr(p.find_last_of("\\/") + 1); - filename = p.substr(p.find_last_of("\\/") + 1); - - // Abre el fichero con la configuracion de las opciones para leer en binario - SDL_RWops *file = SDL_RWFromFile(p.c_str(), "r+b"); - - // El fichero no existe - if (file == NULL) - { - printf("Warning: Unable to open %s file\n", filename.c_str()); - - // Crea el fichero para escribir - file = SDL_RWFromFile(p.c_str(), "w+b"); - if (file != NULL) - { - printf("New file (%s) created!\n", filename.c_str()); - - // Inicializa los datos - mGame.options.fullScreenMode = 0; - SDL_RWwrite(file, &mGame.options.fullScreenMode, sizeof(mGame.options.fullScreenMode), 1); - - mGame.options.windowSize = 3; - SDL_RWwrite(file, &mGame.options.windowSize, sizeof(mGame.options.windowSize), 1); - - // Cierra el fichero - SDL_RWclose(file); - } - else - { - printf("Error: Unable to create file %s\n", filename.c_str()); - success = false; - } - } - // El fichero existe - else - { - // Carga los datos - printf("Reading file %s\n", filename.c_str()); - SDL_RWread(file, &mGame.options.fullScreenMode, sizeof(mGame.options.fullScreenMode), 1); - SDL_SetWindowFullscreen(mWindow, mGame.options.fullScreenMode); - SDL_RWread(file, &mGame.options.windowSize, sizeof(mGame.options.windowSize), 1); - SDL_SetWindowSize(mWindow, SCREEN_WIDTH * mGame.options.windowSize, SCREEN_HEIGHT * mGame.options.windowSize); - - // Cierra el fichero - SDL_RWclose(file); - } - printf("\n"); - - // Texturas - - // Sonidos - - // Musicas - } - break; - - case GAME_SECTION_TITLE: - { - } - break; - - case GAME_SECTION_PLAYING: - { - } - break; - - case GAME_SECTION_GAME_OVER_SCREEN: - { - } - break; - - case GAME_SECTION_INTRO: - { - } - break; - - case GAME_SECTION_DEMO: - { - } - break; - - case GAME_SECTION_INSTRUCTIONS: - { - } - break; - - case GAME_SECTION_LOGO: - { - } - break; - - default: - { - } - break; - } - - return success; -} - -// Descrga los recursos necesarios -bool Game::unLoadMedia(Uint8 section) -{ - // Indicador de éxito en la carga - bool success = true; - std::string path = mGame.path + "/"; - std::string p; - - switch (section) - { - case GAME_SECTION_INIT: - { - p = mResource.file[FILE_CONFIG].file; - std::string filename = p.substr(p.find_last_of("\\/") + 1); - - // Abre el fichero de puntuación para escribir - SDL_RWops *file = SDL_RWFromFile(p.c_str(), "w+b"); - - if (file != NULL) - { - // Guardamos los datos - SDL_RWwrite(file, &mGame.options.fullScreenMode, sizeof(Uint32), 1); - SDL_RWwrite(file, &mGame.options.windowSize, sizeof(Uint8), 1); - - printf("Writing file %s\n", filename.c_str()); - - // Cerramos el fichero - SDL_RWclose(file); - } - else - { - printf("Error: Unable to save %s file! %s\n", filename.c_str(), SDL_GetError()); - } - } - break; - - case GAME_SECTION_TITLE: - { - } - break; - - case GAME_SECTION_PLAYING: - { - } - break; - - case GAME_SECTION_GAME_OVER_SCREEN: - { - } - break; - - case GAME_SECTION_INTRO: - { - } - break; - - case GAME_SECTION_DEMO: - { - } - break; - - case GAME_SECTION_INSTRUCTIONS: - { - } - break; - - case GAME_SECTION_LOGO: - { - } - break; - - default: - { - } - break; - } - - return success; -} - -// Establece el valor de la variable -void Game::setPath(std::string path) -{ - mGame.path = path.substr(0, path.find_last_of("\\/")); -} - -// Obtiene el valor de la variable -Uint8 Game::getGameSection() -{ - return mGame.section; -} - -// Establece el valor de la variable -void Game::setGameSection(Uint8 section) -{ - mGame.section = section; -} - -// Cambia el valor de la variable de modo de pantalla completa -void Game::changeFullScreenMode() -{ - switch (mGame.options.fullScreenMode) - { - case 0: - mGame.options.fullScreenMode = SDL_WINDOW_FULLSCREEN; - break; - case SDL_WINDOW_FULLSCREEN: - mGame.options.fullScreenMode = SDL_WINDOW_FULLSCREEN_DESKTOP; - break; - case SDL_WINDOW_FULLSCREEN_DESKTOP: - mGame.options.fullScreenMode = 0; - break; - - default: - mGame.options.fullScreenMode = 0; - break; - } -} - -// Bucle para el logo del juego -void Game::runLogo() -{ -} - -// Bucle para la intro del juego -void Game::runIntro() -{ -} - -// Bucle para el titulo del juego -void Game::runTitle() -{ -} - -// Bucle para el juego -void Game::runGame() -{ -} \ No newline at end of file diff --git a/source/ltexture.cpp b/source/ltexture.cpp index b51a6fc..a0a1fdd 100644 --- a/source/ltexture.cpp +++ b/source/ltexture.cpp @@ -51,7 +51,6 @@ bool LTexture::loadFromFile(std::string path, SDL_Renderer *renderer) SDL_Texture *newTexture = NULL; // Load image at specified path - //SDL_Surface *loadedSurface = IMG_Load(path.c_str()); SDL_Surface *loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom((void*)data, width, height, depth, pitch, pixel_format); if (loadedSurface == NULL) { @@ -59,9 +58,6 @@ bool LTexture::loadFromFile(std::string path, SDL_Renderer *renderer) } else { - // Color key image - //SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, COLOR_KEY_R, COLOR_KEY_G, COLOR_KEY_B)); - // Create texture from surface pixels newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface); if (newTexture == NULL) diff --git a/source/main.cpp b/source/main.cpp index fcb55c9..3bfa512 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -17,40 +17,34 @@ Repres un 14 de febrer de 2021 #include #include #include "const.h" -#include "game.h" +#include "director.h" int main(int argc, char *args[]) { // Inicia el generador de numeros aleatorios srand(time(nullptr)); - // Crea el objeto game - Game *game = new Game(); + // Crea el objeto director + Director *director = new Director(args[0]); - // Establece el valor de la variable con el path del ejecutable - game->setPath(args[0]); - - // Inicializa la lista de ficheros - game->setFileList(); - - // Comprueba que existen todos los ficheros - if (!game->checkFileList()) - { + // Comprueba si existen todos los ficheros de recursos + if (!director->initResourceList()) return -1; - } // Arranca SDL y crea la ventana - if (!game->initSDL()) - { - printf("Failed to initialize!\n"); + if (!director->initSDL()) return -1; - } - else - { - // Libera todos los recursos y cierra SDL - delete game; - printf("Shutting down the game...\n"); - return 0; + director->initGame(); + while (director->isRunning()) + { + director->runGame(); } + director->quitGame(); + + // Libera todos los recursos y cierra SDL + delete director; + printf("Shutting down the game...\n"); + + return 0; } diff --git a/source/map.cpp b/source/map.cpp new file mode 100644 index 0000000..8857f9a --- /dev/null +++ b/source/map.cpp @@ -0,0 +1,99 @@ +#include "const.h" +#include "map.h" + +// Constructor +Map::Map(SDL_Renderer *renderer, LTexture *texture1, LTexture *texture2, LTexture *texture3, std::string file) +{ + init(renderer, texture1, texture2, texture3, file); +} + +// Destructor +Map::~Map() +{ + delete sprite_tile; + delete sprite_actor; + delete background; + sprite_tile = nullptr; + sprite_actor = nullptr; + background = nullptr; + + //free(tile); + //free(actor); + delete[] tile; + delete[] actor; +} + +// Inicializa todas las variables +void Map::init(SDL_Renderer *renderer, LTexture *texture1, LTexture *texture2, LTexture *texture3, std::string file) +{ + sprite_tile = new AnimatedSprite(); + sprite_tile->init(texture1, renderer); + + sprite_actor = new AnimatedSprite(); + sprite_actor->init(texture2, renderer); + + background = new Sprite(); + background->init(texture3, renderer); + background->setSpriteClip(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); + + src_rect = {0, 0, 0, 0}; + dst_rect = {0, 0, 0, 0}; + //tile = (Uint8 *)malloc(1000 * sizeof(Uint8)); + //actor = (Uint8 *)malloc(1000 * sizeof(Uint8)); + w = 0; + h = 0; + room = 0; + + loadFromFile(file); +} + +// Carga el mapa a partir de un fichero +void Map::loadFromFile(std::string path) +{ + std::string filename = path.substr(path.find_last_of("\\/") + 1); + SDL_RWops *file = SDL_RWFromFile(path.c_str(), "r+b"); + Uint8 *w; + Uint8 *h; + + if (file == NULL) + { + printf("Warning: Unable to open %s file\n", filename.c_str()); + } + else + { + printf("Reading file %s\n", filename.c_str()); + + SDL_RWread(file, &w, sizeof(Uint8), 1); + SDL_RWread(file, &h, sizeof(Uint8), 1); + + long size = (*w) * (*h); + tile = new Uint8[size]; + actor = new Uint8[size]; + + for (long i = 0; i < size; i++) + SDL_RWread(file, &tile[i], sizeof(Uint8), 1); + + for (long i = 0; i < size; i++) + SDL_RWread(file, &actor[i], sizeof(Uint8), 1); + + SDL_RWclose(file); + } +} + +// Resetea ciertas variables +void Map::reset() +{ +} + +// Actualiza todas las variables +void Map::update() +{ + background->setPosX(0); + background->setPosY(0); +} + +// Dibuja el objeto +void Map::render() +{ + background->render(); +} \ No newline at end of file diff --git a/source/map.h b/source/map.h new file mode 100644 index 0000000..45751f1 --- /dev/null +++ b/source/map.h @@ -0,0 +1,48 @@ +#pragma once +#include "animatedsprite.h" +#include "jail_audio.h" +#include "utils.h" + +#ifndef MAP_H +#define MAP_H + +// The player +class Map +{ +public: + // Constructor + Map(SDL_Renderer *renderer, LTexture *texture1, LTexture *texture2, LTexture *texture3, std::string file); + + // Destructor + ~Map(); + + // Inicializa todas las variables + void init(SDL_Renderer *renderer, LTexture *texture1, LTexture *texture2, LTexture *texture3, std::string file); + + // Carga el mapa a partir de un fichero + void loadFromFile(std::string file); + + // Resetea ciertas variables + void reset(); + + // Actualiza todas las variables + void update(); + + // Dibuja el objeto + void render(); + +private: + AnimatedSprite *sprite_tile; // Sprite de los tiles del mapa + AnimatedSprite *sprite_actor; // Sprite de los actores + Sprite *background; // Fondo de la pantalla + SDL_Rect src_rect; // Ni puta idea + SDL_Rect dst_rect; // Ni puta idea + Uint8 *tile; // Vector con los tiles + Uint8 *actor; // Vector con los acores + Uint8 w; // Anchura en habitaciones del mapa + Uint8 h; // Altura en habitaciones del mapa + Uint8 room; // Habitación actual del mapa + std::string mapfile; // Ruta con el fichero del mapa +}; + +#endif diff --git a/source/menu.cpp b/source/menu.cpp index 6c09cb8..a1aeb79 100644 --- a/source/menu.cpp +++ b/source/menu.cpp @@ -253,9 +253,10 @@ void Menu::render() SDL_RenderFillRect(mRenderer, &rect); } + SDL_Rect rect2 = {mSelector.rect.x, mSelector.rect.y, mSelector.rect.w, mSelector.rect.h}; // Renderiza el rectangulo del selector SDL_SetRenderDrawColor(mRenderer, mSelector.rect.r, mSelector.rect.g, mSelector.rect.b, mSelector.rect.a); - SDL_RenderFillRect(mRenderer, &mSelector.rect); + SDL_RenderFillRect(mRenderer, &rect2); // Renderitza el text for (Uint8 i = 0; i < mTotalItems; i++) diff --git a/source/player.cpp b/source/player.cpp index a0f86d4..3d45c9b 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -2,750 +2,68 @@ #include "player.h" // Constructor -Player::Player() +Player::Player(SDL_Renderer *renderer, LTexture *texture) { - mSpriteLegs = new AnimatedSprite(); - mSpriteBody = new AnimatedSprite(); - init(0, 0, nullptr, nullptr, nullptr); + init(renderer, texture); } // Destructor Player::~Player() { - init(0, 0, nullptr, nullptr, nullptr); - mSpriteLegs = nullptr; - mSpriteBody = nullptr; - delete mSpriteLegs; - delete mSpriteBody; + delete sprite; + sprite = nullptr; } -// Iniciador -void Player::init(float x, int y, LTexture *textureLegs, LTexture *textureBody, SDL_Renderer *renderer) +// Inicializa todas las variables +void Player::init(SDL_Renderer *renderer, LTexture *texture) { - // Inicializa variables de estado - mAlive = true; - mStatusWalking = PLAYER_STATUS_WALKING_STOP; - mStatusFiring = PLAYER_STATUS_FIRING_NO; - mInvulnerable = false; - mInvulnerableTimer = PLAYER_INVULNERABLE_TIMER; - mExtraHit = false; - - // Establece la altura y el ancho del jugador - mWidth = 3 * BLOCK; - mHeight = 3 * BLOCK; - - // Establece la posición inicial del jugador - mPosX = x; - mPosY = y; - - // Establece el tamaño del circulo de colisión - mCollider.r = 7; - - // Actualiza la posición del circulo de colisión - shiftColliders(); - - // Establece la velocidad inicial - mVelX = 0; - mVelY = 0; - - // Establece la velocidad base - mBaseSpeed = 1.5; - - // Establece el numero inicial de vidas - mStartingLives = 3; - mLives = mStartingLives; - - // Establece la puntuación inicial - mScore = 0; - - // Establece el multiplicador de puntos inicial - mScoreMultiplier = 1.0f; - - // Inicia el contador para la cadencia de disparo - mCooldown = 10; - - // Inicia el sprite - mSpriteLegs->init(textureLegs, renderer); - mSpriteBody->init(textureBody, renderer); - - // Establece el alto y ancho del sprite - mSpriteLegs->setWidth(mWidth); - mSpriteLegs->setHeight(mHeight); - - mSpriteBody->setWidth(mWidth); - mSpriteBody->setHeight(mHeight); - - // Establece la posición del sprite - mSpriteLegs->setPosX(int(mPosX)); - mSpriteLegs->setPosY(mPosY); - - mSpriteBody->setPosX(int(mPosX)); - mSpriteBody->setPosY(mPosY); - - // Inicializa las variables para la animación - mSpriteLegs->setCurrentFrame(0); - mSpriteLegs->setAnimationCounter(0); - - mSpriteBody->setCurrentFrame(0); - mSpriteBody->setAnimationCounter(0); - - // Establece el numero de frames de cada animacion - mSpriteLegs->setAnimationNumFrames(PLAYER_ANIMATION_LEGS_WALKING_STOP, 4); - mSpriteLegs->setAnimationNumFrames(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 4); - mSpriteLegs->setAnimationNumFrames(PLAYER_ANIMATION_LEGS_WALKING_RIGHT, 4); - - mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_WALKING_LEFT, 4); - mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_FIRING_LEFT, 4); - mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_WALKING_RIGHT, 4); - mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_FIRING_RIGHT, 4); - mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_WALKING_STOP, 4); - mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_FIRING_UP, 4); - mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_WALKING_LEFT_EXTRA_HIT, 4); - mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_FIRING_LEFT_EXTRA_HIT, 4); - mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_WALKING_RIGHT_EXTRA_HIT, 4); - mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_FIRING_RIGHT_EXTRA_HIT, 4); - mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_WALKING_STOP_EXTRA_HIT, 4); - mSpriteBody->setAnimationNumFrames(PLAYER_ANIMATION_BODY_FIRING_UP_EXTRA_HIT, 4); - - // Establece la velocidad de cada animación - mSpriteLegs->setAnimationSpeed(PLAYER_ANIMATION_LEGS_WALKING_STOP, 10); - mSpriteLegs->setAnimationSpeed(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 5); - mSpriteLegs->setAnimationSpeed(PLAYER_ANIMATION_LEGS_WALKING_RIGHT, 5); - - mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_WALKING_LEFT, 5); - mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_FIRING_LEFT, 5); - mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_WALKING_RIGHT, 5); - mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_FIRING_RIGHT, 5); - mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_WALKING_STOP, 10); - mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_FIRING_UP, 5); - mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_WALKING_LEFT_EXTRA_HIT, 5); - mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_FIRING_LEFT_EXTRA_HIT, 5); - mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_WALKING_RIGHT_EXTRA_HIT, 5); - mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_FIRING_RIGHT_EXTRA_HIT, 5); - mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_WALKING_STOP_EXTRA_HIT, 10); - mSpriteBody->setAnimationSpeed(PLAYER_ANIMATION_BODY_FIRING_UP_EXTRA_HIT, 5); - - // Establece si la animación se reproduce en bucle - mSpriteLegs->setAnimationLoop(PLAYER_ANIMATION_LEGS_WALKING_STOP, true); - mSpriteLegs->setAnimationLoop(PLAYER_ANIMATION_LEGS_WALKING_LEFT, true); - mSpriteLegs->setAnimationLoop(PLAYER_ANIMATION_LEGS_WALKING_RIGHT, true); - - mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_WALKING_LEFT, true); - mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_FIRING_LEFT, true); - mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_WALKING_RIGHT, true); - mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_FIRING_RIGHT, true); - mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_WALKING_STOP, true); - mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_FIRING_UP, true); - mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_WALKING_LEFT_EXTRA_HIT, true); - mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_FIRING_LEFT_EXTRA_HIT, true); - mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_WALKING_RIGHT_EXTRA_HIT, true); - mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_FIRING_RIGHT_EXTRA_HIT, true); - mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_WALKING_STOP_EXTRA_HIT, true); - mSpriteBody->setAnimationLoop(PLAYER_ANIMATION_BODY_FIRING_UP_EXTRA_HIT, true); - - // Establece los frames de cada animación - mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 0, mWidth * 0, mHeight * 0, mWidth, mHeight); - mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 1, mWidth * 1, mHeight * 0, mWidth, mHeight); - mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 2, mWidth * 2, mHeight * 0, mWidth, mHeight); - mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_LEFT, 3, mWidth * 3, mHeight * 0, mWidth, mHeight); - - mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_RIGHT, 0, mWidth * 0, mHeight * 1, mWidth, mHeight); - mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_RIGHT, 1, mWidth * 1, mHeight * 1, mWidth, mHeight); - mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_RIGHT, 2, mWidth * 2, mHeight * 1, mWidth, mHeight); - mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_RIGHT, 3, mWidth * 3, mHeight * 1, mWidth, mHeight); - - mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_STOP, 0, mWidth * 0, mHeight * 2, mWidth, mHeight); - mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_STOP, 1, mWidth * 1, mHeight * 2, mWidth, mHeight); - mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_STOP, 2, mWidth * 2, mHeight * 2, mWidth, mHeight); - mSpriteLegs->setAnimationFrames(PLAYER_ANIMATION_LEGS_WALKING_STOP, 3, mWidth * 3, mHeight * 2, mWidth, mHeight); - - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_LEFT, 0, mWidth * 0, mHeight * 0, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_LEFT, 1, mWidth * 1, mHeight * 0, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_LEFT, 2, mWidth * 2, mHeight * 0, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_LEFT, 3, mWidth * 3, mHeight * 0, mWidth, mHeight); - - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_LEFT, 0, mWidth * 0, mHeight * 1, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_LEFT, 1, mWidth * 1, mHeight * 1, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_LEFT, 2, mWidth * 2, mHeight * 1, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_LEFT, 3, mWidth * 3, mHeight * 1, mWidth, mHeight); - - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_RIGHT, 0, mWidth * 0, mHeight * 2, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_RIGHT, 1, mWidth * 1, mHeight * 2, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_RIGHT, 2, mWidth * 2, mHeight * 2, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_RIGHT, 3, mWidth * 3, mHeight * 2, mWidth, mHeight); - - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_RIGHT, 0, mWidth * 0, mHeight * 3, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_RIGHT, 1, mWidth * 1, mHeight * 3, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_RIGHT, 2, mWidth * 2, mHeight * 3, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_RIGHT, 3, mWidth * 3, mHeight * 3, mWidth, mHeight); - - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_STOP, 0, mWidth * 0, mHeight * 4, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_STOP, 1, mWidth * 1, mHeight * 4, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_STOP, 2, mWidth * 2, mHeight * 4, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_STOP, 3, mWidth * 3, mHeight * 4, mWidth, mHeight); - - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP, 0, mWidth * 0, mHeight * 5, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP, 1, mWidth * 1, mHeight * 5, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP, 2, mWidth * 2, mHeight * 5, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP, 3, mWidth * 3, mHeight * 5, mWidth, mHeight); - - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_LEFT_EXTRA_HIT, 0, mWidth * 0, mHeight * 6, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_LEFT_EXTRA_HIT, 1, mWidth * 1, mHeight * 6, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_LEFT_EXTRA_HIT, 2, mWidth * 2, mHeight * 6, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_LEFT_EXTRA_HIT, 3, mWidth * 3, mHeight * 6, mWidth, mHeight); - - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_LEFT_EXTRA_HIT, 0, mWidth * 0, mHeight * 7, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_LEFT_EXTRA_HIT, 1, mWidth * 1, mHeight * 7, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_LEFT_EXTRA_HIT, 2, mWidth * 2, mHeight * 7, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_LEFT_EXTRA_HIT, 3, mWidth * 3, mHeight * 7, mWidth, mHeight); - - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_RIGHT_EXTRA_HIT, 0, mWidth * 0, mHeight * 8, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_RIGHT_EXTRA_HIT, 1, mWidth * 1, mHeight * 8, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_RIGHT_EXTRA_HIT, 2, mWidth * 2, mHeight * 8, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_RIGHT_EXTRA_HIT, 3, mWidth * 3, mHeight * 8, mWidth, mHeight); - - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_RIGHT_EXTRA_HIT, 0, mWidth * 0, mHeight * 9, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_RIGHT_EXTRA_HIT, 1, mWidth * 1, mHeight * 9, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_RIGHT_EXTRA_HIT, 2, mWidth * 2, mHeight * 9, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_RIGHT_EXTRA_HIT, 3, mWidth * 3, mHeight * 9, mWidth, mHeight); - - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_STOP_EXTRA_HIT, 0, mWidth * 0, mHeight * 10, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_STOP_EXTRA_HIT, 1, mWidth * 1, mHeight * 10, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_STOP_EXTRA_HIT, 2, mWidth * 2, mHeight * 10, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_WALKING_STOP_EXTRA_HIT, 3, mWidth * 3, mHeight * 10, mWidth, mHeight); - - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP_EXTRA_HIT, 0, mWidth * 0, mHeight * 11, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP_EXTRA_HIT, 1, mWidth * 1, mHeight * 11, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP_EXTRA_HIT, 2, mWidth * 2, mHeight * 11, mWidth, mHeight); - mSpriteBody->setAnimationFrames(PLAYER_ANIMATION_BODY_FIRING_UP_EXTRA_HIT, 3, mWidth * 3, mHeight * 11, mWidth, mHeight); - - // Selecciona un frame para pintar - mSpriteLegs->setSpriteClip(mSpriteLegs->getAnimationClip(PLAYER_ANIMATION_LEGS_WALKING_STOP, 0)); - mSpriteBody->setSpriteClip(mSpriteBody->getAnimationClip(PLAYER_ANIMATION_BODY_WALKING_STOP, 0)); + rect = {0, 0, 16, 24}; + + can_jump = false; + enabled = false; + jump_pressed_before = false; + jump_pressed_now = false; + for (Uint8 i = 0; i < 6; i++) + key[i] = false; + standing = false; + was_on_background = false; + + coins = 0; + cooldown = 0; + jumpforce = 0; + respawn_x = 0; + respawn_y = 0; + speed_x = 0; + speed_y = 0; + + sprite = new AnimatedSprite(); + sprite->init(texture, renderer); + sprite->setSpriteClip(rect); + + sound_coin = 0; + sound_death = 0; + sound_jump = 0; + + active_animation = 0; + direction = 0; + lifes = 0; + respawn_direction = 0; } -// Actua en consecuencia de la entrada recibida -void Player::setInput(Uint8 input) +// Resetea ciertas variables +void Player::reset() { - switch (input) - { - case INPUT_LEFT: - mVelX = -mBaseSpeed; - if (mExtraHit) - { - setWalkingStatus(PLAYER_STATUS_WALKING_LEFT); - } - else - { - setWalkingStatus(PLAYER_STATUS_WALKING_LEFT); - } - break; - - case INPUT_RIGHT: - mVelX = mBaseSpeed; - if (mExtraHit) - { - setWalkingStatus(PLAYER_STATUS_WALKING_RIGHT); - } - else - { - setWalkingStatus(PLAYER_STATUS_WALKING_RIGHT); - } - break; - - case INPUT_FIRE_UP: - if (mExtraHit) - { - setFiringStatus(PLAYER_STATUS_FIRING_UP); - } - else - { - setFiringStatus(PLAYER_STATUS_FIRING_UP); - } - break; - - case INPUT_FIRE_LEFT: - if (mExtraHit) - { - setFiringStatus(PLAYER_STATUS_FIRING_LEFT); - } - else - { - setFiringStatus(PLAYER_STATUS_FIRING_LEFT); - } - break; - - case INPUT_FIRE_RIGHT: - if (mExtraHit) - { - setFiringStatus(PLAYER_STATUS_FIRING_RIGHT); - } - else - { - setFiringStatus(PLAYER_STATUS_FIRING_RIGHT); - } - break; - - default: - mVelX = 0; - if (mExtraHit) - { - setWalkingStatus(PLAYER_STATUS_WALKING_STOP); - } - else - { - setWalkingStatus(PLAYER_STATUS_WALKING_STOP); - } - break; - } } -// Mueve el jugador a la posición y animación que le corresponde -void Player::move() -{ - if (isAlive()) - { - // Mueve el jugador a derecha o izquierda - mPosX += mVelX; - - // Si el jugador abandona el area de juego por los laterales - if ((mPosX < PLAY_AREA_LEFT) || (mPosX + mWidth > PLAY_AREA_RIGHT)) - { - // Restaura su posición - mPosX -= mVelX; - } - - // Actualiza la posición del sprite - mSpriteLegs->setPosX(getPosX()); - mSpriteLegs->setPosY(mPosY); - - mSpriteBody->setPosX(getPosX()); - mSpriteBody->setPosY(mPosY); - } -} - -// Pinta el jugador en pantalla -void Player::render() -{ - if (isAlive()) - { - if (mInvulnerable) - { - if ((mInvulnerableTimer % 10) > 4) - { - mSpriteLegs->render(); - mSpriteBody->render(); - } - } - else - { - mSpriteLegs->render(); - mSpriteBody->render(); - } - } -} - -// Establece el estado del jugador cuando camina -void Player::setWalkingStatus(Uint8 status) -{ - // Si cambiamos de estado, reiniciamos la animación - if (mStatusWalking != status) - { - mStatusWalking = status; - mSpriteLegs->setCurrentFrame(0); - } -} - -// Establece el estado del jugador cuando dispara -void Player::setFiringStatus(Uint8 status) -{ - // Si cambiamos de estado, reiniciamos la animación - if (mStatusFiring != status) - { - mStatusFiring = status; - mSpriteBody->setCurrentFrame(0); - } -} - -// Establece la animación correspondiente al estado -void Player::setAnimation() -{ - switch (mStatusWalking) - { - case PLAYER_STATUS_WALKING_LEFT: - mSpriteLegs->animate(PLAYER_ANIMATION_LEGS_WALKING_LEFT); - switch (mStatusFiring) - { - case PLAYER_STATUS_FIRING_UP: - if (mExtraHit) - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_UP_EXTRA_HIT); - } - else - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_UP); - } - - break; - - case PLAYER_STATUS_FIRING_LEFT: - if (mExtraHit) - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_LEFT_EXTRA_HIT); - } - else - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_LEFT); - } - - break; - - case PLAYER_STATUS_FIRING_RIGHT: - if (mExtraHit) - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_RIGHT_EXTRA_HIT); - } - else - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_RIGHT); - } - - break; - - case PLAYER_STATUS_FIRING_NO: - if (mExtraHit) - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_LEFT_EXTRA_HIT); - } - else - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_LEFT); - } - - break; - - default: - mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP); - break; - } - break; - - case PLAYER_STATUS_WALKING_RIGHT: - mSpriteLegs->animate(PLAYER_ANIMATION_LEGS_WALKING_RIGHT); - switch (mStatusFiring) - { - case PLAYER_STATUS_FIRING_UP: - if (mExtraHit) - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_UP_EXTRA_HIT); - } - else - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_UP); - } - - break; - - case PLAYER_STATUS_FIRING_LEFT: - if (mExtraHit) - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_LEFT_EXTRA_HIT); - } - else - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_LEFT); - } - - break; - - case PLAYER_STATUS_FIRING_RIGHT: - if (mExtraHit) - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_RIGHT_EXTRA_HIT); - } - else - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_RIGHT); - } - - break; - - case PLAYER_STATUS_FIRING_NO: - if (mExtraHit) - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_RIGHT_EXTRA_HIT); - } - else - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_RIGHT); - } - - break; - - default: - mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP); - break; - } - break; - - case PLAYER_STATUS_WALKING_STOP: - mSpriteLegs->animate(PLAYER_ANIMATION_LEGS_WALKING_STOP); - switch (mStatusFiring) - { - case PLAYER_STATUS_FIRING_UP: - if (mExtraHit) - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_UP_EXTRA_HIT); - } - else - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_UP); - } - - break; - - case PLAYER_STATUS_FIRING_LEFT: - if (mExtraHit) - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_LEFT_EXTRA_HIT); - } - else - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_LEFT); - } - - break; - - case PLAYER_STATUS_FIRING_RIGHT: - if (mExtraHit) - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_RIGHT_EXTRA_HIT); - } - else - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_FIRING_RIGHT); - } - - break; - - case PLAYER_STATUS_FIRING_NO: - if (mExtraHit) - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP_EXTRA_HIT); - } - else - { - mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP); - } - - break; - - default: - mSpriteBody->animate(PLAYER_ANIMATION_BODY_WALKING_STOP); - break; - } - break; - - default: - mSpriteLegs->animate(PLAYER_ANIMATION_LEGS_WALKING_STOP); - break; - } -} - -// Obtiene el valor de la variable -int Player::getPosX() -{ - return int(mPosX); -} - -// Obtiene el valor de la variable -int Player::getPosY() -{ - return mPosY; -} - -// Obtiene el valor de la variable -int Player::getWidth() -{ - return mWidth; -} - -// Obtiene el valor de la variable -int Player::getHeight() -{ - return mHeight; -} - -// Indica si el jugador puede disparar -bool Player::canFire() -{ - // Si el contador a llegado a cero, podemos disparar. En caso contrario decrementamos el contador - if (mCooldown > 0) - { - return false; - } - else - { - return true; - } -} - -// Establece el valor de la variable -void Player::setFireCooldown(int time) -{ - mCooldown = time; -} - -// Actualiza el valor de la variable -void Player::updateCooldown() -{ - if (mCooldown > 0) - { - --mCooldown; - } - else - { - setFiringStatus(PLAYER_STATUS_FIRING_NO); - } -} - -// Actualiza al jugador a su posicion, animación y controla los contadores +// Actualiza todas las variables void Player::update() { - move(); - setAnimation(); - shiftColliders(); - updateCooldown(); - updateInvulnerableTimer(); + sprite->setPosX(rect.x); + sprite->setPosY(rect.y); } -// Obtiene la puntuación del jugador -int Player::getScore() +// Dibuja el objeto +void Player::render() { - return mScore; -} - -// Asigna un valor a la puntuación del jugador -void Player::setScore(int score) -{ - mScore = score; -} - -// Incrementa la puntuación del jugador -void Player::addScore(int score) -{ - mScore += score; -} - -// Obtiene el valor de la variable -bool Player::isAlive() -{ - return mAlive; -} - -// Establece el valor de la variable -void Player::setAlive(bool value) -{ - mAlive = value; -} - -// Obtiene el valor de la variable -float Player::getScoreMultiplier() -{ - return mScoreMultiplier; -} - -// Establece el valor de la variable -void Player::setScoreMultiplier(float value) -{ - mScoreMultiplier = value; -} - -// Aumenta el valor de la variable hasta un máximo -void Player::incScoreMultiplier() -{ - if (mScoreMultiplier < 5.0f) - { - mScoreMultiplier += 0.1f; - } -} - -// Decrementa el valor de la variable hasta un mínimo -void Player::decScoreMultiplier() -{ - if (mScoreMultiplier > 1.0f) - { - mScoreMultiplier -= 0.1f; - } -} - -// Obtiene el valor de la variable -bool Player::isInvulnerable() -{ - return mInvulnerable; -} - -// Establece el valor de la variable -void Player::setInvulnerable(bool value) -{ - mInvulnerable = value; -} - -// Obtiene el valor de la variable -bool Player::getInvulnerableTimer() -{ - return mInvulnerableTimer; -} - -// Establece el valor de la variable -void Player::setInvulnerableTimer(Uint16 value) -{ - mInvulnerableTimer = value; -} - -// Actualiza el valor de la variable -void Player::updateInvulnerableTimer() -{ - if (mInvulnerableTimer > 0) - { - --mInvulnerableTimer; - } - else - { - mInvulnerable = false; - mInvulnerableTimer = PLAYER_INVULNERABLE_TIMER; - } -} - -// Obtiene el valor de la variable -bool Player::hasExtraHit() -{ - return mExtraHit; -} - -// Concede un toque extra al jugador -void Player::giveExtraHit() -{ - mExtraHit = true; -} - -// Quita el toque extra al jugador -void Player::removeExtraHit() -{ - mExtraHit = false; - mInvulnerable = true; - mInvulnerableTimer = PLAYER_INVULNERABLE_TIMER; -} - -// Obtiene el circulo de colisión -Circle &Player::getCollider() -{ - return mCollider; -} - -// Actualiza el circulo de colisión a la posición del jugador -void Player::shiftColliders() -{ - mCollider.x = Uint16(mPosX + (mWidth / 2)); - mCollider.y = mPosY + (mHeight / 2); + sprite->render(); } \ No newline at end of file diff --git a/source/player.h b/source/player.h index 0a9148c..6765563 100644 --- a/source/player.h +++ b/source/player.h @@ -1,6 +1,7 @@ #pragma once -#include "struct.h" #include "animatedsprite.h" +#include "jail_audio.h" +#include "utils.h" #ifndef PLAYER_H #define PLAYER_H @@ -10,164 +11,47 @@ class Player { public: // Constructor - Player(); + Player(SDL_Renderer *renderer, LTexture *texture); // Destructor ~Player(); - // Iniciador - void init(float x, int y, LTexture *textureLegs, LTexture *textureBody, SDL_Renderer *renderer); + // Inicializa todas las variables + void init(SDL_Renderer *renderer, LTexture *texture); - // Actua en consecuencia de la entrada recibida - void setInput(Uint8 input); + // Resetea ciertas variables + void reset(); - // Mueve el jugador a la posición y animación que le corresponde - void move(); - - // Pinta el jugador en pantalla - void render(); - - // Establece el estado del jugador - void setWalkingStatus(Uint8 status); - void setFiringStatus(Uint8 status); - - // Establece la animación correspondiente al estado - void setAnimation(); - - // Obtiene el valor de la variable - int getPosX(); - - // Obtiene el valor de la variable - int getPosY(); - - // Obtiene el valor de la variable - int getWidth(); - - // Obtiene el valor de la variable - int getHeight(); - - // Indica si el jugador puede disparar - bool canFire(); - - // Establece el valor de la variable - void setFireCooldown(int time); - - // Actualiza el valor de la variable - void updateCooldown(); - - // Actualiza al jugador a su posicion, animación y controla los contadores + // Actualiza todas las variables void update(); - // Obtiene la puntuación del jugador - int getScore(); - - // Asigna un valor a la puntuación del jugador - void setScore(int score); - - // Incrementa la puntuación del jugador - void addScore(int score); - - // Obtiene el valor de la variable - bool isAlive(); - - // Establece el valor de la variable - void setAlive(bool value); - - // Obtiene el valor de la variable - float getScoreMultiplier(); - - // Establece el valor de la variable - void setScoreMultiplier(float value); - - // Aumenta el valor de la variable hasta un máximo - void incScoreMultiplier(); - - // Decrementa el valor de la variable hasta un mínimo - void decScoreMultiplier(); - - // Obtiene el valor de la variable - bool isInvulnerable(); - - // Establece el valor de la variable - void setInvulnerable(bool value); - - // Obtiene el valor de la variable - bool getInvulnerableTimer(); - - // Establece el valor de la variable - void setInvulnerableTimer(Uint16 value); - - // Actualiza el valor de la variable - void updateInvulnerableTimer(); - - // Obtiene el valor de la variable - bool hasExtraHit(); - - // Concede un toque extra al jugador - void giveExtraHit(); - - // Quita el toque extra al jugador - void removeExtraHit(); - - // Obtiene el circulo de colisión - Circle &getCollider(); + // Dibuja el objeto + void render(); private: - // Posición X, Y del jugador - float mPosX; - int mPosY; - - // Altura y anchura del jugador - Uint8 mWidth; - Uint8 mHeight; - - // Velocidad X, Y del jugador - float mVelX; - int mVelY; - - // Velocidad base del jugador - float mBaseSpeed; - - // Contador durante el cual no puede disparar - int mCooldown; - - // Vidas actuales del jugador - Uint8 mLives; - - // Vidas iniciales del jugador - Uint8 mStartingLives; - - // Puntos del jugador - Uint32 mScore; - - // Multiplicador de puntos - float mScoreMultiplier; - - // Estado del jugador - Uint8 mStatusWalking; - Uint8 mStatusFiring; - - // Indica si el jugador está vivo - bool mAlive; - - // Indica si el jugador es invulnerable - bool mInvulnerable; - - // Temporizador para la invulnerabilidad - Uint16 mInvulnerableTimer; - - // Indica si el jugador tiene un toque extra - bool mExtraHit; - - // Sprite para dibujar al jugador en pantalla - AnimatedSprite *mSpriteLegs; - AnimatedSprite *mSpriteBody; - - // Circulo de colisión del jugador - Circle mCollider; - - // Actualiza el circulo de colisión a la posición del jugador - void shiftColliders(); + bool can_jump; // Si puede saltar + bool enabled; // Si está habilitado + bool jump_pressed_before; // Si se ha pulsado el botón de salto previamente + bool jump_pressed_now; // Si se acaba de pulsar el salto + bool key[6]; // Indica las llaves que posee el jugador + bool standing; // Si esta de pie (o quieto?) + bool was_on_background; // Si viene de una zona atravesable + int coins; // Cantidad de monedas + int cooldown; // Tiempo de inhabilitación + int jumpforce; // Cantidad de pixels a desplazarse y velocidad que pilla al saltar + int respawn_x; // Coordenadas para revivir + int respawn_y; // Coordenades para revivir + int speed_x; // Cantidad de pixeles a desplazarse + int speed_y; // Cantidad de pixels a desplazarse + JA_Sound sound_coin; // Sonido al coger monedas + JA_Sound sound_death; // Sonido al morir + JA_Sound sound_jump; // Sonido al saltar + SDL_Rect rect; // Rectangulo con la posición del jugador + AnimatedSprite *sprite; // Sprite con los graficos y animaciones + Uint8 active_animation; // Animación activa + Uint8 direction; // Sentido del desplazamiento + Uint8 lifes; // Cantidad de vidas + Uint8 respawn_direction; // Dirección para revivir }; #endif diff --git a/source/sprite.cpp b/source/sprite.cpp index f6ba4d5..6497ba6 100644 --- a/source/sprite.cpp +++ b/source/sprite.cpp @@ -3,7 +3,7 @@ // Constructor Sprite::Sprite() { - init(0, 0, 0, 0, nullptr, nullptr); + init(nullptr, nullptr); } // Destructor @@ -14,7 +14,7 @@ Sprite::~Sprite() } // Inicializador -void Sprite::init(int x, int y, Uint16 w, Uint16 h, LTexture *texture, SDL_Renderer *renderer) +/*void Sprite::init(LTexture *texture, SDL_Renderer *renderer, int x, int y, Uint16 w, Uint16 h) { // Establece el alto y el ancho del sprite setWidth(w); @@ -32,10 +32,10 @@ void Sprite::init(int x, int y, Uint16 w, Uint16 h, LTexture *texture, SDL_Rende // Establece el rectangulo de donde coger la imagen setSpriteClip(0, 0, w, h); -} +}*/ // Inicializador -void Sprite::init(SDL_Rect rect, LTexture *texture, SDL_Renderer *renderer) +void Sprite::init(LTexture *texture, SDL_Renderer *renderer, SDL_Rect rect) { // Establece el alto y el ancho del sprite mWidth = rect.w; diff --git a/source/sprite.h b/source/sprite.h index f81650d..7ae46f7 100644 --- a/source/sprite.h +++ b/source/sprite.h @@ -16,8 +16,8 @@ public: ~Sprite(); // Inicializador - void init(int x, int y, Uint16 w, Uint16 h, LTexture *texture, SDL_Renderer *renderer); - void init(SDL_Rect rect, LTexture *texture, SDL_Renderer *renderer); + //void init(LTexture *texture, SDL_Renderer *renderer, int x = 0, int y = 0, Uint16 w = 0, Uint16 h = 0); + void init(LTexture *texture, SDL_Renderer *renderer, SDL_Rect rect = {0, 0, 0, 0}); // Muestra el sprite por pantalla void render(); @@ -70,10 +70,8 @@ protected: Uint16 mHeight; // Alto del sprite SDL_Renderer *mRenderer; // Puntero al renderizador - - LTexture *mTexture; // Textura donde estan todos los dibujos del sprite - - SDL_Rect mSpriteClip; // Rectangulo de la textura que se dibujará en pantalla + LTexture *mTexture; // Textura donde estan todos los dibujos del sprite + SDL_Rect mSpriteClip; // Rectangulo que apunta a la posición de la textura donde está el grafico que se dibujará en pantalla }; #endif diff --git a/source/text.cpp b/source/text.cpp index 1db1aa9..6c9a3a6 100644 --- a/source/text.cpp +++ b/source/text.cpp @@ -3,7 +3,7 @@ Text::Text() { mSprite = new Sprite(); - init(nullptr, nullptr, 0, 0); + init(nullptr, nullptr, 0); } Text::~Text() diff --git a/source/volcano.cpp b/source/volcano.cpp index 1cf9e75..9e9ec4d 100644 --- a/source/volcano.cpp +++ b/source/volcano.cpp @@ -7,7 +7,7 @@ #include "volcano.h" -void allocatePointers() +/*void allocatePointers() { // Textures hud.sprite = new LTexture(); @@ -20,13 +20,13 @@ void allocatePointers() prog.sprite = new LTexture(); // Sounds - game.sound_drop_enemy = new Mix_Chunk(); - game.sound_drop_splat = new Mix_Chunk(); - menu.sound_logo = new Mix_Chunk(); - menu.sound_start = new Mix_Chunk(); - player.sound_coin = new Mix_Chunk(); - player.sound_death = new Mix_Chunk(); - player.sound_jump = new Mix_Chunk(); + game.sound_drop_enemy = new JA_Sound(); + game.sound_drop_splat = new JA_Sound(); + menu.sound_logo = new JA_Sound(); + menu.sound_start = new JA_Sound(); + player.sound_coin = new JA_Sound(); + player.sound_death = new JA_Sound(); + player.sound_jump = new JA_Sound(); // Music //game.music = new Mix_Music(); @@ -74,18 +74,14 @@ bool loadTextureFromFile(LTexture *texture, std::string path, SDL_Renderer *rend return success; } -void CloseSound(Mix_Chunk *sound) +void CloseSound(JA_Sound *sound) { - if (sound != nullptr) - Mix_FreeChunk(sound); - sound = nullptr; + } void CloseMusic(Mix_Music *music) { - if (music != nullptr) - Mix_FreeMusic(music); - music = nullptr; + } void ClosePicture(LTexture *picture) @@ -2321,3 +2317,4 @@ deletePointers(); } return 0; } +*/ \ No newline at end of file diff --git a/source/volcano.h b/source/volcano.h index 961fd10..c30561e 100644 --- a/source/volcano.h +++ b/source/volcano.h @@ -7,7 +7,8 @@ #include "jail_audio.h" #include "const.h" #include "ltexture.h" - +#include "director.h" +/* struct Tanimation { bool loops; // Salta a true cuando se reinicia la animación @@ -32,9 +33,9 @@ struct Tprogram struct Tgame { bool enabled; - Mix_Chunk *sound_drop_enemy; - Mix_Chunk *sound_drop_splat; - Mix_Music *music; + JA_Sound sound_drop_enemy; + JA_Sound sound_drop_splat; + JA_Music music; Uint8 zone; // Zona en la que estamos }; @@ -45,9 +46,9 @@ struct Tmenu int timer; LTexture *sprite_animation; LTexture *sprite; - Mix_Chunk *sound_logo; - Mix_Chunk *sound_start; - Mix_Music *music; + JA_Sound sound_logo; + JA_Sound sound_start; + JA_Music music; SDL_Rect dst_rect_animation; SDL_Rect dst_rect_fondo; SDL_Rect dst_rect_logo_zoom; @@ -63,34 +64,7 @@ struct Tmenu Uint8 section; }; -struct Tplayer -{ - bool can_jump; // Si puede saltar - bool enabled; // Si está habilitado - bool jump_pressed_before; // Si se ha pulsado el botón de salto previamente - bool jump_pressed_now; // Si se acaba de pulsar el salto - bool key[6]; // Indica las llaves que posee el jugador - bool standing; // Si esta de pie (o quieto?) - bool was_on_background; // Si viene de una zona atravesable - int coins; // Cantidad de monedas - int cooldown; // Tiempo de inhabilitación - int jumpforce; // Cantidad de pixels a desplazarse y velocidad que pilla al saltar - int respawn_x; // Coordenadas para revivir - int respawn_y; // Coordenades para revivir - int speed_x; // Cantidad de pixeles a desplazarse - int speed_y; // Cantidad de pixels a desplazarse - LTexture *sprite; // Textura con los graficos del jugador - Mix_Chunk *sound_coin; // Sonido al coger monedas - Mix_Chunk *sound_death; // Sonido al morir - Mix_Chunk *sound_jump; // Sonido al saltar - SDL_Rect dst_rect; // Rectangulo donde dibujar el sprite del jugador. Es la posición del jugador - SDL_Rect src_rect; // Rectangulo con el dibujo del jugador a pintar - Tanimation animation[8]; // Vector con las animaciones del jugador - Uint8 active_animation; // Animación activa - Uint8 direction; // Sentido del desplazamiento - Uint8 lifes; // Cantidad de vidas - Uint8 respawn_direction; // Dirección para revivir -}; + struct Tactor { @@ -154,7 +128,6 @@ Tgame game; Thud hud; Tmap map; Tmenu menu; -Tplayer player; Tprogram prog; Uint32 delta_time; @@ -171,9 +144,9 @@ void ApplyGravity(); void CheckPlayerCollisionWithActors(); void CheckPlayerCollisionWithActors(); void CheckPlayerCollisionWithMap(); -void CloseMusic(Mix_Music *music); +void CloseMusic(JA_Music *music); void ClosePicture(LTexture *picture); -void CloseSound(Mix_Chunk *sound); +void CloseSound(JA_Sound *sound); void CreateActor(Tactor &a, Uint8 kind, Uint8 id, Sint16 dstx, Sint16 dsty, Sint16 dstw, Sint16 dsth, Sint16 srcx, Sint16 srcy, Sint16 sx, Sint16 sy, Sint16 timer, Sint16 frame, Uint8 direction, Uint8 parent); void DrawHud(); void DrawMap(); @@ -205,5 +178,5 @@ void SetPlayerAnimation(Uint8 anim); void SetPlayerDirection(int direction); void SetProgSection(Uint8 section); void SetZone(int room); - +*/ #endif \ No newline at end of file