1 /**
2  * \file mon-move.c
3  * \brief Monster movement
4  *
5  * Monster AI affecting movement and spells, process a monster
6  * (with spells and actions of all kinds, reproduction, effects of any
7  * terrain on monster movement, picking up and destroying objects),
8  * process all monsters.
9  *
10  * Copyright (c) 1997 Ben Harrison, David Reeve Sward, Keldon Jones.
11  *
12  * This work is free software; you can redistribute it and/or modify it
13  * under the terms of either:
14  *
15  * a) the GNU General Public License as published by the Free Software
16  *    Foundation, version 2, or
17  *
18  * b) the "Angband licence":
19  *    This software may be copied and distributed for educational, research,
20  *    and not for profit purposes provided that this copyright and statement
21  *    are included in all such copies.  Other copyrights may also apply.
22  */
23 
24 
25 #include "angband.h"
26 #include "cave.h"
27 #include "game-world.h"
28 #include "init.h"
29 #include "monster.h"
30 #include "mon-attack.h"
31 #include "mon-desc.h"
32 #include "mon-group.h"
33 #include "mon-lore.h"
34 #include "mon-make.h"
35 #include "mon-predicate.h"
36 #include "mon-spell.h"
37 #include "mon-util.h"
38 #include "mon-timed.h"
39 #include "obj-desc.h"
40 #include "obj-ignore.h"
41 #include "obj-knowledge.h"
42 #include "obj-pile.h"
43 #include "obj-slays.h"
44 #include "obj-tval.h"
45 #include "obj-util.h"
46 #include "player-calcs.h"
47 #include "player-timed.h"
48 #include "player-util.h"
49 #include "project.h"
50 #include "trap.h"
51 
52 
53 /**
54  * ------------------------------------------------------------------------
55  * Routines to enable decisions on monster behaviour
56  * ------------------------------------------------------------------------ */
57 /**
58  * From Will Asher in DJA:
59  * Find whether a monster is near a permanent wall
60  *
61  * this decides whether PASS_WALL & KILL_WALL monsters use the monster flow code
62  */
monster_near_permwall(const struct monster * mon,struct chunk * c)63 static bool monster_near_permwall(const struct monster *mon, struct chunk *c)
64 {
65 	struct loc gp[512];
66 	int path_grids, j;
67 
68 	/* If player is in LOS, there's no need to go around walls */
69     if (projectable(c, mon->grid, player->grid, PROJECT_SHORT)) return false;
70 
71     /* PASS_WALL & KILL_WALL monsters occasionally flow for a turn anyway */
72     if (randint0(99) < 5) return true;
73 
74 	/* Find the shortest path */
75 	path_grids = project_path(gp, z_info->max_sight, mon->grid, player->grid,
76 							  PROJECT_ROCK);
77 
78 	/* See if we can "see" the player without hitting permanent wall */
79 	for (j = 0; j < path_grids; j++) {
80 		if (square_isperm(c, gp[j])) return true;
81 		if (square_isplayer(c, gp[j])) return false;
82 	}
83 
84 	return false;
85 }
86 
87 /**
88  * Check if the monster can see the player
89  */
monster_can_see_player(struct chunk * c,struct monster * mon)90 static bool monster_can_see_player(struct chunk *c, struct monster *mon)
91 {
92 	if (!square_isview(c, mon->grid)) return false;
93 	if (player->timed[TMD_COVERTRACKS] && (mon->cdis > z_info->max_sight / 4)) {
94 		return false;
95 	}
96 	return true;
97 }
98 
99 /**
100  * Check if the monster can hear anything
101  */
monster_can_hear(struct chunk * c,struct monster * mon)102 static bool monster_can_hear(struct chunk *c, struct monster *mon)
103 {
104 	int base_hearing = mon->race->hearing
105 		- player->state.skills[SKILL_STEALTH] / 3;
106 	if (c->noise.grids[mon->grid.y][mon->grid.x] == 0) {
107 		return false;
108 	}
109 	return base_hearing > c->noise.grids[mon->grid.y][mon->grid.x];
110 }
111 
112 /**
113  * Check if the monster can smell anything
114  */
monster_can_smell(struct chunk * c,struct monster * mon)115 static bool monster_can_smell(struct chunk *c, struct monster *mon)
116 {
117 	if (c->scent.grids[mon->grid.y][mon->grid.x] == 0) {
118 		return false;
119 	}
120 	return mon->race->smell > c->scent.grids[mon->grid.y][mon->grid.x];
121 }
122 
123 /**
124  * Compare the "strength" of two monsters XXX XXX XXX
125  */
compare_monsters(const struct monster * mon1,const struct monster * mon2)126 static int compare_monsters(const struct monster *mon1,
127 							const struct monster *mon2)
128 {
129 	u32b mexp1 = (mon1->original_race) ? mon1->original_race->mexp : mon1->race->mexp;
130 	u32b mexp2 = (mon2->original_race) ? mon2->original_race->mexp : mon2->race->mexp;
131 
132 	/* Compare */
133 	if (mexp1 < mexp2) return (-1);
134 	if (mexp1 > mexp2) return (1);
135 
136 	/* Assume equal */
137 	return (0);
138 }
139 
140 /**
141  * Check if the monster can kill any monster on the relevant grid
142  */
monster_can_kill(struct chunk * c,struct monster * mon,struct loc grid)143 static bool monster_can_kill(struct chunk *c, struct monster *mon,
144 							 struct loc grid)
145 {
146 	struct monster *mon1 = square_monster(c, grid);
147 
148 	/* No monster */
149 	if (!mon1) return true;
150 
151 	/* No trampling uniques */
152 	if (rf_has(mon1->race->flags, RF_UNIQUE) ||
153 			(mon1->original_race &&
154 			rf_has(mon1->original_race->flags, RF_UNIQUE))) {
155 		return false;
156 	}
157 
158 	if (rf_has(mon->race->flags, RF_KILL_BODY) &&
159 		compare_monsters(mon, mon1) > 0) {
160 		return true;
161 	}
162 
163 	return false;
164 }
165 
166 /**
167  * Check if the monster can move any monster on the relevant grid
168  */
monster_can_move(struct chunk * c,struct monster * mon,struct loc grid)169 static bool monster_can_move(struct chunk *c, struct monster *mon,
170 							 struct loc grid)
171 {
172 	struct monster *mon1 = square_monster(c, grid);
173 
174 	/* No monster */
175 	if (!mon1) return true;
176 
177 	if (rf_has(mon->race->flags, RF_MOVE_BODY) &&
178 		compare_monsters(mon, mon1) > 0) {
179 		return true;
180 	}
181 
182 	return false;
183 }
184 
185 /**
186  * Check if the monster can occupy a grid safely
187  */
monster_hates_grid(struct chunk * c,struct monster * mon,struct loc grid)188 static bool monster_hates_grid(struct chunk *c, struct monster *mon,
189 							   struct loc grid)
190 {
191 	/* Only some creatures can handle damaging terrain */
192 	if (square_isdamaging(c, grid) &&
193 		!rf_has(mon->race->flags, square_feat(c, grid)->resist_flag)) {
194 		return true;
195 	}
196 	return false;
197 }
198 
199 /**
200  * ------------------------------------------------------------------------
201  * Monster movement routines
202  * These routines, culminating in get_move(), choose if and where a monster
203  * will move on its turn
204  * ------------------------------------------------------------------------ */
205 /**
206  * Calculate minimum and desired combat ranges.  -BR-
207  *
208  * Afraid monsters will set this to their maximum flight distance.
209  * Currently this is recalculated every turn - if it becomes a significant
210  * overhead it could be calculated only when something has changed (monster HP,
211  * chance of escaping, etc)
212  */
get_move_find_range(struct monster * mon)213 static void get_move_find_range(struct monster *mon)
214 {
215 	u16b p_lev, m_lev;
216 	u16b p_chp, p_mhp;
217 	u16b m_chp, m_mhp;
218 	u32b p_val, m_val;
219 
220 	/* Monsters will run up to z_info->flee_range grids out of sight */
221 	int flee_range = z_info->max_sight + z_info->flee_range;
222 
223 	/* All "afraid" monsters will run away */
224 	if (mon->m_timed[MON_TMD_FEAR] || rf_has(mon->race->flags, RF_FRIGHTENED)) {
225 		mon->min_range = flee_range;
226 	} else if (mon->group_info[PRIMARY_GROUP].role == MON_GROUP_BODYGUARD) {
227 		/* Bodyguards don't flee */
228 		mon->min_range = 1;
229 	} else {
230 		/* Minimum distance - stay at least this far if possible */
231 		mon->min_range = 1;
232 
233 		/* Taunted monsters just want to get in your face */
234 		if (player->timed[TMD_TAUNT]) return;
235 
236 		/* Examine player power (level) */
237 		p_lev = player->lev;
238 
239 		/* Hack - increase p_lev based on specialty abilities */
240 
241 		/* Examine monster power (level plus morale) */
242 		m_lev = mon->race->level + (mon->midx & 0x08) + 25;
243 
244 		/* Simple cases first */
245 		if (m_lev + 3 < p_lev) {
246 			mon->min_range = flee_range;
247 		} else if (m_lev - 5 < p_lev) {
248 
249 			/* Examine player health */
250 			p_chp = player->chp;
251 			p_mhp = player->mhp;
252 
253 			/* Examine monster health */
254 			m_chp = mon->hp;
255 			m_mhp = mon->maxhp;
256 
257 			/* Prepare to optimize the calculation */
258 			p_val = (p_lev * p_mhp) + (p_chp << 2);	/* div p_mhp */
259 			m_val = (m_lev * m_mhp) + (m_chp << 2);	/* div m_mhp */
260 
261 			/* Strong players scare strong monsters */
262 			if (p_val * m_mhp > m_val * p_mhp)
263 				mon->min_range = flee_range;
264 		}
265 	}
266 
267 	if (mon->min_range < flee_range) {
268 		/* Creatures that don't move never like to get too close */
269 		if (rf_has(mon->race->flags, RF_NEVER_MOVE))
270 			mon->min_range += 3;
271 
272 		/* Spellcasters that don't strike never like to get too close */
273 		if (rf_has(mon->race->flags, RF_NEVER_BLOW))
274 			mon->min_range += 3;
275 	}
276 
277 	/* Maximum range to flee to */
278 	if (!(mon->min_range < flee_range)) {
279 		mon->min_range = flee_range;
280 	} else if (mon->cdis < z_info->turn_range) {
281 		/* Nearby monsters won't run away */
282 		mon->min_range = 1;
283 	}
284 
285 	/* Now find preferred range */
286 	mon->best_range = mon->min_range;
287 
288 	/* Archers are quite happy at a good distance */
289 	if (monster_loves_archery(mon)) {
290 		mon->best_range += 3;
291 	}
292 
293 	/* Breathers like point blank range */
294 	if (mon->race->freq_innate > 24) {
295 		if (monster_breathes(mon) && (mon->hp > mon->maxhp / 2)) {
296 			mon->best_range = MAX(1, mon->best_range);
297 		}
298 	} else if (mon->race->freq_spell > 24) {
299 		/* Other spell casters will sit back and cast */
300 		mon->best_range += 3;
301 	}
302 }
303 
304 /**
305  * Choose the best direction for a bodyguard.
306  *
307  * The idea is to stay close to the group leader, but attack the player if the
308  * chance arises
309  */
get_move_bodyguard(struct chunk * c,struct monster * mon)310 static bool get_move_bodyguard(struct chunk *c, struct monster *mon)
311 {
312 	int i;
313 	struct monster *leader = monster_group_leader(c, mon);
314 	int dist;
315 	struct loc best;
316 	bool found = false;
317 
318 	if (!leader) return false;
319 
320 	/* Get distance */
321 	dist = distance(mon->grid, leader->grid);
322 
323 	/* If currently adjacent to the leader, we can afford a move */
324 	if (dist <= 1) return false;
325 
326 	/* If the leader's too out of sight and far away, save yourself */
327 	if (!los(cave, mon->grid, leader->grid) && (dist > 10)) return false;
328 
329 	/* Check nearby adjacent grids and assess */
330 	for (i = 0; i < 8; i++) {
331 		/* Get the location */
332 		struct loc grid = loc_sum(mon->grid, ddgrid_ddd[i]);
333 		int new_dist = distance(grid, leader->grid);
334 		int char_dist = distance(grid, player->grid);
335 
336 		/* Bounds check */
337 		if (!square_in_bounds(c, grid)) {
338 			continue;
339 		}
340 
341 		/* There's a monster blocking that we can't deal with */
342 		if (!monster_can_kill(c, mon, grid) && !monster_can_move(c, mon, grid)){
343 			continue;
344 		}
345 
346 		/* There's damaging terrain */
347 		if (monster_hates_grid(c, mon, grid)) {
348 			continue;
349 		}
350 
351 		/* Closer to the leader is always better */
352 		if (new_dist < dist) {
353 			best = grid;
354 			found = true;
355 			/* If there's a grid that's also closer to the player, that wins */
356 			if (char_dist < mon->cdis) {
357 				break;
358 			}
359 		}
360 	}
361 
362 	/* If we found one, set the target */
363 	if (found) {
364 		mon->target.grid = best;
365 		return true;
366 	}
367 
368 	return false;
369 }
370 
371 
372 /**
373  * Choose the best direction to advance toward the player, using sound or scent.
374  *
375  * Ghosts and rock-eaters generally just head straight for the player. Other
376  * monsters try sight, then current sound as saved in c->noise.grids[y][x],
377  * then current scent as saved in c->scent.grids[y][x].
378  *
379  * This function assumes the monster is moving to an adjacent grid, and so the
380  * noise can be louder by at most 1.  The monster target grid set by sound or
381  * scent tracking in this function will be a grid they can step to in one turn,
382  * so is the preferred option for get_move() unless there's some reason
383  * not to use it.
384  *
385  * Tracking by 'scent' means that monsters end up near enough the player to
386  * switch to 'sound' (noise), or they end up somewhere the player left via
387  * teleport.  Teleporting away from a location will cause the monsters who
388  * were chasing the player to converge on that location as long as the player
389  * is still near enough to "annoy" them without being close enough to chase
390  * directly.
391  */
get_move_advance(struct chunk * c,struct monster * mon,bool * track)392 static bool get_move_advance(struct chunk *c, struct monster *mon, bool *track)
393 {
394 	int i;
395 	struct loc decoy = cave_find_decoy(c);
396 	struct loc target = loc_is_zero(decoy) ? player->grid : decoy;
397 
398 	int base_hearing = mon->race->hearing
399 		- player->state.skills[SKILL_STEALTH] / 3;
400 	int current_noise = base_hearing - c->noise.grids[mon->grid.y][mon->grid.x];
401 	int best_scent = 0;
402 
403 	struct loc best_grid;
404 	struct loc backup_grid;
405 	bool found = false;
406 	bool found_backup = false;
407 
408 	/* Bodyguards are special */
409 	if (mon->group_info[PRIMARY_GROUP].role == MON_GROUP_BODYGUARD) {
410 		if (get_move_bodyguard(c, mon)) {
411 			return true;
412 		}
413 	}
414 
415 	/* If the monster can pass through nearby walls, do that */
416 	if (monster_passes_walls(mon) && !monster_near_permwall(mon, c)) {
417 		mon->target.grid = target;
418 		return true;
419 	}
420 
421 	/* If the player can see monster, set target and run towards them */
422 	if (monster_can_see_player(c, mon)) {
423 		mon->target.grid = target;
424 		return true;
425 	}
426 
427 	/* Try to use sound */
428 	if (monster_can_hear(c, mon)) {
429 		/* Check nearby sound, giving preference to the cardinal directions */
430 		for (i = 0; i < 8; i++) {
431 			/* Get the location */
432 			struct loc grid = loc_sum(mon->grid, ddgrid_ddd[i]);
433 			int heard_noise = base_hearing - c->noise.grids[grid.y][grid.x];
434 
435 			/* Bounds check */
436 			if (!square_in_bounds(c, grid)) {
437 				continue;
438 			}
439 
440 			/* Must be some noise */
441 			if (c->noise.grids[grid.y][grid.x] == 0) {
442 				continue;
443 			}
444 
445 			/* There's a monster blocking that we can't deal with */
446 			if (!monster_can_kill(c, mon, grid) &&
447 				!monster_can_move(c, mon, grid)) {
448 				continue;
449 			}
450 
451 			/* There's damaging terrain */
452 			if (monster_hates_grid(c, mon, grid)) {
453 				continue;
454 			}
455 
456 			/* If it's better than the current noise, choose this direction */
457 			if (heard_noise > current_noise) {
458 				best_grid = grid;
459 				found = true;
460 				break;
461 			} else if (heard_noise == current_noise) {
462 				/* Possible move if we can't actually get closer */
463 				backup_grid = grid;
464 				found_backup = true;
465 				continue;
466 			}
467 		}
468 	}
469 
470 	/* If both vision and sound are no good, use scent */
471 	if (monster_can_smell(c, mon) && !found) {
472 		for (i = 0; i < 8; i++) {
473 			/* Get the location */
474 			struct loc grid = loc_sum(mon->grid, ddgrid_ddd[i]);
475 			int smelled_scent;
476 
477 			/* If no good sound yet, use scent */
478 			smelled_scent = mon->race->smell - c->scent.grids[grid.y][grid.x];
479 			if ((smelled_scent > best_scent) &&
480 				(c->scent.grids[grid.y][grid.x] != 0)) {
481 				best_scent = smelled_scent;
482 				best_grid = grid;
483 				found = true;
484 			}
485 		}
486 	}
487 
488 	/* Set the target */
489 	if (found) {
490 		mon->target.grid = best_grid;
491 		*track = true;
492 		return true;
493 	} else if (found_backup) {
494 		/* Move around to try and improve position */
495 		mon->target.grid = backup_grid;
496 		*track = true;
497 		return true;
498 	}
499 
500 	/* No reason to advance */
501 	return false;
502 }
503 
504 /**
505  * Choose a random passable grid adjacent to the monster since is has no better
506  * strategy.
507  */
get_move_random(struct chunk * c,struct monster * mon)508 static struct loc get_move_random(struct chunk *c, struct monster *mon)
509 {
510 	int attempts[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
511 	int nleft = 8;
512 
513 	while (nleft > 0) {
514 		int itry = randint0(nleft);
515 		struct loc trygrid;
516 
517 		trygrid = loc_sum(mon->grid, ddgrid_ddd[attempts[itry]]);
518 		if (square_is_monster_walkable(c, trygrid) &&
519 				!monster_hates_grid(c, mon, trygrid)) {
520 			return ddgrid_ddd[attempts[itry]];
521 		} else {
522 			int tmp = attempts[itry];
523 
524 			--nleft;
525 			attempts[itry] = attempts[nleft];
526 			attempts[nleft] = tmp;
527 		}
528 	}
529 
530 	return loc(0, 0);
531 }
532 
533 /**
534  * Choose a "safe" location near a monster for it to run toward.
535  *
536  * A location is "safe" if it can be reached quickly and the player
537  * is not able to fire into it (it isn't a "clean shot").  So, this will
538  * cause monsters to "duck" behind walls.  Hopefully, monsters will also
539  * try to run towards corridor openings if they are in a room.
540  *
541  * This function may take lots of CPU time if lots of monsters are fleeing.
542  *
543  * Return true if a safe location is available.
544  */
get_move_find_safety(struct chunk * c,struct monster * mon)545 static bool get_move_find_safety(struct chunk *c, struct monster *mon)
546 {
547 	int i, dy, dx, d, dis, gdis = 0;
548 
549 	const int *y_offsets;
550 	const int *x_offsets;
551 
552 	/* Start with adjacent locations, spread further */
553 	for (d = 1; d < 10; d++) {
554 		struct loc best = loc(0, 0);
555 
556 		/* Get the lists of points with a distance d from (fx, fy) */
557 		y_offsets = dist_offsets_y[d];
558 		x_offsets = dist_offsets_x[d];
559 
560 		/* Check the locations */
561 		for (i = 0, dx = x_offsets[0], dy = y_offsets[0];
562 		     dx != 0 || dy != 0;
563 		     i++, dx = x_offsets[i], dy = y_offsets[i]) {
564 			struct loc grid = loc_sum(mon->grid, loc(dx, dy));
565 
566 			/* Skip illegal locations */
567 			if (!square_in_bounds_fully(c, grid)) continue;
568 
569 			/* Skip locations in a wall */
570 			if (!square_ispassable(c, grid)) continue;
571 
572 			/* Ignore too-distant grids */
573 			if (c->noise.grids[grid.y][grid.x] >
574 				c->noise.grids[mon->grid.y][mon->grid.x] + 2 * d)
575 				continue;
576 
577 			/* Ignore damaging terrain if they can't handle it */
578 			if (monster_hates_grid(c, mon, grid)) continue;
579 
580 			/* Check for absence of shot (more or less) */
581 			if (!square_isview(c, grid)) {
582 				/* Calculate distance from player */
583 				dis = distance(grid, player->grid);
584 
585 				/* Remember if further than previous */
586 				if (dis > gdis) {
587 					best = grid;
588 					gdis = dis;
589 				}
590 			}
591 		}
592 
593 		/* Check for success */
594 		if (gdis > 0) {
595 			/* Good location */
596 			mon->target.grid = best;
597 			return (true);
598 		}
599 	}
600 
601 	/* No safe place */
602 	return (false);
603 }
604 
605 /**
606  * Choose a good hiding place near a monster for it to run toward.
607  *
608  * Pack monsters will use this to "ambush" the player and lure him out
609  * of corridors into open space so they can swarm him.
610  *
611  * Return true if a good location is available.
612  */
get_move_find_hiding(struct chunk * c,struct monster * mon)613 static bool get_move_find_hiding(struct chunk *c, struct monster *mon)
614 {
615 	int i, dy, dx, d, dis, gdis = 999, min;
616 
617 	const int *y_offsets, *x_offsets;
618 
619 	/* Closest distance to get */
620 	min = distance(player->grid, mon->grid) * 3 / 4 + 2;
621 
622 	/* Start with adjacent locations, spread further */
623 	for (d = 1; d < 10; d++) {
624 		struct loc best = loc(0, 0);
625 
626 		/* Get the lists of points with a distance d from monster */
627 		y_offsets = dist_offsets_y[d];
628 		x_offsets = dist_offsets_x[d];
629 
630 		/* Check the locations */
631 		for (i = 0, dx = x_offsets[0], dy = y_offsets[0];
632 		     dx != 0 || dy != 0;
633 		     i++, dx = x_offsets[i], dy = y_offsets[i]) {
634 			struct loc grid = loc_sum(mon->grid, loc(dx, dy));
635 
636 			/* Skip illegal locations */
637 			if (!square_in_bounds_fully(c, grid)) continue;
638 
639 			/* Skip occupied locations */
640 			if (!square_isempty(c, grid)) continue;
641 
642 			/* Check for hidden, available grid */
643 			if (!square_isview(c, grid) &&
644 				projectable(c, mon->grid, grid, PROJECT_STOP)) {
645 				/* Calculate distance from player */
646 				dis = distance(grid, player->grid);
647 
648 				/* Remember if closer than previous */
649 				if (dis < gdis && dis >= min) {
650 					best = grid;
651 					gdis = dis;
652 				}
653 			}
654 		}
655 
656 		/* Check for success */
657 		if (gdis < 999) {
658 			/* Good location */
659 			mon->target.grid = best;
660 			return (true);
661 		}
662 	}
663 
664 	/* No good place */
665 	return (false);
666 }
667 
668 /**
669  * Provide a location to flee to, but give the player a wide berth.
670  *
671  * A monster may wish to flee to a location that is behind the player,
672  * but instead of heading directly for it, the monster should "swerve"
673  * around the player so that it has a smaller chance of getting hit.
674  */
get_move_flee(struct chunk * c,struct monster * mon)675 static bool get_move_flee(struct chunk *c, struct monster *mon)
676 {
677 	int i;
678 	struct loc best = loc(0, 0);
679 	int best_score = -1;
680 
681 	/* Taking damage from terrain makes moving vital */
682 	if (!monster_taking_terrain_damage(mon)) {
683 		/* If the player is not currently near the monster, no reason to flow */
684 		if (mon->cdis >= mon->best_range) {
685 			return false;
686 		}
687 
688 		/* Monster is too far away to use sound or scent */
689 		if (!monster_can_hear(c, mon) && !monster_can_smell(c, mon)) {
690 			return false;
691 		}
692 	}
693 
694 	/* Check nearby grids, diagonals first */
695 	for (i = 7; i >= 0; i--) {
696 		int dis, score;
697 
698 		/* Get the location */
699 		struct loc grid = loc_sum(mon->grid, ddgrid_ddd[i]);
700 
701 		/* Bounds check */
702 		if (!square_in_bounds(c, grid)) continue;
703 
704 		/* Calculate distance of this grid from our target */
705 		dis = distance(grid, mon->target.grid);
706 
707 		/* Score this grid
708 		 * First half of calculation is inversely proportional to distance
709 		 * Second half is inversely proportional to grid's distance from player
710 		 */
711 		score = 5000 / (dis + 3) - 500 / (c->noise.grids[grid.y][grid.x] + 1);
712 
713 		/* No negative scores */
714 		if (score < 0) score = 0;
715 
716 		/* Ignore lower scores */
717 		if (score < best_score) continue;
718 
719 		/* Save the score */
720 		best_score = score;
721 
722 		/* Save the location */
723 		best = grid;
724 	}
725 
726 	/* Set the immediate target */
727 	mon->target.grid = best;
728 
729 	/* Success */
730 	return true;
731 }
732 
733 /**
734  * Choose the basic direction of movement, and whether to bias left or right
735  * if the main direction is blocked.
736  *
737  * Note that the input is an offset to the monster's current position, and
738  * the output direction is intended as an index into the side_dirs array.
739  */
get_move_choose_direction(struct loc offset)740 static int get_move_choose_direction(struct loc offset)
741 {
742 	int dir = 0;
743 	int dx = offset.x, dy = offset.y;
744 
745 	/* Extract the "absolute distances" */
746 	int ay = ABS(dy);
747 	int ax = ABS(dx);
748 
749 	/* We mostly want to move vertically */
750 	if (ay > (ax * 2)) {
751 		/* Choose between directions '8' and '2' */
752 		if (dy > 0) {
753 			/* We're heading down */
754 			dir = 2;
755 			if ((dx > 0) || (dx == 0 && turn % 2 == 0))
756 				dir += 10;
757 		} else {
758 			/* We're heading up */
759 			dir = 8;
760 			if ((dx < 0) || (dx == 0 && turn % 2 == 0))
761 				dir += 10;
762 		}
763 	}
764 
765 	/* We mostly want to move horizontally */
766 	else if (ax > (ay * 2)) {
767 		/* Choose between directions '4' and '6' */
768 		if (dx > 0) {
769 			/* We're heading right */
770 			dir = 6;
771 			if ((dy < 0) || (dy == 0 && turn % 2 == 0))
772 				dir += 10;
773 		} else {
774 			/* We're heading left */
775 			dir = 4;
776 			if ((dy > 0) || (dy == 0 && turn % 2 == 0))
777 				dir += 10;
778 		}
779 	}
780 
781 	/* We want to move down and sideways */
782 	else if (dy > 0) {
783 		/* Choose between directions '1' and '3' */
784 		if (dx > 0) {
785 			/* We're heading down and right */
786 			dir = 3;
787 			if ((ay < ax) || (ay == ax && turn % 2 == 0))
788 				dir += 10;
789 		} else {
790 			/* We're heading down and left */
791 			dir = 1;
792 			if ((ay > ax) || (ay == ax && turn % 2 == 0))
793 				dir += 10;
794 		}
795 	}
796 
797 	/* We want to move up and sideways */
798 	else {
799 		/* Choose between directions '7' and '9' */
800 		if (dx > 0) {
801 			/* We're heading up and right */
802 			dir = 9;
803 			if ((ay > ax) || (ay == ax && turn % 2 == 0))
804 				dir += 10;
805 		} else {
806 			/* We're heading up and left */
807 			dir = 7;
808 			if ((ay < ax) || (ay == ax && turn % 2 == 0))
809 				dir += 10;
810 		}
811 	}
812 
813 	return dir;
814 }
815 
816 /**
817  * Choose "logical" directions for monster movement
818  *
819  * This function is responsible for deciding where the monster wants to move,
820  * and so is the core of monster "AI".
821  *
822  * First, we work out how best to advance toward the player:
823  * - Try to head toward the player directly if we can pass through walls or
824  *   if we can see them
825  * - Failing that follow the player by sound, or failing that by scent
826  * - If none of that works, just head in the general direction
827  * Then we look at possible reasons not to just advance:
828  * - If we're part of a pack, try to lure the player into the open
829  * - If we're afraid, try to find a safe place to run to, and if no safe place
830  *   just run in the opposite direction to the advance move
831  * - If we can see the player and we're part of a group, try and surround them
832  *
833  * The function then returns false if we're already where we want to be, and
834  * otherwise sets the chosen direction to step and returns true.
835  */
get_move(struct chunk * c,struct monster * mon,int * dir,bool * good)836 static bool get_move(struct chunk *c, struct monster *mon, int *dir, bool *good)
837 {
838 	struct loc decoy = cave_find_decoy(c);
839 	struct loc target = loc_is_zero(decoy) ? player->grid : decoy;
840 	bool group_ai = rf_has(mon->race->flags, RF_GROUP_AI);
841 
842 	/* Offset to current position to move toward */
843 	struct loc grid = loc(0, 0);
844 
845 	/* Monsters will run up to z_info->flee_range grids out of sight */
846 	int flee_range = z_info->max_sight + z_info->flee_range;
847 
848 	bool done = false;
849 
850 	/* Calculate range */
851 	get_move_find_range(mon);
852 
853 	/* Assume we're heading towards the player */
854 	if (get_move_advance(c, mon, good)) {
855 		/* We have a good move, use it */
856 		grid = loc_diff(mon->target.grid, mon->grid);
857 		mflag_on(mon->mflag, MFLAG_TRACKING);
858 	} else {
859 		/* Try to follow someone who knows where they're going */
860 		struct monster *tracker = group_monster_tracking(c, mon);
861 		if (tracker && los(c, mon->grid, tracker->grid)) { /* Need los? */
862 			grid = loc_diff(tracker->grid, mon->grid);
863 			/* No longer tracking */
864 			mflag_off(mon->mflag, MFLAG_TRACKING);
865 		} else {
866 			if (mflag_has(mon->mflag, MFLAG_TRACKING)) {
867 				/* Keep heading to the most recent goal. */
868 				grid = loc_diff(mon->target.grid, mon->grid);
869 			}
870 			if (loc_is_zero(grid)) {
871 				/* Try a random move and no longer track. */
872 				grid = get_move_random(c, mon);
873 				mflag_off(mon->mflag, MFLAG_TRACKING);
874 			}
875 		}
876 	}
877 
878 	/* Monster is taking damage from terrain */
879 	if (monster_taking_terrain_damage(mon)) {
880 		/* Try to find safe place */
881 		if (get_move_find_safety(c, mon)) {
882 			/* Set a course for the safe place */
883 			get_move_flee(c, mon);
884 			grid = loc_diff(mon->target.grid, mon->grid);
885 			done = true;
886 		}
887 	}
888 
889 	/* Normal animal packs try to get the player out of corridors. */
890 	if (!done && group_ai && !monster_passes_walls(mon)) {
891 		int i, open = 0;
892 
893 		/* Count empty grids next to player */
894 		for (i = 0; i < 8; i++) {
895 			/* Check grid around the player for room interior (room walls count)
896 			 * or other empty space */
897 			struct loc test = loc_sum(target, ddgrid_ddd[i]);
898 			if (square_ispassable(c, test) || square_isroom(c, test)) {
899 				/* One more open grid */
900 				open++;
901 			}
902 		}
903 
904 		/* Not in an empty space and strong player */
905 		if ((open < 5) && (player->chp > player->mhp / 2)) {
906 			/* Find hiding place for an ambush */
907 			if (get_move_find_hiding(c, mon)) {
908 				done = true;
909 				grid = loc_diff(mon->target.grid, mon->grid);
910 
911 				/* No longer tracking */
912 				mflag_off(mon->mflag, MFLAG_TRACKING);
913 			}
914 		}
915 	}
916 
917 	/* Not hiding and monster is afraid */
918 	if (!done && (mon->min_range == flee_range)) {
919 		/* Try to find safe place */
920 		if (get_move_find_safety(c, mon)) {
921 			/* Set a course for the safe place */
922 			get_move_flee(c, mon);
923 			grid = loc_diff(mon->target.grid, mon->grid);
924 		} else {
925 			/* Just leg it away from the player */
926 			grid = loc_diff(loc(0, 0), grid);
927 		}
928 
929 		/* No longer tracking */
930 		mflag_off(mon->mflag, MFLAG_TRACKING);
931 		done = true;
932 	}
933 
934 	/* Monster groups try to surround the player if they're in sight */
935 	if (!done && group_ai && square_isview(c, mon->grid)) {
936 		int i;
937 		struct loc grid1 = mon->target.grid;
938 
939 		/* If we are not already adjacent */
940 		if (mon->cdis > 1) {
941 			/* Find an empty square near the player to fill */
942 			int tmp = randint0(8);
943 			for (i = 0; i < 8; i++) {
944 				/* Pick squares near player (pseudo-randomly) */
945 				grid1 = loc_sum(target, ddgrid_ddd[(tmp + i) % 8]);
946 
947 				/* Ignore filled grids */
948 				if (!square_isempty(c, grid1)) continue;
949 
950 				/* Try to fill this hole */
951 				break;
952 			}
953 		}
954 
955 		/* Head in the direction of the chosen grid */
956 		grid = loc_diff(grid1, mon->grid);
957 	}
958 
959 	/* Check if the monster has already reached its target */
960 	if (loc_is_zero(grid)) return (false);
961 
962 	/* Pick the correct direction */
963 	*dir = get_move_choose_direction(grid);
964 
965 	/* Want to move */
966 	return (true);
967 }
968 
969 
970 /**
971  * ------------------------------------------------------------------------
972  * Monster turn routines
973  * These routines, culminating in monster_turn(), decide how a monster uses
974  * its turn
975  * ------------------------------------------------------------------------ */
976 /**
977  * Lets the given monster attempt to reproduce.
978  *
979  * Note that "reproduction" REQUIRES empty space.
980  *
981  * Returns true if the monster successfully reproduced.
982  */
multiply_monster(struct chunk * c,const struct monster * mon)983 bool multiply_monster(struct chunk *c, const struct monster *mon)
984 {
985 	struct loc grid;
986 	int i;
987 	bool result = false;
988 	struct monster_group_info info = { 0, 0 };
989 
990 	/* Try up to 18 times */
991 	for (i = 0; i < 18; i++) {
992 		int d = 1;
993 
994 		/* Pick a location */
995 		scatter(c, &grid, mon->grid, d, true);
996 
997 		/* Require an "empty" floor grid */
998 		if (!square_isempty(c, grid)) continue;
999 
1000 		/* Create a new monster (awake, no groups) */
1001 		result = place_new_monster(c, grid, mon->race, false, false, info,
1002 								   ORIGIN_DROP_BREED);
1003 
1004 		/* Done */
1005 		break;
1006 	}
1007 
1008 	/* Result */
1009 	return (result);
1010 }
1011 
1012 /**
1013  * Attempt to reproduce, if possible.  All monsters are checked here for
1014  * lore purposes, the unfit fail.
1015  */
monster_turn_multiply(struct chunk * c,struct monster * mon)1016 static bool monster_turn_multiply(struct chunk *c, struct monster *mon)
1017 {
1018 	int k = 0, y, x;
1019 
1020 	struct monster_lore *lore = get_lore(mon->race);
1021 
1022 	/* Too many breeders on the level already */
1023 	if (c->num_repro >= z_info->repro_monster_max) return false;
1024 
1025 	/* No breeding in single combat */
1026 	if (player->upkeep->arena_level) return false;
1027 
1028 	/* Count the adjacent monsters */
1029 	for (y = mon->grid.y - 1; y <= mon->grid.y + 1; y++)
1030 		for (x = mon->grid.x - 1; x <= mon->grid.x + 1; x++)
1031 			if (square(c, loc(x, y))->mon > 0) k++;
1032 
1033 	/* Multiply slower in crowded areas */
1034 	if ((k < 4) && (k == 0 || one_in_(k * z_info->repro_monster_rate))) {
1035 		/* Successful breeding attempt, learn about that now */
1036 		if (monster_is_visible(mon))
1037 			rf_on(lore->flags, RF_MULTIPLY);
1038 
1039 		/* Leave now if not a breeder */
1040 		if (!rf_has(mon->race->flags, RF_MULTIPLY))
1041 			return false;
1042 
1043 		/* Try to multiply */
1044 		if (multiply_monster(c, mon)) {
1045 			/* Make a sound */
1046 			if (monster_is_visible(mon))
1047 				sound(MSG_MULTIPLY);
1048 
1049 			/* Multiplying takes energy */
1050 			return true;
1051 		}
1052 	}
1053 
1054 	return false;
1055 }
1056 
1057 /**
1058  * Check if a monster should stagger (that is, step at random) or not.
1059  * Always stagger when confused, but also deal with random movement for
1060  * RAND_25 and RAND_50 monsters.
1061  */
1062 enum monster_stagger {
1063 	 NO_STAGGER = 0, CONFUSED_STAGGER = 1, INNATE_STAGGER = 2 };
monster_turn_should_stagger(struct monster * mon)1064 static enum monster_stagger monster_turn_should_stagger(struct monster *mon)
1065 {
1066 	struct monster_lore *lore = get_lore(mon->race);
1067 	int chance = 0, confused_chance, roll;
1068 
1069 	/* Increase chance of being erratic for every level of confusion */
1070 	int conf_level = monster_effect_level(mon, MON_TMD_CONF);
1071 	while (conf_level) {
1072 		int accuracy = 100 - chance;
1073 		accuracy *= (100 - CONF_ERRATIC_CHANCE);
1074 		accuracy /= 100;
1075 		chance = 100 - accuracy;
1076 		conf_level--;
1077 	}
1078 	confused_chance = chance;
1079 
1080 	/* RAND_25 and RAND_50 are cumulative */
1081 	if (rf_has(mon->race->flags, RF_RAND_25)) {
1082 		chance += 25;
1083 		if (monster_is_visible(mon))
1084 			rf_on(lore->flags, RF_RAND_25);
1085 	}
1086 
1087 	if (rf_has(mon->race->flags, RF_RAND_50)) {
1088 		chance += 50;
1089 		if (monster_is_visible(mon))
1090 			rf_on(lore->flags, RF_RAND_50);
1091 	}
1092 
1093 	roll = randint0(100);
1094 	return (roll < confused_chance) ?
1095 		 CONFUSED_STAGGER :
1096 		 ((roll < chance) ? INNATE_STAGGER : NO_STAGGER);
1097 }
1098 
1099 
1100 /**
1101  * Helper function for monster_turn_can_move() to display a message for a
1102  * confused move into non-passable terrain.
1103  */
monster_display_confused_move_msg(struct monster * mon,const char * m_name,struct chunk * c,struct loc new)1104 static void monster_display_confused_move_msg(struct monster *mon,
1105 	const char *m_name, struct chunk *c, struct loc new)
1106 {
1107 	if (monster_is_visible(mon) && monster_is_in_view(mon)) {
1108 		const char *m = square_feat(c, new)->confused_msg;
1109 
1110 		msg("%s %s.", m_name, (m) ? m : "stumbles");
1111 	}
1112 }
1113 
1114 
1115 /**
1116  * Helper function for monster_turn_can_move() to slightly stun a monster
1117  * on occasion due to bumbling into something.
1118  */
monster_slightly_stun_by_move(struct monster * mon)1119 static void monster_slightly_stun_by_move(struct monster *mon)
1120 {
1121 	if (mon->m_timed[MON_TMD_STUN] < 5 && one_in_(3)) {
1122 		mon_inc_timed(mon, MON_TMD_STUN, 3, 0);
1123 	}
1124 }
1125 
1126 
1127 /**
1128  * Work out if a monster can move through the grid, if necessary bashing
1129  * down doors in the way.
1130  *
1131  * Returns true if the monster is able to move through the grid.
1132  */
monster_turn_can_move(struct chunk * c,struct monster * mon,const char * m_name,struct loc new,bool confused,bool * did_something)1133 static bool monster_turn_can_move(struct chunk *c, struct monster *mon,
1134 		const char *m_name, struct loc new, bool confused,
1135 		bool *did_something)
1136 {
1137 	struct monster_lore *lore = get_lore(mon->race);
1138 
1139 	/* Always allow an attack upon the player or decoy. */
1140 	if (square_isplayer(c, new) || square_isdecoyed(c, new)) {
1141 		return true;
1142 	}
1143 
1144 	/* Dangerous terrain in the way */
1145 	if (!confused && monster_hates_grid(c, mon, new)) {
1146 		return false;
1147 	}
1148 
1149 	/* Floor is open? */
1150 	if (square_ispassable(c, new)) {
1151 		return true;
1152 	}
1153 
1154 	/* Permanent wall in the way */
1155 	if (square_iswall(c, new) && square_isperm(c, new)) {
1156 		if (confused) {
1157 			*did_something = true;
1158 			monster_display_confused_move_msg(mon, m_name, c, new);
1159 			monster_slightly_stun_by_move(mon);
1160 		}
1161 		return false;
1162 	}
1163 
1164 	/* Normal wall, door, or secret door in the way */
1165 
1166 	/* There's some kind of feature in the way, so learn about
1167 	 * kill-wall and pass-wall now */
1168 	if (monster_is_visible(mon)) {
1169 		rf_on(lore->flags, RF_PASS_WALL);
1170 		rf_on(lore->flags, RF_KILL_WALL);
1171 		rf_on(lore->flags, RF_SMASH_WALL);
1172 	}
1173 
1174 	/* Monster may be able to deal with walls and doors */
1175 	if (rf_has(mon->race->flags, RF_PASS_WALL)) {
1176 		return true;
1177 	} else if (rf_has(mon->race->flags, RF_SMASH_WALL)) {
1178 		/* Remove the wall and much of what's nearby */
1179 		square_smash_wall(c, new);
1180 
1181 		/* Note changes to viewable region */
1182 		player->upkeep->update |= (PU_UPDATE_VIEW | PU_MONSTERS);
1183 
1184 		return true;
1185 	} else if (rf_has(mon->race->flags, RF_KILL_WALL)) {
1186 		/* Remove the wall */
1187 		square_destroy_wall(c, new);
1188 
1189 		/* Note changes to viewable region */
1190 		if (square_isview(c, new))
1191 			player->upkeep->update |= (PU_UPDATE_VIEW | PU_MONSTERS);
1192 
1193 		return true;
1194 	} else if (square_iscloseddoor(c, new) || square_issecretdoor(c, new)) {
1195 		/* Don't allow a confused move to open a door. */
1196 		bool can_open = rf_has(mon->race->flags, RF_OPEN_DOOR) &&
1197 			!confused;
1198 		/* During a confused move, a monster only bashes sometimes. */
1199 		bool can_bash = rf_has(mon->race->flags, RF_BASH_DOOR) &&
1200 			(!confused || one_in_(3));
1201 		bool will_bash = false;
1202 
1203 		/* Take a turn */
1204 		if (can_open || can_bash) *did_something = true;
1205 
1206 		/* Learn about door abilities */
1207 		if (!confused && monster_is_visible(mon)) {
1208 			rf_on(lore->flags, RF_OPEN_DOOR);
1209 			rf_on(lore->flags, RF_BASH_DOOR);
1210 		}
1211 
1212 		/* If creature can open or bash doors, make a choice */
1213 		if (can_open) {
1214 			/* Sometimes bash anyway (impatient) */
1215 			if (can_bash) {
1216 				will_bash = one_in_(2) ? true : false;
1217 			}
1218 		} else if (can_bash) {
1219 			/* Only choice */
1220 			will_bash = true;
1221 		} else {
1222 			/* Door is an insurmountable obstacle */
1223 			if (confused) {
1224 				*did_something = true;
1225 				monster_display_confused_move_msg(mon, m_name, c, new);
1226 				monster_slightly_stun_by_move(mon);
1227 			}
1228 			return false;
1229 		}
1230 
1231 		/* Now outcome depends on type of door */
1232 		if (square_islockeddoor(c, new)) {
1233 			/* Locked door -- test monster strength against door strength */
1234 			int k = square_door_power(c, new);
1235 			if (randint0(mon->hp / 10) > k) {
1236 				if (will_bash) {
1237 					msg("%s slams against the door.", m_name);
1238 				} else {
1239 					msg("%s fiddles with the lock.", m_name);
1240 				}
1241 
1242 				/* Reduce the power of the door by one */
1243 				square_set_door_lock(c, new, k - 1);
1244 			}
1245 			if (confused) {
1246 				/* Didn't learn above; apply now since attempted to bash. */
1247 				if (monster_is_visible(mon)) {
1248 					rf_on(lore->flags, RF_BASH_DOOR);
1249 				}
1250 				/* When confused, can stun itself while bashing. */
1251 				monster_slightly_stun_by_move(mon);
1252 			}
1253 		} else {
1254 			/* Closed or secret door -- always open or bash */
1255 			if (square_isview(c, new))
1256 				player->upkeep->update |= (PU_UPDATE_VIEW | PU_MONSTERS);
1257 
1258 			if (will_bash) {
1259 				square_smash_door(c, new);
1260 
1261 				msg("You hear a door burst open!");
1262 				disturb(player);
1263 
1264 				if (confused) {
1265 					/* Didn't learn above; apply since bashed the door. */
1266 					if (monster_is_visible(mon)) {
1267 						rf_on(lore->flags, RF_BASH_DOOR);
1268 					}
1269 					/* When confused, can stun itself while bashing. */
1270 					monster_slightly_stun_by_move(mon);
1271 				}
1272 
1273 				/* Fall into doorway */
1274 				return true;
1275 			} else {
1276 				square_open_door(c, new);
1277 			}
1278 		}
1279 	} else if (confused) {
1280 		*did_something = true;
1281 		monster_display_confused_move_msg(mon, m_name, c, new);
1282 		monster_slightly_stun_by_move(mon);
1283 	}
1284 
1285 	return false;
1286 }
1287 
1288 /**
1289  * Try to break a glyph.
1290  */
monster_turn_attack_glyph(struct chunk * c,struct monster * mon,struct loc new)1291 static bool monster_turn_attack_glyph(struct chunk *c, struct monster *mon,
1292 									  struct loc new)
1293 {
1294 	assert(square_iswarded(c, new));
1295 
1296 	/* Break the ward */
1297 	if (randint1(z_info->glyph_hardness) < mon->race->level) {
1298 		/* Describe observable breakage */
1299 		if (square_isseen(c, new)) {
1300 			msg("The rune of protection is broken!");
1301 
1302 			/* Forget the rune */
1303 			square_forget(c, new);
1304 		}
1305 
1306 		/* Break the rune */
1307 		square_destroy_trap(c, new);
1308 
1309 		return true;
1310 	}
1311 
1312 	/* Unbroken ward - can't move */
1313 	return false;
1314 }
1315 
1316 /**
1317  * Try to push past / kill another monster.  Returns true on success.
1318  */
monster_turn_try_push(struct chunk * c,struct monster * mon,const char * m_name,struct loc new)1319 static bool monster_turn_try_push(struct chunk *c, struct monster *mon,
1320 									 const char *m_name, struct loc new)
1321 {
1322 	struct monster *mon1 = square_monster(c, new);
1323 	struct monster_lore *lore = get_lore(mon->race);
1324 
1325 	/* Kill weaker monsters */
1326 	int kill_ok = monster_can_kill(c, mon, new);
1327 
1328 	/* Move weaker monsters if they can swap places */
1329 	/* (not in a wall) */
1330 	int move_ok = (monster_can_move(c, mon, new) &&
1331 				   square_ispassable(c, mon->grid));
1332 
1333 	if (kill_ok || move_ok) {
1334 		/* Get the names of the monsters involved */
1335 		char n_name[80];
1336 		monster_desc(n_name, sizeof(n_name), mon1, MDESC_IND_HID);
1337 
1338 		/* Learn about pushing and shoving */
1339 		if (monster_is_visible(mon)) {
1340 			rf_on(lore->flags, RF_KILL_BODY);
1341 			rf_on(lore->flags, RF_MOVE_BODY);
1342 		}
1343 
1344 		/* Reveal mimics */
1345 		if (monster_is_mimicking(mon1))
1346 			become_aware(mon1);
1347 
1348 		/* Note if visible */
1349 		if (monster_is_visible(mon) && monster_is_in_view(mon))
1350 			msg("%s %s %s.", m_name, kill_ok ? "tramples over" : "pushes past",
1351 				n_name);
1352 
1353 		/* Monster ate another monster */
1354 		if (kill_ok)
1355 			delete_monster(new);
1356 
1357 		monster_swap(mon->grid, new);
1358 		return true;
1359 	}
1360 
1361 	return false;
1362 }
1363 
1364 /**
1365  * Grab all objects from the grid.
1366  */
monster_turn_grab_objects(struct chunk * c,struct monster * mon,const char * m_name,struct loc new)1367 void monster_turn_grab_objects(struct chunk *c, struct monster *mon,
1368 							   const char *m_name, struct loc new)
1369 {
1370 	struct monster_lore *lore = get_lore(mon->race);
1371 	struct object *obj;
1372 	bool visible = monster_is_visible(mon);
1373 
1374 	/* Learn about item pickup behavior */
1375 	for (obj = square_object(c, new); obj; obj = obj->next) {
1376 		if (!tval_is_money(obj) && visible) {
1377 			rf_on(lore->flags, RF_TAKE_ITEM);
1378 			rf_on(lore->flags, RF_KILL_ITEM);
1379 			break;
1380 		}
1381 	}
1382 
1383 	/* Abort if can't pickup/kill */
1384 	if (!rf_has(mon->race->flags, RF_TAKE_ITEM) &&
1385 		!rf_has(mon->race->flags, RF_KILL_ITEM)) {
1386 		return;
1387 	}
1388 
1389 	/* Take or kill objects on the floor */
1390 	obj = square_object(c, new);
1391 	while (obj) {
1392 		char o_name[80];
1393 		bool safe = obj->artifact ? true : false;
1394 		struct object *next = obj->next;
1395 
1396 		/* Skip gold */
1397 		if (tval_is_money(obj)) {
1398 			obj = next;
1399 			continue;
1400 		}
1401 
1402 		/* Skip mimicked objects */
1403 		if (obj->mimicking_m_idx) {
1404 			obj = next;
1405 			continue;
1406 		}
1407 
1408 		/* Get the object name */
1409 		object_desc(o_name, sizeof(o_name), obj, ODESC_PREFIX | ODESC_FULL);
1410 
1411 		/* React to objects that hurt the monster */
1412 		if (react_to_slay(obj, mon))
1413 			safe = true;
1414 
1415 		/* Try to pick up, or crush */
1416 		if (safe) {
1417 			/* Only give a message for "take_item" */
1418 			if (rf_has(mon->race->flags, RF_TAKE_ITEM) && visible &&
1419 				square_isview(c, new) && !ignore_item_ok(obj)) {
1420 				/* Dump a message */
1421 				msg("%s tries to pick up %s, but fails.", m_name, o_name);
1422 			}
1423 		} else if (rf_has(mon->race->flags, RF_TAKE_ITEM)) {
1424 			/*
1425 			 * Make a copy so the original can remain as a
1426 			 * placeholder if the player remembers seeing the
1427 			 * object.
1428 			 */
1429 			struct object *taken = object_new();
1430 
1431 			object_copy(taken, obj);
1432 			taken->oidx = 0;
1433 			if (obj->known) {
1434 				taken->known = object_new();
1435 				object_copy(taken->known, obj->known);
1436 				taken->known->oidx = 0;
1437 				taken->known->grid = loc(0, 0);
1438 			}
1439 
1440 			/* Try to carry the copy */
1441 			if (monster_carry(c, mon, taken)) {
1442 				/* Describe observable situations */
1443 				if (square_isseen(c, new) && !ignore_item_ok(obj))
1444 					msg("%s picks up %s.", m_name, o_name);
1445 
1446 				/* Delete the object */
1447 				square_delete_object(c, new, obj, true, true);
1448 			} else {
1449 				if (taken->known) {
1450 					object_delete(&taken->known);
1451 				}
1452 				object_delete(&taken);
1453 			}
1454 		} else {
1455 			/* Describe observable situations */
1456 			if (square_isseen(c, new) && !ignore_item_ok(obj))
1457 				msgt(MSG_DESTROY, "%s crushes %s.", m_name, o_name);
1458 
1459 			/* Delete the object */
1460 			square_delete_object(c, new, obj, true, true);
1461 		}
1462 
1463 		/* Next object */
1464 		obj = next;
1465 	}
1466 }
1467 
1468 
1469 /**
1470  * Process a monster's turn
1471  *
1472  * In several cases, we directly update the monster lore
1473  *
1474  * Note that a monster is only allowed to "reproduce" if there
1475  * are a limited number of "reproducing" monsters on the current
1476  * level.  This should prevent the level from being "swamped" by
1477  * reproducing monsters.  It also allows a large mass of mice to
1478  * prevent a louse from multiplying, but this is a small price to
1479  * pay for a simple multiplication method.
1480  *
1481  * XXX Monster fear is slightly odd, in particular, monsters will
1482  * fixate on opening a door even if they cannot open it.  Actually,
1483  * the same thing happens to normal monsters when they hit a door
1484  *
1485  * In addition, monsters which *cannot* open or bash down a door
1486  * will still stand there trying to open it...  XXX XXX XXX
1487  *
1488  * Technically, need to check for monster in the way combined
1489  * with that monster being in a wall (or door?) XXX
1490  */
monster_turn(struct chunk * c,struct monster * mon)1491 static void monster_turn(struct chunk *c, struct monster *mon)
1492 {
1493 	struct monster_lore *lore = get_lore(mon->race);
1494 
1495 	bool did_something = false;
1496 
1497 	int i;
1498 	int dir = 0;
1499 	enum monster_stagger stagger;
1500 	bool tracking = false;
1501 	char m_name[80];
1502 
1503 	/* Get the monster name */
1504 	monster_desc(m_name, sizeof(m_name), mon, MDESC_CAPITAL | MDESC_IND_HID);
1505 
1506 	/* If we're in a web, deal with that */
1507 	if (square_iswebbed(c, mon->grid)) {
1508 		/* Learn web behaviour */
1509 		if (monster_is_visible(mon)) {
1510 			rf_on(lore->flags, RF_CLEAR_WEB);
1511 			rf_on(lore->flags, RF_PASS_WEB);
1512 		}
1513 
1514 		/* If we can pass, no need to clear */
1515 		if (!rf_has(mon->race->flags, RF_PASS_WEB)) {
1516 			/* Learn wall behaviour */
1517 			if (monster_is_visible(mon)) {
1518 				rf_on(lore->flags, RF_PASS_WALL);
1519 				rf_on(lore->flags, RF_KILL_WALL);
1520 			}
1521 
1522 			/* Now several possibilities */
1523 			if (rf_has(mon->race->flags, RF_PASS_WALL)) {
1524 				/* Insubstantial monsters go right through */
1525 			} else if (monster_passes_walls(mon)) {
1526 				/* If you can destroy a wall, you can destroy a web */
1527 				square_destroy_trap(c, mon->grid);
1528 			} else if (rf_has(mon->race->flags, RF_CLEAR_WEB)) {
1529 				/* Clearing costs a turn (assume there are no other "traps") */
1530 				square_destroy_trap(c, mon->grid);
1531 				return;
1532 			} else {
1533 				/* Stuck */
1534 				return;
1535 			}
1536 		}
1537 	}
1538 
1539 	/* Let other group monsters know about the player */
1540 	monster_group_rouse(c, mon);
1541 
1542 	/* Try to multiply - this can use up a turn */
1543 	if (monster_turn_multiply(c, mon))
1544 		return;
1545 
1546 	/* Attempt a ranged attack */
1547 	if (make_ranged_attack(mon)) return;
1548 
1549 	/* Work out what kind of movement to use - random movement or AI */
1550 	stagger = monster_turn_should_stagger(mon);
1551 	if (stagger == NO_STAGGER) {
1552 		/* If there's no sensible move, we're done */
1553 		if (!get_move(c, mon, &dir, &tracking)) return;
1554 	}
1555 
1556 	/* Try to move first in the chosen direction, or next either side of the
1557 	 * chosen direction, or next at right angles to the chosen direction.
1558 	 * Monsters which are tracking by sound or scent will not move if they
1559 	 * can't move in their chosen direction. */
1560 	for (i = 0; i < 5 && !did_something; i++) {
1561 		/* Get the direction (or stagger) */
1562 		int d = (stagger != NO_STAGGER) ? ddd[randint0(8)] : side_dirs[dir][i];
1563 
1564 		/* Get the grid to step to or attack */
1565 		struct loc new = loc_sum(mon->grid, ddgrid[d]);
1566 
1567 		/* Tracking monsters have their best direction, don't change */
1568 		if ((i > 0) && stagger == NO_STAGGER && !square_isview(c, mon->grid) && tracking) {
1569 			break;
1570 		}
1571 
1572 		/* Check if we can move */
1573 		if (!monster_turn_can_move(c, mon, m_name, new, stagger == CONFUSED_STAGGER, &did_something))
1574 			continue;
1575 
1576 		/* Try to break the glyph if there is one.  This can happen multiple
1577 		 * times per turn because failure does not break the loop */
1578 		if (square_iswarded(c, new) && !monster_turn_attack_glyph(c, mon, new))
1579 			continue;
1580 
1581 		/* Break a decoy if there is one */
1582 		if (square_isdecoyed(c, new)) {
1583 			/* Learn about if the monster attacks */
1584 			if (monster_is_visible(mon))
1585 				rf_on(lore->flags, RF_NEVER_BLOW);
1586 
1587 			/* Some monsters never attack */
1588 			if (rf_has(mon->race->flags, RF_NEVER_BLOW))
1589 				continue;
1590 
1591 			/* Wait a minute... */
1592 			square_destroy_decoy(c, new);
1593 			did_something = true;
1594 			break;
1595 		}
1596 
1597 		/* The player is in the way. */
1598 		if (square_isplayer(c, new)) {
1599 			/* Learn about if the monster attacks */
1600 			if (monster_is_visible(mon))
1601 				rf_on(lore->flags, RF_NEVER_BLOW);
1602 
1603 			/* Some monsters never attack */
1604 			if (rf_has(mon->race->flags, RF_NEVER_BLOW))
1605 				continue;
1606 
1607 			/* Otherwise, attack the player */
1608 			make_attack_normal(mon, player);
1609 
1610 			did_something = true;
1611 			break;
1612 		} else {
1613 			/* Some monsters never move */
1614 			if (rf_has(mon->race->flags, RF_NEVER_MOVE)) {
1615 				/* Learn about lack of movement */
1616 				if (monster_is_visible(mon))
1617 					rf_on(lore->flags, RF_NEVER_MOVE);
1618 
1619 				return;
1620 			}
1621 		}
1622 
1623 		/* A monster is in the way, try to push past/kill */
1624 		if (square_monster(c, new)) {
1625 			did_something = monster_turn_try_push(c, mon, m_name, new);
1626 		} else {
1627 			/* Otherwise we can just move */
1628 			monster_swap(mon->grid, new);
1629 			did_something = true;
1630 		}
1631 
1632 		/* Scan all objects in the grid, if we reached it */
1633 		if (mon == square_monster(c, new)) {
1634 			monster_desc(m_name, sizeof(m_name), mon,
1635 						 MDESC_CAPITAL | MDESC_IND_HID);
1636 			monster_turn_grab_objects(c, mon, m_name, new);
1637 		}
1638 	}
1639 
1640 	if (did_something) {
1641 		/* Learn about no lack of movement */
1642 		if (monster_is_visible(mon))
1643 			rf_on(lore->flags, RF_NEVER_MOVE);
1644 
1645 		/* Possible disturb */
1646 		if (monster_is_visible(mon) && monster_is_in_view(mon) &&
1647 			OPT(player, disturb_near))
1648 			disturb(player);
1649 	}
1650 
1651 	/* Out of options - monster is paralyzed by fear (unless attacked) */
1652 	if (!did_something && mon->m_timed[MON_TMD_FEAR]) {
1653 		int amount = mon->m_timed[MON_TMD_FEAR];
1654 		mon_clear_timed(mon, MON_TMD_FEAR, MON_TMD_FLG_NOMESSAGE);
1655 		mon_inc_timed(mon, MON_TMD_HOLD, amount, MON_TMD_FLG_NOTIFY);
1656 	}
1657 
1658 	/* If we see an unaware monster do something, become aware of it */
1659 	if (did_something && monster_is_camouflaged(mon))
1660 		become_aware(mon);
1661 }
1662 
1663 
1664 /**
1665  * ------------------------------------------------------------------------
1666  * Processing routines that happen to a monster regardless of whether it
1667  * gets a turn, and/or to decide whether it gets a turn
1668  * ------------------------------------------------------------------------ */
1669 /**
1670  * Determine whether a monster is active or passive
1671  */
monster_check_active(struct chunk * c,struct monster * mon)1672 static bool monster_check_active(struct chunk *c, struct monster *mon)
1673 {
1674 	if ((mon->cdis <= mon->race->hearing) && monster_passes_walls(mon)) {
1675 		/* Character is inside scanning range, monster can go straight there */
1676 		mflag_on(mon->mflag, MFLAG_ACTIVE);
1677 	} else if (mon->hp < mon->maxhp) {
1678 		/* Monster is hurt */
1679 		mflag_on(mon->mflag, MFLAG_ACTIVE);
1680 	} else if (square_isview(c, mon->grid)) {
1681 		/* Monster can "see" the player (checked backwards) */
1682 		mflag_on(mon->mflag, MFLAG_ACTIVE);
1683 	} else if (monster_can_hear(c, mon)) {
1684 		/* Monster can hear the player */
1685 		mflag_on(mon->mflag, MFLAG_ACTIVE);
1686 	} else if (monster_can_smell(c, mon)) {
1687 		/* Monster can smell the player */
1688 		mflag_on(mon->mflag, MFLAG_ACTIVE);
1689 	} else if (monster_taking_terrain_damage(mon)) {
1690 		/* Monster is taking damage from the terrain */
1691 		mflag_on(mon->mflag, MFLAG_ACTIVE);
1692 	} else {
1693 		/* Otherwise go passive */
1694 		mflag_off(mon->mflag, MFLAG_ACTIVE);
1695 	}
1696 
1697 	return mflag_has(mon->mflag, MFLAG_ACTIVE) ? true : false;
1698 }
1699 
1700 /**
1701  * Wake a monster or reduce its depth of sleep
1702  *
1703  * Chance of waking up is dependent only on the player's stealth, but the
1704  * amount of sleep reduction takes into account the monster's distance from
1705  * the player.  Currently straight line distance is used; possibly this
1706  * should take into account dungeon structure.
1707  */
monster_reduce_sleep(struct chunk * c,struct monster * mon)1708 static void monster_reduce_sleep(struct chunk *c, struct monster *mon)
1709 {
1710 	int stealth = player->state.skills[SKILL_STEALTH];
1711 	int player_noise = 1 << (30 - stealth);
1712 	int notice = randint0(1024);
1713 	struct monster_lore *lore = get_lore(mon->race);
1714 
1715 	/* Aggravation */
1716 	if (player_of_has(player, OF_AGGRAVATE)) {
1717 		char m_name[80];
1718 
1719 		/* Wake the monster, make it aware */
1720 		monster_wake(mon, false, 100);
1721 
1722 		/* Get the monster name */
1723 		monster_desc(m_name, sizeof(m_name), mon,
1724 					 MDESC_CAPITAL | MDESC_IND_HID);
1725 
1726 		/* Notify the player if aware */
1727 		if (monster_is_obvious(mon)) {
1728 			msg("%s wakes up.", m_name);
1729 			equip_learn_flag(player, OF_AGGRAVATE);
1730 		}
1731 	} else if ((notice * notice * notice) <= player_noise) {
1732 		int sleep_reduction = 1;
1733 		int local_noise = c->noise.grids[mon->grid.y][mon->grid.x];
1734 		bool woke_up = false;
1735 
1736 		/* Test - wake up faster in hearing distance of the player
1737 		 * Note no dependence on stealth for now */
1738 		if ((local_noise > 0) && (local_noise < 50)) {
1739 			sleep_reduction = (100 / local_noise);
1740 		}
1741 
1742 		/* Note a complete wakeup */
1743 		if (mon->m_timed[MON_TMD_SLEEP] <= sleep_reduction) {
1744 			woke_up = true;
1745 		}
1746 
1747 		/* Monster wakes up a bit */
1748 		mon_dec_timed(mon, MON_TMD_SLEEP, sleep_reduction, MON_TMD_FLG_NOTIFY);
1749 
1750 		/* Update knowledge */
1751 		if (monster_is_obvious(mon)) {
1752 			if (!woke_up && lore->ignore < UCHAR_MAX)
1753 				lore->ignore++;
1754 			else if (woke_up && lore->wake < UCHAR_MAX)
1755 				lore->wake++;
1756 			lore_update(mon->race, lore);
1757 		}
1758 	}
1759 }
1760 
1761 /**
1762  * Process a monster's timed effects, e.g. decrease them.
1763  *
1764  * Returns true if the monster is skipping its turn.
1765  */
process_monster_timed(struct chunk * c,struct monster * mon)1766 static bool process_monster_timed(struct chunk *c, struct monster *mon)
1767 {
1768 	/* If the monster is asleep or just woke up, then it doesn't act */
1769 	if (mon->m_timed[MON_TMD_SLEEP]) {
1770 		monster_reduce_sleep(c, mon);
1771 		return true;
1772 	} else {
1773 		/* Awake, active monsters may become aware */
1774 		if (one_in_(10) && mflag_has(mon->mflag, MFLAG_ACTIVE)) {
1775 			mflag_on(mon->mflag, MFLAG_AWARE);
1776 		}
1777 	}
1778 
1779 	if (mon->m_timed[MON_TMD_FAST])
1780 		mon_dec_timed(mon, MON_TMD_FAST, 1, 0);
1781 
1782 	if (mon->m_timed[MON_TMD_SLOW])
1783 		mon_dec_timed(mon, MON_TMD_SLOW, 1, 0);
1784 
1785 	if (mon->m_timed[MON_TMD_HOLD])
1786 		mon_dec_timed(mon, MON_TMD_HOLD, 1, 0);
1787 
1788 	if (mon->m_timed[MON_TMD_DISEN])
1789 		mon_dec_timed(mon, MON_TMD_DISEN, 1, 0);
1790 
1791 	if (mon->m_timed[MON_TMD_STUN])
1792 		mon_dec_timed(mon, MON_TMD_STUN, 1, MON_TMD_FLG_NOTIFY);
1793 
1794 	if (mon->m_timed[MON_TMD_CONF]) {
1795 		mon_dec_timed(mon, MON_TMD_CONF, 1, MON_TMD_FLG_NOTIFY);
1796 	}
1797 
1798 	if (mon->m_timed[MON_TMD_CHANGED]) {
1799 		mon_dec_timed(mon, MON_TMD_CHANGED, 1, MON_TMD_FLG_NOTIFY);
1800 	}
1801 
1802 	if (mon->m_timed[MON_TMD_FEAR]) {
1803 		int d = randint1(mon->race->level / 10 + 1);
1804 		mon_dec_timed(mon, MON_TMD_FEAR, d, MON_TMD_FLG_NOTIFY);
1805 	}
1806 
1807 	/* Always miss turn if held or commanded, one in STUN_MISS_CHANCE chance
1808 	 * of missing if stunned,  */
1809 	if (mon->m_timed[MON_TMD_HOLD] || mon->m_timed[MON_TMD_COMMAND]) {
1810 		return true;
1811 	} else if (mon->m_timed[MON_TMD_STUN]) {
1812 		return one_in_(STUN_MISS_CHANCE);
1813 	} else {
1814 		return false;
1815 	}
1816 }
1817 
1818 /**
1819  * Monster regeneration of HPs.
1820  */
regen_monster(struct monster * mon,int num)1821 static void regen_monster(struct monster *mon, int num)
1822 {
1823 	/* Regenerate (if needed) */
1824 	if (mon->hp < mon->maxhp) {
1825 		/* Base regeneration */
1826 		int frac = mon->maxhp / 100;
1827 
1828 		/* Minimal regeneration rate */
1829 		if (!frac) frac = 1;
1830 
1831 		/* Some monsters regenerate quickly */
1832 		if (rf_has(mon->race->flags, RF_REGENERATE)) frac *= 2;
1833 
1834 		/* Multiply by number of regenerations */
1835 		frac *= num;
1836 
1837 		/* Regenerate */
1838 		mon->hp += frac;
1839 
1840 		/* Do not over-regenerate */
1841 		if (mon->hp > mon->maxhp) mon->hp = mon->maxhp;
1842 
1843 		/* Redraw (later) if needed */
1844 		if (player->upkeep->health_who == mon)
1845 			player->upkeep->redraw |= (PR_HEALTH);
1846 	}
1847 }
1848 
1849 
1850 /**
1851  * ------------------------------------------------------------------------
1852  * Monster processing routines to be called by the main game loop
1853  * ------------------------------------------------------------------------ */
1854 /**
1855  * Process all the "live" monsters, once per game turn.
1856  *
1857  * During each game turn, we scan through the list of all the "live" monsters,
1858  * (backwards, so we can excise any "freshly dead" monsters), energizing each
1859  * monster, and allowing fully energized monsters to move, attack, pass, etc.
1860  *
1861  * This function and its children are responsible for a considerable fraction
1862  * of the processor time in normal situations, greater if the character is
1863  * resting.
1864  */
process_monsters(struct chunk * c,int minimum_energy)1865 void process_monsters(struct chunk *c, int minimum_energy)
1866 {
1867 	int i;
1868 	int mspeed;
1869 
1870 	/* Only process some things every so often */
1871 	bool regen = false;
1872 
1873 	/* Regenerate hitpoints and mana every 100 game turns */
1874 	if (turn % 100 == 0)
1875 		regen = true;
1876 
1877 	/* Process the monsters (backwards) */
1878 	for (i = cave_monster_max(c) - 1; i >= 1; i--) {
1879 		struct monster *mon;
1880 		bool moving;
1881 
1882 		/* Handle "leaving" */
1883 		if (player->is_dead || player->upkeep->generate_level) break;
1884 
1885 		/* Get a 'live' monster */
1886 		mon = cave_monster(c, i);
1887 		if (!mon->race) continue;
1888 
1889 		/* Ignore monsters that have already been handled */
1890 		if (mflag_has(mon->mflag, MFLAG_HANDLED))
1891 			continue;
1892 
1893 		/* Not enough energy to move yet */
1894 		if (mon->energy < minimum_energy) continue;
1895 
1896 		/* Does this monster have enough energy to move? */
1897 		moving = mon->energy >= z_info->move_energy ? true : false;
1898 
1899 		/* Prevent reprocessing */
1900 		mflag_on(mon->mflag, MFLAG_HANDLED);
1901 
1902 		/* Handle monster regeneration if requested */
1903 		if (regen)
1904 			regen_monster(mon, 1);
1905 
1906 		/* Calculate the net speed */
1907 		mspeed = mon->mspeed;
1908 		if (mon->m_timed[MON_TMD_FAST])
1909 			mspeed += 10;
1910 		if (mon->m_timed[MON_TMD_SLOW]) {
1911 			int slow_level = monster_effect_level(mon, MON_TMD_SLOW);
1912 			mspeed -= (2 * slow_level);
1913 		}
1914 
1915 		/* Give this monster some energy */
1916 		mon->energy += turn_energy(mspeed);
1917 
1918 		/* End the turn of monsters without enough energy to move */
1919 		if (!moving)
1920 			continue;
1921 
1922 		/* Use up "some" energy */
1923 		mon->energy -= z_info->move_energy;
1924 
1925 		/* Mimics lie in wait */
1926 		if (monster_is_mimicking(mon)) continue;
1927 
1928 		/* Check if the monster is active */
1929 		if (monster_check_active(c, mon)) {
1930 			/* Process timed effects - skip turn if necessary */
1931 			if (process_monster_timed(c, mon))
1932 				continue;
1933 
1934 			/* Set this monster to be the current actor */
1935 			c->mon_current = i;
1936 
1937 			/* The monster takes its turn */
1938 			monster_turn(c, mon);
1939 
1940 			/* Monster is no longer current */
1941 			c->mon_current = -1;
1942 		}
1943 	}
1944 
1945 	/* Update monster visibility after this */
1946 	/* XXX This may not be necessary */
1947 	player->upkeep->update |= PU_MONSTERS;
1948 }
1949 
1950 /**
1951  * Clear 'moved' status from all monsters.
1952  *
1953  * Clear noise if appropriate.
1954  */
reset_monsters(void)1955 void reset_monsters(void)
1956 {
1957 	int i;
1958 	struct monster *mon;
1959 
1960 	/* Process the monsters (backwards) */
1961 	for (i = cave_monster_max(cave) - 1; i >= 1; i--) {
1962 		/* Access the monster */
1963 		mon = cave_monster(cave, i);
1964 
1965 		/* Dungeon hurts monsters */
1966 		monster_take_terrain_damage(mon);
1967 
1968 		/* Monster is ready to go again */
1969 		mflag_off(mon->mflag, MFLAG_HANDLED);
1970 	}
1971 }
1972 
1973 /**
1974  * Allow monsters on a frozen persistent level to recover
1975  */
restore_monsters(void)1976 void restore_monsters(void)
1977 {
1978 	int i;
1979 	struct monster *mon;
1980 
1981 	/* Get the number of turns that have passed */
1982 	int num_turns = turn - cave->turn;
1983 
1984 	/* Process the monsters (backwards) */
1985 	for (i = cave_monster_max(cave) - 1; i >= 1; i--) {
1986 		int status, status_red;
1987 
1988 		/* Access the monster */
1989 		mon = cave_monster(cave, i);
1990 
1991 		/* Regenerate */
1992 		regen_monster(mon, num_turns / 100);
1993 
1994 		/* Handle timed effects */
1995 		status_red = num_turns * turn_energy(mon->mspeed) / z_info->move_energy;
1996 		if (status_red > 0) {
1997 			for (status = 0; status < MON_TMD_MAX; status++) {
1998 				if (mon->m_timed[status]) {
1999 					mon_dec_timed(mon, status, status_red, 0);
2000 				}
2001 			}
2002 		}
2003 	}
2004 }
2005