1 Commits

Author SHA1 Message Date
dfb4919a3e Prueba de branch 2022-09-07 09:20:25 +02:00
62 changed files with 367 additions and 1603 deletions

View File

@@ -12,8 +12,8 @@ roomRight=02.room
[/tilemap]
[enemy]
tileset=diskette.png
animation=diskette.ani
tileset=paco.png
animation=paco.ani
width=16
height=16
x=1
@@ -28,8 +28,8 @@ color=red
[/enemy]
[enemy]
tileset=diskette.png
animation=diskette.ani
tileset=paco.png
animation=paco.ani
width=16
height=16
x=5
@@ -45,7 +45,7 @@ color=yellow
[item]
tileset=items.png
tile=1
tile=0
x=1
y=7
counter=6
@@ -53,7 +53,7 @@ counter=6
[item]
tileset=items.png
tile=1
tile=0
x=17
y=8
counter=7
@@ -63,7 +63,7 @@ counter=7
[item]
tileset=items.png
tile=1
tile=0
x=12
y=12
counter=1
@@ -71,7 +71,7 @@ counter=1
[item]
tileset=items.png
tile=1
tile=0
x=13
y=12
counter=2
@@ -79,7 +79,7 @@ counter=2
[item]
tileset=items.png
tile=1
tile=0
x=14
y=12
counter=3
@@ -87,7 +87,7 @@ counter=3
[item]
tileset=items.png
tile=1
tile=0
x=15
y=12
counter=4
@@ -95,7 +95,7 @@ counter=4
[item]
tileset=items.png
tile=1
tile=0
x=16
y=12
counter=5

View File

@@ -1,24 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<map version="1.9" tiledversion="1.9.1" orientation="orthogonal" renderorder="right-down" width="32" height="16" tilewidth="8" tileheight="8" infinite="0" nextlayerid="2" nextobjectid="1">
<map version="1.9" tiledversion="1.9.0" orientation="orthogonal" renderorder="right-down" width="32" height="16" tilewidth="8" tileheight="8" infinite="0" nextlayerid="2" nextobjectid="1">
<tileset firstgid="1" source="../../../jaildoctors_dilemma_resources/tilesets/standard.tsx"/>
<layer id="1" name="Capa de patrones 1" width="32" height="16">
<data encoding="csv">
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,
0,0,0,0,0,0,0,0,0,0,0,203,203,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,24,24,24,24,0,0,0,0,0,0,0,0,0,24,
24,24,24,24,24,24,0,0,0,203,0,0,0,0,0,0,0,0,0,24,0,0,0,0,203,203,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,203,0,0,0,0,0,0,0,0,0,24,0,0,0,0,203,203,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,203,203,24,
0,0,0,0,0,0,0,203,203,203,203,203,203,0,0,0,0,0,0,24,0,0,0,0,203,203,0,0,0,0,0,24,
0,0,0,0,0,203,0,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,0,0,24,
44,24,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,84,84,84,84,84,84,84,84,84,84,84,84,
44,44,44,44,44,44,44,44,44,44,44,44,44,44,223,0,0,223,44,44,44,44,44,44,44,44,44,44,44,44,44,44
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,
0,0,0,0,0,0,0,0,0,0,0,203,203,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,23,23,23,23,0,0,0,0,0,0,0,0,0,23,
23,23,23,23,23,23,0,0,0,203,0,0,0,0,0,0,0,0,0,23,0,0,0,0,203,203,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,203,0,0,0,0,0,0,0,0,0,23,0,0,0,0,203,203,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,0,0,0,0,0,0,0,0,0,203,203,23,
0,0,0,0,0,0,0,203,203,203,203,203,203,0,0,0,0,0,0,23,0,0,0,0,203,203,0,0,0,0,0,23,
0,0,0,0,0,203,0,0,0,0,0,0,0,0,0,0,0,0,0,23,0,0,0,0,0,0,0,0,0,0,0,23,
43,23,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23,83,83,83,83,83,83,83,83,83,83,83,83,
43,43,43,43,43,43,43,43,43,43,43,43,43,43,223,0,0,223,43,43,43,43,43,43,43,43,43,43,43,43,43,43
</data>
</layer>
</map>

View File

@@ -1,5 +1,5 @@
name=the test room
bgColor=black
bgColor=blue
border=blue
tileset=standard.png
roomUp=0

View File

@@ -6,17 +6,17 @@
26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,
26,0,0,0,0,0,0,0,0,0,0,0,0,0,0,183,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,183,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,0,0,86,0,0,0,0,0,0,0,0,0,0,183,0,0,0,0,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,86,86,86,0,0,0,0,0,0,0,0,0,0,0,183,0,0,0,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,86,0,86,0,0,0,0,0,0,0,0,167,66,66,66,66,187,0,0,0,0,164,65,65,0,0,0,26,
26,0,0,0,86,0,86,0,0,0,0,0,0,0,162,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,183,0,0,0,0,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,183,0,0,0,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,0,0,0,0,0,0,0,0,0,0,0,167,66,66,66,66,187,0,0,0,0,164,65,65,0,0,0,26,
26,0,0,0,0,0,0,0,0,0,0,0,0,0,162,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,0,0,0,0,0,0,0,0,0,162,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,0,0,0,0,0,0,0,0,162,0,0,0,0,0,0,0,0,0,0,0,0,62,62,0,0,0,0,26,
26,0,0,0,0,0,0,0,0,161,212,212,212,212,212,212,212,0,212,212,0,0,0,0,0,62,62,0,0,0,0,26,
26,0,0,0,0,0,0,0,161,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,0,0,0,161,0,0,0,0,0,0,0,0,0,269,0,0,0,0,0,0,0,0,22,22,0,0,0,26,
26,0,0,0,0,0,161,0,0,0,0,0,0,0,0,0,0,269,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
26,0,0,0,0,161,0,0,0,0,0,0,0,0,0,0,81,289,81,0,0,0,0,0,0,0,0,0,0,0,0,0,
26,0,0,0,0,0,0,0,0,0,0,0,162,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,0,0,0,0,0,161,212,212,212,212,212,212,212,0,212,212,181,0,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,0,0,0,0,161,0,0,0,0,0,0,0,0,0,0,0,0,181,0,0,0,0,0,0,0,0,0,26,
26,0,0,0,0,0,0,161,0,0,0,0,0,0,0,0,0,269,0,0,0,0,181,0,0,0,0,0,0,0,0,26,
26,0,0,0,0,0,161,0,0,0,0,0,0,0,0,0,0,269,0,0,0,0,0,181,0,0,0,0,0,0,0,0,
26,0,0,0,0,161,0,0,0,0,0,0,0,0,0,0,0,289,0,0,0,0,0,0,181,0,0,0,0,0,0,0,
26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,
26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26
</data>

View File

@@ -1,10 +0,0 @@
frames_per_row=4
frame_width=16
frame_height=16
[animation]
name=default
speed=8
loop=0
frames=0,1,2,3
[/animation]

Binary file not shown.

Before

Width:  |  Height:  |  Size: 271 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 579 B

After

Width:  |  Height:  |  Size: 369 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 219 B

BIN
media/player/player01.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 222 B

View File

@@ -1,24 +0,0 @@
frames_per_row=8
frame_width=8
frame_height=16
[animation]
name=stand
speed=8
loop=0
frames=0
[/animation]
[animation]
name=walk
speed=8
loop=0
frames=0,1,2,3,4,5,6,7
[/animation]
[animation]
name=walk_menu
speed=0
loop=0
frames=0,1,2,3,4,5,6,7
[/animation]

Binary file not shown.

Before

Width:  |  Height:  |  Size: 314 B

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

View File

@@ -10,7 +10,7 @@
// Textos
#define WINDOW_CAPTION "JailDoctor's Dilemma"
#define TEXT_COPYRIGHT "@2022 JailDesigner"
#define VERSION "0.7"
#define VERSION "0.6"
// Tamaño de bloque
#define BLOCK 8

View File

@@ -14,7 +14,6 @@ Debug::Debug(SDL_Renderer *renderer, Screen *screen, Asset *asset)
// Inicializa variables
x = 0;
y = 0;
enabled = false;
}
// Destructor
@@ -42,7 +41,7 @@ void Debug::render()
if (y > 192 - text->getCharacterSize())
{
y = this->y;
x += w * text->getCharacterSize() + 2;
x += w*text->getCharacterSize() + 2;
}
}
}
@@ -65,21 +64,3 @@ void Debug::clear()
{
slot.clear();
}
// Establece el valor de la variable
void Debug::setEnabled(bool value)
{
enabled = value;
}
// Obtiene el valor de la variable
bool Debug::getEnabled()
{
return enabled;
}
// Cambia el valor de la variable
void Debug::switchEnabled()
{
enabled = !enabled;
}

View File

@@ -23,7 +23,6 @@ private:
std::vector<std::string> slot; // Vector con los textos a escribir
int x; // Posicion donde escribir el texto de debug
int y; // Posición donde escribir el texto de debug
bool enabled; // Indica si esta activo el modo debug
public:
// Constructor
@@ -46,15 +45,6 @@ public:
// Borra la información de debug
void clear();
// Establece el valor de la variable
void setEnabled(bool value);
// Obtiene el valor de la variable
bool getEnabled();
// Cambia el valor de la variable
void switchEnabled();
};
#endif

View File

@@ -184,11 +184,9 @@ bool Director::setFileList()
asset->add("/media/enemies/wave.ani", data);
asset->add("/media/enemies/sigmasua.png", bitmap);
asset->add("/media/enemies/sigmasua.ani", data);
asset->add("/media/enemies/diskette.png", bitmap);
asset->add("/media/enemies/diskette.ani", data);
asset->add("/media/player/player.png", bitmap);
asset->add("/media/player/player.ani", data);
asset->add("/media/player/player01.png", bitmap);
asset->add("/media/player/player01.ani", data);
asset->add("/media/items/items.png", bitmap);
@@ -199,31 +197,6 @@ bool Director::setFileList()
asset->add("/media/music/loading_sound3.ogg", music);
asset->add("/media/sound/item.wav", sound);
asset->add("/media/sound/death.wav", sound);
asset->add("/media/sound/jump1.wav", sound);
asset->add("/media/sound/jump2.wav", sound);
asset->add("/media/sound/jump3.wav", sound);
asset->add("/media/sound/jump4.wav", sound);
asset->add("/media/sound/jump5.wav", sound);
asset->add("/media/sound/jump6.wav", sound);
asset->add("/media/sound/jump7.wav", sound);
asset->add("/media/sound/jump8.wav", sound);
asset->add("/media/sound/jump9.wav", sound);
asset->add("/media/sound/jump10.wav", sound);
asset->add("/media/sound/jump11.wav", sound);
asset->add("/media/sound/jump12.wav", sound);
asset->add("/media/sound/jump13.wav", sound);
asset->add("/media/sound/jump14.wav", sound);
asset->add("/media/sound/jump15.wav", sound);
asset->add("/media/sound/jump16.wav", sound);
asset->add("/media/sound/jump17.wav", sound);
asset->add("/media/sound/jump18.wav", sound);
asset->add("/media/sound/jump19.wav", sound);
asset->add("/media/sound/jump20.wav", sound);
asset->add("/media/sound/jump21.wav", sound);
asset->add("/media/sound/jump22.wav", sound);
asset->add("/media/sound/jump23.wav", sound);
asset->add("/media/sound/jump24.wav", sound);
asset->add("/media/logo/jailgames.png", bitmap);
asset->add("/media/logo/since_1998.png", bitmap);

View File

@@ -4,10 +4,12 @@
Game::Game(SDL_Renderer *renderer, Screen *screen, Asset *asset, Input *input, Debug *debug)
{
// Inicia algunas variables
board.iniClock = SDL_GetTicks();
clock = SDL_GetTicks();
currentRoom = "01.room";
spawnPoint = {16, 96, 0, 0, 0, s_standing, SDL_FLIP_NONE};
currentRoom = "06.room";
spawnPoint = {240, 96, 0, 0, 0, s_standing, SDL_FLIP_HORIZONTAL};
// Copia los punteros
this->renderer = renderer;
@@ -15,33 +17,25 @@ Game::Game(SDL_Renderer *renderer, Screen *screen, Asset *asset, Input *input, D
this->screen = screen;
this->input = input;
this->debug = debug;
//this->debug->setEnabled(true);
//currentRoom = "06.room";
//spawnPoint = {240, 96, 0, 0, 0, s_standing, SDL_FLIP_HORIZONTAL};
// Crea los objetos
scoreboard = new ScoreBoard(renderer, asset, &board);
scoreboard = new ScoreBoard(renderer, asset, &playerLives, &itemsPicked, &clock);
itemTracker = new ItemTracker();
roomTracker = new RoomTracker();
room = new Room(asset->get(currentRoom), renderer, screen, asset, itemTracker, &board.items, debug);
player = new Player(spawnPoint, asset->get("player.png"), asset->get("player.ani"), renderer, asset, input, room, debug);
room = new Room(asset->get(currentRoom), renderer, screen, asset, itemTracker, &itemsPicked, debug);
player = new Player(spawnPoint, asset->get("player01.png"), asset->get("player01.ani"), renderer, asset, input, room, debug);
eventHandler = new SDL_Event();
text = new Text(asset->get("smb2.png"), asset->get("smb2.txt"), renderer);
music = JA_LoadMusic(asset->get("game.ogg").c_str());
deathSound = JA_LoadSound(asset->get("death.wav").c_str());
test = new Test(renderer, screen, asset, debug);
// Inicializa el resto de variables
ticks = 0;
ticksSpeed = 15;
board.lives = 9;
board.items = 0;
board.rooms = 1;
roomTracker->addRoom(currentRoom);
playerLives = 9;
itemsPicked = 0;
player->setInvincible(debug->getEnabled());
board.music = !debug->getEnabled();
debugEnabled = true;
player->setInvincible(debugEnabled);
musicEnabled = !debugEnabled;
section.name = SECTION_PROG_GAME;
section.subsection = SUBSECTION_GAME_PLAY;
@@ -57,16 +51,10 @@ Game::~Game()
// Libera la memoria de los objetos
delete scoreboard;
delete itemTracker;
delete roomTracker;
delete room;
delete player;
delete eventHandler;
delete text;
JA_DeleteMusic(music);
JA_DeleteSound(deathSound);
delete test;
}
// Comprueba los eventos de la cola
@@ -91,15 +79,14 @@ void Game::checkEventHandler()
break;
case SDL_SCANCODE_D:
debug->switchEnabled();
player->setInvincible(debug->getEnabled());
board.music = !debug->getEnabled();
board.music ? JA_ResumeMusic() : JA_PauseMusic();
debugEnabled = !debugEnabled;
player->setInvincible(debugEnabled);
musicEnabled = !debugEnabled;
musicEnabled ? JA_PlayMusic(music) : JA_StopMusic();
break;
case SDL_SCANCODE_M:
board.music = !board.music;
board.music ? JA_ResumeMusic() : JA_PauseMusic();
(JA_GetMusicState() == JA_MUSIC_PLAYING) ? JA_PauseMusic() : JA_ResumeMusic();
break;
case SDL_SCANCODE_F:
@@ -137,10 +124,9 @@ void Game::checkEventHandler()
// Bucle para el juego
section_t Game::run()
{
JA_PlayMusic(music);
if (!board.music)
if (musicEnabled)
{
JA_PauseMusic();
JA_PlayMusic(music);
}
while (section.name == SECTION_PROG_GAME)
@@ -198,7 +184,6 @@ void Game::render()
// Debug info
renderDebugInfo();
// test->render();
// Actualiza la pantalla
screen->blit();
@@ -208,14 +193,14 @@ void Game::render()
void Game::updateDebugInfo()
{
debug->add("X = " + std::to_string((int)player->x) + ", Y = " + std::to_string((int)player->y));
debug->add("VX = " + std::to_string(player->vx).substr(0, 4) + ", VY = " + std::to_string(player->vy).substr(0, 4));
debug->add("VX = " + std::to_string(player->vx).substr(0,4) + ", VY = " + std::to_string(player->vy).substr(0,4));
debug->add("STATE = " + std::to_string(player->state));
}
// Pone la información de debug en pantalla
void Game::renderDebugInfo()
{
if (!debug->getEnabled())
if (!debugEnabled)
{
return;
}
@@ -226,7 +211,7 @@ void Game::renderDebugInfo()
SDL_RenderFillRect(renderer, &rect);
// Pinta la rejilla
/*SDL_SetRenderDrawColor(renderer, 255, 255, 255, 32);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 64);
for (int i = 0; i < PLAY_AREA_BOTTOM; i += 8)
{ // Lineas horizontales
SDL_RenderDrawLine(renderer, 0, i, PLAY_AREA_RIGHT, i);
@@ -234,7 +219,12 @@ void Game::renderDebugInfo()
for (int i = 0; i < PLAY_AREA_RIGHT; i += 8)
{ // Lineas verticales
SDL_RenderDrawLine(renderer, i, 0, i, PLAY_AREA_BOTTOM - 1);
}*/
}
// Pinta mascaras de sprite
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 192);
rect = player->getRect();
SDL_RenderFillRect(renderer, &rect);
// Pinta el texto
debug->setPos({1, 18 * 8});
@@ -268,13 +258,7 @@ bool Game::changeRoom(std::string file)
room = nullptr;
// Crea un objeto habitación nuevo a partir del fichero
room = new Room(asset->get(file), renderer, screen, asset, itemTracker, &board.items, debug);
// Actualiza el marcador
if (roomTracker->addRoom(file))
{
board.rooms++;
}
room = new Room(asset->get(file), renderer, screen, asset, itemTracker, &itemsPicked, debug);
// Pasa la nueva habitación al jugador
player->setRoom(room);
@@ -325,18 +309,15 @@ void Game::killPlayer()
return;
}
board.lives--;
playerLives--;
// Destruye la habitacion y el jugador
delete room;
delete player;
// Sonido
JA_PlaySound(deathSound);
// Crea la nueva habitación y el nuevo jugador
room = new Room(asset->get(currentRoom), renderer, screen, asset, itemTracker, &board.items, debug);
player = new Player(spawnPoint, asset->get("player.png"), asset->get("player.ani"), renderer, asset, input, room, debug);
room = new Room(asset->get(currentRoom), renderer, screen, asset, itemTracker, &itemsPicked, debug);
player = new Player(spawnPoint, asset->get("player01.png"), asset->get("player01.ani"), renderer, asset, input, room, debug);
}
// Recarga todas las texturas

View File

@@ -10,12 +10,10 @@
#include "asset.h"
#include "room.h"
#include "item_tracker.h"
#include "room_tracker.h"
#include "player.h"
#include "jail_audio.h"
#include "scoreboard.h"
#include "debug.h"
#include "test.h"
#ifndef GAME_H
#define GAME_H
@@ -30,22 +28,22 @@ private:
Room *room; // Objeto encargado de gestionar cada habitación del juego
Player *player; // Objeto con el jugador
ItemTracker *itemTracker; // Lleva el control de los objetos recogidos
RoomTracker *roomTracker; // Lleva el control de las habitaciones visitadas
Asset *asset; // Objeto con la ruta a todos los ficheros de recursos
Input *input; // Objeto pata gestionar la entrada
Text *text; // Objeto para los textos del juego
ScoreBoard *scoreboard; // Objeto encargado de gestionar el marcador
JA_Music music; // Musica que suena durante el juego
Debug *debug; // Objeto para gestionar la información de debug
bool musicEnabled; // Indica si ha de sonar la musica durante el juego
int ticks; // Contador de ticks para ajustar la velocidad del programa
int ticksSpeed; // Velocidad a la que se repiten los bucles del programa
section_t section; // Seccion actual dentro del juego
std::string currentRoom; // Fichero de la habitación actual
player_t spawnPoint; // Lugar de la habitación donde aparece el jugador
bool debugEnabled; // Indica si el modo debug está activo
int playerLives; // Lleva la cuenta de ls vidas restantes del jugador
int itemsPicked; // Lleva la cuenta de los objetos recogidos
Uint32 clock; // Cuenta el tiempo que dura la partida
JA_Sound deathSound; // Sonido a reproducir cuando muere el jugador
board_t board; // Estructura con los datos del marcador
Test *test;
// Actualiza el juego, las variables, comprueba la entrada, etc.
void update();

View File

@@ -61,6 +61,12 @@ void Item::update()
counter++;
}
// Coge el objeto
void Item::pick()
{
sprite->setEnabled(false);
}
// Obtiene el rectangulo de colision del objeto
SDL_Rect &Item::getCollider()
{

View File

@@ -51,6 +51,9 @@ public:
// Actualiza las variables del objeto
void update();
// Coge el item
void pick();
// Obtiene el rectangulo de colision del objeto
SDL_Rect &getCollider();

View File

@@ -22,9 +22,8 @@ Player::Player(player_t ini, std::string tileset, std::string animation, SDL_Ren
border = BORDER_TOP;
invincible = false;
jumpIni = ini.jumpIni;
jump_ini = ini.jump_ini;
state = ini.state;
prevState = state;
x = ini.x;
y = ini.y;
@@ -49,49 +48,6 @@ Player::Player(player_t ini, std::string tileset, std::string animation, SDL_Ren
colliderPoints.insert(colliderPoints.end(), {p, p, p, p, p, p, p, p});
underFeet.insert(underFeet.end(), {p, p});
feet.insert(feet.end(), {p, p});
jumpSound.push_back(JA_LoadSound(asset->get("jump1.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump2.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump3.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump4.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump5.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump6.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump7.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump8.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump9.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump10.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump11.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump12.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump13.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump14.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump15.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump16.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump17.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump18.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump19.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump20.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump21.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump22.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump23.wav").c_str()));
jumpSound.push_back(JA_LoadSound(asset->get("jump24.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump11.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump12.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump13.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump14.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump15.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump16.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump17.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump18.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump19.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump20.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump21.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump22.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump23.wav").c_str()));
fallSound.push_back(JA_LoadSound(asset->get("jump24.wav").c_str()));
r = {0, 0, 0, 0};
jumpCounter = 0;
fallCounter = 0;
}
// Destructor
@@ -99,11 +55,6 @@ Player::~Player()
{
delete texture;
delete sprite;
for (auto s : jumpSound)
{
JA_DeleteSound(s);
}
}
// Pinta el jugador en pantalla
@@ -111,23 +62,6 @@ void Player::render()
{
sprite->getTexture()->setColor(color.r, color.g, color.b);
sprite->render();
if (debug->getEnabled())
{
// Pinta los underfeet
SDL_SetRenderDrawColor(renderer, 255, 0, 255, 255);
SDL_RenderDrawPoint(renderer, underFeet[0].x, underFeet[0].y);
SDL_RenderDrawPoint(renderer, underFeet[1].x, underFeet[1].y);
// Pinta rectangulo del jugador
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 192);
SDL_Rect rect = getRect();
SDL_RenderFillRect(renderer, &rect);
// Pinta el rectangulo de movimiento
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderFillRect(renderer, &r);
debug->add("RECT: " + std::to_string(r.x) + "," + std::to_string(r.y) + "," + std::to_string(r.w) + "," + std::to_string(r.h));
}
}
// Actualiza las variables del objeto
@@ -143,35 +77,30 @@ void Player::update()
// Comprueba las entradas y modifica variables
void Player::checkInput()
{
// Solo comprueba las entradas de dirección cuando está dsobre una superficie
if (state != s_standing)
{
return;
}
if (input->checkInput(INPUT_LEFT, REPEAT_TRUE))
// Solo comprueba las entradas de dirección cuando está de pie
if ((input->checkInput(INPUT_LEFT, REPEAT_TRUE)) && (state == s_standing))
{
vx = -0.6f;
sprite->setFlip(SDL_FLIP_HORIZONTAL);
}
else if (input->checkInput(INPUT_RIGHT, REPEAT_TRUE))
else if ((input->checkInput(INPUT_RIGHT, REPEAT_TRUE)) && (state == s_standing))
{
vx = 0.6f;
sprite->setFlip(SDL_FLIP_NONE);
}
else
else if (state == s_standing)
{
vx = 0.0f;
}
if (input->checkInput(INPUT_UP, REPEAT_TRUE))
{
setState(s_jumping);
vy = -maxVY;
jumpIni = y;
jumpCounter = 0;
if (state == s_standing)
{
state = s_jumping;
vy = -maxVY;
jump_ini = y;
}
}
}
@@ -219,26 +148,15 @@ void Player::checkBorders()
// Comprueba el estado del jugador
void Player::checkState()
{
// Actualiza las variables en función del estado
if (state == s_falling)
{
vx = 0.0f;
vy = maxVY;
fallCounter++;
playFallSound();
}
else if (state == s_standing)
{
vy = 0.0f;
jumpCounter = 0;
fallCounter = 0;
}
else if (state == s_jumping)
{
jumpCounter++;
playJumpSound();
}
}
@@ -248,7 +166,7 @@ void Player::switchBorders()
if (border == BORDER_TOP)
{
y = PLAY_AREA_BOTTOM - h - 1;
jumpIni += 128;
jump_ini += 128;
}
else if (border == BORDER_BOTTOM)
{
@@ -271,8 +189,7 @@ void Player::applyGravity()
{
const float gf = 0.035f;
// La gravedad solo se aplica cuando el jugador esta saltando
// Nunca mientras cae o esta de pie
// La gravedad solo se aplica cuando está saltando
if (state == s_jumping)
{
vy += gf;
@@ -299,155 +216,147 @@ SDL_Rect &Player::getCollider()
// Recalcula la posición del jugador y su animación
void Player::move()
{
const int tileSize = room->getTileSize();
lastPosition = {(int)x, (int)y}; // Guarda la posicion actual antes de modificarla
applyGravity(); // Aplica gravedad al jugador
checkState(); // Comprueba el estado del jugador
// Se mueve hacia la izquierda
if (vx < 0.0f)
// Calcula la nueva posición del jugador y compensa en caso de colisión
x += vx;
// Comprueba colisiones con muros
if (checkWalls())
{
// Crea el rectangulo de proyección en el eje X para ver si colisiona
SDL_Rect proj;
proj.x = (int)(x + vx);
proj.y = (int)y;
proj.h = h;
proj.w = ceil(abs(vx)); // Para evitar que tenga un ancho de 0 pixels
r = proj;
// Comprueba la colisión con las superficies
const int pos = room->checkRightSurfaces(&proj);
// Calcula la nueva posición
if (pos == -1)
{ // Si no hay colisión
x += vx;
// Recoloca
if (vx > 0.0f)
{
x = (int)x - ((int)x + w) % tileSize;
}
else
{ // Si hay colisión lo mueve hasta donde no colisiona
x = pos + 1;
}
// Si ha tocado alguna rampa mientras camina (sin saltar), asciende
if (state != s_jumping)
{
v_line_t leftSide = {(int)x, (int)y + h - 2, (int)y + h - 1};
const int ly = room->checkLeftSlopes(&leftSide);
if (ly > -1)
x = (int)x + tileSize - ((int)x % tileSize);
}
}
// Comprueba colisiones con rampas solo si esta quieto o cayendo
else if (vy >= 0.0f)
{
tile_e slope = checkSlopes();
tile_e slope2 = checkSlopes2();
debug->add("SLOPE = " + std::to_string(slope));
debug->add("SLOPE2 = " + std::to_string(slope2));
if (slope != t_empty)
{ // Cuesta hacia la derecha
if (slope == t_slope_r)
{ // Recoloca
y = -h + room->getSlopeHeight(feet[1], t_slope_r);
debug->add("feet[1] = " + std::to_string(feet[1].y));
}
// Cuesta hacia la izquierda
if (slope == t_slope_l)
{ // Recoloca
y = -h + room->getSlopeHeight(feet[0], t_slope_l);
debug->add("feet[0] = " + std::to_string(feet[0].y));
}
}
else if (slope2 != t_empty)
{ // Cuesta hacia la derecha
if (slope2 == t_slope_r)
{ // Recoloca
y = -h + room->getSlopeHeight(underFeet[1], t_slope_r);
debug->add("ufeet[1] = " + std::to_string(underFeet[1].y));
}
// Cuesta hacia la izquierda
if (slope2 == t_slope_l)
{ // Recoloca
y = -h + room->getSlopeHeight(underFeet[0], t_slope_l);
debug->add("ufeet[0] = " + std::to_string(underFeet[0].y));
}
}
}
y += vy;
if (checkWalls())
{
// Recoloca
if (vy > 0.0f)
{ // Bajando
y -= ((int)y + h) % tileSize;
state = s_standing;
vy = 0.0f;
}
else
{ // Subiendo
y += tileSize - ((int)y % tileSize);
state = s_falling;
vy = maxVY;
}
}
else
// Si no colisiona con los muros, haz comprobaciones extra
{
const int a = (lastPosition.y + h - 1) / tileSize;
const int b = ((int)y + h - 1) / tileSize;
const bool tile_change = a != b;
bool going_down = vy >= 0.0f;
bool tile_aligned = ((int)y + h) % tileSize == 0;
// Si está cayendo y hay cambio de tile o está justo sobre uno
if (going_down && (tile_aligned || tile_change))
{
// Comprueba si tiene uno de los pies sobre una superficie
if (isOnFloor())
{ // Y deja al jugador de pie
state = s_standing;
vy = 0.0f;
// Si ademas ha habido un cambio de tile recoloca al jugador
if (tile_change && !checkSlopes2())
{
y = ((int)y - ((int)y % tileSize));
}
}
// Si tiene ambos pies sobre el vacío y no está saltando
else if (state != s_jumping)
{
y = ly - h;
// setState(s_standing);
state = s_falling;
vy = maxVY;
}
}
// Si está bajando la rampa, recoloca al jugador
if (isOnDownSlope())
going_down = vy >= 0.0f;
tile_aligned = ((int)y + h) % tileSize == 0;
// Si simplemente está cayendo (sin mirar si hay cambio de tile o si está justo sobre uno)
if (going_down)
{
y += 1;
}
}
// Se mueve hacia la derecha
else if (vx > 0.0f)
{
// Crea el rectangulo de proyección en el eje X para ver si colisiona
SDL_Rect proj;
proj.x = (int)x + w;
proj.y = (int)y;
proj.h = h;
proj.w = ceil(vx); // Para evitar que tenga un ancho de 0 pixels
r = proj;
// Comprueba la colisión
const int pos = room->checkLeftSurfaces(&proj);
// Calcula la nueva posición
if (pos == -1)
{ // Si no hay colisión
x += vx;
}
else
{ // Si hay colisión lo mueve hasta donde no colisiona
x = pos - w;
}
// Si ha tocado alguna rampa mientras camina (sin saltar), asciende
if (state != s_jumping)
{
v_line_t rightSide = {(int)x + w - 1, (int)y + h - 2, (int)y + h - 1};
const int ry = room->checkRightSlopes(&rightSide);
if (ry > -1)
if (state != s_jumping)
{
y = ry - h;
// setState(s_standing);
state = s_falling;
vy = maxVY;
}
}
// Si está bajando la rampa, recoloca al jugador
if (isOnDownSlope())
{
y += 1;
}
}
// Si ha salido del suelo, el jugador cae
if (state == s_standing && !isOnFloor())
{
setState(s_falling);
}
// Se mueve hacia arriba
if (vy < 0.0f)
{
// Crea el rectangulo de proyección en el eje Y para ver si colisiona
SDL_Rect proj;
proj.x = (int)x;
proj.y = (int)(y + vy);
proj.h = ceil(abs(vy)); // Para evitar que tenga una altura de 0 pixels
proj.w = w;
r = proj;
// Comprueba la colisión
const int pos = room->checkBottomSurfaces(&proj);
// Calcula la nueva posición
if (pos == -1)
{ // Si no hay colisión
y += vy;
}
else
{ // Si hay colisión lo mueve hasta donde no colisiona y entra en caída
y = pos + 1;
setState(s_falling);
}
}
// Se mueve hacia abajo
else if (vy > 0.0f)
{
// Crea el rectangulo de proyección en el eje Y para ver si colisiona
SDL_Rect proj;
proj.x = (int)x;
proj.y = (int)y + h;
proj.h = ceil(vy); // Para evitar que tenga una altura de 0 pixels
proj.w = w;
r = proj;
// Comprueba la colisión con los muros
const int pos = room->checkTopSurfaces(&proj);
// Calcula la nueva posición
if (pos == -1)
{ // Si no hay colisión
y += vy;
}
else
{ // Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre el suelo
y = pos - h;
setState(s_standing);
// Si está alineado con el tile mira el suelo (para que no lo mire si está
// dentro de un tile atravesable y lo deje a medias)
if (tile_aligned)
{
if (isOnFloor())
{
state = s_standing;
vy = 0.0f;
}
}
// EXPERIMENTAL
else if (checkSlopes())
{
state = s_standing;
vy = 0.0f;
}
}
}
@@ -469,37 +378,12 @@ void Player::animate()
void Player::checkJumpEnd()
{
if (state == s_jumping)
{
if (vy > 0)
{
if (y >= jumpIni)
{ // Si alcanza la altura de salto inicial, pasa al estado de caída
setState(s_falling);
if (y >= jump_ini)
{
state = s_falling;
vy = maxVY;
jumpCounter = 0;
}
}
}
}
// Calcula y reproduce el sonido de salto
void Player::playJumpSound()
{
if (jumpCounter % 4 == 0)
{
JA_PlaySound(jumpSound[jumpCounter / 4]);
}
debug->add("JUMP: " + std::to_string(jumpCounter / 4));
}
// Calcula y reproduce el sonido de caer
void Player::playFallSound()
{
if (fallCounter % 4 == 0)
{
JA_PlaySound(fallSound[std::min((fallCounter / 4), (int)fallSound.size() - 1)]);
}
debug->add("FALL: " + std::to_string(fallCounter / 4));
}
// Comprueba si el jugador tiene suelo debajo de los pies
@@ -509,48 +393,15 @@ bool Player::isOnFloor()
updateFeet();
// Comprueba las superficies
for (auto f : underFeet)
{
onFloor |= room->checkTopSurfaces(&f);
}
// Comprueba las rampas
onFloor |= room->checkLeftSlopes(&underFeet[0]);
onFloor |= room->checkRightSlopes(&underFeet[1]);
if (onFloor)
{
debug->add("ONFLOOR");
const tile_e tile = (room->getTile(f));
onFloor |= (tile == t_wall || tile == t_passable || tile == t_slope_l || tile == t_slope_r);
}
return onFloor;
}
// Comprueba si el jugador está sobre una rampa hacia abajo
bool Player::isOnDownSlope()
{
bool onSlope = false;
updateFeet();
// Cuando el jugador baja una escalera, se queda volando
// Hay que mirar otro pixel más por debajo
underFeet[0].y += 1;
underFeet[1].y += 1;
// Comprueba las rampas
onSlope |= room->checkLeftSlopes(&underFeet[0]);
onSlope |= room->checkRightSlopes(&underFeet[1]);
if (onSlope)
{
debug->add("ONSLOPE");
}
return onSlope;
}
// Comprueba que el jugador no atraviese ninguna pared
bool Player::checkWalls()
{
@@ -568,6 +419,73 @@ bool Player::checkWalls()
return wall;
}
// Comprueba si el jugador está en una rampa
tile_e Player::checkSlopes()
{
// Actualiza los puntos de colisión
updateFeet();
bool slope_l = false;
bool slope_r = false;
// Comprueba si ha colisionado con una rampa
for (auto f : feet)
{
slope_l |= (room->getTile(f) == t_slope_l);
slope_r |= (room->getTile(f) == t_slope_r);
}
if (slope_l)
{
return t_slope_l;
}
if (slope_r)
{
return t_slope_r;
}
return t_empty;
}
// Comprueba si el jugador está en una rampa
tile_e Player::checkSlopes2()
{
// Actualiza los puntos de colisión
updateFeet();
bool slope_l = false;
bool slope_r = false;
bool wall = false;
bool passable = false;
// Comprueba si ha colisionado con una rampa
for (auto f : underFeet)
{
slope_l |= (room->getTile(f) == t_slope_l);
slope_r |= (room->getTile(f) == t_slope_r);
wall |= (room->getTile(f) == t_wall);
passable |= (room->getTile(f) == t_passable);
}
if (wall || passable)
{
return t_empty;
}
if (slope_l)
{
return t_slope_l;
}
if (slope_r)
{
return t_slope_r;
}
return t_empty;
}
// Obtiene algunos parametros del jugador
player_t Player::getSpawnParams()
{
@@ -577,7 +495,7 @@ player_t Player::getSpawnParams()
params.y = y;
params.vx = vx;
params.vy = vy;
params.jumpIni = jumpIni;
params.jump_ini = jump_ini;
params.state = state;
params.flip = sprite->getFlip();
@@ -632,11 +550,4 @@ bool Player::getInvincible()
void Player::setInvincible(bool value)
{
invincible = value;
}
// Cambia el estado del jugador
void Player::setState(state_e value)
{
prevState = state;
state = value;
}

View File

@@ -27,7 +27,7 @@ struct player_t
float y;
float vx;
float vy;
int jumpIni;
int jump_ini;
state_e state;
SDL_RendererFlip flip;
};
@@ -55,18 +55,12 @@ public:
std::vector<SDL_Point> underFeet; // Contiene los puntos que hay bajo cada pie del jugador
std::vector<SDL_Point> feet; // Contiene los puntos que hay en el pie del jugador
state_e state; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo
state_e prevState; // Estado previo en el que se encontraba el jugador
bool onBorder; // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
int border; // Indica en cual de los cuatro bordes se encuentra
bool invincible; // Si es invencible, no puede morir
SDL_Rect lastPosition; // Contiene la ultima posición del jugador, por si hay que deshacer algun movimiento
int jumpIni; // Valor del eje Y en el que se inicia el salto
int jump_ini; // Valor del eje Y en el que se inicia el salto
float maxVY; // Velocidad máxima que puede alcanzar al desplazarse en vertical
std::vector<JA_Sound> jumpSound; // Vecor con todos los sonidos del salto
std::vector<JA_Sound> fallSound; // Vecor con todos los sonidos de la caída
int jumpCounter; // Cuenta el tiempo de salto
int fallCounter; // Cuenta el tiempo de caida
SDL_Rect r;
// Comprueba las entradas y modifica variables
void checkInput();
@@ -92,30 +86,24 @@ public:
// Comprueba si ha finalizado el salto al alcanzar la altura de inicio
void checkJumpEnd();
// Calcula y reproduce el sonido de salto
void playJumpSound();
// Calcula y reproduce el sonido de caer
void playFallSound();
// Comprueba si el jugador tiene suelo debajo de los pies
bool isOnFloor();
// Comprueba si el jugador está sobre una rampa hacia abajo
bool isOnDownSlope();
// Comprueba que el jugador no atraviese ninguna pared
bool checkWalls();
// Comprueba si el jugador está en una rampa
tile_e checkSlopes();
// Comprueba si el jugador está en una rampa
tile_e checkSlopes2();
// Actualiza los puntos de colisión
void updateColliderPoints();
// Actualiza los puntos de los pies
void updateFeet();
// Cambia el estado del jugador
void setState(state_e value);
public:
// Constructor
Player(player_t ini, std::string tileset, std::string animation, SDL_Renderer *renderer, Asset *asset, Input *input, Room *room, Debug *debug);

View File

@@ -6,12 +6,6 @@
// Constructor
Room::Room(std::string file_path, SDL_Renderer *renderer, Screen *screen, Asset *asset, ItemTracker *itemTracker, int *items, Debug *debug)
{
// Inicializa variables
tileSize = 8;
mapWidth = 32;
mapHeight = 16;
tilesetWidth = 20;
// Copia los punteros a objetos
this->renderer = renderer;
this->asset = asset;
@@ -25,14 +19,6 @@ Room::Room(std::string file_path, SDL_Renderer *renderer, Screen *screen, Asset
texture = new LTexture(renderer, asset->get(tileset));
itemSound = JA_LoadSound(asset->get("item.wav").c_str());
// Calcula las superficies
setBottomSurfaces();
setTopSurfaces();
setLeftSurfaces();
setRightSurfaces();
setLeftSlopes();
setRightSlopes();
// Crea la textura para el mapa de tiles de la habitación
mapTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
if (mapTexture == NULL)
@@ -43,6 +29,12 @@ Room::Room(std::string file_path, SDL_Renderer *renderer, Screen *screen, Asset
// Establece el color del borde
screen->setBorderColor(borderColor);
// Inicializa variables
tileSize = 8;
mapWidth = 32;
mapHeight = 16;
tilesetWidth = 20;
}
// Destructor
@@ -109,11 +101,13 @@ bool Room::load(std::string _file_path)
// Si la linea contiene el texto [tilemap] se realiza el proceso de carga del fichero tmx
else if (line == "[tilemap]")
{
// printf("Loading tilemap...\n");
do
{
std::getline(file, line);
if (line.find(".tmx") != std::string::npos)
{
// printf("Reading file %s\n", asset->get(line).c_str());
std::ifstream file2(asset->get(line)); // Abre el fichero tmx
if (file2.good())
{
@@ -126,7 +120,11 @@ bool Room::load(std::string _file_path)
do
{
std::getline(file2, line);
// printf("parsing: %s\n", line.c_str());
pos = line.find("data encoding");
// printf("pos: %i\n", pos);
} while (pos == std::string::npos);
do
@@ -135,10 +133,12 @@ bool Room::load(std::string _file_path)
std::getline(file2, line);
if (line != "</data>")
{
// printf("data: %s\n", line.c_str());
std::stringstream ss(line);
std::string tmp;
while (getline(ss, tmp, ','))
{
// printf("tile: %s\n", tmp.c_str());
tilemap.push_back(std::stoi(tmp));
}
}
@@ -432,83 +432,8 @@ void Room::fillMapTexture()
clip.x = ((tilemap[(y * 32) + x] - 1) % 20) * 8;
clip.y = ((tilemap[(y * 32) + x] - 1) / 20) * 8;
texture->render(renderer, x * 8, y * 8, &clip);
if (debug->getEnabled())
{
if (clip.x != -8)
{
clip.x = x * 8;
clip.y = y * 8;
SDL_SetRenderDrawColor(renderer, 64, 64, 64, 224);
SDL_RenderFillRect(renderer, &clip);
}
}
}
// ****
if (debug->getEnabled())
{
// BottomSurfaces
if (true)
{
for (auto l : bottomSurfaces)
{
SDL_SetRenderDrawColor(renderer, (rand() % 128) + 96, (rand() % 128) + 96, (rand() % 128) + 96, 0xFF);
SDL_RenderDrawLine(renderer, l.x1, l.y, l.x2, l.y);
}
}
// TopSurfaces
if (true)
{
for (auto l : topSurfaces)
{
SDL_SetRenderDrawColor(renderer, (rand() % 128) + 96, (rand() % 128) + 96, (rand() % 128) + 96, 0xFF);
SDL_RenderDrawLine(renderer, l.x1, l.y, l.x2, l.y);
}
}
// LeftSurfaces
if (true)
{
for (auto l : leftSurfaces)
{
SDL_SetRenderDrawColor(renderer, (rand() % 128) + 96, (rand() % 128) + 96, (rand() % 128) + 96, 0xFF);
SDL_RenderDrawLine(renderer, l.x, l.y1, l.x, l.y2);
}
}
// RightSurfaces
if (true)
{
for (auto l : rightSurfaces)
{
SDL_SetRenderDrawColor(renderer, (rand() % 128) + 96, (rand() % 128) + 96, (rand() % 128) + 96, 0xFF);
SDL_RenderDrawLine(renderer, l.x, l.y1, l.x, l.y2);
}
}
// LeftSlopes
if (true)
{
for (auto l : leftSlopes)
{
SDL_SetRenderDrawColor(renderer, (rand() % 128) + 96, (rand() % 128) + 96, (rand() % 128) + 96, 0xFF);
SDL_RenderDrawLine(renderer, l.x1, l.y1, l.x2, l.y2);
}
}
// RightSlopes
if (true)
{
for (auto l : rightSlopes)
{
SDL_SetRenderDrawColor(renderer, (rand() % 128) + 96, (rand() % 128) + 96, (rand() % 128) + 96, 0xFF);
SDL_RenderDrawLine(renderer, l.x1, l.y1, l.x2, l.y2);
}
}
}
// ****
SDL_SetRenderTarget(renderer, nullptr);
}
@@ -617,42 +542,6 @@ tile_e Room::getTile(SDL_Point point)
return tile;
}
// Devuelve el tipo de tile que hay en ese indice
tile_e Room::getTile(int index)
{
const int maxTile = mapWidth * mapHeight;
tile_e tile = t_empty;
if (index < maxTile)
{
// Las filas 0-7 son de tiles t_wall
if ((tilemap[index] > 0) && (tilemap[index] < 8 * tilesetWidth))
{
return t_wall;
}
// La fila 8 es de tiles t_slope_r
else if ((tilemap[index] >= 8 * tilesetWidth) && (tilemap[index] < 9 * tilesetWidth))
{
return t_slope_r;
}
// La fila 9 es de tiles t_slope_l
else if ((tilemap[index] >= 9 * tilesetWidth) && (tilemap[index] < 10 * tilesetWidth))
{
return t_slope_l;
}
// Las filas 10-14 son de tiles t_passable
if ((tilemap[index] >= 10 * tilesetWidth) && (tilemap[index] < 15 * tilesetWidth))
{
return t_passable;
}
}
return tile;
}
// Indica si hay colision con un enemigo a partir de un rectangulo
bool Room::enemyCollision(SDL_Rect &rect)
{
@@ -713,387 +602,27 @@ int Room::getSlopeHeight(SDL_Point p, tile_e slope)
{
// Calcula la base del tile
int base = ((p.y / tileSize) * tileSize) + tileSize;
printf("base %i\n", base);
debug->add("BASE = " + std::to_string(base));
// Calcula cuanto se ha entrado en el tile horizontalmente
const int pos = (p.x % tileSize); // esto da un valor entre 0 y 7
printf("pos %i\n", base);
debug->add("POS = " + std::to_string(pos));
// Se resta a la base la cantidad de pixeles pos en funcion de la rampa
if (slope == t_slope_r)
{
base -= pos + 1;
printf("base_R %i\n", base);
debug->add("BASE_R = " + std::to_string(base));
}
else
{
base -= (tileSize - pos);
printf("base_L %i\n", base);
debug->add("BASE_L = " + std::to_string(base));
}
return base;
}
// Calcula las superficies inferiores
void Room::setBottomSurfaces()
{
std::vector<int> tile;
// Busca todos los tiles de tipo muro que no tengan debajo otro muro
// Hay que recorrer la habitación por filas (excepto los de la última fila)
for (int i = 0; i < tilemap.size() - mapWidth; i++)
{
if (getTile(i) == t_wall && getTile(i + mapWidth) != t_wall)
{
tile.push_back(i);
// Si llega al final de la fila, introduce un separador
if (i % mapWidth == mapWidth - 1)
{
tile.push_back(-1);
}
}
}
// Recorre el vector de tiles buscando tiles consecutivos para localizar las superficies
int i = 0;
while (i < tile.size())
{
h_line_t line;
line.x1 = (tile[i] % mapWidth) * tileSize;
line.y = ((tile[i] / mapWidth) * tileSize) + tileSize - 1;
while (tile[i] + 1 == tile[i + 1])
{
i++;
}
line.x2 = ((tile[i] % mapWidth) * tileSize) + tileSize - 1;
bottomSurfaces.push_back(line);
i++;
}
}
// Calcula las superficies superiores
void Room::setTopSurfaces()
{
std::vector<int> tile;
// Busca todos los tiles de tipo muro o pasable que no tengan encima un muro
// Hay que recorrer la habitación por filas (excepto los de la primera fila)
for (int i = mapWidth; i < tilemap.size(); i++)
{
if ((getTile(i) == t_wall || getTile(i) == t_passable) && getTile(i - mapWidth) != t_wall)
{
tile.push_back(i);
// Si llega al final de la fila, introduce un separador
if (i % mapWidth == mapWidth - 1)
{
tile.push_back(-1);
}
}
}
// Recorre el vector de tiles buscando tiles consecutivos para localizar las superficies
int i = 0;
while (i < tile.size())
{
h_line_t line;
line.x1 = (tile[i] % mapWidth) * tileSize;
line.y = (tile[i] / mapWidth) * tileSize;
while (tile[i] + 1 == tile[i + 1])
{
i++;
}
line.x2 = ((tile[i] % mapWidth) * tileSize) + tileSize - 1;
topSurfaces.push_back(line);
i++;
}
}
// Calcula las superficies laterales izquierdas
void Room::setLeftSurfaces()
{
std::vector<int> tile;
// Busca todos los tiles de tipo muro que no tienen a su izquierda un tile de tipo muro
// Hay que recorrer la habitación por columnas (excepto los de la primera columna)
for (int i = 1; i < mapWidth; ++i)
{
for (int j = 0; j < mapHeight; ++j)
{
const int pos = (j * mapWidth + i);
if (getTile(pos) == t_wall && getTile(pos - 1) != t_wall)
{
tile.push_back(pos);
}
}
}
// Recorre el vector de tiles buscando tiles consecutivos
// (Los tiles de la misma columna, la diferencia entre ellos es de mapWidth)
// para localizar las superficies
int i = 0;
while (i < tile.size())
{
v_line_t line;
line.x = (tile[i] % mapWidth) * tileSize;
line.y1 = ((tile[i] / mapWidth) * tileSize);
while (tile[i] + mapWidth == tile[i + 1])
{
i++;
}
line.y2 = ((tile[i] / mapWidth) * tileSize) + tileSize - 1;
leftSurfaces.push_back(line);
i++;
}
}
// Calcula las superficies laterales derechas
void Room::setRightSurfaces()
{
std::vector<int> tile;
// Busca todos los tiles de tipo muro que no tienen a su derecha un tile de tipo muro
// Hay que recorrer la habitación por columnas (excepto los de la última columna)
for (int i = 0; i < mapWidth - 1; ++i)
{
for (int j = 0; j < mapHeight; ++j)
{
const int pos = (j * mapWidth + i);
if (getTile(pos) == t_wall && getTile(pos + 1) != t_wall)
{
tile.push_back(pos);
}
}
}
// Recorre el vector de tiles buscando tiles consecutivos
// (Los tiles de la misma columna, la diferencia entre ellos es de mapWidth)
// para localizar las superficies
int i = 0;
while (i < tile.size())
{
v_line_t line;
line.x = ((tile[i] % mapWidth) * tileSize) + tileSize - 1;
line.y1 = ((tile[i] / mapWidth) * tileSize);
while (tile[i] + mapWidth == tile[i + 1])
{
i++;
}
line.y2 = ((tile[i] / mapWidth) * tileSize) + tileSize - 1;
rightSurfaces.push_back(line);
i++;
}
}
// Encuentra todas las rampas que suben hacia la izquierda
void Room::setLeftSlopes()
{
// Recorre la habitación entera por filas buscando tiles de tipo t_slope_l
std::vector<int> found;
for (int i = 0; i < tilemap.size(); ++i)
{
if (getTile(i) == t_slope_l)
{
found.push_back(i);
}
}
// El primer elemento es el inicio de una rampa. Se añade ese elemento y se buscan los siguientes,
// que seran i + mapWidth + 1. Conforme se añaden se eliminan y se vuelve a escudriñar el vector de
// tiles encontrados hasta que esté vacío
while (found.size() > 0)
{
d_line_t line;
line.x1 = (found[0] % mapWidth) * tileSize;
line.y1 = (found[0] / mapWidth) * tileSize;
int lookingFor = found[0] + mapWidth + 1;
int lastOneFound = found[0];
found.erase(found.begin());
for (int i = 0; i < found.size(); i++)
{
if (found[i] == lookingFor)
{
lastOneFound = lookingFor;
lookingFor += mapWidth + 1;
found.erase(found.begin() + i);
--i;
}
}
line.x2 = ((lastOneFound % mapWidth) * tileSize) + tileSize - 1;
line.y2 = ((lastOneFound / mapWidth) * tileSize) + tileSize - 1;
leftSlopes.push_back(line);
}
}
// Encuentra todas las rampas que suben hacia la derecha
void Room::setRightSlopes()
{
// Recorre la habitación entera por filas buscando tiles de tipo t_slope_r
std::vector<int> found;
for (int i = 0; i < tilemap.size(); ++i)
{
if (getTile(i) == t_slope_r)
{
found.push_back(i);
}
}
// El primer elemento es el inicio de una rampa. Se añade ese elemento y se buscan los siguientes,
// que seran i + mapWidth - 1. Conforme se añaden se eliminan y se vuelve a escudriñar el vector de
// tiles encontrados hasta que esté vacío
while (found.size() > 0)
{
d_line_t line;
line.x1 = ((found[0] % mapWidth) * tileSize) + tileSize - 1;
line.y1 = (found[0] / mapWidth) * tileSize;
int lookingFor = found[0] + mapWidth - 1;
int lastOneFound = found[0];
found.erase(found.begin());
for (int i = 0; i < found.size(); i++)
{
if (found[i] == lookingFor)
{
lastOneFound = lookingFor;
lookingFor += mapWidth - 1;
found.erase(found.begin() + i);
--i;
}
}
line.x2 = (lastOneFound % mapWidth) * tileSize;
line.y2 = ((lastOneFound / mapWidth) * tileSize) + tileSize - 1;
rightSlopes.push_back(line);
}
}
// Comprueba las colisiones
int Room::checkRightSurfaces(SDL_Rect *rect)
{
for (auto s : rightSurfaces)
{
if (checkCollision(s, *rect))
{
return s.x;
}
}
return -1;
}
// Comprueba las colisiones
int Room::checkLeftSurfaces(SDL_Rect *rect)
{
for (auto s : leftSurfaces)
{
if (checkCollision(s, *rect))
{
return s.x;
}
}
return -1;
}
// Comprueba las colisiones
int Room::checkTopSurfaces(SDL_Rect *rect)
{
for (auto s : topSurfaces)
{
if (checkCollision(s, *rect))
{
return s.y;
}
}
return -1;
}
// Comprueba las colisiones
int Room::checkBottomSurfaces(SDL_Rect *rect)
{
for (auto s : bottomSurfaces)
{
if (checkCollision(s, *rect))
{
return s.y;
}
}
return -1;
}
// Comprueba las colisiones
bool Room::checkTopSurfaces(SDL_Point *p)
{
for (auto s : topSurfaces)
{
if (checkCollision(s, *p))
{
return true;
}
}
return false;
}
// Comprueba las colisiones
int Room::checkLeftSlopes(v_line_t *line)
{
for (auto s : leftSlopes)
{
const SDL_Point p = checkCollision(s, *line);
if (p.x != -1)
{
return p.y;
}
}
return -1;
}
// Comprueba las colisiones
bool Room::checkLeftSlopes(SDL_Point *p)
{
for (auto s : leftSlopes)
{
if (checkCollision(*p, s))
{
return true;
}
}
return false;
}
// Comprueba las colisiones
int Room::checkRightSlopes(v_line_t *line)
{
for (auto s : rightSlopes)
{
const SDL_Point p = checkCollision(s, *line);
if (p.x != -1)
{
return p.y;
}
}
return -1;
}
// Comprueba las colisiones
bool Room::checkRightSlopes(SDL_Point *p)
{
for (auto s : rightSlopes)
{
if (checkCollision(*p, s))
{
return true;
}
}
return false;
}

View File

@@ -64,12 +64,7 @@ private:
JA_Sound itemSound; // Sonido producido al coger un objeto
int *itemsPicked; // Puntero a la cantidad de items recogidos que lleva el juego
Debug *debug; // Objeto para gestionar la información de debug
std::vector<h_line_t> bottomSurfaces; // Lista con las superficies inferiores de la habitación
std::vector<h_line_t> topSurfaces; // Lista con las superficies superiores de la habitación
std::vector<v_line_t> leftSurfaces; // Lista con las superficies laterales de la parte izquierda de la habitación
std::vector<v_line_t> rightSurfaces; // Lista con las superficies laterales de la parte derecha de la habitación
std::vector<d_line_t> leftSlopes; // Lista con todas las rampas que suben hacia la izquierda
std::vector<d_line_t> rightSlopes; // Lista con todas las rampas que suben hacia la derecha
std::vector<SDL_Rect> bottomSurfaces; // Lista con las superficies de colisón inferiores
int tileSize; // Ancho del tile en pixels
int mapWidth; // Ancho del mapa en tiles
@@ -91,27 +86,6 @@ private:
// Pinta el mapa de la habitación en la textura
void fillMapTexture();
// Calcula las superficies inferiores
void setBottomSurfaces();
// Calcula las superficies superiores
void setTopSurfaces();
// Calcula las superficies laterales izquierdas
void setLeftSurfaces();
// Calcula las superficies laterales derechas
void setRightSurfaces();
// Encuentra todas las rampas que suben hacia la izquierda
void setLeftSlopes();
// Encuentra todas las rampas que suben hacia la derecha
void setRightSlopes();
// Devuelve el tipo de tile que hay en ese indice
tile_e getTile(int index);
public:
// Constructor
Room(std::string file_path, SDL_Renderer *renderer, Screen *screen, Asset *asset, ItemTracker *item_tracker, int *items, Debug *debug);
@@ -157,33 +131,6 @@ public:
// Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile
int getSlopeHeight(SDL_Point p, tile_e slope);
// Comprueba las colisiones
int checkRightSurfaces(SDL_Rect *rect);
// Comprueba las colisiones
int checkLeftSurfaces(SDL_Rect *rect);
// Comprueba las colisiones
int checkTopSurfaces(SDL_Rect *rect);
// Comprueba las colisiones
int checkBottomSurfaces(SDL_Rect *rect);
// Comprueba las colisiones
bool checkTopSurfaces(SDL_Point *p);
// Comprueba las colisiones
int checkLeftSlopes(v_line_t *line);
// Comprueba las colisiones
bool checkLeftSlopes(SDL_Point *p);
// Comprueba las colisiones
int checkRightSlopes(v_line_t *line);
// Comprueba las colisiones
bool checkRightSlopes(SDL_Point *p);
};
#endif

View File

@@ -1,40 +0,0 @@
#include "room_tracker.h"
// Constructor
RoomTracker::RoomTracker()
{
}
// Destructor
RoomTracker::~RoomTracker()
{
list.clear();
}
// Comprueba si la habitación ya ha sido visitada
bool RoomTracker::hasBeenVisited(std::string name)
{
for (auto l : list)
{
if (l == name)
{
return true;
}
}
return false;
}
// Añade la habitación a la lista
bool RoomTracker::addRoom(std::string name)
{
// Comprueba si la habitación ya ha sido visitada
if (!hasBeenVisited(name))
{
// En caso contrario añádela a la lista
list.push_back(name);
return true;
}
return false;
}

View File

@@ -1,30 +0,0 @@
#pragma once
#include <SDL2/SDL.h>
#include "utils.h"
#include <string>
#include <vector>
#ifndef ROOM_TRACKER_H
#define ROOM_TRACKER_H
// Clase RoomTracker
class RoomTracker
{
private:
std::vector<std::string> list; // Lista con las habitaciones visitadas
// Comprueba si la habitación ya ha sido visitada
bool hasBeenVisited(std::string name);
public:
// Constructor
RoomTracker();
// Destructor
~RoomTracker();
// Añade la habitación a la lista
bool addRoom(std::string name);
};
#endif

View File

@@ -3,17 +3,18 @@
#include <sstream>
// Constructor
ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Asset *asset, board_t *board)
ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Asset *asset, int *lives, int *items, Uint32 *clock)
{
// Obten punteros a objetos
this->asset = asset;
this->renderer = renderer;
this->board = board;
this->lives = lives;
this->items = items;
this->clock = clock;
// Reserva memoria para los objetos
playerTexture = new LTexture(renderer, asset->get("player.png"));
itemTexture = new LTexture(renderer, asset->get("items.png"));
sprite = new AnimatedSprite(playerTexture, renderer, asset->get("player.ani"));
texture = new LTexture(renderer, asset->get("player01.png"));
sprite = new AnimatedSprite(texture, renderer, asset->get("player01.ani"));
sprite->setCurrentAnimation("walk_menu");
text = new Text(asset->get("smb2.png"), asset->get("smb2.txt"), renderer);
@@ -25,8 +26,8 @@ ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Asset *asset, board_t *board)
color_t c = stringToColor("blue");
color.push_back(c);
//c = stringToColor("red");
//color.push_back(c);
c = stringToColor("red");
color.push_back(c);
c = stringToColor("magenta");
color.push_back(c);
@@ -46,8 +47,8 @@ ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Asset *asset, board_t *board)
c = stringToColor("bright_blue");
color.push_back(c);
//c = stringToColor("bright_red");
//color.push_back(c);
c = stringToColor("bright_red");
color.push_back(c);
c = stringToColor("bright_magenta");
color.push_back(c);
@@ -68,8 +69,7 @@ ScoreBoard::ScoreBoard(SDL_Renderer *renderer, Asset *asset, board_t *board)
// Destructor
ScoreBoard::~ScoreBoard()
{
delete playerTexture;
delete itemTexture;
delete texture;
delete sprite;
delete text;
}
@@ -89,7 +89,7 @@ void ScoreBoard::render()
const int frame = desp % 4;
sprite->setCurrentFrame(frame);
for (int i = 0; i < board->lives; i++)
for (int i = 0; i < *lives; i++)
{
sprite->setPosX(8 + (16 * i) + desp);
index = i % color.size();
@@ -97,25 +97,18 @@ void ScoreBoard::render()
sprite->render();
}
// Muestra si suena la música
if (board->music)
{
const color_t c = stringToColor("bright_blue");
SDL_Rect clip = {0, 8, 8, 8};
itemTexture->setColor(c.r, c.g, c.b);
itemTexture->render(renderer, 20 * BLOCK, 20 * BLOCK, &clip);
}
// Escribe los textos
const std::string timeTxt = std::to_string((clock.minutes % 60) / 10) + std::to_string(clock.minutes % 10) + clock.separator + std::to_string((clock.seconds % 60) / 10) + std::to_string(clock.seconds % 10);
const std::string itemsTxt = std::to_string(board->items / 100) + std::to_string((board->items % 100) / 10) + std::to_string(board->items % 10);
const std::string roomsTxt = std::to_string(board->rooms / 100) + std::to_string((board->rooms % 100) / 10) + std::to_string(board->rooms % 10);
this->text->writeColored(22 * BLOCK, 20 * BLOCK, "Rooms", stringToColor("yellow"));
this->text->writeColored(28 * BLOCK, 20 * BLOCK, roomsTxt, stringToColor("bright_blue"));
this->text->writeColored(BLOCK, 22 * BLOCK, "Items collected ", stringToColor("yellow"));
this->text->writeColored(17 * BLOCK, 22 * BLOCK, itemsTxt, stringToColor("bright_blue"));
this->text->writeColored(20 * BLOCK, 22 * BLOCK, " Time ", stringToColor("yellow"));
this->text->writeColored(26 * BLOCK, 22 * BLOCK, timeTxt, stringToColor("bright_blue"));
const clock_t clock = getTime();
std::string itemsTxt = std::to_string(*items / 100) + std::to_string((*items % 100) / 10) + std::to_string(*items % 10);
std::string separator = " ";
if (clock.separator)
{
separator = ":";
}
std::string timeTxt = std::to_string((clock.minutes % 60) / 10) + std::to_string(clock.minutes % 10) + separator + std::to_string((clock.seconds % 60) / 10) + std::to_string(clock.seconds % 10);
std::string text = "Items collected " + itemsTxt + " Time " + timeTxt;
const color_t color = stringToColor("white");
this->text->writeColored(BLOCK, 22 * BLOCK, text, color);
}
// Actualiza las variables del objeto
@@ -123,27 +116,23 @@ void ScoreBoard::update()
{
counter++;
sprite->update();
clock = getTime();
}
// Obtiene el tiempo transcurrido de partida
ScoreBoard::clock_t ScoreBoard::getTime()
{
const Uint32 timeElapsed = SDL_GetTicks() - board->iniClock;
const Uint32 timeElapsed = SDL_GetTicks() - *clock;
clock_t time;
time.hours = timeElapsed / 3600000;
time.minutes = timeElapsed / 60000;
time.seconds = timeElapsed / 1000;
time.separator = (timeElapsed % 1000 <= 500) ? ":" : " ";
time.separator = (timeElapsed % 1000 <= 500);
return time;
}
// Recarga la textura
void ScoreBoard::reLoadTexture()
{
playerTexture->reLoad();
itemTexture->reLoad();
texture->reLoad();
text->reLoadTexture();
}

View File

@@ -11,15 +11,6 @@
#ifndef SCOREBOARD_H
#define SCOREBOARD_H
struct board_t
{
int items; // Lleva la cuenta de los objetos recogidos
int lives; // Lleva la cuenta de ls vidas restantes del jugador
int rooms; // Lleva la cuenta de las habitaciones visitadas
bool music; // Indica si ha de sonar la musica durante el juego
Uint32 iniClock;
};
// Clase ScoreBoard
class ScoreBoard
{
@@ -29,10 +20,10 @@ private:
int hours;
int minutes;
int seconds;
std::string separator;
bool separator;
};
LTexture *playerTexture; // Textura con los graficos para las vidas
LTexture *texture; // Textura con los graficos para las vidas
AnimatedSprite *sprite; // Sprite para mostrar las vidas en el marcador
SDL_Renderer *renderer; // El renderizador de la ventana
Asset *asset; // Objeto con la ruta a todos los ficheros de recursos
@@ -40,16 +31,16 @@ private:
std::vector<color_t> color; // Vector con los colores del objeto
int counter; // Contador interno
int colorChangeSpeed; // Cuanto mas alto, mas tarda en cambiar de color
clock_t clock; // Contiene las horas, minutos y segundos transcurridos desde el inicio de la partida
LTexture *itemTexture; // Textura con los graficos para las vidas
board_t *board; // Contiene las variables a mostrar en el marcador
int *lives; // Número ara mostrar en el marcador de vidas
int *items; // Número para mostrar en el marcador de items
Uint32 *clock; // Contiene el tiempo de inicio de la partida
// Obtiene el tiempo transcurrido de partida
clock_t getTime();
public:
// Constructor
ScoreBoard(SDL_Renderer *renderer, Asset *asset, board_t *board);
ScoreBoard(SDL_Renderer *renderer, Asset *asset, int *lives, int *items, Uint32 *clock);
// Destructor
~ScoreBoard();

View File

@@ -1,79 +0,0 @@
#include "test.h"
// Constructor
Test::Test(SDL_Renderer *renderer, Screen *screen, Asset *asset, Debug *debug)
{
// Copia la dirección de los objetos
this->renderer = renderer;
this->screen = screen;
this->asset = asset;
this->debug = debug;
// Inicializa variables
for (int i = 0; i < 4; ++i)
{
point_t p;
p.x = rand() % 256;
p.y = rand() % 192;
p.vx = (float)((rand() % 10) + 1) / 10.0f;
p.vy = (float)((rand() % 10) + 1) / 10.0f;
rand() % 2 == 0 ? p.dx = -1 : p.dx = 1;
rand() % 2 == 0 ? p.dy = -1 : p.dy = 1;
p.vx *= p.dx;
p.vy *= p.dy;
points.push_back(p);
}
}
// Destructor
Test::~Test()
{
}
// Actualiza las variables
void Test::update()
{
for (int i = 0; i < points.size(); ++i)
{
points[i].x += points[i].vx;
points[i].y += points[i].vy;
if (points[i].x > 255)
{
points[i].x = 255;
points[i].vx = -(float)((rand() % 10) + 1) / 10.0f;
}
else if (points[i].x < 0)
{
points[i].x = 0;
points[i].vx = (float)((rand() % 10) + 1) / 10.0f;
}
if (points[i].y > 191)
{
points[i].y = 191;
points[i].vy = -(float)((rand() % 10) + 1) / 10.0f;
}
else if (points[i].y < 0)
{
points[i].y = 0;
points[i].vy = (float)((rand() % 10) + 1) / 10.0f;
}
std::string text = "P" + std::to_string(i) + ": x=" + std::to_string(points[i].x).substr(0,3) + " y=" + std::to_string(points[i].y).substr(0,3) + " vx=" + std::to_string(points[i].vx).substr(0,3) + " vy=" + std::to_string(points[i].vy).substr(0,3);
debug->add(text);
}
}
// Dibuja en pantalla
void Test::render()
{
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
line_t l1 = {(int)points[0].x, (int)points[0].y, (int)points[1].x, (int)points[1].y};
line_t l2 = {(int)points[2].x, (int)points[2].y, (int)points[3].x, (int)points[3].y};
SDL_RenderDrawLine(renderer, l1.x1, l1.y1, l1.x2, l1.y2);
SDL_RenderDrawLine(renderer, l2.x1, l2.y1, l2.x2, l2.y2);
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_Point p = checkCollision(l1, l2);
SDL_RenderDrawPoint(renderer, p.x, p.y);
}

View File

@@ -1,48 +0,0 @@
#pragma once
#include <SDL2/SDL.h>
#include "const.h"
#include "utils.h"
#include "screen.h"
#include "asset.h"
#include "text.h"
#include "debug.h"
#include <vector>
#include <string>
#ifndef TEST_H
#define TEST_H
struct point_t
{
float x, y;
float vx, vy;
int dx, dy;
};
// Clase Test
class Test
{
private:
SDL_Renderer *renderer; // El renderizador de la ventana
Screen *screen; // Objeto encargado de dibujar en pantalla
Asset *asset; // Objeto con los ficheros de recursos
Debug *debug;
std::vector<point_t> points;
public:
// Constructor
Test(SDL_Renderer *renderer, Screen *screen, Asset *asset, Debug *debug);
// Destructor
~Test();
// Actualiza las variables
void update();
// Dibuja en pantalla
void render();
};
#endif

View File

@@ -73,31 +73,6 @@ void Title::checkEventHandler()
section.subsection = 0;
break;
case SDL_SCANCODE_F:
screen->switchVideoMode();
texture->reLoad();
break;
case SDL_SCANCODE_F1:
screen->setWindowSize(1);
texture->reLoad();
break;
case SDL_SCANCODE_F2:
screen->setWindowSize(2);
texture->reLoad();
break;
case SDL_SCANCODE_F3:
screen->setWindowSize(3);
texture->reLoad();
break;
case SDL_SCANCODE_F4:
screen->setWindowSize(4);
texture->reLoad();
break;
default:
break;
}

View File

@@ -1,5 +1,4 @@
#include "utils.h"
#include <math.h>
// Calcula el cuadrado de la distancia entre dos puntos
double distanceSquared(int x1, int y1, int x2, int y2)
@@ -75,19 +74,19 @@ bool checkCollision(circle_t &a, SDL_Rect &b)
// Detector de colisiones entre dos rectangulos
bool checkCollision(SDL_Rect &a, SDL_Rect &b)
{
// Calcula las caras del rectangulo a
// Calculate the sides of rect A
const int leftA = a.x;
const int rightA = a.x + a.w;
const int topA = a.y;
const int bottomA = a.y + a.h;
// Calcula las caras del rectangulo b
// Calculate the sides of rect B
const int leftB = b.x;
const int rightB = b.x + b.w;
const int topB = b.y;
const int bottomB = b.y + b.h;
// Si cualquiera de las caras de a está fuera de b
// If any of the sides from A are outside of B
if (bottomA <= topB)
{
return false;
@@ -108,252 +107,36 @@ bool checkCollision(SDL_Rect &a, SDL_Rect &b)
return false;
}
// Si ninguna de las caras está fuera de b
// If none of the sides from A are outside B
return true;
}
// Detector de colisiones entre un punto y un rectangulo
// Detector de colisiones entre un punto y u rectangulo
bool checkCollision(SDL_Point &p, SDL_Rect &r)
{
// Comprueba si el punto está a la izquierda del rectangulo
// Comprueba si el punto está fuera del rectangulo en el eje X
if (p.x < r.x)
{
return false;
}
// Comprueba si el punto está a la derecha del rectangulo
if (p.x > r.x + r.w)
{
return false;
}
// Comprueba si el punto está por encima del rectangulo
// Comprueba si el punto está fuera del rectangulo en el eje Y
if (p.y < r.y)
{
return false;
}
// Comprueba si el punto está por debajo del rectangulo
if (p.y > r.y + r.h)
{
return false;
}
// Si no está fuera, es que está dentro
return true;
}
// Detector de colisiones entre una linea horizontal y un rectangulo
bool checkCollision(h_line_t &l, SDL_Rect &r)
{
// Comprueba si la linea esta por encima del rectangulo
if (l.y < r.y)
{
return false;
}
// Comprueba si la linea esta por debajo del rectangulo
if (l.y >= r.y + r.h)
{
return false;
}
// Comprueba si el inicio de la linea esta a la derecha del rectangulo
if (l.x1 >= r.x + r.w)
{
return false;
}
// Comprueba si el final de la linea esta a la izquierda del rectangulo
if (l.x2 < r.x)
{
return false;
}
// Si ha llegado hasta aquí, hay colisión
return true;
}
// Detector de colisiones entre una linea vertical y un rectangulo
bool checkCollision(v_line_t &l, SDL_Rect &r)
{
// Comprueba si la linea esta por la izquierda del rectangulo
if (l.x < r.x)
{
return false;
}
// Comprueba si la linea esta por la derecha del rectangulo
if (l.x >= r.x + r.w)
{
return false;
}
// Comprueba si el inicio de la linea esta debajo del rectangulo
if (l.y1 >= r.y + r.h)
{
return false;
}
// Comprueba si el final de la linea esta encima del rectangulo
if (l.y2 < r.y)
{
return false;
}
// Si ha llegado hasta aquí, hay colisión
return true;
}
// Detector de colisiones entre una linea horizontal y un punto
bool checkCollision(h_line_t &l, SDL_Point &p)
{
// Comprueba si el punto esta sobre la linea
if (p.y > l.y)
{
return false;
}
// Comprueba si el punto esta bajo la linea
if (p.y < l.y)
{
return false;
}
// Comprueba si el punto esta a la izquierda de la linea
if (p.x < l.x1)
{
return false;
}
// Comprueba si el punto esta a la derecha de la linea
if (p.x > l.x2)
{
return false;
}
// Si ha llegado aquí, hay colisión
return true;
}
// Detector de colisiones entre dos lineas
SDL_Point checkCollision(line_t &l1, line_t &l2)
{
const float x1 = l1.x1;
const float y1 = l1.y1;
const float x2 = l1.x2;
const float y2 = l1.y2;
const float x3 = l2.x1;
const float y3 = l2.y1;
const float x4 = l2.x2;
const float y4 = l2.y2;
// calculate the direction of the lines
float uA = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1));
float uB = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1));
// if uA and uB are between 0-1, lines are colliding
if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1)
{
// Calcula la intersección
const float x = x1 + (uA * (x2 - x1));
const float y = y1 + (uA * (y2 - y1));
return {(int)round(x), (int)round(y)};
}
return {-1, -1};
}
// Detector de colisiones entre dos lineas
SDL_Point checkCollision(d_line_t &l1, v_line_t &l2)
{
const float x1 = l1.x1;
const float y1 = l1.y1;
const float x2 = l1.x2;
const float y2 = l1.y2;
const float x3 = l2.x;
const float y3 = l2.y1;
const float x4 = l2.x;
const float y4 = l2.y2;
// calculate the direction of the lines
float uA = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1));
float uB = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1));
// if uA and uB are between 0-1, lines are colliding
if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1)
{
// Calcula la intersección
const float x = x1 + (uA * (x2 - x1));
const float y = y1 + (uA * (y2 - y1));
return {(int)x, (int)y};
}
return {-1, -1};
}
// Detector de colisiones entre una linea diagonal y una vertical
/*bool checkCollision(d_line_t &l1, v_line_t &l2)
{
// Normaliza la linea diagonal
normalizeLine(l1);
// Comprueba si la linea vertical esta a la izquierda de la linea diagonal
if (l2.x < l1.x1)
{
return false;
}
// Comprueba si la linea vertical esta a la derecha de la linea diagonal
if (l2.x > l1.x2)
{
return false;
}
// Inacabada
return true;
}*/
// Normaliza una linea diagonal
void normalizeLine(d_line_t &l)
{
// Las lineas diagonales van de izquierda a derecha
// x2 mayor que x1
if (l.x2 < l.x1)
{
const int x = l.x1;
const int y = l.y1;
l.x1 = l.x2;
l.y1 = l.y2;
l.x2 = x;
l.y2 = y;
}
}
// Detector de colisiones entre un punto y una linea diagonal
bool checkCollision(SDL_Point &p, d_line_t &l)
{
// Comprueba si el punto está en alineado con la linea
if (abs(p.x - l.x1) != abs(p.y - l.y1))
{
return false;
}
// Comprueba si está a la derecha de la linea
if (p.x > l.x1 && p.x > l.x2)
{
return false;
}
// Comprueba si está a la izquierda de la linea
if (p.x < l.x1 && p.x < l.x2)
{
return false;
}
// En caso contrario, el punto está en la linea
// Si ha llegado hasta aquí, es que está dentro
return true;
}

View File

@@ -34,30 +34,6 @@ struct circle_t
int r;
};
// Estructura para definir una linea horizontal
struct h_line_t
{
int x1, x2, y;
};
// Estructura para definir una linea vertical
struct v_line_t
{
int x, y1, y2;
};
// Estructura para definir una linea diagonal
struct d_line_t
{
int x1, y1, x2, y2;
};
// Estructura para definir una linea
struct line_t
{
int x1, y1, x2, y2;
};
// Estructura para definir un color
struct color_t
{
@@ -98,33 +74,9 @@ bool checkCollision(circle_t &a, SDL_Rect &b);
// Detector de colisiones entre un dos rectangulos
bool checkCollision(SDL_Rect &a, SDL_Rect &b);
// Detector de colisiones entre un punto y un rectangulo
// Detector de colisiones entre un punto y u rectangulo
bool checkCollision(SDL_Point &p, SDL_Rect &r);
// Detector de colisiones entre una linea horizontal y un rectangulo
bool checkCollision(h_line_t &l, SDL_Rect &r);
// Detector de colisiones entre una linea vertical y un rectangulo
bool checkCollision(v_line_t &l, SDL_Rect &r);
// Detector de colisiones entre una linea horizontal y un punto
bool checkCollision(h_line_t &l, SDL_Point &p);
// Detector de colisiones entre dos lineas
SDL_Point checkCollision(line_t &l1, line_t &l2);
// Detector de colisiones entre dos lineas
SDL_Point checkCollision(d_line_t &l1, v_line_t &l2);
// Detector de colisiones entre una linea diagonal y una vertical
//bool checkCollision(d_line_t &l1, v_line_t &l2);
// Detector de colisiones entre un punto y una linea diagonal
bool checkCollision(SDL_Point &p, d_line_t &l);
// Normaliza una linea diagonal
void normalizeLine(d_line_t &l);
// Devuelve un color_t a partir de un string
color_t stringToColor(std::string str);

View File

@@ -12,7 +12,6 @@ x (A) Modificar el salto para que coincida con el del JSW, no ha de colisionar l
(A) Crear tiles que arrastren, tipo cinta transportadora
(A) Tiles animados
(A) Crear ascensores
x (A) Crear rampas
x (A) Enemigos de diferente tamaño {cm:2022-08-30}
(A) Color de los items al estilo jet set willy de amstrad, que brillan con dos colores
x (A) Temporizador de inicio de los items, para poder hacer que brillen a distinto ritmo. Esto es incompatible con lo anterior {cm:2022-08-30}
@@ -24,9 +23,8 @@ x (A) Tecla F para pasar a pantalla completa {cm:2022-08-30}
x (A) Tecla + y - para cambiar tamaño de ventana. O control F1 a F4 {cm:2022-08-30}
(A) Poner en el marcador el indicador de si esta sonando la música
(A) Poner en el marcador el numero de habitaciones visitadas
(A) Los textos del marcador de colores
x (A) Añadir a cada habitación el color del borde
x (A) Añadir a cada habitación el color del nombre de la habitación
(A) Añadir a cada habitación el color del nombre de la habitación
x (A) Crear el logo al estilo del logo de ERBE o TOPO, con lineas que lo formen
x (A) El titulo del juego hacerlo parecido al del Jet Set Willy in Paris