#include "jugador.hpp"

//el puntero estático por defecto vale NULL
SDL_Surface * Jugador::imagen=0;
int Jugador::numeroDeJugadores=0;

Jugador::Jugador()
{
	//cargamos la imagen solamente si no ha sido ya cargada (si el puntero vale NULL)
	if (!imagen)
	{
		imagen = SDL_LoadBMP("ghost.bmp");
		//llevamos la cuenta de jugadores para luego saber si debemos liberar la imagen o no
	}
	numeroDeJugadores++;
	//Le informamos de que su color clave es el blanco
	SDL_SetColorKey(imagen,SDL_SRCCOLORKEY,SDL_MapRGB(imagen->format,0xFF,0xFF,0xFF));
	posicion.x = posicion.y = posicion.w = posicion.h = 0;
	velocidadX = velocidadY = 0;
}

void Jugador::presionDerecha()
{
	velocidadX += incrementoX;
}

void Jugador::presionIzquierda()
{
	velocidadX -= incrementoX;
}

void Jugador::presionArriba()
{
	velocidadY -= incrementoY;
}

void Jugador::presionAbajo()
{
	velocidadY += incrementoY;
}

void Jugador::noPresionDerecha()
{
	velocidadX -= incrementoX;
}

void Jugador::noPresionIzquierda()
{
	velocidadX += incrementoX;
}

void Jugador::noPresionArriba()
{
	velocidadY += incrementoY;
}

void Jugador::noPresionAbajo()
{
	velocidadY -= incrementoY;
}


void Jugador::calcularSiguiente(Uint32 tiempo)
{
	//Aquí tomamos el tiempo actual, le restamos el anterior, y lo dividimos para 
	//pasarlo a segundos (0.02 segundos, por ejemplo). Lo multiplicamos por la 
	//velocidad, lo pasamos a int, y el resultado se lo sumamos a la x y a la y
	posicion.x += (int)(velocidadX * (tiempo/1000.0));
	if (posicion.x < 0) posicion.x = 0;
	if (posicion.x > (640 - imagen->w) ) posicion.x = (640 - imagen->w);
	posicion.y += (int)(velocidadY * (tiempo/1000.0));
	if (posicion.y < 0) posicion.y = 0;
	if (posicion.y > (480 - imagen->h) ) posicion.y = (480 - imagen->h);
}

bool Jugador::dibujar(SDL_Surface *pantalla)
{
	//Copiamos la imagen en la pantalla
	return SDL_BlitSurface(imagen,0,pantalla,&posicion);
}

Jugador::~Jugador()
{
	//decrementamos la cuenta de jugadores
	numeroDeJugadores--;
	
	//si ya no quedan jugadores, se puede liberar la (unica) imagen que habiamos cargado en memoria
	if (!numeroDeJugadores)
	{
		SDL_FreeSurface(imagen);
	
	}
}

