#include "Ghost.h"
#include "User.h"
#include <stdlib.h>


// Default Constructor- draws ghost at given coordinates
Ghost::Ghost( DisplayInterface &d, int x, int y, int _actingspeed,
			  Direction _direction ) : Mobile( _actingspeed, _direction )
{
	d.DrawSprite( x, y, SPRITE_GHOST_1 );
}

// returns Ghost identity
int Ghost::identify( )
{
	return ghost_id;
}

// takes a turn to act in the world
bool Ghost::act( DisplayInterface &d, World *w, int x, int y, int time )
{
	if( time % actingspeed == 0 && lastmoved != time ) {
		lastmoved = time;
		int newx = x, newy = y;
		if( rand( ) % 2 == 0 ) {
			newx = x + rand( ) % 3 - 1;
		}
		else {
			newy = y + rand( ) % 3 - 1;
		}

		// Slightly intelligent ghosts-  move toward user if 1 or 2
		// postions away.
		if( w->get_object( x + 1, y )->identify( ) == user_id ) {
			newx = x + 1;
			newy = y;
		}
		if( w->get_object( x - 1, y )->identify( ) == user_id ) {
			newx = x - 1;
			newy = y;
		}
		if( w->get_object( x, y + 1 )->identify( ) == user_id ) {
			newx = x;
			newy = y + 1;
		}
		if( w->get_object( x, y - 1 )->identify( ) == user_id ) {
			newx = x;
			newy = y - 1;
		}
		if( w->get_object( x + 2, y )->identify( ) == user_id ) {
			newx = x + 1;
			newy = y;
		}
		if( w->get_object( x - 2, y )->identify( ) == user_id ) {
			newx = x - 1;
			newy = y;
		}
		if( w->get_object( x, y + 2 )->identify( ) == user_id ) {
			newx = x;
			newy = y + 1;
		}
		if( w->get_object( x, y - 2 )->identify( ) == user_id ) {
			newx = x;
			newy = y - 1;
		}
		if( newx != x || newy != y ) {
			switch( w->get_object( newx, newy )->identify( ) ) {
			case space_id: case pellet_id:
				w->swap_object( d, x, y, newx, newy );
				break;
			case user_id:
				{
					User *u = static_cast<User*>(w->get_object(newx, newy));
					if (! u->is_super())
					{
						u->die( d, w, newx, newy );
						return (w->GetLives() > 0);
					}
				}
			}
		}
	}
	return true;
}

// disappears from the world
void Ghost::die( DisplayInterface &d, World *w, int x, int y ) { }


// shows the object at its spot in the world
void Ghost::show( DisplayInterface &d, World *w, int x, int y )
{
	d.DrawSprite( x, y, SPRITE_GHOST_1 );
}