Reticadas las classes de la carpeta utils

This commit is contained in:
2022-10-18 19:48:13 +02:00
parent 5c68006cb5
commit 07a9ba5b87
15 changed files with 846 additions and 504 deletions

View File

@@ -353,239 +353,239 @@ bool Director::initSDL()
// Crea el indice de ficheros // Crea el indice de ficheros
bool Director::setFileList() bool Director::setFileList()
{ {
asset->add("/data/font/smb2.png", t_font); asset->add("/../data/font/smb2.png", t_font);
asset->add("/data/font/smb2.txt", t_font); asset->add("/../data/font/smb2.txt", t_font);
asset->add("/data/font/debug.png", t_font); asset->add("/../data/font/debug.png", t_font);
asset->add("/data/font/debug.txt", t_font); asset->add("/../data/font/debug.txt", t_font);
asset->add("/data/input/gamecontrollerdb.txt", t_data); asset->add("/../data/input/gamecontrollerdb.txt", t_data);
asset->add("/data/config/config.txt", t_data, false); asset->add("/../data/config/config.txt", t_data, false);
asset->add("/data/room/01.room", t_room); asset->add("/../data/room/01.room", t_room);
asset->add("/data/room/02.room", t_room); asset->add("/../data/room/02.room", t_room);
asset->add("/data/room/03.room", t_room); asset->add("/../data/room/03.room", t_room);
asset->add("/data/room/04.room", t_room); asset->add("/../data/room/04.room", t_room);
asset->add("/data/room/05.room", t_room); asset->add("/../data/room/05.room", t_room);
asset->add("/data/room/06.room", t_room); asset->add("/../data/room/06.room", t_room);
asset->add("/data/room/07.room", t_room); asset->add("/../data/room/07.room", t_room);
asset->add("/data/room/08.room", t_room); asset->add("/../data/room/08.room", t_room);
asset->add("/data/room/09.room", t_room); asset->add("/../data/room/09.room", t_room);
asset->add("/data/room/10.room", t_room); asset->add("/../data/room/10.room", t_room);
asset->add("/data/room/11.room", t_room); asset->add("/../data/room/11.room", t_room);
asset->add("/data/room/12.room", t_room); asset->add("/../data/room/12.room", t_room);
asset->add("/data/room/13.room", t_room); asset->add("/../data/room/13.room", t_room);
asset->add("/data/room/14.room", t_room); asset->add("/../data/room/14.room", t_room);
asset->add("/data/room/15.room", t_room); asset->add("/../data/room/15.room", t_room);
asset->add("/data/room/16.room", t_room); asset->add("/../data/room/16.room", t_room);
asset->add("/data/room/17.room", t_room); asset->add("/../data/room/17.room", t_room);
asset->add("/data/room/18.room", t_room); asset->add("/../data/room/18.room", t_room);
asset->add("/data/room/19.room", t_room); asset->add("/../data/room/19.room", t_room);
asset->add("/data/room/20.room", t_room); asset->add("/../data/room/20.room", t_room);
asset->add("/data/room/21.room", t_room); asset->add("/../data/room/21.room", t_room);
asset->add("/data/room/22.room", t_room); asset->add("/../data/room/22.room", t_room);
asset->add("/data/room/23.room", t_room); asset->add("/../data/room/23.room", t_room);
asset->add("/data/room/24.room", t_room); asset->add("/../data/room/24.room", t_room);
asset->add("/data/room/25.room", t_room); asset->add("/../data/room/25.room", t_room);
asset->add("/data/room/26.room", t_room); asset->add("/../data/room/26.room", t_room);
asset->add("/data/room/27.room", t_room); asset->add("/../data/room/27.room", t_room);
asset->add("/data/room/28.room", t_room); asset->add("/../data/room/28.room", t_room);
asset->add("/data/room/29.room", t_room); asset->add("/../data/room/29.room", t_room);
asset->add("/data/room/30.room", t_room); asset->add("/../data/room/30.room", t_room);
asset->add("/data/room/31.room", t_room); asset->add("/../data/room/31.room", t_room);
asset->add("/data/room/32.room", t_room); asset->add("/../data/room/32.room", t_room);
asset->add("/data/room/33.room", t_room); asset->add("/../data/room/33.room", t_room);
asset->add("/data/room/34.room", t_room); asset->add("/../data/room/34.room", t_room);
asset->add("/data/room/35.room", t_room); asset->add("/../data/room/35.room", t_room);
asset->add("/data/room/36.room", t_room); asset->add("/../data/room/36.room", t_room);
asset->add("/data/room/37.room", t_room); asset->add("/../data/room/37.room", t_room);
asset->add("/data/room/38.room", t_room); asset->add("/../data/room/38.room", t_room);
asset->add("/data/room/39.room", t_room); asset->add("/../data/room/39.room", t_room);
asset->add("/data/room/40.room", t_room); asset->add("/../data/room/40.room", t_room);
asset->add("/data/room/41.room", t_room); asset->add("/../data/room/41.room", t_room);
asset->add("/data/room/42.room", t_room); asset->add("/../data/room/42.room", t_room);
asset->add("/data/room/43.room", t_room); asset->add("/../data/room/43.room", t_room);
asset->add("/data/room/44.room", t_room); asset->add("/../data/room/44.room", t_room);
asset->add("/data/room/45.room", t_room); asset->add("/../data/room/45.room", t_room);
asset->add("/data/room/46.room", t_room); asset->add("/../data/room/46.room", t_room);
asset->add("/data/room/47.room", t_room); asset->add("/../data/room/47.room", t_room);
asset->add("/data/room/48.room", t_room); asset->add("/../data/room/48.room", t_room);
asset->add("/data/room/49.room", t_room); asset->add("/../data/room/49.room", t_room);
asset->add("/data/room/50.room", t_room); asset->add("/../data/room/50.room", t_room);
asset->add("/data/room/51.room", t_room); asset->add("/../data/room/51.room", t_room);
asset->add("/data/room/52.room", t_room); asset->add("/../data/room/52.room", t_room);
asset->add("/data/room/53.room", t_room); asset->add("/../data/room/53.room", t_room);
asset->add("/data/room/54.room", t_room); asset->add("/../data/room/54.room", t_room);
asset->add("/data/room/55.room", t_room); asset->add("/../data/room/55.room", t_room);
asset->add("/data/room/56.room", t_room); asset->add("/../data/room/56.room", t_room);
asset->add("/data/room/57.room", t_room); asset->add("/../data/room/57.room", t_room);
asset->add("/data/room/58.room", t_room); asset->add("/../data/room/58.room", t_room);
asset->add("/data/room/59.room", t_room); asset->add("/../data/room/59.room", t_room);
asset->add("/data/room/60.room", t_room); asset->add("/../data/room/60.room", t_room);
asset->add("/data/room/01.tmx", t_room); asset->add("/../data/room/01.tmx", t_room);
asset->add("/data/room/02.tmx", t_room); asset->add("/../data/room/02.tmx", t_room);
asset->add("/data/room/03.tmx", t_room); asset->add("/../data/room/03.tmx", t_room);
asset->add("/data/room/04.tmx", t_room); asset->add("/../data/room/04.tmx", t_room);
asset->add("/data/room/05.tmx", t_room); asset->add("/../data/room/05.tmx", t_room);
asset->add("/data/room/06.tmx", t_room); asset->add("/../data/room/06.tmx", t_room);
asset->add("/data/room/07.tmx", t_room); asset->add("/../data/room/07.tmx", t_room);
asset->add("/data/room/08.tmx", t_room); asset->add("/../data/room/08.tmx", t_room);
asset->add("/data/room/09.tmx", t_room); asset->add("/../data/room/09.tmx", t_room);
asset->add("/data/room/10.tmx", t_room); asset->add("/../data/room/10.tmx", t_room);
asset->add("/data/room/11.tmx", t_room); asset->add("/../data/room/11.tmx", t_room);
asset->add("/data/room/12.tmx", t_room); asset->add("/../data/room/12.tmx", t_room);
asset->add("/data/room/13.tmx", t_room); asset->add("/../data/room/13.tmx", t_room);
asset->add("/data/room/14.tmx", t_room); asset->add("/../data/room/14.tmx", t_room);
asset->add("/data/room/15.tmx", t_room); asset->add("/../data/room/15.tmx", t_room);
asset->add("/data/room/16.tmx", t_room); asset->add("/../data/room/16.tmx", t_room);
asset->add("/data/room/17.tmx", t_room); asset->add("/../data/room/17.tmx", t_room);
asset->add("/data/room/18.tmx", t_room); asset->add("/../data/room/18.tmx", t_room);
asset->add("/data/room/19.tmx", t_room); asset->add("/../data/room/19.tmx", t_room);
asset->add("/data/room/20.tmx", t_room); asset->add("/../data/room/20.tmx", t_room);
asset->add("/data/room/21.tmx", t_room); asset->add("/../data/room/21.tmx", t_room);
asset->add("/data/room/22.tmx", t_room); asset->add("/../data/room/22.tmx", t_room);
asset->add("/data/room/23.tmx", t_room); asset->add("/../data/room/23.tmx", t_room);
asset->add("/data/room/24.tmx", t_room); asset->add("/../data/room/24.tmx", t_room);
asset->add("/data/room/25.tmx", t_room); asset->add("/../data/room/25.tmx", t_room);
asset->add("/data/room/26.tmx", t_room); asset->add("/../data/room/26.tmx", t_room);
asset->add("/data/room/27.tmx", t_room); asset->add("/../data/room/27.tmx", t_room);
asset->add("/data/room/28.tmx", t_room); asset->add("/../data/room/28.tmx", t_room);
asset->add("/data/room/29.tmx", t_room); asset->add("/../data/room/29.tmx", t_room);
asset->add("/data/room/30.tmx", t_room); asset->add("/../data/room/30.tmx", t_room);
asset->add("/data/room/31.tmx", t_room); asset->add("/../data/room/31.tmx", t_room);
asset->add("/data/room/32.tmx", t_room); asset->add("/../data/room/32.tmx", t_room);
asset->add("/data/room/33.tmx", t_room); asset->add("/../data/room/33.tmx", t_room);
asset->add("/data/room/34.tmx", t_room); asset->add("/../data/room/34.tmx", t_room);
asset->add("/data/room/35.tmx", t_room); asset->add("/../data/room/35.tmx", t_room);
asset->add("/data/room/36.tmx", t_room); asset->add("/../data/room/36.tmx", t_room);
asset->add("/data/room/37.tmx", t_room); asset->add("/../data/room/37.tmx", t_room);
asset->add("/data/room/38.tmx", t_room); asset->add("/../data/room/38.tmx", t_room);
asset->add("/data/room/39.tmx", t_room); asset->add("/../data/room/39.tmx", t_room);
asset->add("/data/room/40.tmx", t_room); asset->add("/../data/room/40.tmx", t_room);
asset->add("/data/room/41.tmx", t_room); asset->add("/../data/room/41.tmx", t_room);
asset->add("/data/room/42.tmx", t_room); asset->add("/../data/room/42.tmx", t_room);
asset->add("/data/room/43.tmx", t_room); asset->add("/../data/room/43.tmx", t_room);
asset->add("/data/room/44.tmx", t_room); asset->add("/../data/room/44.tmx", t_room);
asset->add("/data/room/45.tmx", t_room); asset->add("/../data/room/45.tmx", t_room);
asset->add("/data/room/46.tmx", t_room); asset->add("/../data/room/46.tmx", t_room);
asset->add("/data/room/47.tmx", t_room); asset->add("/../data/room/47.tmx", t_room);
asset->add("/data/room/48.tmx", t_room); asset->add("/../data/room/48.tmx", t_room);
asset->add("/data/room/49.tmx", t_room); asset->add("/../data/room/49.tmx", t_room);
asset->add("/data/room/50.tmx", t_room); asset->add("/../data/room/50.tmx", t_room);
asset->add("/data/room/51.tmx", t_room); asset->add("/../data/room/51.tmx", t_room);
asset->add("/data/room/52.tmx", t_room); asset->add("/../data/room/52.tmx", t_room);
asset->add("/data/room/53.tmx", t_room); asset->add("/../data/room/53.tmx", t_room);
asset->add("/data/room/54.tmx", t_room); asset->add("/../data/room/54.tmx", t_room);
asset->add("/data/room/55.tmx", t_room); asset->add("/../data/room/55.tmx", t_room);
asset->add("/data/room/56.tmx", t_room); asset->add("/../data/room/56.tmx", t_room);
asset->add("/data/room/57.tmx", t_room); asset->add("/../data/room/57.tmx", t_room);
asset->add("/data/room/58.tmx", t_room); asset->add("/../data/room/58.tmx", t_room);
asset->add("/data/room/59.tmx", t_room); asset->add("/../data/room/59.tmx", t_room);
asset->add("/data/room/60.tmx", t_room); asset->add("/../data/room/60.tmx", t_room);
asset->add("/data/tilesets/standard.png", t_bitmap); asset->add("/../data/tilesets/standard.png", t_bitmap);
asset->add("/data/enemies/paco.png", t_bitmap); asset->add("/../data/enemies/paco.png", t_bitmap);
asset->add("/data/enemies/paco.ani", t_data); asset->add("/../data/enemies/paco.ani", t_data);
asset->add("/data/enemies/chip.png", t_bitmap); asset->add("/../data/enemies/chip.png", t_bitmap);
asset->add("/data/enemies/chip.ani", t_data); asset->add("/../data/enemies/chip.ani", t_data);
asset->add("/data/enemies/wave.png", t_bitmap); asset->add("/../data/enemies/wave.png", t_bitmap);
asset->add("/data/enemies/wave.ani", t_data); asset->add("/../data/enemies/wave.ani", t_data);
asset->add("/data/enemies/wave_v.png", t_bitmap); asset->add("/../data/enemies/wave_v.png", t_bitmap);
asset->add("/data/enemies/wave_v.ani", t_data); asset->add("/../data/enemies/wave_v.ani", t_data);
asset->add("/data/enemies/sigmasua.png", t_bitmap); asset->add("/../data/enemies/sigmasua.png", t_bitmap);
asset->add("/data/enemies/sigmasua.ani", t_data); asset->add("/../data/enemies/sigmasua.ani", t_data);
asset->add("/data/enemies/diskette.png", t_bitmap); asset->add("/../data/enemies/diskette.png", t_bitmap);
asset->add("/data/enemies/diskette.ani", t_data); asset->add("/../data/enemies/diskette.ani", t_data);
asset->add("/data/enemies/bird.png", t_bitmap); asset->add("/../data/enemies/bird.png", t_bitmap);
asset->add("/data/enemies/bird.ani", t_data); asset->add("/../data/enemies/bird.ani", t_data);
asset->add("/data/enemies/bin.png", t_bitmap); asset->add("/../data/enemies/bin.png", t_bitmap);
asset->add("/data/enemies/bin.ani", t_data); asset->add("/../data/enemies/bin.ani", t_data);
asset->add("/data/enemies/qvoid.png", t_bitmap); asset->add("/../data/enemies/qvoid.png", t_bitmap);
asset->add("/data/enemies/qvoid.ani", t_data); asset->add("/../data/enemies/qvoid.ani", t_data);
asset->add("/data/enemies/batman.png", t_bitmap); asset->add("/../data/enemies/batman.png", t_bitmap);
asset->add("/data/enemies/batman.ani", t_data); asset->add("/../data/enemies/batman.ani", t_data);
asset->add("/data/enemies/tuno.png", t_bitmap); asset->add("/../data/enemies/tuno.png", t_bitmap);
asset->add("/data/enemies/tuno.ani", t_data); asset->add("/../data/enemies/tuno.ani", t_data);
asset->add("/data/enemies/matatunos.png", t_bitmap); asset->add("/../data/enemies/matatunos.png", t_bitmap);
asset->add("/data/enemies/matatunos.ani", t_data); asset->add("/../data/enemies/matatunos.ani", t_data);
asset->add("/data/enemies/abad.png", t_bitmap); asset->add("/../data/enemies/abad.png", t_bitmap);
asset->add("/data/enemies/abad.ani", t_data); asset->add("/../data/enemies/abad.ani", t_data);
asset->add("/data/enemies/jailbattle_human.png", t_bitmap); asset->add("/../data/enemies/jailbattle_human.png", t_bitmap);
asset->add("/data/enemies/jailbattle_human.ani", t_data); asset->add("/../data/enemies/jailbattle_human.ani", t_data);
asset->add("/data/enemies/jailbattle_alien.png", t_bitmap); asset->add("/../data/enemies/jailbattle_alien.png", t_bitmap);
asset->add("/data/enemies/jailbattle_alien.ani", t_data); asset->add("/../data/enemies/jailbattle_alien.ani", t_data);
asset->add("/data/enemies/jailer.png", t_bitmap); asset->add("/../data/enemies/jailer.png", t_bitmap);
asset->add("/data/enemies/jailer.ani", t_data); asset->add("/../data/enemies/jailer.ani", t_data);
asset->add("/data/enemies/jailer2.png", t_bitmap); asset->add("/../data/enemies/jailer2.png", t_bitmap);
asset->add("/data/enemies/jailer2.ani", t_data); asset->add("/../data/enemies/jailer2.ani", t_data);
asset->add("/data/enemies/jailer3.png", t_bitmap); asset->add("/../data/enemies/jailer3.png", t_bitmap);
asset->add("/data/enemies/jailer3.ani", t_data); asset->add("/../data/enemies/jailer3.ani", t_data);
asset->add("/data/enemies/printer.png", t_bitmap); asset->add("/../data/enemies/printer.png", t_bitmap);
asset->add("/data/enemies/printer.ani", t_data); asset->add("/../data/enemies/printer.ani", t_data);
asset->add("/data/enemies/code.png", t_bitmap); asset->add("/../data/enemies/code.png", t_bitmap);
asset->add("/data/enemies/code.ani", t_data); asset->add("/../data/enemies/code.ani", t_data);
asset->add("/data/enemies/demon.png", t_bitmap); asset->add("/../data/enemies/demon.png", t_bitmap);
asset->add("/data/enemies/demon.ani", t_data); asset->add("/../data/enemies/demon.ani", t_data);
asset->add("/data/enemies/dimallas.png", t_bitmap); asset->add("/../data/enemies/dimallas.png", t_bitmap);
asset->add("/data/enemies/dimallas.ani", t_data); asset->add("/../data/enemies/dimallas.ani", t_data);
asset->add("/data/enemies/dimallas_v.png", t_bitmap); asset->add("/../data/enemies/dimallas_v.png", t_bitmap);
asset->add("/data/enemies/dimallas_v.ani", t_data); asset->add("/../data/enemies/dimallas_v.ani", t_data);
asset->add("/data/enemies/heavy.png", t_bitmap); asset->add("/../data/enemies/heavy.png", t_bitmap);
asset->add("/data/enemies/heavy.ani", t_data); asset->add("/../data/enemies/heavy.ani", t_data);
asset->add("/data/enemies/spider.png", t_bitmap); asset->add("/../data/enemies/spider.png", t_bitmap);
asset->add("/data/enemies/spider.ani", t_data); asset->add("/../data/enemies/spider.ani", t_data);
asset->add("/data/enemies/macaronni_ted.png", t_bitmap); asset->add("/../data/enemies/macaronni_ted.png", t_bitmap);
asset->add("/data/enemies/macaronni_ted.ani", t_data); asset->add("/../data/enemies/macaronni_ted.ani", t_data);
asset->add("/data/enemies/mummy.png", t_bitmap); asset->add("/../data/enemies/mummy.png", t_bitmap);
asset->add("/data/enemies/mummy.ani", t_data); asset->add("/../data/enemies/mummy.ani", t_data);
asset->add("/data/enemies/sam.png", t_bitmap); asset->add("/../data/enemies/sam.png", t_bitmap);
asset->add("/data/enemies/sam.ani", t_data); asset->add("/../data/enemies/sam.ani", t_data);
asset->add("/data/player/player.png", t_bitmap); asset->add("/../data/player/player.png", t_bitmap);
asset->add("/data/player/player.ani", t_data); asset->add("/../data/player/player.ani", t_data);
asset->add("/data/items/items.png", t_bitmap); asset->add("/../data/items/items.png", t_bitmap);
asset->add("/data/music/title.ogg", t_music); asset->add("/../data/music/title.ogg", t_music);
asset->add("/data/music/game.ogg", t_music); asset->add("/../data/music/game.ogg", t_music);
asset->add("/data/music/loading_sound1.ogg", t_music); asset->add("/../data/music/loading_sound1.ogg", t_music);
asset->add("/data/music/loading_sound2.ogg", t_music); asset->add("/../data/music/loading_sound2.ogg", t_music);
asset->add("/data/music/loading_sound3.ogg", t_music); asset->add("/../data/music/loading_sound3.ogg", t_music);
asset->add("/data/sound/item.wav", t_sound); asset->add("/../data/sound/item.wav", t_sound);
asset->add("/data/sound/death.wav", t_sound); asset->add("/../data/sound/death.wav", t_sound);
asset->add("/data/sound/jump1.wav", t_sound); asset->add("/../data/sound/jump1.wav", t_sound);
asset->add("/data/sound/jump2.wav", t_sound); asset->add("/../data/sound/jump2.wav", t_sound);
asset->add("/data/sound/jump3.wav", t_sound); asset->add("/../data/sound/jump3.wav", t_sound);
asset->add("/data/sound/jump4.wav", t_sound); asset->add("/../data/sound/jump4.wav", t_sound);
asset->add("/data/sound/jump5.wav", t_sound); asset->add("/../data/sound/jump5.wav", t_sound);
asset->add("/data/sound/jump6.wav", t_sound); asset->add("/../data/sound/jump6.wav", t_sound);
asset->add("/data/sound/jump7.wav", t_sound); asset->add("/../data/sound/jump7.wav", t_sound);
asset->add("/data/sound/jump8.wav", t_sound); asset->add("/../data/sound/jump8.wav", t_sound);
asset->add("/data/sound/jump9.wav", t_sound); asset->add("/../data/sound/jump9.wav", t_sound);
asset->add("/data/sound/jump10.wav", t_sound); asset->add("/../data/sound/jump10.wav", t_sound);
asset->add("/data/sound/jump11.wav", t_sound); asset->add("/../data/sound/jump11.wav", t_sound);
asset->add("/data/sound/jump12.wav", t_sound); asset->add("/../data/sound/jump12.wav", t_sound);
asset->add("/data/sound/jump13.wav", t_sound); asset->add("/../data/sound/jump13.wav", t_sound);
asset->add("/data/sound/jump14.wav", t_sound); asset->add("/../data/sound/jump14.wav", t_sound);
asset->add("/data/sound/jump15.wav", t_sound); asset->add("/../data/sound/jump15.wav", t_sound);
asset->add("/data/sound/jump16.wav", t_sound); asset->add("/../data/sound/jump16.wav", t_sound);
asset->add("/data/sound/jump17.wav", t_sound); asset->add("/../data/sound/jump17.wav", t_sound);
asset->add("/data/sound/jump18.wav", t_sound); asset->add("/../data/sound/jump18.wav", t_sound);
asset->add("/data/sound/jump19.wav", t_sound); asset->add("/../data/sound/jump19.wav", t_sound);
asset->add("/data/sound/jump20.wav", t_sound); asset->add("/../data/sound/jump20.wav", t_sound);
asset->add("/data/sound/jump21.wav", t_sound); asset->add("/../data/sound/jump21.wav", t_sound);
asset->add("/data/sound/jump22.wav", t_sound); asset->add("/../data/sound/jump22.wav", t_sound);
asset->add("/data/sound/jump23.wav", t_sound); asset->add("/../data/sound/jump23.wav", t_sound);
asset->add("/data/sound/jump24.wav", t_sound); asset->add("/../data/sound/jump24.wav", t_sound);
asset->add("/data/logo/jailgames.png", t_bitmap); asset->add("/../data/logo/jailgames.png", t_bitmap);
asset->add("/data/logo/since_1998.png", t_bitmap); asset->add("/../data/logo/since_1998.png", t_bitmap);
asset->add("/data/logo/seagull.png", t_bitmap); asset->add("/../data/logo/seagull.png", t_bitmap);
asset->add("/data/title/loading_screen1.png", t_bitmap); asset->add("/../data/title/loading_screen1.png", t_bitmap);
asset->add("/data/title/loading_screen2.png", t_bitmap); asset->add("/../data/title/loading_screen2.png", t_bitmap);
return asset->check(); return asset->check();
} }

View File

@@ -177,7 +177,7 @@ void Intro::renderLoad()
{ {
rect.x = (i * 8) % 256; rect.x = (i * 8) % 256;
rect.y = (i / 32) * 8; rect.y = (i / 32) * 8;
sprite2->setPos(rect); sprite2->setRect(rect);
sprite2->setSpriteClip(rect); sprite2->setSpriteClip(rect);
sprite2->render(); sprite2->render();
} }

View File

@@ -1,15 +1,22 @@
#include "animatedsprite.h" #include "animatedsprite.h"
// Constructor // Constructor
AnimatedSprite::AnimatedSprite(LTexture *texture, SDL_Renderer *renderer, std::string file) AnimatedSprite::AnimatedSprite(LTexture *texture, SDL_Renderer *renderer, std::string file, std::vector<std::string> *buffer)
{ {
// Copia los punteros // Copia los punteros
setTexture(texture); setTexture(texture);
setRenderer(renderer); setRenderer(renderer);
// Carga las animaciones // Carga las animaciones
load(file); if (file != "")
{
loadFromFile(file);
}
else if (buffer)
{
loadFromVector(buffer);
}
// Inicializa variables // Inicializa variables
currentAnimation = 0; currentAnimation = 0;
@@ -47,37 +54,37 @@ int AnimatedSprite::getIndex(std::string name)
// Calcula el frame correspondiente a la animación // Calcula el frame correspondiente a la animación
void AnimatedSprite::animate() void AnimatedSprite::animate()
{ {
if (!enabled || animation[currentAnimation].speed == 0) if (!enabled || animation.at(currentAnimation).speed == 0)
{ {
return; return;
} }
// Calcula el frame actual a partir del contador // Calcula el frame actual a partir del contador
animation[currentAnimation].currentFrame = animation[currentAnimation].counter / animation[currentAnimation].speed; animation.at(currentAnimation).currentFrame = animation.at(currentAnimation).counter / animation.at(currentAnimation).speed;
// Si alcanza el final de la animación, reinicia el contador de la animación // Si alcanza el final de la animación, reinicia el contador de la animación
// en función de la variable loop y coloca el nuevo frame // en función de la variable loop y coloca el nuevo frame
if (animation[currentAnimation].currentFrame >= (int)animation[currentAnimation].frames.size()) if (animation.at(currentAnimation).currentFrame >= (int)animation.at(currentAnimation).frames.size())
{ {
if (animation[currentAnimation].loop == -1) if (animation.at(currentAnimation).loop == -1)
{ // Si no hay loop, deja el último frame { // Si no hay loop, deja el último frame
animation[currentAnimation].currentFrame = animation[currentAnimation].frames.size(); animation.at(currentAnimation).currentFrame = animation.at(currentAnimation).frames.size();
animation[currentAnimation].completed = true; animation.at(currentAnimation).completed = true;
} }
else else
{ // Si hay loop, vuelve al frame indicado { // Si hay loop, vuelve al frame indicado
animation[currentAnimation].counter = 0; animation.at(currentAnimation).counter = 0;
animation[currentAnimation].currentFrame = animation[currentAnimation].loop; animation.at(currentAnimation).currentFrame = animation.at(currentAnimation).loop;
} }
} }
// En caso contrario // En caso contrario
else else
{ {
// Escoge el frame correspondiente de la animación // Escoge el frame correspondiente de la animación
setSpriteClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]); setSpriteClip(animation.at(currentAnimation).frames.at(animation.at(currentAnimation).currentFrame));
// Incrementa el contador de la animacion // Incrementa el contador de la animacion
animation[currentAnimation].counter++; animation.at(currentAnimation).counter++;
} }
} }
@@ -85,56 +92,80 @@ void AnimatedSprite::animate()
void AnimatedSprite::setCurrentFrame(int num) void AnimatedSprite::setCurrentFrame(int num)
{ {
// Descarta valores fuera de rango // Descarta valores fuera de rango
if (num >= (int)animation[currentAnimation].frames.size()) if (num >= (int)animation.at(currentAnimation).frames.size())
{ {
num = 0; num = 0;
} }
// Cambia el valor de la variable // Cambia el valor de la variable
animation[currentAnimation].counter = animation[currentAnimation].speed * num; animation.at(currentAnimation).counter = animation.at(currentAnimation).speed * num;
// Escoge el frame correspondiente de la animación // Escoge el frame correspondiente de la animación
setSpriteClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]); setSpriteClip(animation.at(currentAnimation).frames.at(animation.at(currentAnimation).currentFrame));
} }
// Establece el valor del contador // Establece el valor del contador
void AnimatedSprite::setAnimationCounter(std::string name, int num) void AnimatedSprite::setAnimationCounter(std::string name, int num)
{ {
animation[getIndex(name)].counter = num; animation.at(getIndex(name)).counter = num;
} }
// Establece la velocidad de una animación // Establece la velocidad de una animación
void AnimatedSprite::setAnimationSpeed(std::string name, int speed) void AnimatedSprite::setAnimationSpeed(std::string name, int speed)
{ {
animation[getIndex(name)].counter = speed; animation.at(getIndex(name)).counter = speed;
}
// Establece la velocidad de una animación
void AnimatedSprite::setAnimationSpeed(int index, int speed)
{
animation.at(index).counter = speed;
} }
// Establece si la animación se reproduce en bucle // Establece si la animación se reproduce en bucle
void AnimatedSprite::setAnimationLoop(std::string name, int loop) void AnimatedSprite::setAnimationLoop(std::string name, int loop)
{ {
animation[getIndex(name)].loop = loop; animation.at(getIndex(name)).loop = loop;
}
// Establece si la animación se reproduce en bucle
void AnimatedSprite::setAnimationLoop(int index, int loop)
{
animation.at(index).loop = loop;
} }
// Establece el valor de la variable // Establece el valor de la variable
void AnimatedSprite::setAnimationCompleted(std::string name, bool value) void AnimatedSprite::setAnimationCompleted(std::string name, bool value)
{ {
animation[getIndex(name)].completed = value; animation.at(getIndex(name)).completed = value;
}
// OLD - Establece el valor de la variable
void AnimatedSprite::setAnimationCompleted(int index, bool value)
{
animation.at(index).completed = value;
} }
// Comprueba si ha terminado la animación // Comprueba si ha terminado la animación
bool AnimatedSprite::animationIsCompleted() bool AnimatedSprite::animationIsCompleted()
{ {
return animation[currentAnimation].completed; return animation.at(currentAnimation).completed;
} }
// Devuelve el rectangulo de una animación y frame concreto // Devuelve el rectangulo de una animación y frame concreto
SDL_Rect AnimatedSprite::getAnimationClip(std::string name, Uint8 index) SDL_Rect AnimatedSprite::getAnimationClip(std::string name, Uint8 index)
{ {
return animation[getIndex(name)].frames[index]; return animation.at(getIndex(name)).frames.at(index);
}
// Devuelve el rectangulo de una animación y frame concreto
SDL_Rect AnimatedSprite::getAnimationClip(int indexA, Uint8 indexF)
{
return animation.at(indexA).frames.at(indexF);
} }
// Carga la animación desde un fichero // Carga la animación desde un fichero
bool AnimatedSprite::load(std::string filePath) bool AnimatedSprite::loadFromFile(std::string filePath)
{ {
int framesPerRow = 0; int framesPerRow = 0;
int frameWidth = 0; int frameWidth = 0;
@@ -152,7 +183,7 @@ bool AnimatedSprite::load(std::string filePath)
if (file.good()) if (file.good())
{ {
// Procesa el fichero linea a linea // Procesa el fichero linea a linea
printf("Reading file %s\n", filename.c_str()); std::cout << "Loading animation from file: " << filePath.c_str() << std::endl;
while (std::getline(file, line)) while (std::getline(file, line))
{ {
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
@@ -177,14 +208,17 @@ bool AnimatedSprite::load(std::string filePath)
{ {
buffer.name = line.substr(pos + 1, line.length()); buffer.name = line.substr(pos + 1, line.length());
} }
else if (line.substr(0, pos) == "speed") else if (line.substr(0, pos) == "speed")
{ {
buffer.speed = std::stoi(line.substr(pos + 1, line.length())); buffer.speed = std::stoi(line.substr(pos + 1, line.length()));
} }
else if (line.substr(0, pos) == "loop") else if (line.substr(0, pos) == "loop")
{ {
buffer.loop = std::stoi(line.substr(pos + 1, line.length())); buffer.loop = std::stoi(line.substr(pos + 1, line.length()));
} }
else if (line.substr(0, pos) == "frames") else if (line.substr(0, pos) == "frames")
{ {
// Se introducen los valores separados por comas en un vector // Se introducen los valores separados por comas en un vector
@@ -200,6 +234,7 @@ bool AnimatedSprite::load(std::string filePath)
buffer.frames.push_back(rect); buffer.frames.push_back(rect);
} }
} }
else else
{ {
printf("Warning: file %s, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str()); printf("Warning: file %s, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str());
@@ -259,7 +294,6 @@ bool AnimatedSprite::load(std::string filePath)
} }
// Cierra el fichero // Cierra el fichero
printf("Closing file %s\n\n", filename.c_str());
file.close(); file.close();
} }
// El fichero no se puede abrir // El fichero no se puede abrir
@@ -270,7 +304,145 @@ bool AnimatedSprite::load(std::string filePath)
} }
// Pone un valor por defecto // Pone un valor por defecto
setPos({0, 0, frameWidth, frameHeight}); setRect({0, 0, frameWidth, frameHeight});
return success;
}
// Carga la animación desde un vector
bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
{
// Inicializa variables
int framesPerRow = 0;
int frameWidth = 0;
int frameHeight = 0;
int maxTiles = 0;
// Indicador de éxito en el proceso
bool success = true;
std::string line;
// Recorre todo el vector
int index = 0;
while (index < (int)source->size())
{
// Lee desde el vector
line = source->at(index);
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]")
{
t_animation buffer;
buffer.counter = 0;
buffer.currentFrame = 0;
buffer.completed = false;
do
{
// Aumenta el indice para leer la siguiente linea
index++;
line = source->at(index);
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (pos != (int)line.npos)
{
if (line.substr(0, pos) == "name")
{
buffer.name = line.substr(pos + 1, line.length());
}
else if (line.substr(0, pos) == "speed")
{
buffer.speed = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "loop")
{
buffer.loop = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frames")
{
// Se introducen los valores separados por comas en un vector
std::stringstream ss(line.substr(pos + 1, line.length()));
std::string tmp;
SDL_Rect rect = {0, 0, frameWidth, frameHeight};
while (getline(ss, tmp, ','))
{
// Comprueba que el tile no sea mayor que el maximo indice permitido
const int numTile = std::stoi(tmp) > maxTiles ? 0 : std::stoi(tmp);
rect.x = (numTile % framesPerRow) * frameWidth;
rect.y = (numTile / framesPerRow) * frameHeight;
buffer.frames.push_back(rect);
}
}
else
{
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl;
success = false;
}
}
} while (line != "[/animation]");
// Añade la animación al vector de animaciones
animation.push_back(buffer);
}
// En caso contrario se parsea el fichero para buscar las variables y los valores
else
{
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (pos != (int)line.npos)
{
if (line.substr(0, pos) == "framesPerRow")
{
framesPerRow = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frameWidth")
{
frameWidth = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frameHeight")
{
frameHeight = std::stoi(line.substr(pos + 1, line.length()));
}
else
{
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl;
success = false;
}
// Normaliza valores
if (framesPerRow == 0 && frameWidth > 0)
{
framesPerRow = texture->getWidth() / frameWidth;
}
if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0)
{
const int w = texture->getWidth() / frameWidth;
const int h = texture->getHeight() / frameHeight;
maxTiles = w * h;
}
}
}
// Una vez procesada la linea, aumenta el indice para pasar a la siguiente
index++;
}
// Pone un valor por defecto
setRect({0, 0, frameWidth, frameHeight});
return success; return success;
} }
@@ -282,9 +454,22 @@ void AnimatedSprite::setCurrentAnimation(std::string name)
if (currentAnimation != newAnimation) if (currentAnimation != newAnimation)
{ {
currentAnimation = newAnimation; currentAnimation = newAnimation;
animation[currentAnimation].currentFrame = 0; animation.at(currentAnimation).currentFrame = 0;
animation[currentAnimation].counter = 0; animation.at(currentAnimation).counter = 0;
animation[currentAnimation].completed = false; animation.at(currentAnimation).completed = false;
}
}
// Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(int index)
{
const int newAnimation = index;
if (currentAnimation != newAnimation)
{
currentAnimation = newAnimation;
animation.at(currentAnimation).currentFrame = 0;
animation.at(currentAnimation).counter = 0;
animation.at(currentAnimation).completed = false;
} }
} }
@@ -294,3 +479,26 @@ void AnimatedSprite::update()
animate(); animate();
MovingSprite::update(); MovingSprite::update();
} }
// Establece el rectangulo para un frame de una animación
void AnimatedSprite::setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h)
{
animation.at(index_animation).frames.push_back({x, y, w, h});
}
// OLD - Establece el contador para todas las animaciones
void AnimatedSprite::setAnimationCounter(int value)
{
for (auto &a : animation)
{
a.counter = value;
}
}
// Reinicia la animación
void AnimatedSprite::resetAnimation()
{
animation.at(currentAnimation).currentFrame = 0;
animation.at(currentAnimation).counter = 0;
animation.at(currentAnimation).completed = false;
}

View File

@@ -2,10 +2,11 @@
#include <SDL2/SDL.h> #include <SDL2/SDL.h>
#include "movingsprite.h" #include "movingsprite.h"
#include <fstream>
#include <sstream>
#include <string>
#include <vector> #include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
#ifndef ANIMATEDSPRITE_H #ifndef ANIMATEDSPRITE_H
#define ANIMATEDSPRITE_H #define ANIMATEDSPRITE_H
@@ -29,7 +30,7 @@ private:
public: public:
// Constructor // Constructor
AnimatedSprite(LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = ""); AnimatedSprite(LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = "", std::vector<std::string> *buffer = nullptr);
// Destructor // Destructor
~AnimatedSprite(); ~AnimatedSprite();
@@ -45,30 +46,47 @@ public:
// Establece la velocidad de una animación // Establece la velocidad de una animación
void setAnimationSpeed(std::string name, int speed); void setAnimationSpeed(std::string name, int speed);
void setAnimationSpeed(int index, int speed);
// Establece el frame al que vuelve la animación al finalizar // Establece el frame al que vuelve la animación al finalizar
void setAnimationLoop(std::string name, int loop); void setAnimationLoop(std::string name, int loop);
void setAnimationLoop(int index, int loop);
// Establece el valor de la variable // Establece el valor de la variable
void setAnimationCompleted(std::string name, bool value); void setAnimationCompleted(std::string name, bool value);
void setAnimationCompleted(int index, bool value);
// Comprueba si ha terminado la animación // Comprueba si ha terminado la animación
bool animationIsCompleted(); bool animationIsCompleted();
// Devuelve el rectangulo de una animación y frame concreto // Devuelve el rectangulo de una animación y frame concreto
SDL_Rect getAnimationClip(std::string name, Uint8 index); SDL_Rect getAnimationClip(std::string name, Uint8 index);
SDL_Rect getAnimationClip(int indexA, Uint8 indexF);
// Obtiene el indice de la animación a partir del nombre // Obtiene el indice de la animación a partir del nombre
int getIndex(std::string name); int getIndex(std::string name);
// Carga la animación desde un fichero // Carga la animación desde un fichero
bool load(std::string filePath); bool loadFromFile(std::string filePath);
// Carga la animación desde un vector
bool loadFromVector(std::vector<std::string> *source);
// Establece la animacion actual // Establece la animacion actual
void setCurrentAnimation(std::string name = "default"); void setCurrentAnimation(std::string name = "default");
void setCurrentAnimation(int index = 0);
// Actualiza las variables del objeto // Actualiza las variables del objeto
void update(); void update();
// OLD - Establece el rectangulo para un frame de una animación
void setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h);
// OLD - Establece el contador para todas las animaciones
void setAnimationCounter(int value);
// Reinicia la animación
void resetAnimation();
}; };
#endif #endif

View File

@@ -16,7 +16,7 @@ Asset::~Asset()
void Asset::add(std::string file, enum assetType type, bool required) void Asset::add(std::string file, enum assetType type, bool required)
{ {
item_t temp; item_t temp;
temp.file = executablePath + "/.." + file; temp.file = executablePath + file;
temp.type = type; temp.type = type;
temp.required = required; temp.required = required;
fileList.push_back(temp); fileList.push_back(temp);

View File

@@ -8,35 +8,35 @@ Input::Input(std::string file)
dbPath = file; dbPath = file;
// Inicializa las variables // Inicializa las variables
for (int i = 0; i < 17; ++i) keyBindings_t kb;
{ kb.scancode = 0;
keyBindings[i].scancode = 0; kb.active = false;
keyBindings[i].active = false; keyBindings.resize(17, kb);
gameControllerBindings[i].button = SDL_CONTROLLER_BUTTON_INVALID; GameControllerBindings_t gcb;
gameControllerBindings[i].active = false; gcb.button = SDL_CONTROLLER_BUTTON_INVALID;
} gcb.active = false;
gameControllerBindings.resize(17, gcb);
// Comprueba si hay un mando conectado
discoverGameController(); discoverGameController();
} }
// Destructor // Destructor
Input::~Input() Input::~Input()
{ {
for (int i = 0; i < numGamepads; ++i)
connectedControllers[i] = nullptr;
} }
// Asigna uno de los posibles inputs a una tecla del teclado // Asigna uno de los posibles inputs a una tecla del teclado
void Input::bindKey(Uint8 input, SDL_Scancode code) void Input::bindKey(Uint8 input, SDL_Scancode code)
{ {
keyBindings[input].scancode = code; keyBindings.at(input).scancode = code;
} }
// Asigna uno de los posibles inputs a un botón del mando // Asigna uno de los posibles inputs a un botón del mando
void Input::bindGameControllerButton(Uint8 input, SDL_GameControllerButton button) void Input::bindGameControllerButton(Uint8 input, SDL_GameControllerButton button)
{ {
gameControllerBindings[input].button = button; gameControllerBindings.at(input).button = button;
} }
// Comprueba si un input esta activo // Comprueba si un input esta activo
@@ -48,24 +48,28 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
if (device == INPUT_USE_ANY) if (device == INPUT_USE_ANY)
index = 0; index = 0;
if ((device == INPUT_USE_KEYBOARD) || (device == INPUT_USE_ANY)) if (device == INPUT_USE_KEYBOARD || device == INPUT_USE_ANY)
{ {
const Uint8 *mKeystates = SDL_GetKeyboardState(nullptr); const Uint8 *keyStates = SDL_GetKeyboardState(nullptr);
if (repeat) if (repeat)
{ {
if (mKeystates[keyBindings[input].scancode] != 0) if (keyStates[keyBindings.at(input).scancode] != 0)
{
successKeyboard = true; successKeyboard = true;
}
else else
{
successKeyboard = false; successKeyboard = false;
}
} }
else else
{ {
if (!keyBindings[input].active) if (!keyBindings.at(input).active)
{ {
if (mKeystates[keyBindings[input].scancode] != 0) if (keyStates[keyBindings.at(input).scancode] != 0)
{ {
keyBindings[input].active = true; keyBindings.at(input).active = true;
successKeyboard = true; successKeyboard = true;
} }
else else
@@ -75,9 +79,9 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
} }
else else
{ {
if (mKeystates[keyBindings[input].scancode] == 0) if (keyStates[keyBindings.at(input).scancode] == 0)
{ {
keyBindings[input].active = false; keyBindings.at(input).active = false;
successKeyboard = false; successKeyboard = false;
} }
else else
@@ -93,18 +97,22 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
{ {
if (repeat) if (repeat)
{ {
if (SDL_GameControllerGetButton(connectedControllers[index], gameControllerBindings[input].button) != 0) if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings.at(input).button) != 0)
{
successGameController = true; successGameController = true;
}
else else
{
successGameController = false; successGameController = false;
}
} }
else else
{ {
if (!gameControllerBindings[input].active) if (!gameControllerBindings.at(input).active)
{ {
if (SDL_GameControllerGetButton(connectedControllers[index], gameControllerBindings[input].button) != 0) if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings.at(input).button) != 0)
{ {
gameControllerBindings[input].active = true; gameControllerBindings.at(input).active = true;
successGameController = true; successGameController = true;
} }
else else
@@ -114,9 +122,9 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
} }
else else
{ {
if (SDL_GameControllerGetButton(connectedControllers[index], gameControllerBindings[input].button) == 0) if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings.at(input).button) == 0)
{ {
gameControllerBindings[input].active = false; gameControllerBindings.at(input).active = false;
successGameController = false; successGameController = false;
} }
else else
@@ -133,38 +141,39 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index)
// Comprueba si hay almenos un input activo // Comprueba si hay almenos un input activo
bool Input::checkAnyInput(int device, int index) bool Input::checkAnyInput(int device, int index)
{ {
bool successKeyboard = false;
bool successGameController = false;
if (device == INPUT_USE_ANY) if (device == INPUT_USE_ANY)
{
index = 0; index = 0;
}
if ((device == INPUT_USE_KEYBOARD) || (device == INPUT_USE_ANY)) if (device == INPUT_USE_KEYBOARD || device == INPUT_USE_ANY)
{ {
const Uint8 *mKeystates = SDL_GetKeyboardState(nullptr); const Uint8 *mKeystates = SDL_GetKeyboardState(nullptr);
for (int i = 0; i < 17; ++i) for (int i = 0; i < (int)keyBindings.size(); ++i)
{ {
if (mKeystates[keyBindings[i].scancode] != 0) if (mKeystates[keyBindings.at(i).scancode] != 0)
{ {
successKeyboard |= true; return true;
} }
} }
} }
if (gameControllerFound()) if (gameControllerFound())
if ((device == INPUT_USE_GAMECONTROLLER) || (device == INPUT_USE_ANY)) {
if (device == INPUT_USE_GAMECONTROLLER || device == INPUT_USE_ANY)
{ {
for (int i = 0; i < 17; ++i) for (int i = 0; i < (int)gameControllerBindings.size(); ++i)
{ {
if (SDL_GameControllerGetButton(connectedControllers[index], gameControllerBindings[i].button) != 0) if (SDL_GameControllerGetButton(connectedControllers.at(index), gameControllerBindings.at(i).button) != 0)
{ {
successGameController |= true; return true;
} }
} }
} }
}
return (successKeyboard || successGameController); return false;
} }
// Comprueba si hay un mando conectado // Comprueba si hay un mando conectado
@@ -173,34 +182,42 @@ bool Input::discoverGameController()
bool found = false; bool found = false;
if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) != 1) if (SDL_WasInit(SDL_INIT_GAMECONTROLLER) != 1)
{
SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER); SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);
}
if (SDL_GameControllerAddMappingsFromFile(dbPath.c_str()) < 0) if (SDL_GameControllerAddMappingsFromFile(dbPath.c_str()) < 0)
{
printf("Error, could not load %s file: %s\n", dbPath.c_str(), SDL_GetError()); printf("Error, could not load %s file: %s\n", dbPath.c_str(), SDL_GetError());
}
int nJoysticks = SDL_NumJoysticks(); const int nJoysticks = SDL_NumJoysticks();
numGamepads = 0; numGamepads = 0;
// Cuenta el numero de mandos // Cuenta el numero de mandos
for (int i = 0; i < nJoysticks; ++i) for (int i = 0; i < nJoysticks; ++i)
{
if (SDL_IsGameController(i)) if (SDL_IsGameController(i))
{
numGamepads++; numGamepads++;
}
}
printf("** Checking for game controllers ...\n"); printf("\nChecking for game controllers...\n");
printf("%i joysticks found, %i are gamepads\n\n", nJoysticks, numGamepads); printf("%i joysticks found, %i are gamepads\n", nJoysticks, numGamepads);
if (numGamepads > 0) if (numGamepads > 0)
{ {
found = true; found = true;
for (int i = 0; i < numGamepads; ++i) for (int i = 0; i < numGamepads; i++)
{ {
// Abre el mando y lo añade a la lista // Abre el mando y lo añade a la lista
SDL_GameController *pad = SDL_GameControllerOpen(i); SDL_GameController *pad = SDL_GameControllerOpen(i);
if (SDL_GameControllerGetAttached(pad) == 1) if (SDL_GameControllerGetAttached(pad) == 1)
{ {
connectedControllers.push_back(pad); connectedControllers.push_back(pad);
std::string separator(" #"); const std::string separator(" #");
std::string name = SDL_GameControllerNameForIndex(i); std::string name = SDL_GameControllerNameForIndex(i);
name.resize(25); name.resize(25);
name = name + separator + std::to_string(i); name = name + separator + std::to_string(i);
@@ -208,10 +225,11 @@ bool Input::discoverGameController()
controllerNames.push_back(name); controllerNames.push_back(name);
} }
else else
{
std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl; std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl;
}
} }
// mGameController = connectedControllers[0];
SDL_GameControllerEventState(SDL_ENABLE); SDL_GameControllerEventState(SDL_ENABLE);
} }
@@ -222,18 +240,26 @@ bool Input::discoverGameController()
bool Input::gameControllerFound() bool Input::gameControllerFound()
{ {
if (numGamepads > 0) if (numGamepads > 0)
{
return true; return true;
}
else else
{
return false; return false;
}
} }
// Obten el nombre de un mando de juego // Obten el nombre de un mando de juego
std::string Input::getControllerName(int index) std::string Input::getControllerName(int index)
{ {
if (numGamepads > 0) if (numGamepads > 0)
return controllerNames[index]; {
return controllerNames.at(index);
}
else else
{
return ""; return "";
}
} }
// Obten el numero de mandos conectados // Obten el numero de mandos conectados

View File

@@ -48,12 +48,12 @@ private:
bool active; // Indica si está activo bool active; // Indica si está activo
}; };
keyBindings_t keyBindings[17]; // Vector con las teclas asociadas a los inputs predefinidos std::vector<keyBindings_t> keyBindings; // Vector con las teclas asociadas a los inputs predefinidos
GameControllerBindings_t gameControllerBindings[17]; // Vector con las teclas asociadas a los inputs predefinidos std::vector<GameControllerBindings_t> gameControllerBindings; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<SDL_GameController *> connectedControllers; // Vector con todos los mandos conectados std::vector<SDL_GameController *> connectedControllers; // Vector con todos los mandos conectados
std::vector<std::string> controllerNames; // Vector con los nombres de los mandos std::vector<std::string> controllerNames; // Vector con los nombres de los mandos
int numGamepads; // Numero de mandos conectados int numGamepads; // Numero de mandos conectados
std::string dbPath; // Ruta al archivo gamecontrollerdb.txt std::string dbPath; // Ruta al archivo gamecontrollerdb.txt
// Comprueba si hay un mando conectado // Comprueba si hay un mando conectado
bool discoverGameController(); bool discoverGameController();
@@ -75,7 +75,7 @@ public:
bool checkInput(Uint8 input, bool repeat, int device = INPUT_USE_ANY, int index = 0); bool checkInput(Uint8 input, bool repeat, int device = INPUT_USE_ANY, int index = 0);
// Comprueba si hay almenos un input activo // Comprueba si hay almenos un input activo
bool checkAnyInput(int device = INPUT_USE_ANY, int index = 0); bool checkAnyInput(int device, int index);
// Comprueba si hay algun mando conectado // Comprueba si hay algun mando conectado
bool gameControllerFound(); bool gameControllerFound();

View File

@@ -32,6 +32,7 @@ LTexture::~LTexture()
// Carga una imagen desde un fichero // Carga una imagen desde un fichero
bool LTexture::loadFromFile(std::string path, SDL_Renderer *renderer) bool LTexture::loadFromFile(std::string path, SDL_Renderer *renderer)
{ {
const std::string filename = path.substr(path.find_last_of("\\/") + 1);
int req_format = STBI_rgb_alpha; int req_format = STBI_rgb_alpha;
int width, height, orig_format; int width, height, orig_format;
unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format); unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format);
@@ -40,6 +41,10 @@ bool LTexture::loadFromFile(std::string path, SDL_Renderer *renderer)
SDL_Log("Loading image failed: %s", stbi_failure_reason()); SDL_Log("Loading image failed: %s", stbi_failure_reason());
exit(1); exit(1);
} }
else
{
printf("Image loaded: %s\n", filename.c_str());
}
int depth, pitch; int depth, pitch;
Uint32 pixel_format; Uint32 pixel_format;
@@ -144,7 +149,7 @@ void LTexture::setAlpha(Uint8 alpha)
// Renderiza la textura en un punto específico // Renderiza la textura en un punto específico
void LTexture::render(SDL_Renderer *renderer, int x, int y, SDL_Rect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip) void LTexture::render(SDL_Renderer *renderer, int x, int y, SDL_Rect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip)
{ {
// Establece el destini de renderizado en la pantalla // Establece el destino de renderizado en la pantalla
SDL_Rect renderQuad = {x, y, width, height}; SDL_Rect renderQuad = {x, y, width, height};
// Obtiene las dimesiones del clip de renderizado // Obtiene las dimesiones del clip de renderizado

View File

@@ -4,20 +4,63 @@
// Constructor // Constructor
Menu::Menu(SDL_Renderer *renderer, Asset *asset, Input *input, std::string file) Menu::Menu(SDL_Renderer *renderer, Asset *asset, Input *input, std::string file)
{ {
// Copia punteros
this->renderer = renderer; this->renderer = renderer;
this->asset = asset; this->asset = asset;
this->input = input; this->input = input;
// Inicializa punteros
soundMove = nullptr; soundMove = nullptr;
soundAccept = nullptr; soundAccept = nullptr;
soundCancel = nullptr; soundCancel = nullptr;
init(); // Inicializa variables
name = "";
selector.index = 0;
itemSelected = MENU_NO_OPTION;
x = 0;
y = 0;
w = 0;
rectBG.rect = {0, 0, 0, 0};
rectBG.color = {0, 0, 0};
rectBG.a = 0;
backgroundType = MENU_BACKGROUND_SOLID;
isCenteredOnX = false;
isCenteredOnY = false;
areElementsCenteredOnX = false;
centerX = 0;
centerY = 0;
widestItem = 0;
colorGreyed = {128, 128, 128};
defaultActionWhenCancel = 0;
font_png = "";
font_txt = "";
// Selector
selector.originY = 0;
selector.targetY = 0;
selector.despY = 0;
selector.originH = 0;
selector.targetH = 0;
selector.incH = 0;
selector.y = 0.0f;
selector.h = 0.0f;
selector.numJumps = 8;
selector.moving = false;
selector.resizing = false;
selector.rect = {0, 0, 0, 0};
selector.color = {0, 0, 0};
selector.itemColor = {0, 0, 0};
selector.a = 255;
// Inicializa las variables desde un fichero
if (file != "") if (file != "")
{ {
load(file); load(file);
} }
reorganize();
// Deja el cursor en el primer elemento
reset();
} }
Menu::~Menu() Menu::~Menu()
@@ -56,7 +99,7 @@ bool Menu::load(std::string file_path)
// Indica si se ha creado ya el objeto de texto // Indica si se ha creado ya el objeto de texto
bool textAllocated = false; bool textAllocated = false;
std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1); const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
std::string line; std::string line;
std::ifstream file(file_path); std::ifstream file(file_path);
@@ -78,7 +121,7 @@ bool Menu::load(std::string file_path)
do do
{ {
// Lee la siguiente linea
std::getline(file, line); std::getline(file, line);
// Encuentra la posición del caracter '=' // Encuentra la posición del caracter '='
@@ -118,7 +161,7 @@ bool Menu::load(std::string file_path)
} }
// Cierra el fichero // Cierra el fichero
printf("Closing file %s\n\n", filename.c_str()); printf("Closing file %s\n", filename.c_str());
file.close(); file.close();
} }
// El fichero no se puede abrir // El fichero no se puede abrir
@@ -165,6 +208,7 @@ bool Menu::setItem(item_t *item, std::string var, std::string value)
else if ((var == "") || (var == "[/item]")) else if ((var == "") || (var == "[/item]"))
{ {
} }
else else
{ {
success = false; success = false;
@@ -309,48 +353,6 @@ bool Menu::setVars(std::string var, std::string value)
return success; return success;
} }
// Inicializa las variables
void Menu::init()
{
// Inicia variables
name = "";
selector.index = 0;
itemSelected = MENU_NO_OPTION;
x = 0;
y = 0;
rectBG.rect = {0, 0, 0, 0};
rectBG.color = {0, 0, 0};
rectBG.a = 0;
backgroundType = MENU_BACKGROUND_SOLID;
isCenteredOnX = false;
isCenteredOnY = false;
areElementsCenteredOnX = false;
centerX = 0;
centerY = 0;
widestItem = 0;
colorGreyed = {128, 128, 128};
defaultActionWhenCancel = 0;
font_png = "";
font_txt = "";
// Selector
selector.originY = 0;
selector.targetY = 0;
selector.despY = 0;
selector.originH = 0;
selector.targetH = 0;
selector.incH = 0;
selector.y = 0.0f;
selector.h = 0.0f;
selector.numJumps = 8;
selector.moving = false;
selector.resizing = false;
selector.rect = {0, 0, 0, 0};
selector.color = {0, 0, 0};
selector.itemColor = {0, 0, 0};
selector.a = 255;
}
// Carga los ficheros de audio // Carga los ficheros de audio
void Menu::loadAudioFile(std::string file, int sound) void Menu::loadAudioFile(std::string file, int sound)
{ {
@@ -403,7 +405,8 @@ void Menu::updateSelector()
selector.moving = false; selector.moving = false;
} }
} }
if (selector.despY < 0) // Va hacia arriba
else if (selector.despY < 0) // Va hacia arriba
{ {
if (selector.y < selector.targetY) // Ha llegado al destino if (selector.y < selector.targetY) // Ha llegado al destino
{ {
@@ -431,7 +434,8 @@ void Menu::updateSelector()
selector.resizing = false; selector.resizing = false;
} }
} }
if (selector.incH < 0) // Decrece
else if (selector.incH < 0) // Decrece
{ {
if (selector.h < selector.targetH) // Ha llegado al destino if (selector.h < selector.targetH) // Ha llegado al destino
{ {
@@ -454,7 +458,7 @@ void Menu::setSelectorPos(int index)
if (index < (int)item.size()) if (index < (int)item.size())
{ {
selector.index = index; selector.index = index;
selector.rect.y = selector.y = selector.originY = selector.targetY = item[selector.index].rect.y; selector.rect.y = selector.y = selector.originY = selector.targetY = item.at(selector.index).rect.y;
selector.rect.w = rectBG.rect.w; selector.rect.w = rectBG.rect.w;
selector.rect.x = rectBG.rect.x; selector.rect.x = rectBG.rect.x;
selector.originH = selector.targetH = selector.rect.h = getSelectorHeight(selector.index); selector.originH = selector.targetH = selector.rect.h = getSelectorHeight(selector.index);
@@ -482,10 +486,17 @@ void Menu::reset()
{ {
itemSelected = MENU_NO_OPTION; itemSelected = MENU_NO_OPTION;
selector.index = 0; selector.index = 0;
selector.originY = selector.targetY = selector.y = item[0].rect.y; selector.originY = selector.targetY = selector.y = item.at(0).rect.y;
selector.originH = selector.targetH = item[0].rect.h; selector.originH = selector.targetH = item.at(0).rect.h;
selector.moving = false; selector.moving = false;
selector.resizing = false; selector.resizing = false;
// Si el primer elemento no es seleccionable, incrementa el selector
if (!item.at(selector.index).selectable)
{
increaseSelectorIndex();
setSelectorPos(selector.index);
}
} }
// Actualiza el menu para recolocarlo correctamente y establecer el tamaño // Actualiza el menu para recolocarlo correctamente y establecer el tamaño
@@ -513,18 +524,18 @@ void Menu::reorganize()
bool Menu::increaseSelectorIndex() bool Menu::increaseSelectorIndex()
{ {
// Obten las coordenadas del elemento actual // Obten las coordenadas del elemento actual
selector.y = selector.originY = item[selector.index].rect.y; selector.y = selector.originY = item.at(selector.index).rect.y;
selector.h = selector.originH = getSelectorHeight(selector.index); selector.h = selector.originH = getSelectorHeight(selector.index);
// Calcula cual es el siguiente elemento // Calcula cual es el siguiente elemento
++selector.index %= item.size(); ++selector.index %= item.size();
while (!item[selector.index].selectable) while (!item.at(selector.index).selectable)
{ {
++selector.index %= item.size(); ++selector.index %= item.size();
} }
// Establece las coordenadas y altura de destino // Establece las coordenadas y altura de destino
selector.targetY = item[selector.index].rect.y; selector.targetY = item.at(selector.index).rect.y;
selector.despY = (selector.targetY - selector.originY) / selector.numJumps; selector.despY = (selector.targetY - selector.originY) / selector.numJumps;
selector.targetH = getSelectorHeight(selector.index); selector.targetH = getSelectorHeight(selector.index);
@@ -543,24 +554,24 @@ bool Menu::increaseSelectorIndex()
bool Menu::decreaseSelectorIndex() bool Menu::decreaseSelectorIndex()
{ {
// Obten las coordenadas del elemento actual // Obten las coordenadas del elemento actual
selector.y = selector.originY = item[selector.index].rect.y; selector.y = selector.originY = item.at(selector.index).rect.y;
selector.h = selector.originH = getSelectorHeight(selector.index); selector.h = selector.originH = getSelectorHeight(selector.index);
// Calcula cual es el siguiente elemento // Calcula cual es el siguiente elemento
if (selector.index == 0) if (selector.index == 0)
{ {
selector.index = item.size(); selector.index = item.size() - 1;
} }
else else
{ {
selector.index--; selector.index--;
} }
while (!item[selector.index].selectable) while (!item.at(selector.index).selectable)
{ {
if (selector.index == 0) if (selector.index == 0)
{ {
selector.index = item.size(); selector.index = item.size() - 1;
} }
else else
{ {
@@ -569,7 +580,7 @@ bool Menu::decreaseSelectorIndex()
} }
// Establece las coordenadas y altura de destino // Establece las coordenadas y altura de destino
selector.targetY = item[selector.index].rect.y; selector.targetY = item.at(selector.index).rect.y;
selector.despY = (selector.targetY - selector.originY) / selector.numJumps; selector.despY = (selector.targetY - selector.originY) / selector.numJumps;
selector.targetH = getSelectorHeight(selector.index); selector.targetH = getSelectorHeight(selector.index);
@@ -603,8 +614,6 @@ void Menu::render()
// Renderiza el rectangulo del selector // Renderiza el rectangulo del selector
const SDL_Rect temp = {selector.rect.x, selector.rect.y - 1, selector.rect.w, selector.rect.h + 1}; const SDL_Rect temp = {selector.rect.x, selector.rect.y - 1, selector.rect.w, selector.rect.h + 1};
// temp.y--;
// temp.h++;
SDL_SetRenderDrawColor(renderer, selector.color.r, selector.color.g, selector.color.b, selector.a); SDL_SetRenderDrawColor(renderer, selector.color.r, selector.color.g, selector.color.b, selector.a);
SDL_RenderFillRect(renderer, &temp); SDL_RenderFillRect(renderer, &temp);
@@ -621,40 +630,74 @@ void Menu::render()
if (i == selector.index) if (i == selector.index)
{ {
const color_t color = {selector.itemColor.r, selector.itemColor.g, selector.itemColor.b}; const color_t color = {selector.itemColor.r, selector.itemColor.g, selector.itemColor.b};
text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, color); text->writeColored(item.at(i).rect.x, item.at(i).rect.y, item.at(i).label, color);
} }
else if (item[i].selectable)
else if (item.at(i).selectable)
{ {
text->write(item[i].rect.x, item[i].rect.y, item[i].label); text->write(item.at(i).rect.x, item.at(i).rect.y, item.at(i).label);
} }
else if (item[i].greyed)
else if (item.at(i).greyed)
{ {
text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, colorGreyed); text->writeColored(item.at(i).rect.x, item.at(i).rect.y, item.at(i).label, colorGreyed);
} }
else else
// No seleccionable { // No seleccionable
{ if ((item.at(i).linkedUp) && (i == selector.index + 1))
if ((item[i].linkedUp) && (i == selector.index + 1))
{ {
const color_t color = {selector.itemColor.r, selector.itemColor.g, selector.itemColor.b}; const color_t color = {selector.itemColor.r, selector.itemColor.g, selector.itemColor.b};
text->writeColored(item[i].rect.x, item[i].rect.y, item[i].label, color); text->writeColored(item.at(i).rect.x, item.at(i).rect.y, item.at(i).label, color);
} }
else // No enlazado con el de arriba else // No enlazado con el de arriba
{ {
text->write(item[i].rect.x, item[i].rect.y, item[i].label); text->write(item.at(i).rect.x, item.at(i).rect.y, item.at(i).label);
} }
} }
} }
} }
// Establece el rectangulo de fondo del menu y el selector // Establece el rectangulo de fondo del menu y el selector
void Menu::setRectSize() void Menu::setRectSize(int w, int h)
{ {
rectBG.rect.w = findWidth() + text->getCharacterSize(); // Establece el ancho
rectBG.rect.h = findHeight() + text->getCharacterSize(); if (w == 0)
{ // Si no se pasa un valor, se busca si hay uno prefijado
if (this->w == 0)
{ // Si no hay prefijado, coge el item mas ancho
rectBG.rect.w = findWidth() + text->getCharacterSize();
}
else
{ // Si hay prefijado, coge ese
rectBG.rect.w = this->w;
}
}
else
{ // Si se pasa un valor, se usa y se prefija
rectBG.rect.w = w;
this->w = w;
}
// Establece el alto
if (h == 0)
{ // Si no se pasa un valor, se busca de manera automatica
rectBG.rect.h = findHeight() + text->getCharacterSize();
}
else
{ // Si se pasa un valor, se aplica
rectBG.rect.h = h;
}
// La posición X es la del menú menos medio caracter // La posición X es la del menú menos medio caracter
rectBG.rect.x = x - (text->getCharacterSize() / 2); if (this->w != 0)
{ // Si el ancho esta prefijado, la x coinccide
rectBG.rect.x = x;
}
else
{ // Si el ancho es automatico, se le da un poco de margen
rectBG.rect.x = x - (text->getCharacterSize() / 2);
}
// La posición Y es la del menu menos la altura de medio caracter // La posición Y es la del menu menos la altura de medio caracter
rectBG.rect.y = y - (text->getCharacterSize() / 2); rectBG.rect.y = y - (text->getCharacterSize() / 2);
@@ -687,10 +730,28 @@ void Menu::setSelectorTextColor(color_t color)
void Menu::centerMenuOnX(int value) void Menu::centerMenuOnX(int value)
{ {
isCenteredOnX = true; isCenteredOnX = true;
centerX = value; if (value != 0)
{
centerX = value;
}
else if (centerX == 0)
{
return;
}
// Establece la nueva posición centrada en funcion del elemento más ancho // Establece la nueva posición centrada en funcion del elemento más ancho o del ancho fijo del menu
x = (value) - (findWidth() / 2); if (w != 0)
{ // Si se ha definido un ancho fijo
x = (centerX) - (w / 2);
}
else
{ // Si se actua en función del elemento más ancho
x = (centerX) - (findWidth() / 2);
}
// Actualiza el rectangulo de fondo y del selector
rectBG.rect.x = x;
selector.rect.x = x;
// Reposiciona los elementos del menu // Reposiciona los elementos del menu
for (auto &i : item) for (auto &i : item)
@@ -700,6 +761,12 @@ void Menu::centerMenuOnX(int value)
// Recalcula el rectangulo de fondo // Recalcula el rectangulo de fondo
setRectSize(); setRectSize();
// Vuelve a centrar los elementos si fuera el caso
if (areElementsCenteredOnX)
{
centerMenuElementsOnX();
}
} }
// Centra el menu respecto un punto en el eje Y // Centra el menu respecto un punto en el eje Y
@@ -733,14 +800,13 @@ void Menu::centerMenuElementsOnX()
void Menu::addItem(std::string text, int hPaddingDown, bool selectable, bool greyed, bool linkedDown) void Menu::addItem(std::string text, int hPaddingDown, bool selectable, bool greyed, bool linkedDown)
{ {
item_t temp; item_t temp;
// Si es el primer item coge la posición en el eje Y del propio menu
if (item.size() == 0) if (item.empty())
{ { // Si es el primer item coge la posición en el eje Y del propio menu
temp.rect.y = y; temp.rect.y = y;
} }
else else
// En caso contrario, coge la posición en el eje Y a partir del elemento anterior { // En caso contrario, coge la posición en el eje Y a partir del último elemento
{
temp.rect.y = item.back().rect.y + item.back().rect.h + item.back().hPaddingDown; temp.rect.y = item.back().rect.y + item.back().rect.h + item.back().hPaddingDown;
} }
@@ -751,13 +817,14 @@ void Menu::addItem(std::string text, int hPaddingDown, bool selectable, bool gre
temp.linkedDown = linkedDown; temp.linkedDown = linkedDown;
item.push_back(temp); item.push_back(temp);
setItemCaption(item.size() - 1, text); setItemCaption(item.size() - 1, text);
if (item.size() > 0) if (item.size() > 1)
{ {
if (item[item.size() - 1].linkedDown) if (item.at(item.size() - 2).linkedDown)
{ {
item[item.size()].linkedUp = true; item.back().linkedUp = true;
} }
} }
@@ -768,13 +835,10 @@ void Menu::addItem(std::string text, int hPaddingDown, bool selectable, bool gre
// Cambia el texto de un item // Cambia el texto de un item
void Menu::setItemCaption(int index, std::string text) void Menu::setItemCaption(int index, std::string text)
{ {
item[index].label = text; item.at(index).label = text;
item[index].rect.w = this->text->lenght(item[index].label); item.at(index).rect.w = this->text->lenght(item.at(index).label);
item[index].rect.h = this->text->getCharacterSize(); item.at(index).rect.h = this->text->getCharacterSize();
reorganize(); reorganize();
const std::string texto = item[index].label + ":" + std::to_string(item[index].rect.w);
printf("Adding menu item -> %s\n", texto.c_str());
} }
// Establece el indice del itemm que se usará por defecto al cancelar el menu // Establece el indice del itemm que se usará por defecto al cancelar el menu
@@ -850,41 +914,69 @@ int Menu::findHeight()
// Recoloca los elementos del menu en el eje Y // Recoloca los elementos del menu en el eje Y
void Menu::replaceElementsOnY() void Menu::replaceElementsOnY()
{ {
item[0].rect.y = y; item.at(0).rect.y = y;
for (int i = 1; i < (int)item.size(); i++) for (int i = 1; i < (int)item.size(); i++)
{ {
item[i].rect.y = item[i - 1].rect.y + item[i - 1].rect.h + item[i - 1].hPaddingDown; item.at(i).rect.y = item.at(i - 1).rect.y + item.at(i - 1).rect.h + item.at(i - 1).hPaddingDown;
} }
} }
// Establece el estado seleccionable de un item // Establece el estado seleccionable de un item
void Menu::setSelectable(int index, bool value) void Menu::setSelectable(int index, bool value)
{ {
item[index].selectable = value; item.at(index).selectable = value;
} }
// Establece el estado agrisado de un item // Establece el estado agrisado de un item
void Menu::setGreyed(int index, bool value) void Menu::setGreyed(int index, bool value)
{ {
item[index].greyed = value; item.at(index).greyed = value;
} }
// Establece el estado de enlace de un item // Establece el estado de enlace de un item
void Menu::setLinkedDown(int index, bool value) void Menu::setLinkedDown(int index, bool value)
{ {
item[index].linkedDown = value; item.at(index).linkedDown = value;
} }
// Calcula la altura del selector // Calcula la altura del selector
int Menu::getSelectorHeight(int value) int Menu::getSelectorHeight(int value)
{ {
if (item[value].linkedDown) if (item.at(value).linkedDown)
{ {
return item[value].rect.h + item[value].hPaddingDown + item[value + 1].rect.h; return item.at(value).rect.h + item.at(value).hPaddingDown + item.at(value + 1).rect.h;
} }
else else
{ {
return item[value].rect.h; return item.at(value).rect.h;
}
}
// Establece el nombre del menu
void Menu::setName(std::string name)
{
this->name = name;
}
// Establece la posición del menu
void Menu::setPos(int x, int y)
{
this->x = x;
this->y = y;
}
// Establece el tipo de fondo del menu
void Menu::setBackgroundType(int value)
{
backgroundType = value;
}
// Establece la fuente de texto que se utilizará
void Menu::setText(std::string font_png, std::string font_txt)
{
if (!text)
{
text = new Text(font_png, font_txt, renderer);
} }
} }

View File

@@ -1,15 +1,15 @@
#pragma once #pragma once
#include <SDL2/SDL.h> #include <SDL2/SDL.h>
#include "asset.h" #include <vector>
#include "input.h"
#include "jail_audio.h"
#include "sprite.h" #include "sprite.h"
#include "text.h" #include "text.h"
#include "asset.h"
#include "input.h"
#include "utils.h" #include "utils.h"
#include <fstream> #include "jail_audio.h"
#include <sstream> #include <sstream>
#include <vector> #include <fstream>
#ifndef MENU_H #ifndef MENU_H
#define MENU_H #define MENU_H
@@ -68,6 +68,13 @@ private:
int a; // Cantidad de transparencia para el rectangulo del selector int a; // Cantidad de transparencia para el rectangulo del selector
}; };
// Objetos
SDL_Renderer *renderer; // Puntero al renderizador de la ventana
Text *text; // Texto para poder escribir los items del menu
Input *input; // Gestor de eventos de entrada de teclado o gamepad
Asset *asset; // Objeto para gestionar los ficheros de recursos
// Variables
std::string name; // Nombre del menu std::string name; // Nombre del menu
int x; // Posición en el eje X de la primera letra del primer elemento int x; // Posición en el eje X de la primera letra del primer elemento
int y; // Posición en el eje Y de la primera letra del primer elemento int y; // Posición en el eje Y de la primera letra del primer elemento
@@ -85,10 +92,6 @@ private:
JA_Sound soundAccept; // Sonido al aceptar o elegir una opción del menu JA_Sound soundAccept; // Sonido al aceptar o elegir una opción del menu
JA_Sound soundCancel; // Sonido al cancelar el menu JA_Sound soundCancel; // Sonido al cancelar el menu
JA_Sound soundMove; // Sonido al mover el selector JA_Sound soundMove; // Sonido al mover el selector
SDL_Renderer *renderer; // Puntero al renderizador de la ventana
Text *text; // Texto para poder escribir los items del menu
Input *input; // Gestor de eventos de entrada de teclado o gamepad
Asset *asset; // Objeto para gestionar los ficheros de recursos
color_t colorGreyed; // Color para los elementos agrisados color_t colorGreyed; // Color para los elementos agrisados
rectangle_t rectBG; // Rectangulo de fondo del menu rectangle_t rectBG; // Rectangulo de fondo del menu
std::vector<item_t> item; // Estructura para cada elemento del menu std::vector<item_t> item; // Estructura para cada elemento del menu
@@ -105,12 +108,6 @@ private:
// Asigna variables a partir de dos cadenas // Asigna variables a partir de dos cadenas
bool setItem(item_t *item, std::string var, std::string value); bool setItem(item_t *item, std::string var, std::string value);
// Inicializa las variables
void init();
// Establece el rectangulo de fondo del menu
void setRectSize();
// Actualiza el menu para recolocarlo correctamente y establecer el tamaño // Actualiza el menu para recolocarlo correctamente y establecer el tamaño
void reorganize(); void reorganize();
@@ -143,7 +140,7 @@ private:
public: public:
// Constructor // Constructor
Menu(SDL_Renderer *renderer, Asset *asset, Input *input, std::string file=""); Menu(SDL_Renderer *renderer, Asset *asset, Input *input, std::string file = "");
// Destructor // Destructor
~Menu(); ~Menu();
@@ -179,7 +176,7 @@ public:
void setSelectorTextColor(color_t color); void setSelectorTextColor(color_t color);
// Centra el menu respecto a un punto en el eje X // Centra el menu respecto a un punto en el eje X
void centerMenuOnX(int value); void centerMenuOnX(int value = 0);
// Centra el menu respecto a un punto en el eje Y // Centra el menu respecto a un punto en el eje Y
void centerMenuOnY(int value); void centerMenuOnY(int value);
@@ -208,7 +205,20 @@ public:
// Establece el estado de enlace de un item // Establece el estado de enlace de un item
void setLinkedDown(int index, bool value); void setLinkedDown(int index, bool value);
// hacer procedimientos para establecer el titulo, la x, la y, la tipografia y el tipo de fondo // Establece el nombre del menu
void setName(std::string name);
// Establece la posición del menu
void setPos(int x, int y);
// Establece el tipo de fondo del menu
void setBackgroundType(int value);
// Establece la fuente de texto que se utilizará
void setText(std::string font_png, std::string font_txt);
// Establece el rectangulo de fondo del menu
void setRectSize(int w = 0, int h = 0);
}; };
#endif #endif

View File

@@ -1,4 +1,4 @@
#include "../const.h"
#include "movingsprite.h" #include "movingsprite.h"
// Constructor // Constructor
@@ -45,7 +45,7 @@ MovingSprite::MovingSprite(float x, float y, int w, int h, float velx, float vel
spriteClip = {0, 0, w, h}; spriteClip = {0, 0, w, h};
// Establece el centro de rotación // Establece el centro de rotación
center = {0, 0}; center = nullptr;
// Establece el tipo de volteado // Establece el tipo de volteado
currentFlip = SDL_FLIP_NONE; currentFlip = SDL_FLIP_NONE;
@@ -73,7 +73,7 @@ void MovingSprite::clear()
angle = 0.0; // Angulo para dibujarlo angle = 0.0; // Angulo para dibujarlo
rotateEnabled = false; // Indica si ha de rotar rotateEnabled = false; // Indica si ha de rotar
center = {0, 0}; // Centro de rotación center = nullptr; // Centro de rotación
rotateSpeed = 0; // Velocidad de giro rotateSpeed = 0; // Velocidad de giro
rotateAmount = 0.0; // Cantidad de grados a girar en cada iteración rotateAmount = 0.0; // Cantidad de grados a girar en cada iteración
counter = 0; // Contador interno counter = 0; // Contador interno
@@ -101,7 +101,9 @@ void MovingSprite::move()
void MovingSprite::render() void MovingSprite::render()
{ {
if (enabled) if (enabled)
texture->render(renderer, (int)x, (int)y, &spriteClip, zoomW, zoomH, angle, &center, currentFlip); {
texture->render(renderer, (int)x, (int)y, &spriteClip, zoomW, zoomH, angle, center, currentFlip);
}
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
@@ -158,8 +160,8 @@ double MovingSprite::getAngle()
return angle; return angle;
} }
// Establece la posición del objeto // Establece la posición y el tamaño del objeto
void MovingSprite::setPos(SDL_Rect rect) void MovingSprite::setRect(SDL_Rect rect)
{ {
x = (float)rect.x; x = (float)rect.x;
y = (float)rect.y; y = (float)rect.y;
@@ -267,7 +269,14 @@ void MovingSprite::setRotate(bool value)
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setRotateSpeed(int value) void MovingSprite::setRotateSpeed(int value)
{ {
rotateSpeed = value; if (value < 1)
{
rotateSpeed = 1;
}
else
{
rotateSpeed = value;
}
} }
// Establece el valor de la variable // Establece el valor de la variable
@@ -326,15 +335,6 @@ SDL_Rect MovingSprite::getRect()
return rect; return rect;
} }
// Establece los valores de posición y tamaño del sprite
void MovingSprite::setRect(SDL_Rect rect)
{
x = (float)rect.x;
y = (float)rect.y;
w = rect.w;
h = rect.h;
}
// Deshace el último movimiento // Deshace el último movimiento
void MovingSprite::undoMove() void MovingSprite::undoMove()
{ {

View File

@@ -30,7 +30,7 @@ protected:
int rotateSpeed; // Velocidad de giro int rotateSpeed; // Velocidad de giro
double rotateAmount; // Cantidad de grados a girar en cada iteración double rotateAmount; // Cantidad de grados a girar en cada iteración
int counter; // Contador interno int counter; // Contador interno
SDL_Point center; // Centro de rotación SDL_Point *center; // Centro de rotación
SDL_RendererFlip currentFlip; // Indica como se voltea el sprite SDL_RendererFlip currentFlip; // Indica como se voltea el sprite
public: public:
@@ -88,8 +88,8 @@ public:
// Obtiene el valor de la variable // Obtiene el valor de la variable
Uint16 getRotateSpeed(); Uint16 getRotateSpeed();
// Establece la posición del objeto // Establece la posición y el tamaño del objeto
void setPos(SDL_Rect rect); void setRect(SDL_Rect rect);
// Establece el valor de la variable // Establece el valor de la variable
void setPosX(float value); void setPosX(float value);
@@ -151,9 +151,6 @@ public:
// Devuelve el rectangulo donde está el sprite // Devuelve el rectangulo donde está el sprite
SDL_Rect getRect(); SDL_Rect getRect();
// Establece los valores de posición y tamaño del sprite
void setRect(SDL_Rect rect);
// Deshace el último movimiento // Deshace el último movimiento
void undoMove(); void undoMove();

View File

@@ -22,7 +22,9 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer, options_t *options, i
// Crea la textura donde se dibujan los graficos del juego // Crea la textura donde se dibujan los graficos del juego
gameCanvas = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, gameCanvasWidth, gameCanvasHeight); gameCanvas = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, gameCanvasWidth, gameCanvasHeight);
if (gameCanvas == nullptr) if (gameCanvas == nullptr)
{
printf("TitleSurface could not be created!\nSDL Error: %s\n", SDL_GetError()); printf("TitleSurface could not be created!\nSDL Error: %s\n", SDL_GetError());
}
// Establece el modo de video // Establece el modo de video
setVideoMode(options->fullScreenMode); setVideoMode(options->fullScreenMode);
@@ -344,7 +346,7 @@ void Screen::renderSpectrumFade()
const float step = (float)spectrumFadeCounter / (float)spectrumFadeLenght; const float step = (float)spectrumFadeCounter / (float)spectrumFadeLenght;
const int max = spectrumColor.size() - 1; const int max = spectrumColor.size() - 1;
const int index = max + (0 - max) * step; const int index = max + (0 - max) * step;
const color_t c = spectrumColor[index]; const color_t c = spectrumColor.at(index);
SDL_SetTextureColorMod(gameCanvas, c.r, c.g, c.b); SDL_SetTextureColorMod(gameCanvas, c.r, c.g, c.b);
} }

View File

@@ -1,3 +1,4 @@
#include "text.h" #include "text.h"
#include <iostream> #include <iostream>
#include <fstream> #include <fstream>
@@ -5,13 +6,12 @@
// Constructor // Constructor
Text::Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer) Text::Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer)
{ {
texture = new LTexture(renderer, bitmapFile); // Carga los offsets desde el fichero
sprite = new Sprite({0, 0, 0, 0}, texture, renderer); initOffsetFromFile(textFile);
sprite->setTexture(texture);
sprite->setRenderer(renderer);
file = textFile;
init(); // Crea los objetos
texture = new LTexture(renderer, bitmapFile);
sprite = new Sprite({0, 0, boxWidth, boxHeight}, texture, renderer);
} }
// Destructor // Destructor
@@ -21,35 +21,6 @@ Text::~Text()
delete sprite; delete sprite;
} }
// Inicializador
void Text::init()
{
// Inicializa a cero el vector con las coordenadas
for (int i = 0; i < 128; ++i)
{
offset[i].x = 0;
offset[i].y = 0;
offset[i].w = 0;
}
// Carga los offsets desde el fichero
initOffsetFromFile();
// Inicia los valores del sprite que dibuja las letras
sprite->setWidth(boxWidth);
sprite->setHeight(boxHeight);
sprite->setPosX(0);
sprite->setPosY(0);
sprite->setSpriteClip(0, 0, sprite->getWidth(), sprite->getHeight());
// Establece las coordenadas para cada caracter ascii de la cadena y su ancho
for (int i = 32; i < 128; ++i)
{
offset[i].x = ((i - 32) % 15) * boxWidth;
offset[i].y = ((i - 32) / 15) * boxHeight;
}
}
// Escribe texto en pantalla // Escribe texto en pantalla
void Text::write(int x, int y, std::string text, int kerning, int lenght) void Text::write(int x, int y, std::string text, int kerning, int lenght)
{ {
@@ -138,10 +109,19 @@ int Text::lenght(std::string text, int kerning)
} }
// Inicializa el vector de offsets desde un fichero // Inicializa el vector de offsets desde un fichero
void Text::initOffsetFromFile() void Text::initOffsetFromFile(std::string file)
{ {
// Inicializa a cero el vector con las coordenadas
for (int i = 0; i < 128; ++i)
{
offset[i].x = 0;
offset[i].y = 0;
offset[i].w = 0;
}
// Abre el fichero para leer los valores
const std::string filename = file.substr(file.find_last_of("\\/") + 1).c_str();
std::ifstream rfile(file); std::ifstream rfile(file);
printf("Reading file %s\n", file.c_str());
if (rfile.is_open() && rfile.good()) if (rfile.is_open() && rfile.good())
{ {
@@ -173,14 +153,21 @@ void Text::initOffsetFromFile()
}; };
// Cierra el fichero // Cierra el fichero
printf("Closing file %s\n\n", file.c_str()); printf("Text loaded: %s\n", filename.c_str());
rfile.close(); rfile.close();
} }
// El fichero no se puede abrir // El fichero no se puede abrir
else else
{ {
printf("Warning: Unable to open %s file\n", file.c_str()); printf("Warning: Unable to open %s file\n", filename.c_str());
}
// Establece las coordenadas para cada caracter ascii de la cadena y su ancho
for (int i = 32; i < 128; ++i)
{
offset[i].x = ((i - 32) % 15) * boxWidth;
offset[i].y = ((i - 32) / 15) * boxHeight;
} }
} }

View File

@@ -1,6 +1,5 @@
#pragma once #pragma once
#include <SDL2/SDL.h>
#include "sprite.h" #include "sprite.h"
#include "utils.h" #include "utils.h"
@@ -16,26 +15,24 @@
class Text class Text
{ {
private: private:
Sprite *sprite; // Objeto con los graficos para el texto struct offset_t
struct Offset
{ {
int x; int x;
int y; int y;
int w; int w;
}; };
Offset offset[128]; // Vector con las posiciones y ancho de cada letra
int boxWidth; // Anchura de la caja de cada caracter en el png // Objetos
int boxHeight; // Altura de la caja de cada caracter en el png Sprite *sprite; // Objeto con los graficos para el texto
std::string file; // Fichero con los descriptores de la fuente
LTexture *texture; // Textura con los bitmaps del texto LTexture *texture; // Textura con los bitmaps del texto
// Inicializador // Variables
void init(); int boxWidth; // Anchura de la caja de cada caracter en el png
int boxHeight; // Altura de la caja de cada caracter en el png
offset_t offset[128]; // Vector con las posiciones y ancho de cada letra
// Inicializa el vector de offsets desde un fichero // Inicializa el vector de offsets desde un fichero
void initOffsetFromFile(); void initOffsetFromFile(std::string file);
public: public:
// Constructor // Constructor