#!/usr/bin/perl 
# Any object can perhaps be used as a weapon, with varying success.
#use Mooix::Thing;
#use Mooix::Root;
run sub {
	my $this=shift;
	%_=@_;
	my $avatar=$_{avatar};
	my $target=$_{direct_object};

	# Autotake.
	if ($this != $avatar && $this->location != $avatar) {
		$this->take_verb(%_);
		if ($this->location != $avatar) {
			fail "You look for something else to attack with.";
		}
	}

	# Check for unset combat_ok field in outermost location.
	if ($target->isa($Mooix::Root->abstract->animate)) {
		my $loc = $target->location;
		while ($loc->location) {
			$loc=$loc->location;
		}
		unless ($loc->combat_ok) {
			fail "A mysterious force quells your thoughts of violence.";
		}
	}
	
	if ($target->hitpoints <= $target->minhitpoints) {
		fail ucfirst($target->gender_subject_pronoun)."'s already dead!";
	}
	elsif ($target == $this) {
		fail "That is foolish.";
	}
	
	# Close to D&D style dice rolling here with natural 20 and 1.
	my $roll = int(rand(19))+1;
	my $hit;
	if ($roll == 20) {
		$hit = 1;
	}
	elsif ($roll == 1) {
		$hit = 0;
	}
	else {
		$hit = (($roll + $avatar->offense - $target->defense) >= 1);
	}

	if ($hit) {
		my $damage=int($this->calcdamage(target => $target, %_));
		if ($damage <= 0) {
			fail "That seems unlikely to do any real damage.";
		}
		$this->msg('attack', %_, target => $target);
		$target->damage($damage) if $damage > 0;
	}
	else {
		$this->msg('miss', %_, target => $target);
	}
}
