#include "beast.h"
#include "map.h"
#include "main.h"
#include "player.h"

beast::beast() {
	setchar('H');
	setcol(RED);
	live = true;
	settype("beast");
}

int beast::setpos(int px, int py) {
	std::string s = "";
	if (m->spriteat(px, py) == NULL) s = "null";
	else s = m->spriteat(px, py)->mytype();

	if (s == "null" || s == "player") {
		x = px; y = py;
		return 0;
	}
	return 1;
}
bool beast::isalive() {return live;}
int beast::squish(int dir) {
	if (!live) return -1;
	sprite* s = m->spriteat(x + DIRX[dir], y + DIRY[dir]);
	if (s == NULL) return -1;

	if (s->mytype() == "block" || s->mytype() == "wall") {
		live = false;
		return 5;
	}
	return -1;
}

bool beast::move() {
	if (!live) return false;

	//int dir = dirclose();
	int score = -1;
	int dir = -1;
	sprite *s;
	for (int i = 0; i < 8; i++) {
		//dir = (dir + (i * (-1 * (i % 2)))) % 8;
		std::string type = "null";
		if (m->spriteat(x + DIRX[i], y + DIRY[i]) != NULL)
			type = m->spriteat(x + DIRX[i], y + DIRY[i])->mytype();

		//score[i] = '?';
		if (type == "null" || type == "player") {
			int tmpscore = -1;
			for (int p = 0; p < NUM_PLAYERS; p++) {
				if (playas[p] == NULL || !playas[p]->isalive()) continue;
				int dx = playas[p]->getx() - (x + DIRX[i]);
				int dy = playas[p]->gety() - (y + DIRY[i]);
				int d = (dx * dx + dy * dy);
				if (tmpscore == -1 || d < tmpscore) tmpscore = d;
			}
			if (type == "player")
				tmpscore = 0;
			if (tmpscore < score || score == -1) {
				score = tmpscore;
				dir = i;
				s = m->spriteat(x + DIRX[i], y + DIRY[i]);
			}
		}
	}
	if (dir == -1) return false;
	m->setsprite(x, y, NULL);
	setpos(x + DIRX[dir], y + DIRY[dir]);
	if (s != NULL && s->mytype() == "player") {
		((player*)m->spriteat(x, y))->incscore(-5);
		((player*)m->spriteat(x, y))->setlive(false);
	}
	m->setsprite(x, y, this);
	return true;
}
int beast::getx() { return x; }
int beast::gety() { return y; }

beast::~beast() { }
//bool live;
//int x; int y;
