Source:NetHack 5.0.0/src/monmove.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to monmove.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/monmove.c#line12]], for example.

The NetHack General Public License applies to screenshots, source code and other content from NetHack.

This content was modified from the original NetHack source code distribution (by splitting up NetHack content between wiki pages, and possibly further editing). See the page history for a list of who changed it, and on what dates.

1. /* NetHack 5.0	monmove.c	$NHDT-Date: 1737392015 2025/01/20 08:53:35 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.266 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Michael Allison, 2006. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. #include "mfndpos.h"
8. #include "artifact.h"
9. 
10. staticfn void msg_mon_movement(struct monst *, coordxy, coordxy) NONNULLARG1;
11. staticfn void watch_on_duty(struct monst *);
12. staticfn int disturb(struct monst *);
13. staticfn void release_hero(struct monst *);
14. staticfn void distfleeck(struct monst *, int *, int *, int *);
15. staticfn int m_arrival(struct monst *);
16. staticfn void mind_blast(struct monst *);
17. staticfn boolean holds_up_web(coordxy, coordxy);
18. staticfn int count_webbing_walls(coordxy, coordxy);
19. staticfn boolean soko_allow_web(struct monst *);
20. staticfn boolean m_search_items(struct monst *, coordxy *, coordxy *, int *,
21.                                 int *) NONNULLPTRS;
22. staticfn int postmov(struct monst *, struct permonst *, coordxy, coordxy, int,
23.                      unsigned, boolean, boolean, boolean) NONNULLPTRS;
24. staticfn boolean leppie_avoidance(struct monst *);
25. staticfn void leppie_stash(struct monst *);
26. staticfn int m_balks_at_approaching(int, struct monst *, int *, int *);
27. staticfn boolean stuff_prevents_passage(struct monst *);
28. staticfn int vamp_shift(struct monst *, struct permonst *, boolean);
29. staticfn void maybe_spin_web(struct monst *);
30. 
31. /* a11y: give a message when monster moved */
32. staticfn void
33. msg_mon_movement(struct monst *mtmp, coordxy omx, coordxy omy)
34. {
35.     if (a11y.mon_movement && canspotmon(mtmp) && mtmp->mspotted) {
36.         coordxy nix = mtmp->mx, niy = mtmp->my;
37.         boolean n2u = next2u(nix, niy),
38.             close = !n2u && (distu(nix, niy) <= (BOLT_LIM * BOLT_LIM)),
39.             closer = !n2u && (distu(nix, niy) <= distu(omx, omy));
40. 
41.         pline_xy(nix, niy, "%s %s%s.", Monnam(mtmp),
42.                  vtense((char *) 0, locomotion(mtmp->data, "move")),
43.                  n2u ? " next to you"
44.                  : (close && closer) ? " closer"
45.                  : (close && !closer) ? " further away"
46.                  : " in the distance");
47.     }
48. }
49. 
50. /* monster has triggered trapped door lock or was present when it got
51.    triggered remotely (at door spot, door hit by zap);
52.    returns True if mtmp dies */
53. boolean
54. mb_trapped(struct monst *mtmp, boolean canseeit)
55. {
56.     if (flags.verbose) {
57.         if (canseeit && !Unaware)
58.             pline_mon(mtmp, "KABOOM!!  You see a door explode.");
59.         else if (!Deaf)
60.             You_hear("a %s explosion.",
61.                      (mdistu(mtmp) > 7 * 7) ? "distant" : "nearby");
62.     }
63.     wake_nearto(mtmp->mx, mtmp->my, 7 * 7);
64.     mtmp->mstun = 1;
65.     mtmp->mhp -= rnd(15);
66.     if (DEADMONSTER(mtmp)) {
67.         mondied(mtmp);
68.         if (DEADMONSTER(mtmp))
69.             return TRUE;
70.         /* will get here if lifesaved */
71.     }
72.     mon_learns_traps(mtmp, TRAPPED_DOOR);
73.     return FALSE;
74. }
75. 
76. /* push coordinate x,y to mtrack, making monster remember where it was */
77. void
78. mon_track_add(struct monst *mtmp, coordxy x, coordxy y)
79. {
80.     int j;
81. 
82.     for (j = MTSZ - 1; j > 0; j--)
83.         mtmp->mtrack[j] = mtmp->mtrack[j - 1];
84.     mtmp->mtrack[0].x = x;
85.     mtmp->mtrack[0].y = y;
86. }
87. 
88. void
89. mon_track_clear(struct monst *mtmp)
90. {
91.     memset(mtmp->mtrack, 0, sizeof(mtmp->mtrack));
92. }
93. 
94. /* check whether a monster is carrying a locking/unlocking tool */
95. boolean
96. monhaskey(
97.     struct monst *mon,
98.     boolean for_unlocking) /* true => credit card ok, false => not ok */
99. {
100.     if (for_unlocking && m_carrying(mon, CREDIT_CARD))
101.         return TRUE;
102.     return m_carrying(mon, SKELETON_KEY) || m_carrying(mon, LOCK_PICK);
103. }
104. 
105. void
106. mon_yells(struct monst *mon, const char *shout)
107. {
108.     if (Deaf) {
109.         if (canspotmon(mon))
110.             /* Sidenote on "A watchman angrily waves her arms!"
111.              * Female being called watchman is correct (career name).
112.              */
113.             pline_mon(mon, "%s angrily %s %s %s!",
114.                 Amonnam(mon),
115.                 nolimbs(mon->data) ? "shakes" : "waves",
116.                 mhis(mon),
117.                 nolimbs(mon->data) ? mbodypart(mon, HEAD)
118.                                    : makeplural(mbodypart(mon, ARM)));
119.     } else {
120.         if (canspotmon(mon)) {
121.             pline_mon(mon, "%s yells:", Amonnam(mon));
122.         } else {
123.             /* Soundeffect(se_someone_yells, 75); */
124.             You_hear("someone yell:");
125.         }
126.         SetVoice(mon, 0, 80, 0);
127.         verbalize1(shout);
128.     }
129. }
130. 
131. /* can monster mtmp break boulders? */
132. boolean
133. m_can_break_boulder(struct monst *mtmp)
134. {
135.     return (is_rider(mtmp->data)
136.             || (!mtmp->mspec_used
137.                 && (mtmp->isshk || mtmp->ispriest
138.                     || (mtmp->data->msound == MS_LEADER))));
139. }
140. 
141. /* monster mtmp breaks boulder at x,y */
142. void
143. m_break_boulder(struct monst *mtmp, coordxy x, coordxy y)
144. {
145.     struct obj *otmp;
146. 
147.     if (m_can_break_boulder(mtmp) && ((otmp = sobj_at(BOULDER, x, y)) != 0)) {
148.         if (!is_rider(mtmp->data)) {
149.             if (!Deaf && (mdistu(mtmp) < 4*4)) {
150.                 if (canspotmon(mtmp))
151.                     set_msg_xy(mtmp->mx, mtmp->my);
152.                 pline("%s mutters %s.",
153.                       Monnam(mtmp),
154.                       mtmp->ispriest ? "a prayer" : "an incantation");
155.             }
156.             mtmp->mspec_used += rn1(20, 10);
157.         }
158.         if (cansee(x, y)) {
159.             set_msg_xy(x, y);
160.             pline_The("boulder falls apart.");
161.         }
162. 
163.         /* boulders pushed onto shop's boundary or free spot are cases where
164.            an item not in hero's inventory can have its unpaid flag set;
165.            if the boulder isn't already on the bill, don't charge for it */
166.         if (otmp->unpaid) {
167.             /* remove original from bill + add cloned copy to used-up bill */
168.             bill_dummy_object(otmp);
169.         }
170.         /* fracturing keeps otmp, changing its otyp from BOULDER to ROCK */
171.         fracture_rock(otmp);
172.     }
173. }
174. 
175. staticfn void
176. watch_on_duty(struct monst *mtmp)
177. {
178.     coordxy x, y;
179. 
180.     if (mtmp->mpeaceful && in_town(u.ux + u.dx, u.uy + u.dy)
181.         && mtmp->mcansee && m_canseeu(mtmp) && !rn2(3)) {
182.         if (picking_lock(&x, &y) && IS_DOOR(levl[x][y].typ)
183.             && (levl[x][y].doormask & D_LOCKED)) {
184.             if (couldsee(mtmp->mx, mtmp->my)) {
185.                 if (levl[x][y].looted & D_WARNED) {
186.                     mon_yells(mtmp, "Halt, thief!  You're under arrest!");
187.                     (void) angry_guards(!!Deaf);
188.                 } else {
189.                     mon_yells(mtmp, "Hey, stop picking that lock!");
190.                     levl[x][y].looted |= D_WARNED;
191.                 }
192.                 stop_occupation();
193.             }
194.         } else if (is_digging()) {
195.             /* chewing, wand/spell of digging are checked elsewhere */
196.             watch_dig(mtmp, svc.context.digging.pos.x,
197.                       svc.context.digging.pos.y, FALSE);
198.         }
199.     }
200. }
201. 
202. /* move a monster; if a threat to busy hero, stop doing whatever it is */
203. int
204. dochugw(
205.     struct monst *mtmp,
206.     boolean chug) /* True: monster is moving;
207.                    * False: monster was just created or has teleported
208.                    * so perform stop-what-you're-doing-if-close-enough-
209.                    * to-be-a-threat check but don't move mtmp */
210. {
211.     coordxy x = mtmp->mx, y = mtmp->my; /* 'mtmp's location before dochug() */
212.     /* skip canspotmon() if occupation is Null */
213.     boolean already_saw_mon = (chug && go.occupation) ? canspotmon(mtmp) : 0;
214.     int rd = chug ? dochug(mtmp) : 0;
215. 
216.     /*
217.      * A similar check is in monster_nearby() in hack.c.
218.      * [The two checks have a lot of differences and chances are high
219.      * that some of those are unintentional.]
220.      */
221. 
222.     /* check whether hero notices monster and stops current activity */
223.     if (go.occupation && !rd
224.         /* monster is hostile and can attack (or hallu distorts knowledge) */
225.         && (Hallucination || (!mtmp->mpeaceful && !noattacks(mtmp->data)))
226.         /* it's close enough to be a threat */
227.         && mdistu(mtmp) <= (BOLT_LIM + 1) * (BOLT_LIM + 1)
228.         /* and either couldn't see it before, or it was too far away */
229.         && (!already_saw_mon || !couldsee(x, y)
230.             || distu(x, y) > (BOLT_LIM + 1) * (BOLT_LIM + 1))
231.         /* can see it now, or sense it and would normally see it */
232.         && canspotmon(mtmp) && couldsee(mtmp->mx, mtmp->my)
233.         /* monster isn't paralyzed or afraid (scare monster/Elbereth) */
234.         && mtmp->mcanmove && !onscary(u.ux, u.uy, mtmp))
235.         stop_occupation();
236. 
237.     return rd;
238. }
239. 
240. boolean
241. onscary(coordxy x, coordxy y, struct monst *mtmp)
242. {
243.     struct engr *ep;
244.     /* <0,0> is used by musical scaring;
245.      * it doesn't care about scrolls or engravings or dungeon branch */
246.     boolean auditory_scare = (x == 0 && y == 0),
247.             magical_scare = !auditory_scare;
248. 
249.     /* creatures who are directly resistant to any type of scaring:
250.      * Rodney, lawful minions, Angels, the Riders */
251.     if (mtmp->iswiz || is_lminion(mtmp) || mtmp->data == &mons[PM_ANGEL]
252.         || is_rider(mtmp->data))
253.         return FALSE;
254. 
255.     /* creatures who are directly resistant to magical scaring
256.      * based on the mere presence of something at a location:
257.      * humans etc.
258.      * uniques have ascended their base monster instincts */
259.     if (magical_scare
260.         && (mtmp->data->mlet == S_HUMAN || unique_corpstat(mtmp->data)))
261.         return FALSE;
262. 
263.     /* creatues who resist scaring under particular circumstances:
264.      * shopkeepers inside their own shop
265.      * priests inside their own temple */
266.     if ((mtmp->isshk && inhishop(mtmp))
267.         || (mtmp->ispriest && inhistemple(mtmp)))
268.         return FALSE;
269. 
270.     if (auditory_scare)
271.         return TRUE;
272. 
273.     /* should this still be true for defiled/molochian altars? */
274.     if (IS_ALTAR(levl[x][y].typ)
275.         && (mtmp->data->mlet == S_VAMPIRE || is_vampshifter(mtmp)))
276.         return TRUE;
277. 
278.     /* the scare monster scroll doesn't have any of the below
279.      * restrictions, being its own source of power */
280.     if (sobj_at(SCR_SCARE_MONSTER, x, y))
281.         return TRUE;
282. 
283.     /*
284.      * Creatures who don't (or can't) fear a written Elbereth:
285.      * all the above plus shopkeepers (even if poly'd into non-human),
286.      * vault guards (also even if poly'd), blind or peaceful monsters,
287.      * humans and elves, and minotaurs.
288.      *
289.      * If the player isn't actually on the square OR the player's image
290.      * isn't displaced to the square, no protection is being granted.
291.      *
292.      * Elbereth doesn't work in Gehennom, the Elemental Planes, or the
293.      * Astral Plane; the influence of the Valar only reaches so far.
294.      */
295.     return ((ep = sengr_at("Elbereth", x, y, TRUE)) != 0
296.             && (u_at(x, y)
297.                 || (Displaced && mtmp->mux == x && mtmp->muy == y)
298.                 || (ep->guardobjects && vobj_at(x, y)))
299.             && !(mtmp->isshk || mtmp->isgd || !mtmp->mcansee
300.                  || mtmp->mpeaceful
301.                  || mtmp->data == &mons[PM_MINOTAUR]
302.                  || Inhell || In_endgame(&u.uz)));
303. }
304. 
305. /* regenerate lost hit points */
306. void
307. mon_regen(struct monst *mon, boolean digest_meal)
308. {
309.     if (svm.moves % 20 == 0 || regenerates(mon->data))
310.         healmon(mon, 1, 0);
311.     if (mon->mspec_used)
312.         mon->mspec_used--;
313.     if (digest_meal) {
314.         if (mon->meating) {
315.             mon->meating--;
316.             if (mon->meating <= 0)
317.                 finish_meating(mon);
318.         }
319.     }
320. }
321. 
322. /*
323.  * Possibly awaken the given monster.  Return a 1 if the monster has been
324.  * jolted awake.
325.  */
326. staticfn int
327. disturb(struct monst *mtmp)
328. {
329.     /*
330.      * + Ettins are hard to surprise.
331.      * + Nymphs, jabberwocks, and leprechauns do not easily wake up.
332.      *
333.      * Wake up if:
334.      *  in direct LOS                                           AND
335.      *  within 10 squares                                       AND
336.      *  not stealthy or (mon is an ettin and 9/10)              AND
337.      *  (mon is not a nymph, jabberwock, or leprechaun) or 1/50 AND
338.      *  Aggravate or mon is (dog or human) or
339.      *      (1/7 and mon is not mimicking furniture or object)
340.      */
341.     if (couldsee(mtmp->mx, mtmp->my) && mdistu(mtmp) <= 100
342.         && (!Stealth || (mtmp->data == &mons[PM_ETTIN] && rn2(10)))
343.         && (!(mtmp->data->mlet == S_NYMPH
344.               || mtmp->data == &mons[PM_JABBERWOCK]
345. #if 0 /* DEFERRED */
346.               || mtmp->data == &mons[PM_VORPAL_JABBERWOCK]
347. #endif
348.               || mtmp->data->mlet == S_LEPRECHAUN) || !rn2(50))
349.         && (Aggravate_monster
350.             || (mtmp->data->mlet == S_DOG || mtmp->data->mlet == S_HUMAN)
351.             || (!rn2(7) && M_AP_TYPE(mtmp) != M_AP_FURNITURE
352.                 && M_AP_TYPE(mtmp) != M_AP_OBJECT))) {
353.         wake_msg(mtmp, !mtmp->mpeaceful);
354.         mtmp->msleeping = 0;
355.         return 1;
356.     }
357.     return 0;
358. }
359. 
360. /* ungrab/expel held/swallowed hero */
361. staticfn void
362. release_hero(struct monst *mon)
363. {
364.     if (mon == u.ustuck) {
365.         if (u.uswallow) {
366.             expels(mon, mon->data, TRUE);
367.         } else if (!sticks(gy.youmonst.data)) {
368.             unstuck(mon); /* let go */
369.             You("get released!");
370.         }
371.     }
372. }
373. 
374. struct monst *
375. find_pmmonst(int pm)
376. {
377.     struct monst *mtmp = 0;
378. 
379.     if ((svm.mvitals[pm].mvflags & G_GENOD) == 0)
380.         for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
381.             if (DEADMONSTER(mtmp))
382.                 continue;
383.             if (mtmp->data == &mons[pm])
384.                 break;
385.         }
386. 
387.     return mtmp;
388. }
389. 
390. /* killer bee 'mon' is on a spot containing lump of royal jelly 'obj' and
391.    will eat it if there is no queen bee on the level; return 1: mon died,
392.    0: mon ate jelly and lived; -1: mon didn't eat jelly to use its move */
393. int
394. bee_eat_jelly(struct monst *mon, struct obj *obj)
395. {
396.     int m_delay;
397.     struct monst *mtmp = find_pmmonst(PM_QUEEN_BEE);
398. 
399.     /* if there's no queen on the level, eat the royal jelly and become one */
400.     if (!mtmp) {
401.         m_delay = obj->blessed ? 3 : !obj->cursed ? 5 : 7;
402.         if (obj->quan > 1L)
403.             obj = splitobj(obj, 1L);
404.         if (canseemon(mon))
405.             pline_mon(mon, "%s eats %s.", Monnam(mon), an(xname(obj)));
406.         delobj(obj);
407. 
408.         if ((int) mon->m_lev < mons[PM_QUEEN_BEE].mlevel - 1)
409.             mon->m_lev = (uchar) (mons[PM_QUEEN_BEE].mlevel - 1);
410.         /* there should be delay after eating, but that's too much
411.            hassle; transform immediately, then have a short delay */
412.         (void) grow_up(mon, (struct monst *) 0);
413. 
414.         if (DEADMONSTER(mon))
415.             return 1; /* dead; apparently queen bees have been genocided */
416.         mon->mfrozen = m_delay, mon->mcanmove = 0;
417.         return 0; /* bee used its move */
418.     }
419.     return -1; /* a queen is already present; ordinary bee hasn't moved yet */
420. }
421. 
422. /* gelatinous cube eats something from its inventory */
423. static int
424. gelcube_digests(struct monst *mtmp)
425. {
426.     struct obj *otmp = mtmp->minvent;
427. 
428.     if (mtmp->meating || !mtmp->minvent)
429.         return -1;
430. 
431.     while (otmp) {
432.         if (is_organic(otmp) && !otmp->oartifact
433.             && !is_mines_prize(otmp) && !is_soko_prize(otmp))
434.             break;
435.         otmp = otmp->nobj;
436.     }
437. 
438.     if (!otmp)
439.         return -1;
440. 
441.     mtmp->meating = eaten_stat(mtmp->meating, otmp);
442.     extract_from_minvent(mtmp, otmp, TRUE, TRUE);
443.     m_consume_obj(mtmp, otmp);
444.     return 0; /* used a move */
445. }
446. 
447. 
448. /* FIXME: gremlins don't flee from monsters wielding Sunsword or wearing
449.    gold dragon scales/mail, nor from gold dragons, only from the hero */
450. #define flees_light(mon) \
451.     ((mon)->data == &mons[PM_GREMLIN]                                     \
452.      && ((uwep && uwep->lamplit && artifact_light(uwep))                  \
453.          || (uarm && uarm->lamplit && artifact_light(uarm)))              \
454.      /* not applicable if mon can't see or hero isn't in line of sight */ \
455.      && mon->mcansee && couldsee(mon->mx, mon->my))                       \
456.      /* doesn't matter if hero is invisible--light being emitted isn't */
457. 
458. /* monster begins fleeing for the specified time, 0 means untimed flee
459.  * if first, only adds fleetime if monster isn't already fleeing
460.  * if fleemsg, prints a message about new flight, otherwise, caller should */
461. void
462. monflee(
463.     struct monst *mtmp,
464.     int fleetime,
465.     boolean first,
466.     boolean fleemsg)
467. {
468.     /* shouldn't happen; maybe warrants impossible()? */
469.     if (DEADMONSTER(mtmp))
470.         return;
471. 
472.     if (mtmp == u.ustuck)
473.         release_hero(mtmp); /* expels/unstuck */
474. 
475.     if (!first || !mtmp->mflee) {
476.         /* don't lose untimed scare */
477.         if (!fleetime)
478.             mtmp->mfleetim = 0;
479.         else if (!mtmp->mflee || mtmp->mfleetim) {
480.             fleetime += (int) mtmp->mfleetim;
481.             /* ensure monster flees long enough to visibly stop fighting */
482.             if (fleetime == 1)
483.                 fleetime++;
484.             mtmp->mfleetim = (unsigned) min(fleetime, 127);
485.         }
486.         if (!mtmp->mflee && fleemsg && canseemon(mtmp)
487.             && M_AP_TYPE(mtmp) != M_AP_FURNITURE
488.             && M_AP_TYPE(mtmp) != M_AP_OBJECT) {
489.             /* unfortunately we can't distinguish between temporary
490.                sleep and temporary paralysis, so both conditions
491.                receive the same alternate message */
492.             if (!mtmp->mcanmove || !mtmp->data->mmove) {
493.                 pline_mon(mtmp, "%s seems to flinch.",
494.                           Adjmonnam(mtmp, "immobile"));
495.             } else if (flees_light(mtmp)) {
496.                 if (Unaware) {
497.                     /* tell the player even if the hero is unconscious */
498.                     pline_mon(mtmp, "%s is frightened.", Monnam(mtmp));
499.                 } else if (rn2(10) || Deaf) {
500.                     /* via flees_light(), will always be either via uwep
501.                        (Sunsword) or uarm (gold dragon scales/mail) or both;
502.                        TODO? check for both and describe the one which is
503.                        emitting light with a bigger radius */
504.                     const char *lsrc = (uwep && artifact_light(uwep))
505.                                        ? bare_artifactname(uwep)
506.                                        : (uarm && artifact_light(uarm))
507.                                          ? yname(uarm)
508.                                          : "[its imagination?]";
509. 
510.                     pline_mon(mtmp, "%s flees from the painful light of %s.",
511.                           Monnam(mtmp), lsrc);
512.                 } else {
513.                     SetVoice(mtmp, 0, 80, 0);
514.                     verbalize("Bright light!");
515.                 }
516.             } else {
517.                 pline_mon(mtmp, "%s turns to flee.", Monnam(mtmp));
518.             }
519.         }
520. 
521.         if (mtmp->data == &mons[PM_VROCK] && !mtmp->mspec_used) {
522.             mtmp->mspec_used = 75 + rn2(25);
523.             (void) create_gas_cloud(mtmp->mx, mtmp->my, 5, 8);
524.         }
525. 
526.         mtmp->mflee = 1;
527.     }
528.     /* ignore recently-stepped spaces when made to flee */
529.     mon_track_clear(mtmp);
530. }
531. 
532. staticfn void
533. distfleeck(
534.     struct monst *mtmp,
535.     int *inrange, int *nearby, int *scared) /* output */
536. {
537.     int seescaryx, seescaryy;
538.     boolean sawscary = FALSE, bravegremlin = (rn2(5) == 0);
539. 
540.     *inrange = (dist2(mtmp->mx, mtmp->my, mtmp->mux, mtmp->muy)
541.                 <= (BOLT_LIM * BOLT_LIM));
542.     *nearby = *inrange && monnear(mtmp, mtmp->mux, mtmp->muy);
543. 
544.     /* Note: if your image is displaced, the monster sees the Elbereth
545.      * at your displaced position, thus never attacking your displaced
546.      * position, but possibly attacking you by accident.  If you are
547.      * invisible, it sees the Elbereth at your real position, thus never
548.      * running into you by accident but possibly attacking the spot
549.      * where it guesses you are.
550.      */
551.     if (!mtmp->mcansee || (Invis && !perceives(mtmp->data))) {
552.         seescaryx = mtmp->mux;
553.         seescaryy = mtmp->muy;
554.     } else {
555.         seescaryx = u.ux;
556.         seescaryy = u.uy;
557.     }
558. 
559.     sawscary = onscary(seescaryx, seescaryy, mtmp);
560.     if (*nearby && (sawscary
561.                     || (flees_light(mtmp) && !bravegremlin)
562.                     || (!mtmp->mpeaceful && in_your_sanctuary(mtmp, 0, 0)))) {
563.         *scared = 1;
564.         monflee(mtmp, rnd(rn2(7) ? 10 : 100), TRUE, TRUE);
565.     } else
566.         *scared = 0;
567. }
568. 
569. #undef flees_light
570. 
571. /* perform a special one-time action for a monster; returns -1 if nothing
572.    special happened, 0 if monster uses up its turn, 1 if monster is killed */
573. staticfn int
574. m_arrival(struct monst *mon)
575. {
576.     mon->mstrategy &= ~STRAT_ARRIVE; /* always reset */
577. 
578.     return -1;
579. }
580. 
581. /* a mind flayer unleashes a mind blast  */
582. staticfn void
583. mind_blast(struct monst *mtmp)
584. {
585.     struct monst *m2, *nmon = (struct monst *) 0;
586. 
587.     if (canseemon(mtmp))
588.         pline_mon(mtmp, "%s concentrates.", Monnam(mtmp));
589.     if (mdistu(mtmp) > BOLT_LIM * BOLT_LIM) {
590.         You("sense a faint wave of psychic energy.");
591.         return;
592.     }
593.     pline("A wave of psychic energy pours over you!");
594.     if (mtmp->mpeaceful
595.         && (!Conflict || resist_conflict(mtmp))) {
596.         pline("It feels quite soothing.");
597.     } else if (!u.uinvulnerable) {
598.         int dmg;
599.         boolean m_sen = sensemon(mtmp);
600. 
601.         if (m_sen || (Blind_telepat && rn2(2)) || !rn2(10)) {
602.             /* hiding monsters are brought out of hiding when hit by
603.                 a psychic blast, so do the same for hiding poly'd hero */
604.             if (u.uundetected) {
605.                 u.uundetected = 0;
606.                 newsym(u.ux, u.uy);
607.             } else if (U_AP_TYPE != M_AP_NOTHING
608.                         /* hero has no way to hide as monster but
609.                             check for that theoretical case anyway */
610.                         && U_AP_TYPE != M_AP_MONSTER) {
611.                 gy.youmonst.m_ap_type = M_AP_NOTHING;
612.                 gy.youmonst.mappearance = 0;
613.                 newsym(u.ux, u.uy);
614.             }
615.             pline("It locks on to your %s!",
616.                     m_sen ? "telepathy"
617.                     : Blind_telepat ? "latent telepathy"
618.                     : "mind"); /* note: hero is never mindless */
619.             dmg = rnd(15);
620.             if (Half_spell_damage)
621.                 dmg = (dmg + 1) / 2;
622.             losehp(dmg, "psychic blast", KILLED_BY_AN);
623.         }
624.     }
625.     for (m2 = fmon; m2; m2 = nmon) {
626.         nmon = m2->nmon;
627.         if (DEADMONSTER(m2))
628.             continue;
629.         if (m2->mpeaceful == mtmp->mpeaceful)
630.             continue;
631.         if (mindless(m2->data))
632.             continue;
633.         if (m2 == mtmp)
634.             continue;
635.         if ((telepathic(m2->data) && (rn2(2) || m2->mblinded)) || !rn2(10)) {
636.             /* wake it up first, to bring hidden monster out of hiding */
637.             wakeup(m2, FALSE);
638.             if (cansee(m2->mx, m2->my))
639.                 pline("It locks on to %s.", mon_nam(m2));
640.             m2->mhp -= rnd(15);
641.             if (DEADMONSTER(m2))
642.                 monkilled(m2, "", AD_DRIN);
643.         }
644.     }
645. }
646. 
647. /* called every turn for each living monster on the map, and the hero;
648.    caller makes sure that we're not called for DEADMONSTER() */
649. void
650. m_everyturn_effect(struct monst *mtmp)
651. {
652.     boolean is_u = (mtmp == &gy.youmonst) ? TRUE : FALSE;
653.     coordxy x = is_u ? u.ux : mtmp->mx,
654.             y = is_u ? u.uy : mtmp->my;
655. 
656.     if (mtmp->data == &mons[PM_FOG_CLOUD]) {
657.         /* don't leave a vapor cloud if some other gas cloud is already
658.            present, or when flowing under closed doors so that visibility
659.            changes aren't mixed with messages about doing such */
660.         if (!closed_door(x, y) && !visible_region_at(x, y))
661.             create_gas_cloud(x, y, 1, 0); /* harmless vapor */
662.     }
663. }
664. 
665. /* do whatever effects monster has after moving.
666.    called for both monsters and polyed hero.
667.    for hero, called after location changes,
668.    to prevent spam messages for hero getting enveloped in a cloud.
669.    for monsters, called before location changes,
670.    because monsters don't have "previous location" field */
671. void
672. m_postmove_effect(struct monst *mtmp)
673. {
674.     boolean is_u = (mtmp == &gy.youmonst) ? TRUE : FALSE;
675.     coordxy x = is_u ? u.ux0 : mtmp->mx,
676.             y = is_u ? u.uy0 : mtmp->my;
677. 
678.     /* Hezrous create clouds of stench. This does not cost a move. */
679.     if (mtmp->data == &mons[PM_HEZROU]) /* stench */
680.         create_gas_cloud(x, y, 1, 8);
681.     else if (mtmp->data == &mons[PM_STEAM_VORTEX] && !mtmp->mcan)
682.         create_gas_cloud(x, y, 1, 0); /* harmless vapor */
683. }
684. 
685. /* returns 1 if monster died moving, 0 otherwise */
686. /* The whole dochugw/m_move/distfleeck/mfndpos section is serious spaghetti
687.  * code. --KAA
688.  */
689. int
690. dochug(struct monst *mtmp)
691. {
692.     struct permonst *mdat;
693.     int status = MMOVE_NOTHING;
694.     int inrange, nearby, scared, res;
695.     struct obj *otmp;
696.     boolean panicattk = FALSE;
697. 
698.     /*
699.      * PHASE ONE: Pre-movement adjustments
700.      */
701. 
702.     mdat = mtmp->data;
703. 
704.     if (mtmp->mstrategy & STRAT_ARRIVE) {
705.         res = m_arrival(mtmp);
706.         if (res >= 0)
707.             return res;
708.     }
709.     /* check for waitmask status change */
710.     if ((mtmp->mstrategy & STRAT_WAITFORU)
711.         && (m_canseeu(mtmp) || mtmp->mhp < mtmp->mhpmax))
712.         mtmp->mstrategy &= ~STRAT_WAITFORU;
713. 
714.     /* update quest status flags */
715.     quest_stat_check(mtmp);
716. 
717.     if (!mtmp->mcanmove || (mtmp->mstrategy & STRAT_WAITMASK)) {
718.         if (Hallucination)
719.             newsym(mtmp->mx, mtmp->my);
720.         if (mtmp->mcanmove && (mtmp->mstrategy & STRAT_CLOSE)
721.             && !mtmp->msleeping && monnear(mtmp, u.ux, u.uy))
722.             quest_talk(mtmp); /* give the leaders a chance to speak */
723.         return 0;             /* other frozen monsters can't do anything */
724.     }
725. 
726.     /* there is a chance we will wake it */
727.     if (mtmp->msleeping && !disturb(mtmp)) {
728.         if (Hallucination)
729.             newsym(mtmp->mx, mtmp->my);
730.         return 0;
731.     }
732. 
733.     /* not frozen or sleeping: wipe out texts written in the dust */
734.     wipe_engr_at(mtmp->mx, mtmp->my, 1, FALSE);
735. 
736.     /* confused monsters get unconfused with small probability */
737.     if (mtmp->mconf && !rn2(50))
738.         mtmp->mconf = 0;
739. 
740.     /* stunned monsters get un-stunned with larger probability */
741.     if (mtmp->mstun && !rn2(10))
742.         mtmp->mstun = 0;
743. 
744.     /* Some monsters teleport. Teleportation costs a turn. */
745.     if (mtmp->mflee && !rn2(40) && can_teleport(mdat) && !mtmp->iswiz
746.         && !noteleport_level(mtmp)) {
747.         if (rloc(mtmp, RLOC_MSG))
748.             leppie_stash(mtmp);
749.         return 0;
750.     }
751. 
752.     /* some monsters have special abilities */
753.     m_respond(mtmp);
754.     if (DEADMONSTER(mtmp))
755.         return 1; /* m_respond gaze can kill medusa */
756. 
757.     /* fleeing monsters might regain courage */
758.     if (mtmp->mflee && !mtmp->mfleetim && mtmp->mhp == mtmp->mhpmax
759.         && !rn2(25))
760.         mtmp->mflee = 0;
761. 
762.     /* Cease conflict-induced swallow/grab if conflict has ended. Releasing
763.        the hero in this way uses up the monster's turn. */
764.     if (mtmp == u.ustuck && mtmp->mpeaceful && !mtmp->mconf && !Conflict) {
765.         release_hero(mtmp);
766.         return 0;
767.     }
768. 
769.     /*
770.      * PHASE TWO: Special Movements and Actions
771.      */
772. 
773.     /* The monster decides where it thinks you are. This call to set_apparxy()
774.        must be done after you move and before the monster does. The
775.        set_apparxy() call in m_move() doesn't suffice since the variables
776.        inrange, etc. all depend on stuff set by set_apparxy().
777.      */
778.     set_apparxy(mtmp);
779. 
780.     /* Monsters that want to acquire things may teleport, so do it before
781.        inrange is set. This costs a turn only if mstate is set.  */
782.     if (is_covetous(mdat)) {
783.         (void) tactics(mtmp);
784.         /* tactics -> mnexto -> deal_with_overcrowding */
785.         if (mtmp->mstate)
786.             return 0;
787.         set_apparxy(mtmp);
788.     }
789. 
790.     /* check distance and scariness of attacks */
791.     distfleeck(mtmp, &inrange, &nearby, &scared);
792. 
793.     /* search for and potentially use defensive or miscellaneous items. */
794.     if (find_defensive(mtmp, FALSE)) {
795.         if (use_defensive(mtmp) != 0)
796.             return 1;
797.     } else if (find_misc(mtmp)) {
798.         if (use_misc(mtmp) != 0)
799.             return 1;
800.     }
801. 
802.     /* Demonic Blackmail! */
803.     if (nearby && mdat->msound == MS_BRIBE && mtmp->mpeaceful && !mtmp->mtame
804.         && !u.uswallow) {
805.         if (mtmp->mux != u.ux || mtmp->muy != u.uy) {
806.             pline("%s whispers at thin air.",
807.                   cansee(mtmp->mux, mtmp->muy) ? Monnam(mtmp) : "It");
808. 
809.             if (is_demon(gy.youmonst.data)) {
810.                 /* "Good hunting, brother" */
811.                 if (!tele_restrict(mtmp))
812.                     (void) rloc(mtmp, RLOC_MSG);
813.             } else {
814.                 mtmp->minvis = mtmp->perminvis = 0;
815.                 /* Why?  For the same reason in real demon talk */
816.                 if (canseemon(mtmp))
817.                     set_msg_xy(mtmp->mx, mtmp->my);
818.                 pline("%s gets angry!", Amonnam(mtmp));
819.                 mtmp->mpeaceful = 0;
820.                 set_malign(mtmp);
821.                 /* since no way is an image going to pay it off */
822.             }
823.         } else if (demon_talk(mtmp))
824.             return 1; /* you paid it off */
825.     }
826. 
827.     /* the watch will look around and see if you are up to no good :-) */
828.     if (is_watch(mdat)) {
829.         watch_on_duty(mtmp);
830.     /* mind flayers can make psychic attacks! */
831.     } else if (is_mind_flayer(mdat) && !rn2(20)) {
832.         mind_blast(mtmp);
833.         set_apparxy(mtmp);
834.         distfleeck(mtmp, &inrange, &nearby, &scared);
835.     }
836. 
837.     /* If monster is nearby you, and has to wield a weapon, do so.  This
838.      * costs the monster a move, of course.
839.      */
840.     if ((!mtmp->mpeaceful || Conflict) && inrange
841.         && dist2(mtmp->mx, mtmp->my, mtmp->mux, mtmp->muy) <= 8
842.         && attacktype(mdat, AT_WEAP)) {
843.         struct obj *mw_tmp;
844. 
845.         /* The scared check is necessary.  Otherwise a monster that is
846.          * one square near the player but fleeing into a wall would keep
847.          * switching between pick-axe and weapon.  If monster is stuck
848.          * in a trap, prefer ranged weapon (wielding is done in thrwmu).
849.          * This may cost the monster an attack, but keeps the monster
850.          * from switching back and forth if carrying both.
851.          */
852.         mw_tmp = MON_WEP(mtmp);
853.         if (!(scared && mw_tmp && is_pick(mw_tmp))
854.             && mtmp->weapon_check == NEED_WEAPON
855.             && !(mtmp->mtrapped && !nearby && select_rwep(mtmp))) {
856.             mtmp->weapon_check = NEED_HTH_WEAPON;
857.             if (mon_wield_item(mtmp) != 0)
858.                 return 0;
859.         }
860.     }
861. 
862.     /*
863.      * PHASE THREE: Now the actual movement phase
864.      */
865. 
866.     /* A killer bee may eat honey in order to turn into a queen bee,
867.        costing it a move. */
868.     if (mdat == &mons[PM_KILLER_BEE]
869.         /* could be smarter and deliberately move to royal jelly, but
870.            then we'd need to scan the level for queen bee in advance;
871.            avoid that overhead and rely on serendipity... */
872.         && (otmp = sobj_at(LUMP_OF_ROYAL_JELLY, mtmp->mx, mtmp->my)) != 0
873.         && (res = bee_eat_jelly(mtmp, otmp)) >= 0)
874.         return res;
875. 
876.     if (mdat == &mons[PM_GELATINOUS_CUBE]
877.         && (res = gelcube_digests(mtmp)) >= 0)
878.         return res;
879. 
880.     /* A monster that passes the following checks has the opportunity
881.        to move. Movement itself is handled by the m_move() function. */
882.     if (!nearby || mtmp->mflee || scared || mtmp->mconf || mtmp->mstun
883.         || (mtmp->minvis && !rn2(3))
884.         || (mdat->mlet == S_LEPRECHAUN && !findgold(gi.invent)
885.             && (findgold(mtmp->minvent) || rn2(2)))
886.         || (is_wanderer(mdat) && !rn2(4)) || (Conflict && !mtmp->iswiz)
887.         || (!mtmp->mcansee && !rn2(4)) || mtmp->mpeaceful) {
888. 
889.         /* Possibly cast an undirected spell if not attacking you */
890.         /* note that most of the time castmu() will pick a directed
891.            spell and do nothing, so the monster moves normally */
892.         /* arbitrary distance restriction to keep monster far away
893.            from you from having cast dozens of sticks-to-snakes
894.            or similar spells by the time you reach it */
895.         if (!mtmp->mspec_used
896.             && dist2(mtmp->mx, mtmp->my, u.ux, u.uy) <= 49) {
897.             struct attack *a;
898. 
899.             for (a = &mdat->mattk[0]; a < &mdat->mattk[NATTK]; a++) {
900.                 if (a->aatyp == AT_MAGC
901.                     && (a->adtyp == AD_SPEL || a->adtyp == AD_CLRC)) {
902.                     if ((castmu(mtmp, a, FALSE, FALSE) & M_ATTK_HIT)) {
903.                         status = MMOVE_DONE; /* bypass m_move() */
904.                         break;
905.                     }
906.                 }
907.             }
908.         }
909. 
910.         if (!status)
911.             status = m_move(mtmp, 0);
912.         if (mon_offmap(mtmp))
913.             return 1;
914.         if (status != MMOVE_DIED)
915.             distfleeck(mtmp, &inrange, &nearby, &scared); /* recalc */
916. 
917.         switch (status) { /* for pets, cases 0 and 3 are equivalent */
918.         case MMOVE_NOMOVES:
919.             if (scared)
920.                 panicattk = TRUE;
921.             FALLTHROUGH;
922.             /*FALLTHRU*/
923.         case MMOVE_NOTHING: /* no movement, but it can still attack you */
924.         case MMOVE_DONE: /* absolutely no movement */
925.             /* vault guard might have vanished */
926.             if (mtmp->isgd && (DEADMONSTER(mtmp) || mtmp->mx == 0))
927.                 return 1; /* behave as if it died */
928.             /* During hallucination, monster appearance should
929.              * still change - even if it doesn't move.
930.              */
931.             if (Hallucination)
932.                 newsym(mtmp->mx, mtmp->my);
933.             break;
934.         case MMOVE_MOVED: /* monster moved */
935.             /* if confused grabber has wandered off, let go */
936.             if (mtmp == u.ustuck && !m_next2u(mtmp))
937.                 unstuck(mtmp);
938.             if (grounded(mdat))
939.                 disturb_buried_zombies(mtmp->mx, mtmp->my);
940.             /* Maybe it stepped on a trap and fell asleep... */
941.             if (helpless(mtmp))
942.                 return 0;
943.             /* Monsters can move and then shoot on same turn;
944.                our hero can't.  Is that fair? */
945.             if (!nearby
946.                 && (ranged_attk_available(mtmp)
947.                             || attacktype(mdat, AT_WEAP)
948.                             || find_offensive(mtmp)))
949.                 break;
950.             /* a monster that's digesting you can move at the
951.              * same time -dlc
952.              */
953.             if (engulfing_u(mtmp))
954.                 return mattacku(mtmp);
955.             return 0;
956.         case MMOVE_DIED: /* monster died */
957.             return 1;
958.         }
959.     }
960. 
961.     /*
962.      * PHASE FOUR: Standard Attacks
963.      */
964. 
965.     /* Now, attack the player if possible - one attack set per monst */
966.     if (status != MMOVE_DONE && (!mtmp->mpeaceful
967.                                  || (Conflict && !resist_conflict(mtmp)))) {
968.         if (((inrange && !scared) || panicattk) && !noattacks(mdat)
969.             /* [is this hp check really needed?] */
970.             && (Upolyd ? u.mh : u.uhp) > 0) {
971.             if (mattacku(mtmp))
972.                 return 1; /* monster died (e.g. exploded) */
973.         }
974.         if (mtmp->wormno) {
975.             if (wormhitu(mtmp))
976.                 return 1; /* worm died (poly'd hero passive counter-attack) */
977.         }
978.     }
979.     /* special speeches for quest monsters */
980.     if (!helpless(mtmp) && nearby)
981.         quest_talk(mtmp);
982.     /* extra emotional attack for vile monsters */
983.     if (inrange && mtmp->data->msound == MS_CUSS && !mtmp->mpeaceful
984.         && couldsee(mtmp->mx, mtmp->my) && !mtmp->minvis && !rn2(5))
985.         cuss(mtmp);
986. 
987.     /* note: can't get here when monster is dead, so this always returns 0 */
988.     return (status == MMOVE_DIED);
989. }
990. 
991. static NEARDATA const char practical[] = { WEAPON_CLASS, ARMOR_CLASS,
992.                                            GEM_CLASS, FOOD_CLASS, 0 };
993. static NEARDATA const char magical[] = { AMULET_CLASS, POTION_CLASS,
994.                                          SCROLL_CLASS, WAND_CLASS,
995.                                          RING_CLASS,   SPBOOK_CLASS, 0 };
996. 
997. /* monster mtmp would love to take object otmp? */
998. boolean
999. mon_would_take_item(struct monst *mtmp, struct obj *otmp)
1000. {
1001.     int pctload = (curr_mon_load(mtmp) * 100) / max_mon_load(mtmp);
1002. 
1003.     if (otmp == uball || otmp == uchain)
1004.         return FALSE;
1005.     if (mtmp->mtame && otmp->cursed)
1006.         return FALSE; /* note: will get overridden if mtmp will eat otmp */
1007.     if (is_unicorn(mtmp->data) && objects[otmp->otyp].oc_material != GEMSTONE)
1008.         return FALSE;
1009.     if (!mindless(mtmp->data) && !is_animal(mtmp->data) && pctload < 75
1010.         && searches_for_item(mtmp, otmp))
1011.         return TRUE;
1012.     if (likes_gold(mtmp->data) && otmp->otyp == GOLD_PIECE && pctload < 95)
1013.         return TRUE;
1014.     if (likes_gems(mtmp->data) && otmp->oclass == GEM_CLASS
1015.         && objects[otmp->otyp].oc_material != MINERAL && pctload < 85)
1016.         return TRUE;
1017.     if (likes_objs(mtmp->data) && strchr(practical, otmp->oclass)
1018.         && pctload < 75)
1019.         return TRUE;
1020.     if (likes_magic(mtmp->data) && strchr(magical, otmp->oclass)
1021.         && pctload < 85)
1022.         return TRUE;
1023.     if (throws_rocks(mtmp->data) && otmp->otyp == BOULDER
1024.         && pctload < 50 && !Sokoban)
1025.         return TRUE;
1026.     if (mtmp->data == &mons[PM_GELATINOUS_CUBE]
1027.         && otmp->oclass != ROCK_CLASS && otmp->oclass != BALL_CLASS
1028.         && !(otmp->otyp == CORPSE && touch_petrifies(&mons[otmp->corpsenm])))
1029.         return TRUE;
1030. 
1031.     return FALSE;
1032. }
1033. 
1034. /* monster mtmp would love to consume object otmp, without picking it up */
1035. boolean
1036. mon_would_consume_item(struct monst *mtmp, struct obj *otmp)
1037. {
1038.     int ftyp;
1039. 
1040.     if (otmp->otyp == CORPSE && !touch_petrifies(&mons[otmp->corpsenm])
1041.         && corpse_eater(mtmp->data))
1042.         return TRUE;
1043. 
1044.     if (mtmp->mtame && has_edog(mtmp) /* has_edog(): not guardian angel */
1045.         && (ftyp = dogfood(mtmp, otmp)) < MANFOOD
1046.         && (ftyp < ACCFOOD || EDOG(mtmp)->hungrytime <= svm.moves))
1047.         return TRUE;
1048. 
1049.     return FALSE;
1050. }
1051. 
1052. boolean
1053. itsstuck(struct monst *mtmp)
1054. {
1055.     if (sticks(gy.youmonst.data) && mtmp == u.ustuck && !u.uswallow) {
1056.         pline_mon(mtmp, "%s cannot escape from you!", Monnam(mtmp));
1057.         return TRUE;
1058.     }
1059.     return FALSE;
1060. }
1061. 
1062. /*
1063.  * should_displace()
1064.  *
1065.  * Displacement of another monster is a last resort and only
1066.  * used on approach. If there are better ways to get to target,
1067.  * those should be used instead. This function does that evaluation.
1068.  */
1069. boolean
1070. should_displace(
1071.     struct monst *mtmp,
1072.     const struct mfndposdata *data,
1073.     coordxy ggx,
1074.     coordxy ggy)
1075. {
1076.     int shortest_with_displacing = -1;
1077.     int shortest_without_displacing = -1;
1078.     int count_without_displacing = 0;
1079.     int i, nx, ny;
1080.     int ndist;
1081. 
1082.     for (i = 0; i < data->cnt; i++) {
1083.         nx = data->poss[i].x;
1084.         ny = data->poss[i].y;
1085.         ndist = dist2(nx, ny, ggx, ggy);
1086.         if (MON_AT(nx, ny) && (data->info[i] & ALLOW_MDISP) && !(data->info[i] & ALLOW_M)
1087.             && !undesirable_disp(mtmp, nx, ny)) {
1088.             if (shortest_with_displacing == -1
1089.                 || (ndist < shortest_with_displacing))
1090.                 shortest_with_displacing = ndist;
1091.         } else {
1092.             if ((shortest_without_displacing == -1)
1093.                 || (ndist < shortest_without_displacing))
1094.                 shortest_without_displacing = ndist;
1095.             count_without_displacing++;
1096.         }
1097.     }
1098.     if (shortest_with_displacing > -1
1099.         && (shortest_with_displacing < shortest_without_displacing
1100.             || !count_without_displacing))
1101.         return TRUE;
1102.     return FALSE;
1103. }
1104. 
1105. /* have monster wield a pick-axe if it wants to dig and it has one;
1106.    return True if it spends this move wielding one, False otherwise */
1107. boolean
1108. m_digweapon_check(
1109.     struct monst *mtmp,
1110.     coordxy nix, coordxy niy)
1111. {
1112.     boolean can_tunnel = FALSE;
1113.     struct obj *mw_tmp = MON_WEP(mtmp);
1114. 
1115.     if (!Is_rogue_level(&u.uz))
1116.         can_tunnel = tunnels(mtmp->data);
1117. 
1118.     if (can_tunnel && needspick(mtmp->data) && !mwelded(mw_tmp)
1119.         && (may_dig(nix, niy) || closed_door(nix, niy))) {
1120.         /* may_dig() is either IS_STWALL or IS_TREE */
1121.         if (closed_door(nix, niy)) {
1122.             if (!mw_tmp || !is_pick(mw_tmp) || !is_axe(mw_tmp))
1123.                 mtmp->weapon_check = NEED_PICK_OR_AXE;
1124.         } else if (IS_TREE(levl[nix][niy].typ)) {
1125.             if (!mw_tmp || !is_axe(mw_tmp))
1126.                 mtmp->weapon_check = NEED_AXE;
1127.         } else if (IS_STWALL(levl[nix][niy].typ)) {
1128.             if (!mw_tmp || !is_pick(mw_tmp))
1129.                 mtmp->weapon_check = NEED_PICK_AXE;
1130.         }
1131.         if (mtmp->weapon_check >= NEED_PICK_AXE && mon_wield_item(mtmp))
1132.             return TRUE;
1133.     }
1134.     return FALSE;
1135. }
1136. 
1137. /* does leprechaun want to avoid the hero? */
1138. staticfn boolean
1139. leppie_avoidance(struct monst *mtmp)
1140. {
1141.     struct obj *lepgold, *ygold;
1142. 
1143.     if (mtmp->data == &mons[PM_LEPRECHAUN]
1144.         && ((lepgold = findgold(mtmp->minvent))
1145.             && (lepgold->quan
1146.                 > ((ygold = findgold(gi.invent)) ? ygold->quan : 0L))))
1147.         return TRUE;
1148. 
1149.     return FALSE;
1150. }
1151. 
1152. /* unseen leprechaun with gold might stash it */
1153. staticfn void
1154. leppie_stash(struct monst *mtmp)
1155. {
1156.     struct obj *gold;
1157. 
1158.     if (mtmp->data == &mons[PM_LEPRECHAUN]
1159.         && !DEADMONSTER(mtmp)
1160.         && !m_canseeu(mtmp)
1161.         && !*in_rooms(mtmp->mx, mtmp->my, SHOPBASE)
1162.         && levl[mtmp->mx][mtmp->my].typ == ROOM
1163.         && !t_at(mtmp->mx, mtmp->my)
1164.         && rn2(4)
1165.         && (gold = findgold(mtmp->minvent)) != 0) {
1166.         mdrop_obj(mtmp, gold, FALSE);
1167.         gold = g_at(mtmp->mx, mtmp->my);
1168.         if (gold)
1169.             (void) bury_an_obj(gold, (boolean *) 0);
1170.     }
1171. }
1172. 
1173. /* does monster want to avoid you?
1174.  *  returns the original value of appr if not.
1175.  *  returns -1 if so.
1176.  *  returns -2 if monster wants to adhere to a particular range,
1177.  *             which may actually be further away,
1178.  *             and sets *pdistmin and *pdistmax to describe that range
1179.  */
1180. staticfn int
1181. m_balks_at_approaching(int oldappr, struct monst *mtmp, int *pdistmin,
1182.                        int *pdistmax)
1183. {
1184.     struct obj *mwep = MON_WEP(mtmp);
1185.     coordxy x = mtmp->mx, y = mtmp->my, ux = mtmp->mux, uy = mtmp->muy;
1186.     int edist = dist2(x, y, ux, uy);
1187.     const struct throw_and_return_weapon *arw;
1188. 
1189.     if (pdistmin)
1190.         *pdistmin = 0;
1191.     if (pdistmax)
1192.         *pdistmax = 0;
1193. 
1194.     /* peaceful, far away, or can't see you */
1195.     if (mtmp->mpeaceful || (edist >= 5 * 5) || !m_canseeu(mtmp))
1196.         return oldappr;
1197. 
1198.     /* has ammo+launcher */
1199.     if (m_has_launcher_and_ammo(mtmp))
1200.         return -1;
1201. 
1202.     /* is using a polearm and in range */
1203.     if (MON_WEP(mtmp) && is_pole(MON_WEP(mtmp))
1204.         && edist <= MON_POLE_DIST)
1205.         return -1;
1206. 
1207.     /* is using a throw-and-return weapon; provide min and max preferred range
1208.      */
1209.     if (mwep && (arw = autoreturn_weapon(mwep)) != 0) {
1210.         if (pdistmin)
1211.             *pdistmin = 2 * 2;
1212.         if (pdistmax)
1213.             *pdistmax = arw->range;
1214.         return -2;
1215.     }
1216. 
1217.     /* can attack from distance, and hp loss or attack not used */
1218.     if (ranged_attk_available(mtmp)
1219.         && ((mtmp->mhp < (mtmp->mhpmax+1) / 3)
1220.             || !mtmp->mspec_used))
1221.         return -1;
1222. 
1223.     return oldappr; /* leaves appr unchanged */
1224. }
1225. 
1226. staticfn boolean
1227. holds_up_web(coordxy x, coordxy y)
1228. {
1229.     stairway *sway;
1230. 
1231.     if (!isok(x, y)
1232.         || IS_OBSTRUCTED(levl[x][y].typ)
1233.         || ((levl[x][y].typ == STAIRS || levl[x][y].typ == LADDER)
1234.             && (sway = stairway_at(x, y)) != 0 && sway->up)
1235.         || levl[x][y].typ == IRONBARS)
1236.         return TRUE;
1237. 
1238.     return FALSE;
1239. }
1240. 
1241. /* returns the number of walls in the four cardinal directions that could
1242.    hold up a web */
1243. staticfn int
1244. count_webbing_walls(coordxy x, coordxy y)
1245. {
1246.     return (holds_up_web(x, y - 1) + holds_up_web(x + 1, y)
1247.             + holds_up_web(x, y + 1) + holds_up_web(x - 1, y));
1248. }
1249. 
1250. /* reject webs which interfere with solving Sokoban */
1251. staticfn boolean
1252. soko_allow_web(struct monst *mon)
1253. {
1254.     stairway *stway;
1255. 
1256.     /* for a non-Sokoban level or a solved Sokoban level, no restriction */
1257.     if (!Sokoban)
1258.         return TRUE;
1259.     /* not-yet-solved Sokoban level:  allow web only when spinner can see
1260.        the stairs up [we really want 'is in same chamber as stairs up'] */
1261.     stway = stairway_find_dir(TRUE); /* stairs up */
1262.     if (stway && m_cansee(mon, stway->sx, stway->sy))
1263.         return TRUE;
1264.     return FALSE;
1265. }
1266. 
1267. /* monster might spin a web */
1268. staticfn void
1269. maybe_spin_web(struct monst *mtmp)
1270. {
1271.     if (webmaker(mtmp->data)
1272.         && !helpless(mtmp) && !mtmp->mspec_used
1273.         && !t_at(mtmp->mx, mtmp->my) && soko_allow_web(mtmp)) {
1274.         struct trap *trap;
1275.         int prob = ((((mtmp->data == &mons[PM_GIANT_SPIDER]) ? 15 : 5)
1276.                      * (count_webbing_walls(mtmp->mx, mtmp->my) + 1))
1277.                     - (3 * count_traps(WEB)));
1278. 
1279.         if (rn2(1000) < prob
1280.             && (trap = maketrap(mtmp->mx, mtmp->my, WEB)) != 0) {
1281.             mtmp->mspec_used = d(4, 4); /* 4..16 */
1282.             if (cansee(mtmp->mx, mtmp->my)) {
1283.                 char mbuf[BUFSZ];
1284. 
1285.                 Strcpy(mbuf, canspotmon(mtmp) ? y_monnam(mtmp) : something);
1286.                 pline_mon(mtmp, "%s spins a web.", upstart(mbuf));
1287.                 trap->tseen = 1;
1288.             }
1289.             if (*in_rooms(mtmp->mx, mtmp->my, SHOPBASE))
1290.                 add_damage(mtmp->mx, mtmp->my, 0L);
1291.         }
1292.     }
1293. }
1294. 
1295. /* monster avoids a location nx, ny, if hero kicked that location */
1296. boolean
1297. m_avoid_kicked_loc(struct monst *mtmp, coordxy nx, coordxy ny)
1298. {
1299.     if ((mtmp->mpeaceful || mtmp->mtame)
1300.         && mtmp->mcansee
1301.         && !mtmp->mconf && !mtmp->mstun
1302.         && !Conflict
1303.         && isok(gk.kickedloc.x, gk.kickedloc.y)
1304.         && nx == gk.kickedloc.x && ny == gk.kickedloc.y
1305.         && next2u(nx, ny))
1306.         return TRUE;
1307.     return FALSE;
1308. }
1309. 
1310. /* monster avoids a location nx, ny, if we're in sokoban, and
1311.    there's a boulder between the location and hero */
1312. boolean
1313. m_avoid_soko_push_loc(struct monst *mtmp, coordxy nx, coordxy ny)
1314. {
1315.     if (Sokoban
1316.         && (mtmp->mpeaceful || mtmp->mtame)
1317.         && !mtmp->mconf && !mtmp->mstun
1318.         && !Conflict
1319.         && (dist2(nx, ny, u.ux, u.uy) == 4)
1320.         && sobj_at(BOULDER, nx + sgn(u.ux - nx), ny + sgn(u.uy - ny)))
1321.         return TRUE;
1322.     return FALSE;
1323. }
1324. 
1325. /* max distmin() distance for monster to look for items */
1326. #define SQSRCHRADIUS 5
1327. 
1328. /* monster looks for items it wants nearby */
1329. staticfn boolean
1330. m_search_items(
1331.     struct monst *mtmp,
1332.     coordxy *ggx, coordxy *ggy,
1333.     int *mmoved,
1334.     int *appr)
1335. {
1336.     int minr = SQSRCHRADIUS; /* not too far away */
1337.     struct obj *otmp;
1338.     coordxy xx, yy;
1339.     coordxy hmx, hmy, lmx, lmy;
1340.     struct trap *ttmp;
1341.     coordxy omx = mtmp->mx, omy = mtmp->my;
1342.     struct permonst *ptr = mtmp->data;
1343.     struct monst *mtoo;
1344.     boolean costly;
1345. 
1346.     /* cut down the search radius if it thinks character is closer. */
1347.     if (distmin(mtmp->mux, mtmp->muy, omx, omy) < SQSRCHRADIUS
1348.         && !mtmp->mpeaceful)
1349.         minr--;
1350.     /* guards shouldn't get too distracted */
1351.     if (!mtmp->mpeaceful && is_mercenary(ptr))
1352.         minr = 1;
1353. 
1354.     /* in shop, usually skip */
1355.     if (*in_rooms(omx, omy, SHOPBASE) && (rn2(25) || mtmp->isshk))
1356.         goto finish_search;
1357. 
1358.     /* distmin() gives a rectangular area */
1359.     hmx = min(COLNO - 1, omx + minr);
1360.     hmy = min(ROWNO - 1, omy + minr);
1361.     lmx = max(1, omx - minr);
1362.     lmy = max(0, omy - minr);
1363. 
1364.     for (xx = lmx; xx <= hmx; xx++) {
1365.         for (yy = lmy; yy <= hmy; yy++) {
1366.             /* no object here */
1367.             if (!OBJ_AT(xx, yy))
1368.                 continue;
1369.             /* found an object closer already */
1370.             if (minr < distmin(omx, omy, xx, yy))
1371.                 continue;
1372.             /* the mfndpos() test for whether to allow a move to a
1373.                water location accepts flyers, but they can't reach
1374.                underwater objects, so being able to move to a spot
1375.                is insufficient for deciding whether to do so */
1376.             if (!could_reach_item(mtmp, xx, yy))
1377.                 continue;
1378.             /* hiders avoid hero's line of sight */
1379.             if (hides_under(ptr) && cansee(xx, yy))
1380.                 continue;
1381.             /* don't get stuck circling around object that's
1382.                underneath an immobile or hidden monster;
1383.                paralysis victims excluded */
1384.             if ((mtoo = m_at(xx, yy)) != 0
1385.                 && (helpless(mtoo) || mtoo->mundetected
1386.                     || (mtoo->mappearance && !mtoo->iswiz)
1387.                     || !mtoo->data->mmove))
1388.                 continue;
1389.             /* Don't get stuck circling an Elbereth */
1390.             if (onscary(xx, yy, mtmp))
1391.                 continue;
1392.             /* ignore obj if there's a trap and monster knows it */
1393.             if ((ttmp = t_at(xx, yy)) != 0
1394.                 && mon_knows_traps(mtmp, ttmp->ttyp)) {
1395.                 if (*ggx == xx && *ggy == yy) {
1396.                     *ggx = mtmp->mux;
1397.                     *ggy = mtmp->muy;
1398.                 }
1399.                 continue;
1400.             }
1401.             /* avoid getting stuck on eg. items in niches */
1402.             if (!m_cansee(mtmp, xx, yy))
1403.                 continue;
1404. 
1405.             costly = costly_spot(xx, yy);
1406. 
1407.             /* look through the items on this location */
1408.             for (otmp = svl.level.objects[xx][yy];
1409.                  otmp; otmp = otmp->nexthere) {
1410.                 /* monsters may pick rocks up, but won't go out of their way
1411.                    to grab them; this might hamper sling wielders, but it cuts
1412.                    down on move overhead by filtering out most common item */
1413.                 if (otmp->otyp == ROCK)
1414.                     continue;
1415.                 /* avoid special items; once hero picks them up, they'll
1416.                    cease being special */
1417.                 if (is_mines_prize(otmp) || is_soko_prize(otmp))
1418.                     continue;
1419.                 /* skip shop merchandise */
1420.                 if (costly && !otmp->no_charge)
1421.                     continue;
1422. 
1423.                 if (((mon_would_take_item(mtmp, otmp)
1424.                       && (can_carry(mtmp, otmp) > 0))
1425.                      || mon_would_consume_item(mtmp, otmp))
1426.                     && can_touch_safely(mtmp, otmp)) {
1427.                     minr = distmin(omx, omy, xx, yy);
1428.                     *ggx = otmp->ox;
1429.                     *ggy = otmp->oy;
1430.                     if (*ggx == omx && *ggy == omy) {
1431.                         *mmoved = MMOVE_DONE; /* actually unnecessary */
1432.                         return TRUE;
1433.                     }
1434.                     /* found an item of interest; skip the rest of the pile */
1435.                     break;
1436.                 }
1437.             }
1438.         }
1439.     }
1440. 
1441.  finish_search:
1442.     if (minr < SQSRCHRADIUS && *appr == -1) {
1443.         if (distmin(omx, omy, mtmp->mux, mtmp->muy) <= 3) {
1444.             *ggx = mtmp->mux;
1445.             *ggy = mtmp->muy;
1446.         } else
1447.             *appr = 1;
1448.     }
1449.     return FALSE;
1450. }
1451. 
1452. #undef SQSRCHRADIUS
1453. 
1454. staticfn int
1455. postmov(
1456.     struct monst *mtmp,
1457.     struct permonst *ptr,
1458.     coordxy omx, coordxy omy,
1459.     int mmoved,
1460.     unsigned seenflgs,
1461.     boolean can_tunnel,
1462.     boolean can_unlock,
1463.     boolean can_open)
1464. {
1465.     coordxy nix, niy;
1466.     int etmp, trapret;
1467.     boolean canseeit = cansee(mtmp->mx, mtmp->my),
1468.             didseeit = canseeit;
1469. 
1470.     notice_mon(mtmp);
1471. 
1472.     if (mmoved == MMOVE_MOVED) {
1473.         nix = mtmp->mx, niy = mtmp->my;
1474.         /* sequencing issue:  when monster movement decides that a
1475.            monster can move to a door location, it moves the monster
1476.            there before dealing with the door rather than after;
1477.            so a vampire/bat that is going to shift to fog cloud and
1478.            pass under the door is already there but transformation
1479.            into fog form--and its message, when in sight--has not
1480.            happened yet; we have to move monster back to previous
1481.            location before performing the vamp_shift() to make the
1482.            message happen at right time, then back to the door again
1483.            [if we did the shift sooner, before moving the monster,
1484.            we would need to duplicate it in dog_move()...] */
1485.         if (is_vampshifter(mtmp) && !amorphous(mtmp->data)
1486.             && IS_DOOR(levl[nix][niy].typ)
1487.             && ((levl[nix][niy].doormask & (D_LOCKED | D_CLOSED)) != 0)
1488.             && can_fog(mtmp)) {
1489.             /* note: remove_monster()+place_monster is not right for
1490.                long worms but they won't reach here */
1491.             if (seenflgs) {
1492.                 remove_monster(nix, niy);
1493.                 place_monster(mtmp, omx, omy);
1494.                 newsym(nix, niy), newsym(omx, omy);
1495.             }
1496.             if (vamp_shift(mtmp, &mons[PM_FOG_CLOUD],
1497.                            ((seenflgs & 1) != 0) ? TRUE : FALSE)) {
1498.                 ptr = mtmp->data; /* update cached value */
1499.                 nhUse(ptr);
1500.             }
1501.             if (seenflgs) {
1502.                 remove_monster(omx, omy);
1503.                 place_monster(mtmp, nix, niy);
1504.                 newsym(omx, omy), newsym(nix, niy);
1505.             }
1506.         }
1507. 
1508.         newsym(omx, omy); /* update the old position */
1509.         trapret = mintrap(mtmp, NO_TRAP_FLAGS);
1510.         if (trapret == Trap_Killed_Mon || trapret == Trap_Moved_Mon) {
1511.             if (mtmp->mx)
1512.                 newsym(mtmp->mx, mtmp->my);
1513.             return MMOVE_DIED; /* it died */
1514.         } else if (mon_offmap(mtmp)) {
1515.             return MMOVE_DONE;
1516.         }
1517.         ptr = mtmp->data; /* in case mintrap() caused polymorph */
1518. 
1519.         /* open a door, or crash through it, if 'mtmp' can */
1520.         if (IS_DOOR(levl[mtmp->mx][mtmp->my].typ)
1521.             && !passes_walls(ptr) /* doesn't need to open doors */
1522.             && !can_tunnel) {     /* taken care of below */
1523.             struct rm *here = &levl[mtmp->mx][mtmp->my];
1524.             boolean btrapped = (here->doormask & D_TRAPPED) != 0;
1525. 
1526.     /* used after monster 'who' has been moved to closed door spot 'where'
1527.        which will now be changed to door state 'what' with map update */
1528. #define UnblockDoor(where,who,what) \
1529.     do {                                                        \
1530.         (where)->doormask = (what);                             \
1531.         newsym((who)->mx, (who)->my);                           \
1532.         recalc_block_point((who)->mx, (who)->my);               \
1533.         vision_recalc(0);                                       \
1534.         /* update cached value since it might change */         \
1535.         canseeit = didseeit || cansee((who)->mx, (who)->my);    \
1536.     } while (0)
1537. 
1538.             /* if mon has MKoT, disarm door trap; no message given */
1539.             if (btrapped && has_magic_key(mtmp)) {
1540.                 /* BUG: this lets a vampire or blob or a doorbuster
1541.                    holding the Key disarm the trap even though it isn't
1542.                    using that Key when squeezing under or smashing the
1543.                    door.  Not significant enough to worry about; perhaps
1544.                    the Key's magic is more powerful for monsters? */
1545.                 here->doormask &= ~D_TRAPPED;
1546.                 btrapped = FALSE;
1547.             }
1548.             if ((here->doormask & (D_LOCKED | D_CLOSED)) != 0
1549.                 && amorphous(ptr)) {
1550.                 if (flags.verbose && canseemon(mtmp))
1551.                     pline_mon(mtmp, "%s %s under the door.", YMonnam(mtmp),
1552.                               (ptr == &mons[PM_FOG_CLOUD]
1553.                                || ptr->mlet == S_LIGHT) ? "flows" : "oozes");
1554.             } else if ((here->doormask & D_LOCKED) != 0 && can_unlock) {
1555.                 /* like the vampshift hack, there are sequencing
1556.                    issues when the monster is moved to the door's spot
1557.                    first then door handling plus feedback comes after */
1558. 
1559.                 UnblockDoor(here, mtmp, !btrapped ? D_ISOPEN : D_NODOOR);
1560.                 if (btrapped) {
1561.                     if (mb_trapped(mtmp, canseeit))
1562.                         return MMOVE_DIED;
1563.                 } else {
1564.                     Soundeffect(se_door_unlock_and_open, 50);
1565.                     if (flags.verbose) {
1566.                         if (canseeit && canspotmon(mtmp)) {
1567.                             pline_mon(mtmp, "%s unlocks and opens a door.",
1568.                                   Monnam(mtmp));
1569.                         } else if (canseeit) {
1570.                             You_see("a door unlock and open.");
1571.                         } else if (!Deaf) {
1572.                             You_hear("a door unlock and open.");
1573.                         }
1574.                     }
1575.                 }
1576.             } else if (here->doormask == D_CLOSED && can_open) {
1577.                 UnblockDoor(here, mtmp, !btrapped ? D_ISOPEN : D_NODOOR);
1578.                 if (btrapped) {
1579.                     if (mb_trapped(mtmp, canseeit))
1580.                         return MMOVE_DIED;
1581.                 } else {
1582.                     Soundeffect(se_door_open, 100);
1583.                     if (flags.verbose) {
1584.                         if (canseeit && canspotmon(mtmp)) {
1585.                             pline_mon(mtmp, "%s opens a door.", Monnam(mtmp));
1586.                         } else if (canseeit) {
1587.                             You_see("a door open.");
1588.                         } else if (!Deaf) {
1589.                             You_hear("a door open.");
1590.                         }
1591.                     }
1592.                 }
1593.             } else if ((here->doormask & (D_LOCKED | D_CLOSED)) != 0) {
1594.                 /* mfndpos guarantees this must be a doorbuster */
1595.                 unsigned mask;
1596. 
1597.                 mask = ((btrapped
1598.                          || ((here->doormask & D_LOCKED) != 0 && !rn2(2)))
1599.                         ? D_NODOOR
1600.                         : D_BROKEN);
1601.                 UnblockDoor(here, mtmp, mask);
1602.                 if (btrapped) {
1603.                     if (mb_trapped(mtmp, canseeit))
1604.                         return MMOVE_DIED;
1605.                 } else {
1606.                     Soundeffect(se_door_crash_open, 50);
1607.                     if (flags.verbose) {
1608.                         if (canseeit && canspotmon(mtmp)) {
1609.                             pline_mon(mtmp, "%s smashes down a door.",
1610.                                       Monnam(mtmp));
1611.                         } else if (canseeit) {
1612.                             You_see("a door crash open.");
1613.                         } else if (!Deaf) {
1614.                             You_hear("a door crash open.");
1615.                         }
1616.                     }
1617.                 }
1618.                 /* if it's a shop door, schedule repair */
1619.                 if (*in_rooms(mtmp->mx, mtmp->my, SHOPBASE))
1620.                     add_damage(mtmp->mx, mtmp->my, 0L);
1621.             }
1622. #undef UnblockDoor
1623. 
1624.         } else if (levl[mtmp->mx][mtmp->my].typ == IRONBARS) {
1625.             /* 3.6.2: was using may_dig() but that doesn't handle bars;
1626.                AD_RUST catches rust monsters but metallivorous() is
1627.                    needed for xorns and rock moles */
1628.             if (!(levl[mtmp->mx][mtmp->my].wall_info & W_NONDIGGABLE)
1629.                 && (dmgtype(ptr, AD_RUST) || dmgtype(ptr, AD_CORR)
1630.                     || metallivorous(ptr))) {
1631.                 if (canseemon(mtmp))
1632.                     pline_mon(mtmp, "%s eats through the iron bars.",
1633.                               Monnam(mtmp));
1634.                 dissolve_bars(mtmp->mx, mtmp->my);
1635.                 return MMOVE_DONE;
1636.             } else if (flags.verbose && canseemon(mtmp))
1637.                 Norep("%s %s %s the iron bars.", Monnam(mtmp),
1638.                       /* pluralization fakes verb conjugation */
1639.                       makeplural(locomotion(ptr, "pass")),
1640.                       passes_walls(ptr) ? "through" : "between");
1641.         } /* doors and bars */
1642. 
1643.         /* possibly dig */
1644.         if (can_tunnel && may_dig(mtmp->mx, mtmp->my)
1645.             && mdig_tunnel(mtmp))
1646.             return MMOVE_DIED; /* mon died (position already updated) */
1647. 
1648.         /* set also in domove(), hack.c */
1649.         if (engulfing_u(mtmp) && (mtmp->mx != omx || mtmp->my != omy)) {
1650.             /* If the monster moved, then update */
1651.             u.ux0 = u.ux;
1652.             u.uy0 = u.uy;
1653.             u_on_newpos(mtmp->mx, mtmp->my);
1654.             swallowed(0);
1655.         } else {
1656.             newsym(mtmp->mx, mtmp->my);
1657.         }
1658.     } /* mmoved==MMOVE_MOVED */
1659. 
1660.     if (mmoved == MMOVE_MOVED || mmoved == MMOVE_DONE) {
1661.         if (OBJ_AT(mtmp->mx, mtmp->my) && mtmp->mcanmove) {
1662. 
1663.             /* Maybe a rock mole just ate some metal object */
1664.             if (metallivorous(ptr)) {
1665.                 if (meatmetal(mtmp) == 2)
1666.                     return MMOVE_DIED; /* it died */
1667.             }
1668. 
1669.             /* Maybe a cube ate just about anything */
1670.             if (ptr == &mons[PM_GELATINOUS_CUBE]) {
1671.                 if ((etmp = meatobj(mtmp)) >= 2)
1672.                     return etmp; /* it died or got forced off the level */
1673.             }
1674.             /* Maybe a purple worm ate a corpse */
1675.             if (corpse_eater(ptr)) {
1676.                 if ((etmp = meatcorpse(mtmp)) >= 2)
1677.                     return etmp; /* it died or got forced off the level */
1678.             }
1679. 
1680.             if (mpickstuff(mtmp))
1681.                 mmoved = MMOVE_DONE;
1682. 
1683.             if (mtmp->minvis) {
1684.                 newsym(mtmp->mx, mtmp->my);
1685.                 if (mtmp->wormno)
1686.                     see_wsegs(mtmp);
1687.             }
1688.         }
1689. 
1690.         maybe_spin_web(mtmp);
1691. 
1692.         if (hides_under(ptr) || ptr->mlet == S_EEL) {
1693.             /* Always set--or reset--mundetected if it's already hidden
1694.                (just in case the object it was hiding under went away);
1695.                usually set mundetected unless monster can't move. */
1696.             if (mtmp->mundetected || (!helpless(mtmp) && rn2(5)))
1697.                 (void) hideunder(mtmp);
1698.             newsym(mtmp->mx, mtmp->my);
1699.         }
1700.         if (mtmp->isshk) {
1701.             after_shk_move(mtmp);
1702.         }
1703.     }
1704.     return mmoved;
1705. }
1706. 
1707. /* Handles the movement of a standard monster.
1708.  * Return values:
1709.  * 0: did not move, but can still attack and do other stuff;
1710.  * 1: moved, possibly can attack;
1711.  * 2: monster died;
1712.  * 3: did not move, and can't do anything else either.
1713.  */
1714. int
1715. m_move(struct monst *mtmp, int after)
1716. {
1717.     int appr;
1718.     coordxy ggx, ggy, nix, niy;
1719.     xint16 chcnt;
1720.     boolean can_tunnel = 0;
1721.     boolean can_open = 0, can_unlock = 0 /*, doorbuster = 0 */;
1722.     boolean getitems = FALSE;
1723.     boolean avoid = FALSE;
1724.     boolean better_with_displacing = FALSE;
1725.     unsigned seenflgs;
1726.     struct permonst *ptr;
1727.     int chi, mmoved = MMOVE_NOTHING, /* not strictly nec.: chi >= 0 will do */
1728.         preferredrange_min = 0, preferredrange_max = 0;
1729.     struct mfndposdata mfp;
1730.     long flag;
1731.     coordxy omx = mtmp->mx, omy = mtmp->my;
1732. 
1733.     if (mtmp->mtrapped) {
1734.         int i = mintrap(mtmp, NO_TRAP_FLAGS);
1735. 
1736.         if (i == Trap_Killed_Mon) {
1737.             newsym(mtmp->mx, mtmp->my);
1738.             return MMOVE_DIED;
1739.         } /* it died */
1740.         if (i == Trap_Caught_Mon)
1741.             return MMOVE_NOTHING; /* still in trap, so didn't move */
1742.     }
1743.     ptr = mtmp->data; /* mintrap() can change mtmp->data -dlc */
1744. 
1745.     if (mtmp->meating) {
1746.         mtmp->meating--;
1747.         if (mtmp->meating <= 0)
1748.             finish_meating(mtmp);
1749.         return MMOVE_DONE; /* still eating */
1750.     }
1751.     if (hides_under(ptr) && OBJ_AT(mtmp->mx, mtmp->my)
1752.         && can_hide_under_obj(svl.level.objects[mtmp->mx][mtmp->my])
1753.         && rn2(10))
1754.         return MMOVE_NOTHING; /* do not leave hiding place */
1755. 
1756.     /* set up pre-move visibility flags */
1757.     seenflgs = (canseemon(mtmp) ? 1 : 0) | (canspotmon(mtmp) ? 2 : 0);
1758. 
1759.     /* Where does 'mtmp' think you are?  Not necessary if m_move() called
1760.        from this file, but needed for other calls of m_move(). */
1761.     set_apparxy(mtmp); /* set mtmp->mux, mtmp->muy */
1762. 
1763.     if (!Is_rogue_level(&u.uz))
1764.         can_tunnel = tunnels(ptr);
1765.     can_open = !(nohands(ptr) || verysmall(ptr));
1766.     can_unlock = ((can_open && monhaskey(mtmp, TRUE))
1767.                   || mtmp->iswiz || is_rider(ptr));
1768.     /* doorbuster = is_giant(ptr); */
1769.     if (mtmp->wormno)
1770.         goto not_special;
1771.     /* my dog gets special treatment */
1772.     if (mtmp->mtame) {
1773.         return postmov(mtmp, ptr, omx, omy, dog_move(mtmp, after),
1774.                        seenflgs, can_tunnel, can_unlock, can_open);
1775.     }
1776. 
1777.     /* and the acquisitive monsters get special treatment */
1778.     if (is_covetous(ptr)) { /* [should this include
1779.                              *  '&& mtmp->mstrategy != STRAT_NONE'?] */
1780.         int covetousattack;
1781.         coordxy tx = mtmp->mgoal.x,
1782.                 ty = mtmp->mgoal.y;
1783.         struct monst *intruder = isok(tx, ty) ? m_at(tx, ty) : NULL;
1784.         /*
1785.          * if there's a monster on the object or in possession of it,
1786.          * attack it.
1787.          */
1788.         if (intruder && intruder != mtmp
1789.             /* 5.0: this used to use 'dist2() < 2' which meant that intended
1790.                attack was disallowed if they were adjacent diagonally */
1791.             && dist2(mtmp->mx, mtmp->my, tx, ty) <= 2) {
1792.             gb.bhitpos.x = tx, gb.bhitpos.y = ty;
1793.             gn.notonhead = (intruder->mx != tx || intruder->my != ty);
1794.             covetousattack = mattackm(mtmp, intruder);
1795.             /* 5.0: this used to erroneously use '== 2' (M_ATTK_DEF_DIED) */
1796.             if (covetousattack & M_ATTK_AGR_DIED)
1797.                 return MMOVE_DIED;
1798.             mmoved = MMOVE_MOVED;
1799.             return postmov(mtmp, ptr, omx, omy, mmoved,
1800.                            seenflgs, can_tunnel, can_unlock, can_open);
1801.         }
1802.         /* otherwise continue with normal AI routine */
1803.     }
1804. 
1805.     /* likewise for shopkeeper, guard, or priest */
1806.     if (mtmp->isshk || mtmp->isgd || mtmp->ispriest) {
1807.         int xm = mtmp->isshk ? shk_move(mtmp)
1808.                  : mtmp->isgd ? gd_move(mtmp)
1809.                    : pri_move(mtmp);
1810. 
1811.         switch (xm) {
1812.         case -2:
1813.             return MMOVE_DIED;
1814.         case -1:
1815.             mmoved = MMOVE_NOTHING; /* shk follow hero outside shop */
1816.             break;
1817.         default:
1818.             impossible("unknown shk/gd/pri_move return value (%d)", xm);
1819.             FALLTHROUGH;
1820.             /*FALLTHRU*/
1821.         case 0:
1822.         case 1:
1823.             return postmov(mtmp, ptr, omx, omy,
1824.                            (xm != 1) ? MMOVE_NOTHING : MMOVE_MOVED,
1825.                            seenflgs, can_tunnel, can_unlock, can_open);
1826.         }
1827.     }
1828. 
1829. #ifdef MAIL_STRUCTURES
1830.     if (ptr == &mons[PM_MAIL_DAEMON]) {
1831.         if (!Deaf && canseemon(mtmp)) {
1832.             SetVoice(mtmp, 0, 80, 0);
1833.             verbalize("I'm late!");
1834.         }
1835.         mongone(mtmp);
1836.         return MMOVE_DIED;
1837.     }
1838. #endif
1839. 
1840.     /* teleport if that lies in our nature */
1841.     if (ptr == &mons[PM_TENGU] && !rn2(5) && !mtmp->mcan
1842.         && !tele_restrict(mtmp)) {
1843.         if (mtmp->mhp < 7 || mtmp->mpeaceful || rn2(2))
1844.             (void) rloc(mtmp, RLOC_MSG);
1845.         else
1846.             mnexto(mtmp, RLOC_MSG);
1847.         return postmov(mtmp, ptr, omx, omy, MMOVE_MOVED,
1848.                        seenflgs, can_tunnel, can_unlock, can_open);
1849.     }
1850.  not_special:
1851.     if (u.uswallow && !mtmp->mflee && u.ustuck != mtmp)
1852.         return MMOVE_MOVED;
1853.     omx = mtmp->mx;
1854.     omy = mtmp->my;
1855.     ggx = mtmp->mux;
1856.     ggy = mtmp->muy;
1857.     appr = mtmp->mflee ? -1 : 1;
1858.     if (mtmp->mconf || engulfing_u(mtmp)) {
1859.         appr = 0;
1860.     } else {
1861.         boolean should_see = (couldsee(omx, omy)
1862.                               && (levl[ggx][ggy].lit || !levl[omx][omy].lit)
1863.                               && (dist2(omx, omy, ggx, ggy) <= 36));
1864. 
1865.         if (!mtmp->mcansee
1866.             || (should_see && Invis && !perceives(ptr) && rn2(11))
1867.             || is_obj_mappear(&gy.youmonst, STRANGE_OBJECT) || u.uundetected
1868.             || (is_obj_mappear(&gy.youmonst, GOLD_PIECE) && !likes_gold(ptr))
1869.             || (mtmp->mpeaceful && !mtmp->isshk) /* allow shks to follow */
1870.             || ((monsndx(ptr) == PM_STALKER || ptr->mlet == S_BAT
1871.                  || ptr->mlet == S_LIGHT) && !rn2(3)))
1872.             appr = 0;
1873. 
1874.         if (appr == 1 && leppie_avoidance(mtmp))
1875.             appr = -1;
1876. 
1877.         /* hostiles with ranged weapon or attack try to stay away */
1878.         appr = m_balks_at_approaching(appr, mtmp, &preferredrange_min, &preferredrange_max);
1879. 
1880.         if (!should_see && can_track(ptr)) {
1881.             coord *cp;
1882. 
1883.             cp = gettrack(omx, omy);
1884.             if (cp) {
1885.                 ggx = cp->x;
1886.                 ggy = cp->y;
1887.             }
1888.         }
1889.     }
1890. 
1891.     if ((!mtmp->mpeaceful || !rn2(10)) && (!Is_rogue_level(&u.uz))) {
1892.         boolean in_line = (lined_up(mtmp)
1893.              && (distmin(mtmp->mx, mtmp->my, mtmp->mux, mtmp->muy)
1894.                  <= (throws_rocks(gy.youmonst.data) ? 20
1895.                                                     : (ACURRSTR / 2 + 1))));
1896. 
1897.         if (appr != 1 || !in_line) {
1898.             /* Monsters in combat won't pick stuff up, avoiding the
1899.              * situation where you toss arrows at it and it has nothing
1900.              * better to do than pick the arrows up.
1901.              */
1902.             getitems = TRUE;
1903.         }
1904.     }
1905. 
1906.     if (getitems && m_search_items(mtmp, &ggx, &ggy, &mmoved, &appr))
1907.         return postmov(mtmp, ptr, omx, omy, mmoved,
1908.                        seenflgs, can_tunnel, can_unlock, can_open);
1909. 
1910.     /* don't tunnel if hostile and close enough to prefer a weapon */
1911.     if (can_tunnel && needspick(ptr)
1912.         && ((!mtmp->mpeaceful || Conflict)
1913.             && dist2(mtmp->mx, mtmp->my, mtmp->mux, mtmp->muy) <= 8))
1914.         can_tunnel = FALSE;
1915. 
1916.     nix = omx;
1917.     niy = omy;
1918.     flag = mon_allowflags(mtmp);
1919.     {
1920.         int i, j, nx, ny, nearer;
1921.         int jcnt, cnt;
1922.         int ndist, nidist;
1923.         coord *mtrk;
1924. 
1925.         cnt = mfndpos(mtmp, &mfp, flag);
1926.         if (cnt == 0 && !is_unicorn(mtmp->data)) {
1927.             if (find_defensive(mtmp, TRUE) && use_defensive(mtmp))
1928.                 return MMOVE_DONE;
1929.             return MMOVE_NOMOVES;
1930.         }
1931.         chcnt = 0;
1932.         jcnt = min(MTSZ, cnt - 1);
1933.         chi = -1;
1934.         nidist = dist2(nix, niy, ggx, ggy);
1935.         /* allow monsters be shortsighted on some levels for balance */
1936.         if (!mtmp->mpeaceful && svl.level.flags.shortsighted
1937.             && nidist > (couldsee(nix, niy) ? 144 : 36) && appr == 1)
1938.             appr = 0;
1939.         if (is_unicorn(ptr) && noteleport_level(mtmp)) {
1940.             /* on noteleport levels, perhaps we cannot avoid hero */
1941.             for (i = 0; i < cnt; i++)
1942.                 if (!(mfp.info[i] & NOTONL))
1943.                     avoid = TRUE;
1944.         }
1945.         better_with_displacing =
1946.             should_displace(mtmp, &mfp, ggx, ggy);
1947.         for (i = 0; i < cnt; i++) {
1948.             if (avoid && (mfp.info[i] & NOTONL))
1949.                 continue;
1950.             nx = mfp.poss[i].x;
1951.             ny = mfp.poss[i].y;
1952. 
1953.             if (m_avoid_kicked_loc(mtmp, nx, ny))
1954.                 continue;
1955. 
1956.             if (MON_AT(nx, ny) && (mfp.info[i] & ALLOW_MDISP)
1957.                 && !(mfp.info[i] & ALLOW_M) && !better_with_displacing)
1958.                 continue;
1959.             if (appr != 0) {
1960.                 mtrk = &mtmp->mtrack[0];
1961.                 for (j = 0; j < jcnt; mtrk++, j++)
1962.                     if (nx == mtrk->x && ny == mtrk->y)
1963.                         if (rn2(4 * (cnt - j)))
1964.                             goto nxti;
1965.             }
1966. 
1967.             nearer = ((ndist = dist2(nx, ny, ggx, ggy)) < nidist);
1968. 
1969.             if ((appr == 1 && nearer) || (appr == -1 && !nearer)
1970.                 || (!appr && !rn2(++chcnt))
1971.                 || (appr == -2
1972.                     && ((ndist <= preferredrange_min && !nearer)
1973.                         || (ndist >= preferredrange_max && nearer)))
1974.                 || (mmoved == MMOVE_NOTHING)) {
1975.                 nix = nx;
1976.                 niy = ny;
1977.                 nidist = ndist;
1978.                 chi = i;
1979.                 mmoved = MMOVE_MOVED;
1980.             }
1981.  nxti:
1982.             ;
1983.         }
1984.     }
1985. 
1986.     if (mmoved != MMOVE_NOTHING) {
1987.         if (mmoved == MMOVE_MOVED && !u_at(nix, niy) && itsstuck(mtmp))
1988.             return MMOVE_DONE;
1989. 
1990.         if (mmoved == MMOVE_MOVED && m_digweapon_check(mtmp, nix, niy))
1991.             return MMOVE_DONE;
1992. 
1993.         /* If ALLOW_U is set, either it's trying to attack you, or it
1994.          * thinks it is.  In either case, attack this spot in preference to
1995.          * all others.
1996.          */
1997.         /* Actually, this whole section of code doesn't work as you'd expect.
1998.          * Most attacks are handled in dochug().  It calls distfleeck(), which
1999.          * among other things sets nearby if the monster is near you--and if
2000.          * nearby is set, we never call m_move unless it is a special case
2001.          * (confused, stun, etc.)  The effect is that this ALLOW_U (and
2002.          * mfndpos) has no effect for normal attacks, though it lets a
2003.          * confused monster attack you by accident.
2004.          */
2005.         assert(IndexOk(chi, mfp.info));
2006.         if (mfp.info[chi] & ALLOW_U) {
2007.             nix = mtmp->mux;
2008.             niy = mtmp->muy;
2009.         }
2010.         if (u_at(nix, niy)) {
2011.             mtmp->mux = u.ux;
2012.             mtmp->muy = u.uy;
2013.             return MMOVE_NOTHING;
2014.         }
2015.         /* The monster may attack another based on 1 of 2 conditions:
2016.          * 1 - It may be confused.
2017.          * 2 - It may mistake the monster for your (displaced) image.
2018.          * Pets get taken care of above and shouldn't reach this code.
2019.          * Conflict gets handled even farther away (movemon()).
2020.          */
2021.         if ((mfp.info[chi] & ALLOW_M) != 0
2022.             || (nix == mtmp->mux && niy == mtmp->muy))
2023.             return m_move_aggress(mtmp, nix, niy);
2024. 
2025.         if ((mfp.info[chi] & ALLOW_MDISP) != 0) {
2026.             struct monst *mtmp2;
2027.             int mstatus;
2028. 
2029.             mtmp2 = m_at(nix, niy); /* ALLOW_MDISP implies m_at() is !Null */
2030.             mstatus = mdisplacem(mtmp, mtmp2, FALSE);
2031.             /*[if either dies, this reports mtmp has died; is that correct?]*/
2032.             if (mstatus & (M_ATTK_AGR_DIED | M_ATTK_DEF_DIED))
2033.                 return MMOVE_DIED;
2034.             if (mstatus & M_ATTK_HIT)
2035.                 return MMOVE_MOVED;
2036.             return MMOVE_DONE;
2037.         }
2038. 
2039.         if (!m_in_out_region(mtmp, nix, niy))
2040.             return MMOVE_DONE;
2041. 
2042.         if ((mfp.info[chi] & ALLOW_ROCK) && m_can_break_boulder(mtmp)) {
2043.             (void) m_break_boulder(mtmp, nix, niy);
2044.             return MMOVE_DONE;
2045.         }
2046. 
2047.         m_postmove_effect(mtmp);
2048. 
2049.         /* move a normal monster; for a long worm, remove_monster() and
2050.            place_monster() only manipulate the head; they leave tail as-is */
2051.         remove_monster(omx, omy);
2052.         place_monster(mtmp, nix, niy);
2053.         msg_mon_movement(mtmp, omx, omy);
2054.         /* for a long worm, insert a new segment to reconnect the head
2055.            with the tail; worm_move() keeps the end of the tail if worm
2056.            is scheduled to grow, removes that for move-without-growing */
2057.         if (mtmp->wormno)
2058.             worm_move(mtmp);
2059. 
2060.         maybe_unhide_at(mtmp->mx, mtmp->my);
2061. 
2062.         mon_track_add(mtmp, omx, omy);
2063.     } else {
2064.         if (is_unicorn(ptr) && rn2(2) && !tele_restrict(mtmp)) {
2065.             (void) rloc(mtmp, RLOC_MSG);
2066.             return MMOVE_MOVED;
2067.         }
2068.         /* for a long worm, shrink it (by discarding end of tail) when
2069.            it has failed to move */
2070.         if (mtmp->wormno)
2071.             worm_nomove(mtmp);
2072.     }
2073.     return postmov(mtmp, ptr, omx, omy, mmoved,
2074.                    seenflgs, can_tunnel, can_unlock, can_open);
2075. }
2076. 
2077. /* The part of m_move that deals with a monster attacking another monster (and
2078.  * that monster possibly retaliating).
2079.  * Extracted into its own function so that it can be called with monsters that
2080.  * have special move patterns (shopkeepers, priests, etc) that want to attack
2081.  * other monsters but aren't just roaming freely around the level (so allowing
2082.  * m_move to run fully for them could select an invalid move).
2083.  * x and y are the coordinates mtmp wants to attack.
2084.  * Return values are the same as for m_move, but this function only return 2
2085.  * (mtmp died) or 3 (mtmp made its move).
2086.  */
2087. int
2088. m_move_aggress(struct monst *mtmp, coordxy x, coordxy y)
2089. {
2090.     struct monst *mtmp2;
2091.     int mstatus = 0; /* M_ATTK_MISS */
2092. 
2093.     mtmp2 = m_at(x, y);
2094.     if (mtmp2) {
2095.         gb.bhitpos.x = x, gb.bhitpos.y = y;
2096.         gn.notonhead = (x != mtmp2->mx || y != mtmp2->my);
2097.         mstatus = mattackm(mtmp, mtmp2);
2098.     }
2099. 
2100.     if ((mstatus & M_ATTK_AGR_DIED) || DEADMONSTER(mtmp)) /* aggressor died */
2101.         return MMOVE_DIED;
2102. 
2103.     if ((mstatus & (M_ATTK_HIT | M_ATTK_DEF_DIED)) == M_ATTK_HIT
2104.         && rn2(4) && mtmp2->movement > rn2(NORMAL_SPEED)) {
2105.         if (mtmp2->movement > NORMAL_SPEED)
2106.             mtmp2->movement -= NORMAL_SPEED;
2107.         else
2108.             mtmp2->movement = 0;
2109.         gb.bhitpos.x = mtmp->mx, gb.bhitpos.y = mtmp->my;
2110.         gn.notonhead = FALSE;
2111.         mstatus = mattackm(mtmp2, mtmp); /* return attack */
2112.         /* note: at this point, defender is the original (moving) aggressor */
2113.         if (mstatus & M_ATTK_DEF_DIED)
2114.             return MMOVE_DIED;
2115.     }
2116.     return MMOVE_DONE;
2117. }
2118. 
2119. /* returns TRUE if a mon can hide under the obj */
2120. boolean
2121. can_hide_under_obj(struct obj *obj)
2122. {
2123. /* uncomment '#define NO_HIDING_UNDER_STATUES' to prevent hiding under
2124.  * statues; that was introduced to avoid nullifying statue traps but
2125.  * isn't needed now that hiding at any non-pit trap site is disallowed */
2126. /* #define NO_HIDING_UNDER_STATUES */
2127.     struct trap *t;
2128. 
2129.     if (!obj || obj->where != OBJ_FLOOR)
2130.         return FALSE;
2131.     /* can't hide in/on/under traps (except pits) even when there is an
2132.        object here; since obj is on floor, its <ox,oy> are up to date */
2133.     if ((t = t_at(obj->ox, obj->oy)) != 0 && !is_pit(t->ttyp))
2134.         return FALSE;
2135.     /* can't hide under small amount of coins unless non-coins are also
2136.        present; we expect coins to be a single stack but don't assume that */
2137.     if (obj->oclass == COIN_CLASS) {
2138.         long coinquan = 0L;
2139. 
2140.         do {
2141.             /* 10 coins is arbitrary amount considered enough to hide under */
2142.             if ((coinquan += obj->quan) >= 10L)
2143.                 break; /* fall through to other checks */
2144.             obj = obj->nexthere;
2145.             if (!obj)
2146.                 return FALSE; /* whole pile was less than 10 coins */
2147.         } while (obj->oclass == COIN_CLASS);
2148.     }
2149. #ifdef NO_HIDING_UNDER_STATUES
2150.     /*
2151.      * 'obj' might have been changed, but only if we've skipped coins that
2152.      * are on the top of a pile.  However, the statue loop will clobber it.
2153.      */
2154.     /* can't hide under statues regardless of pile stacking order */
2155.     while (obj) {
2156.         if (obj->otyp == STATUE)
2157.             return FALSE;
2158.         obj = obj->nexthere;
2159.     }
2160.     /*
2161.      * If we reach here, 'obj' is now Null but wasn't earlier so the original
2162.      * 'obj' can be hidden beneath.
2163.      */
2164. #undef NO_HIDING_UNDER_STATUES
2165. #endif
2166.     return TRUE; /* can hide under the object */
2167. }
2168. 
2169. void
2170. dissolve_bars(coordxy x, coordxy y)
2171. {
2172.     levl[x][y].typ = (levl[x][y].edge == 1) ? DOOR
2173.         : (Is_special(&u.uz) || *in_rooms(x, y, 0)) ? ROOM : CORR;
2174.     levl[x][y].flags = 0; /* doormask = D_NODOOR */
2175.     newsym(x, y);
2176.     if (u_at(x, y))
2177.         switch_terrain();
2178. }
2179. 
2180. boolean
2181. closed_door(coordxy x, coordxy y)
2182. {
2183.     return (boolean) (IS_DOOR(levl[x][y].typ)
2184.                       && (levl[x][y].doormask & (D_LOCKED | D_CLOSED)));
2185. }
2186. 
2187. boolean
2188. accessible(coordxy x, coordxy y)
2189. {
2190.     /* use underlying terrain in front of closed drawbridge */
2191.     int levtyp = SURFACE_AT(x, y);
2192. 
2193.     return (boolean) (ACCESSIBLE(levtyp) && !closed_door(x, y));
2194. }
2195. 
2196. /* decide where the monster thinks you are standing */
2197. void
2198. set_apparxy(struct monst *mtmp)
2199. {
2200.     boolean notseen, notthere, gotu;
2201.     int displ;
2202.     coordxy mx = mtmp->mux, my = mtmp->muy;
2203.     long umoney = money_cnt(gi.invent);
2204. 
2205.     /*
2206.      * do cheapest and/or most likely tests first
2207.      */
2208. 
2209.     /* pet knows your smell; grabber still has hold of you; monsters which
2210.        know where you are don't suddenly forget, if you haven't moved away */
2211.     if (mtmp->mtame || mtmp == u.ustuck || u_at(mx, my)) {
2212.             mtmp->mux = u.ux;
2213.             mtmp->muy = u.uy;
2214.             return;
2215.     }
2216. 
2217.     notseen = (!mtmp->mcansee || (Invis && !perceives(mtmp->data)));
2218.     notthere = (Displaced && mtmp->data != &mons[PM_DISPLACER_BEAST]);
2219.     /* add cases as required.  eg. Displacement ... */
2220.     if (Underwater) {
2221.         displ = 1;
2222.     } else if (notseen) {
2223.         /* Xorns can smell quantities of valuable metal
2224.            like that in solid gold coins, treat as seen */
2225.         displ = (mtmp->data == &mons[PM_XORN] && umoney) ? 0 : 1;
2226.     } else if (notthere) {
2227.         displ = couldsee(mx, my) ? 2 : 1;
2228.     } else {
2229.         displ = 0;
2230.     }
2231.     if (!displ) {
2232.         mtmp->mux = u.ux;
2233.         mtmp->muy = u.uy;
2234.         return;
2235.     }
2236. 
2237.     /* without something like the following, invisibility and displacement
2238.        are too powerful */
2239.     gotu = notseen ? !rn2(3) : notthere ? !rn2(4) : FALSE;
2240. 
2241.     if (!gotu) {
2242.         int try_cnt = 0;
2243. 
2244.         do {
2245.             if (++try_cnt > 200) {
2246.                 mx = u.ux;
2247.                 my = u.uy;
2248.                 break; /* punt */
2249.             }
2250.             mx = u.ux - displ + rn2(2 * displ + 1);
2251.             my = u.uy - displ + rn2(2 * displ + 1);
2252.         } while (!isok(mx, my)
2253.                  || (displ != 2 && mx == mtmp->mx && my == mtmp->my)
2254.                  || ((mx != u.ux || my != u.uy) && !passes_walls(mtmp->data)
2255.                      && !(accessible(mx, my)
2256.                           || (closed_door(mx, my)
2257.                               && (can_ooze(mtmp) || can_fog(mtmp)))))
2258.                  || !couldsee(mx, my));
2259.     } else {
2260.         mx = u.ux;
2261.         my = u.uy;
2262.     }
2263. 
2264.     mtmp->mux = mx;
2265.     mtmp->muy = my;
2266. }
2267. 
2268. /*
2269.  * mon-to-mon displacement is a deliberate "get out of my way" act,
2270.  * not an accidental bump, so we don't consider mstun or mconf in
2271.  * undesired_disp().
2272.  *
2273.  * We do consider many other things about the target and its
2274.  * location however.
2275.  */
2276. boolean
2277. undesirable_disp(
2278.     struct monst *mtmp, /* barging creature */
2279.     coordxy x,
2280.     coordxy y) /* spot 'mtmp' is considering moving to */
2281. {
2282.     boolean is_pet = (mtmp->mtame && !mtmp->isminion);
2283.     struct trap *trap = t_at(x, y);
2284. 
2285.     if (is_pet) {
2286.         /* Pets avoid a trap if you've seen it usually. */
2287.         if (trap && trap->tseen && rn2(40))
2288.             return TRUE;
2289.         /* Pets avoid cursed locations */
2290.         if (cursed_object_at(x, y))
2291.             return TRUE;
2292. 
2293.     /* Monsters avoid a trap if they've seen that type before */
2294.     } else if (trap && rn2(40)
2295.                && mon_knows_traps(mtmp, trap->ttyp)) {
2296.         return TRUE;
2297.     }
2298. 
2299.     /* oversimplification:  creatures that bargethrough can't swap places
2300.        when target monster is in rock or closed door or water (in particular,
2301.        avoid moving to spots where mondied() won't leave a corpse; doesn't
2302.        matter whether barger is capable of moving to such a target spot if
2303.        it were unoccupied) */
2304.     if (!accessible(x, y)
2305.         /* mondied() allows is_pool() as an exception to !accessible(),
2306.            but we'll only do that if 'mtmp' is already at a water location
2307.            so that we don't swap a water critter onto land */
2308.         && !(is_pool(x, y) && is_pool(mtmp->mx, mtmp->my)))
2309.         return TRUE;
2310. 
2311.     return FALSE;
2312. }
2313. 
2314. /*
2315.  * Inventory prevents passage under door.
2316.  * Used by can_ooze() and can_fog().
2317.  */
2318. staticfn boolean
2319. stuff_prevents_passage(struct monst *mtmp)
2320. {
2321.     struct obj *chain, *obj;
2322. 
2323.     if (mtmp == &gy.youmonst) {
2324.         chain = gi.invent;
2325.     } else {
2326.         chain = mtmp->minvent;
2327.     }
2328.     for (obj = chain; obj; obj = obj->nobj) {
2329.         int typ = obj->otyp;
2330. 
2331.         if (typ == COIN_CLASS && obj->quan > 100L)
2332.             return TRUE;
2333.         if (obj->oclass != GEM_CLASS && !(typ >= ARROW && typ <= BOOMERANG)
2334.             && !(typ >= DAGGER && typ <= CRYSKNIFE) && typ != SLING
2335.             && !is_cloak(obj) && typ != FEDORA && !is_gloves(obj)
2336.             && typ != LEATHER_JACKET && typ != CREDIT_CARD && !is_shirt(obj)
2337.             && !(typ == CORPSE && verysmall(&mons[obj->corpsenm]))
2338.             && typ != FORTUNE_COOKIE && typ != CANDY_BAR && typ != PANCAKE
2339.             && typ != LEMBAS_WAFER && typ != LUMP_OF_ROYAL_JELLY
2340.             && obj->oclass != AMULET_CLASS && obj->oclass != RING_CLASS
2341.             && obj->oclass != VENOM_CLASS && typ != SACK
2342.             && typ != BAG_OF_HOLDING && typ != BAG_OF_TRICKS
2343.             && !Is_candle(obj) && typ != OILSKIN_SACK && typ != LEASH
2344.             && typ != STETHOSCOPE && typ != BLINDFOLD && typ != TOWEL
2345.             && typ != TIN_WHISTLE && typ != MAGIC_WHISTLE
2346.             && typ != MAGIC_MARKER && typ != TIN_OPENER && typ != SKELETON_KEY
2347.             && typ != LOCK_PICK)
2348.             return TRUE;
2349.         if (Is_container(obj) && obj->cobj)
2350.             return TRUE;
2351.     }
2352.     return FALSE;
2353. }
2354. 
2355. boolean
2356. can_ooze(struct monst *mtmp)
2357. {
2358.     if (!amorphous(mtmp->data) || stuff_prevents_passage(mtmp))
2359.         return FALSE;
2360.     return TRUE;
2361. }
2362. 
2363. /* monster can change form into a fog if necessary */
2364. boolean
2365. can_fog(struct monst *mtmp)
2366. {
2367.     if (!(svm.mvitals[PM_FOG_CLOUD].mvflags & G_GENOD) && is_vampshifter(mtmp)
2368.         && !Protection_from_shape_changers && !stuff_prevents_passage(mtmp))
2369.         return TRUE;
2370.     return FALSE;
2371. }
2372. 
2373. /* this is called when a vampire turns into a fog cloud in order to move
2374.    under a closed door; if it was sensed via telepathy or seen via
2375.    infravision, its new fog cloud shape will disappear */
2376. staticfn int
2377. vamp_shift(
2378.     struct monst *mon,
2379.     struct permonst *ptr,
2380.     boolean domsg)
2381. {
2382.     int reslt = 0;
2383. 
2384.     if (mon->data == ptr) {
2385.         /* already right shape */
2386.         reslt = 1;
2387.     } else if (is_vampshifter(mon)) {
2388.         reslt = newcham(mon, ptr, domsg ? NC_SHOW_MSG : NO_NC_FLAGS);
2389.         /* shape-change message is given when vampshifter turns into a
2390.            fog cloud in order to move under a closed door */
2391.         display_nhwindow(WIN_MESSAGE, FALSE);
2392.     }
2393.     return reslt;
2394. }
2395. 
2396. /*monmove.c*/