// v1.0.1
// groupnpc.txt
// Xoid (xoid@hotmail.com)

// Version History:
//   v1.0.1 - Version by Xoid. Forked off from v1.0.2 of basicnpc.txt
//   v1.0.0 - Version by Jeff Vogel. Original.

// basicnpc.txt
// A very simple, naive script. Creature attacks anything nearby that's hostile
// to it. If it wins, it returns to its home.

// Memory Cells:
//   0 - Movement type.
//     Legal values are: 0 - Wander randomly.
//                       1 - Stand still until a target appears.
//                       2 - Completely immobile, even if target appears.

// 1,2 - SDF coordinates. If these are left at 0 and 0, these memory cells are
//     ignored. Otherwise, the SDF is incremented by 1 when this creature dies.

//   3 - Dialogue node. The creature will start with this node if talked to. If
//     this memory cell is left at 0, the creature doesn't talk.

//   4 - Maximum distance.  If memory cell 0 is != 0, then this memory cell is
//       ignored. Otherwise, this is the maximum distance the creature will roam
//       from its starting position. If left at 0, this will default to 6 tiles.
//
//     [Making this script backwards compatible with v1.0.0 of basicnpc.txt]

begincreaturescript;

variables;
	short i,target;
	short i_gave_alert = 0;
body;

beginstate INIT_STATE;
	if (get_memory_cell(0) == 2)
		set_mobility(ME,0);

	if (get_memory_cell(4) == 0)
		set_memory_cell(4,6);
break;

beginstate DEAD_STATE;
	// Increment the appropriate SDF for this NPC's death.
	if ((get_memory_cell(1) != 0) || (get_memory_cell(2) != 0))
		inc_flag(get_memory_cell(1),get_memory_cell(2),1);
break;

beginstate START_STATE;
	// If I have a target, go attack it.
	if (target_ok()) {
		if (dist_to_char(get_target()) <= 16)
			set_state(3);
		else set_target(ME,-1);
	}

	// Look for a target, and attack it if its visible.
	if (select_target(ME,8,0)) {
		do_attack();
		set_state(3);
	}

	// React if I have been attacked.
	if (who_hit_me() >= 0) {
		set_target(ME,who_hit_me());
		do_attack();
		set_state(3);
	}

	// Otherwise, just peacefully move around. Go back to start if I roam
	// too far.
	if ((my_dist_from_start() >= get_memory_cell(4)) || ((my_dist_from_start() > 0) && (get_memory_cell(0) > 0))) {
		if (get_ran(1,1,100) < 40)
			return_to_start(ME,1);
	}
	else if (get_memory_cell(0) == 0) {
		fidget(ME,25);
	}

	// If I'm in combat and nothing above gave me something to do, stop now.
	// Otherwise the script will keep running, eating up CPU cycles.
	if (am_i_doing_action() == FALSE)
		end_combat_turn();
break;

beginstate 3; // Attacking...
	if ((what_group_in(ME) > 0) && (i_gave_alert == 0)) {
		alert_char(1000 + what_group_in(ME));
		i_gave_alert = 1;
	}
	if (target_ok() == FALSE)
		set_state(START_STATE);
	do_attack();
break;

beginstate TALKING_STATE;
	if (get_memory_cell(3) == 0) {
		print_str("Talking: It doesn't respond.");
		end();
	}
	begin_talk_mode(get_memory_cell(3));
break;