/*
 * arcane - A rogue-like game engine
 * Copyright (C) 2005  Petr Baudis <pasky@ucw.cz>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <cstdlib>

#include "cinfo.h"
#include "mainui.h"
#include "monster.h"


Monster::Monster(CreatureInfo &cinfo, Level *level, unsigned x, unsigned y)
	: Creature(cinfo, level, x, y)
{
}

Monster *
Monster::spawn_random(CreatureInfo &cinfo, Level *level)
{
	unsigned x, y;
	do { level->randpos(x, y); } while ((*level)(x, y).occupied());

	Monster *m = new Monster(cinfo, level, x, y);
	m->get();
	return m;
}

Monster *
Monster::spawn_nearby(CreatureInfo &cinfo, MapObject &whom, Level *level)
{
	unsigned x, y; int dx, dy;
	do {
		level->randpos(x, y);
		dx = (x - whom.x()); dx *= dx;
		dy = (y - whom.y()); dy *= dy;
	} while ((*level)(x, y).occupied() || (rand(4*(dx + dy))));

	Monster *m = new Monster(cinfo, level, x, y);
	m->get();
	return m;
}

void
Monster::move(enum Direction dir)
{
	try {
		Creature::move(dir);
	} catch (class Creature::X_creatdir x) {
		std::string msg;
		fight(*this, *x.c, msg, FF_NORMAL);
		ui->msg(msg);
	}
}

void
Monster::tick(Game &game)
{
	Creature::tick(game);

	int hint;
	enum Direction dir = getdir(x(), y(), game.player().x(), game.player().y(), hint);
	try {
		move(dir);
	} catch (class MapObject::X_rockdir x) {
		if (hint == 0)
			hint = 1 - 2*(rand(2));
		dir = Direction((int(dir) + hint + DIRS) % DIRS);
		try {
			move(dir);
		} catch (class MapObject::X_rockdir x) {
			// tough luck
		}
	}
}
