Source:NetHack 5.0.0/src/mon.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to mon.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/mon.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	mon.c	$NHDT-Date: 1770949988 2026/02/12 18:33:08 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.621 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Derek S. Ray, 2015. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. #include "mfndpos.h"
8. 
9. staticfn void pet_sanity_check(struct monst *, const char *);
10. staticfn void sanity_check_single_mon(struct monst *, boolean, const char *);
11. staticfn struct obj *make_corpse(struct monst *, unsigned);
12. staticfn int minliquid_core(struct monst *);
13. staticfn void m_calcdistress(struct monst *);
14. staticfn boolean monlineu(struct monst *, int, int);
15. staticfn long mm_2way_aggression(struct monst *, struct monst *);
16. staticfn long mm_aggression(struct monst *, struct monst *);
17. staticfn long mm_displacement(struct monst *, struct monst *);
18. staticfn void mon_leaving_level(struct monst *);
19. staticfn void m_detach(struct monst *, struct permonst *, boolean);
20. staticfn void set_mon_min_mhpmax(struct monst *, int);
21. staticfn void lifesaved_monster(struct monst *);
22. staticfn boolean vamprises(struct monst *);
23. staticfn void logdeadmon(struct monst *, int);
24. staticfn void anger_quest_guardians(struct monst *);
25. staticfn boolean ok_to_obliterate(struct monst *);
26. staticfn void m_respond_shrieker(struct monst *);
27. staticfn void m_respond_medusa(struct monst *);
28. staticfn void qst_guardians_respond(void);
29. staticfn void peacefuls_respond(struct monst *);
30. staticfn void wake_nearto_core(coordxy, coordxy, int, boolean);
31. staticfn void m_restartcham(struct monst *);
32. staticfn boolean restrap(struct monst *);
33. staticfn int pick_animal(void);
34. staticfn int pickvampshape(struct monst *);
35. staticfn boolean isspecmon(struct monst *);
36. staticfn boolean validspecmon(struct monst *, int);
37. staticfn int wiz_force_cham_form(struct monst *);
38. staticfn struct permonst *accept_newcham_form(struct monst *, int);
39. staticfn void kill_eggs(struct obj *) NO_NNARGS;
40. staticfn void pacify_guard(struct monst *);
41. 
42. extern const struct shclass shtypes[]; /* defined in shknam.c */
43. 
44. #define LEVEL_SPECIFIC_NOCORPSE(mdat) \
45.     (Is_rogue_level(&u.uz)            \
46.      || !svl.level.flags.deathdrops    \
47.      || (svl.level.flags.graveyard && is_undead(mdat) && rn2(3)))
48. 
49. #if 0   /* potentially of historical interest */
50. /* part of the original warning code which was replaced in 3.3.1 */
51. const char *warnings[] = {
52.     "white", "pink", "red", "ruby", "purple", "black"
53. };
54. #endif /* 0 */
55. 
56. staticfn void
57. pet_sanity_check(
58.     struct monst *mtmp,
59.     const char *msgarg)
60. {
61.     if (has_edog(mtmp)) {
62.         struct edog *edog = EDOG(mtmp);
63. 
64.         if (edog->droptime > svm.moves)
65.             impossible("insane pet #%u has droptime (%ld)"
66.                        " in the future (%ld) (%s)",
67.                        mtmp->m_id, edog->droptime, svm.moves, msgarg);
68.         /* TODO: verify some of the other edog fields */
69.     }
70. }
71. 
72. staticfn void
73. sanity_check_single_mon(
74.     struct monst *mtmp,
75.     boolean chk_geno,
76.     const char *msg)
77. {
78.     struct permonst *mptr = mtmp->data;
79.     coordxy mx = mtmp->mx, my = mtmp->my;
80. 
81.     if (!mptr || mptr < &mons[LOW_PM] || mptr > &mons[HIGH_PM]) {
82.         /* most sanity checks issue warnings if they detect a problem,
83.            but this would be too extreme to keep going */
84.         panic("illegal mon data %s; mnum=%d (%s)",
85.               fmt_ptr((genericptr_t) mptr), mtmp->mnum, msg);
86.         /*NOTREACHED*/
87.     } else {
88.         int mndx = monsndx(mptr);
89. 
90.         if (mtmp->mnum != mndx) {
91.             impossible("monster mnum=%d, monsndx=%d (%s)",
92.                        mtmp->mnum, mndx, msg);
93.             mtmp->mnum = mndx;
94.         }
95.         /* check before DEADMONSTER() because dead monsters should still
96.            have sane mhpmax */
97.         if (mtmp->mhpmax < 1
98.             /* Gremlins don't obey the (mhpmax >= m_lev) rule so disable
99.              * this check, at least for the time being.  We could skip it
100.              * when the cloned flag is set, but the original gremlin would
101.              * still be an issue.
102.             || mtmp->mhpmax < (int) mtmp->m_lev
103.              */
104.             || mtmp->mhp > mtmp->mhpmax)
105.             impossible("%s: level %d %s #%u [%s] has %d cur HP, %d max HP",
106.                        msg, (int) mtmp->m_lev, mptr->pmnames[NEUTRAL],
107.                        mtmp->m_id, fmt_ptr((genericptr_t) mtmp),
108.                        mtmp->mhp, mtmp->mhpmax);
109.         if (DEADMONSTER(mtmp)) {
110. #if 0
111.             /* bad if not fmon list or if not vault guard */
112.             if (strcmp(msg, "fmon") || !mtmp->isgd)
113.                 impossible("dead monster on %s; %s at <%d,%d>",
114.                            msg, mptr->pmnames[NEUTRAL], mx, my);
115. #endif
116.             return;
117.         }
118.         if (chk_geno && (svm.mvitals[mndx].mvflags & G_GENOD) != 0)
119.             impossible("genocided %s in play (%s)",
120.                        pmname(mptr, Mgender(mtmp)), msg);
121.         if (mtmp->mtame && !mtmp->mpeaceful)
122.             impossible("tame %s is not peaceful (%s)",
123.                        pmname(mptr, Mgender(mtmp)), msg);
124.     }
125.     if (mtmp->isshk && !has_eshk(mtmp))
126.         impossible("shk without eshk (%s)", msg);
127.     if (mtmp->ispriest && !has_epri(mtmp))
128.         impossible("priest without epri (%s)", msg);
129.     if (mtmp->isgd && !has_egd(mtmp))
130.         impossible("guard without egd (%s)", msg);
131.     if (mtmp->isminion && !has_emin(mtmp))
132.         impossible("minion without emin (%s)", msg);
133.     /* guardian angel on astral level is tame but has emin rather than edog */
134.     if (mtmp->mtame) {
135.         if (!has_edog(mtmp) && !mtmp->isminion)
136.             impossible("pet without edog (%s)", msg);
137.         else
138.             pet_sanity_check(mtmp, msg);
139.     }
140.     /* steed should be tame and saddled */
141.     if (mtmp == u.usteed) {
142.         const char *ns, *nt = !mtmp->mtame ? "not tame" : 0;
143. 
144.         ns = !m_carrying(mtmp, SADDLE) ? "no saddle"
145.              : !which_armor(mtmp, W_SADDLE) ? "saddle not worn"
146.                : 0;
147.         if (ns || nt)
148.             impossible("steed: %s%s%s (%s)",
149.                        ns ? ns : "", (ns && nt) ? ", " : "", nt ? nt : "",
150.                        msg);
151.     }
152. 
153.     if (mtmp->mtrapped) {
154.         if (mtmp->wormno) {
155.             ; /* TODO: how to check worm in trap? */
156.         } else if (!t_at(mx, my))
157.             impossible("trapped without a trap (%s)", msg);
158.     }
159.     /* monst->mfrozen is difficult to deal with--it's used for paralysis,
160.        for temporary sleep, and for being busy (usually donning armor);
161.        code that sets mfrozen needs to also clear mcanmove, otherwise the
162.        helpless() test will be unreliable */
163.     if (mtmp->mfrozen && mtmp->mcanmove)
164.         impossible("frozen monster [%s%s] is able to move (%s)",
165.                    mtmp->mtame ? "tame " : mtmp->mpeaceful ? "peaceful " : "",
166.                    pmname(mptr, Mgender(mtmp)), msg);
167. 
168.     /* monster is hiding? */
169.     if (mtmp->mundetected) {
170.         struct trap *t;
171. 
172.         if (!isok(mx, my)) /* caller will have checked this but not fixed it */
173.             mx = my = 0;
174.         if (mtmp == u.ustuck)
175.             impossible("hiding monster stuck to you (%s)", msg);
176.         if (m_at(mx, my) == mtmp && hides_under(mptr) && !OBJ_AT(mx, my))
177.             impossible("mon hiding under nonexistent obj (%s)", msg);
178.         if (mptr->mlet == S_EEL
179.             && !(is_pool(mx, my) && !Is_waterlevel(&u.uz)))
180.             impossible("eel hiding %s (%s)",
181.                        !Is_waterlevel(&u.uz) ? "out of water"
182.                                              : "on Plane of Water", msg);
183.         if (ceiling_hider(mptr)
184.             /* normally !accessible would be overridable with passes_walls,
185.                but not for hiding on the ceiling */
186.             && (!has_ceiling(&u.uz)
187.                 || !(levl[mx][my].typ == POOL
188.                      || levl[mx][my].typ == MOAT
189.                      || levl[mx][my].typ == WATER
190.                      || levl[mx][my].typ == LAVAPOOL
191.                      || levl[mx][my].typ == LAVAWALL
192.                      || accessible(mx, my))))
193.             impossible("ceiling hider hiding %s (%s)",
194.                        !has_ceiling(&u.uz) ? "without ceiling"
195.                                            : "in solid stone",
196.                        msg);
197.         if (mtmp->mtrapped && (t = t_at(mx, my)) != 0 && !is_pit(t->ttyp))
198.             impossible("hiding while trapped in a non-pit (%s)", msg);
199.     } else if (M_AP_TYPE(mtmp) != M_AP_NOTHING) {
200.         boolean is_mimic = (mptr->mlet == S_MIMIC);
201.         const char *what = (M_AP_TYPE(mtmp) == M_AP_FURNITURE) ? "furniture"
202.                            : (M_AP_TYPE(mtmp) == M_AP_MONSTER) ? "a monster"
203.                              : (M_AP_TYPE(mtmp) == M_AP_OBJECT) ? "an object"
204.                                : "something strange";
205. 
206.         if (!strcmp(msg, "migr")) {
207.             if (M_AP_TYPE(mtmp) != M_AP_MONSTER)
208.                 impossible("migrating %s mimicking %s %s",
209.                            is_mimic ? "mimic" : "monster", what, msg);
210.         } else if (Protection_from_shape_changers) {
211.             impossible(
212.                 "mimic%s concealed as %s despite Prot-from-shape-changers %s",
213.                        is_mimic ? "" : "ker", what, msg);
214.         }
215.         /* the Wizard's clone after "double trouble" starts out mimicking
216.            some other monster; pet's quickmimic effect can temporarily take
217.            on furniture, object, or monster shape, but only until the pet
218.            finishes eating a mimic corpse */
219.         if (!(is_mimic || mtmp->meating
220.               || (mtmp->iswiz && M_AP_TYPE(mtmp) == M_AP_MONSTER)))
221.             impossible("non-mimic (%s) posing as %s (%s)",
222.                        mptr->pmnames[NEUTRAL], what, msg);
223. #if 0   /* mimics who end up in strange locations do still hide while there */
224.         if (!(accessible(mx, my) || passes_walls(mptr))) {
225.             char buf[BUFSZ];
226.             const char *typnam = levltyp_to_name(levl[mx][my].typ);
227. 
228.             if (!typnam) {
229.                 Sprintf(buf, "[%d]", levl[mx][my].typ);
230.                 typnam = buf;
231.             }
232.             impossible("mimic%s concealed in inaccessible location: %s (%s)",
233.                        is_mimic ? "" : "ker", typnam, msg);
234.         }
235. #endif
236.     }
237.     if (mtmp->mleashed) {
238.         if (!get_mleash(mtmp))
239.             impossible("monst %u: leashed but no leash for %s",
240.                        mtmp->m_id, mon_pmname(mtmp));
241.         else if (!mtmp->mtame)
242.             impossible("monst %u: leashed but not tame %s",
243.                        mtmp->m_id, mon_pmname(mtmp));
244. #if 0
245.         /* after hero moves, leashed mon won't necessarily pass 'm_next2u()'
246.            test; 90 is farthest observed distance with expert jumping spell
247.            when very slow mon is already several steps away and hero jumps in
248.            opposite direction (if hero teleports, leashed mon moves adjacent
249.            immediately; knockback has shorter range than magical jumping) */
250.         else if (distu(mtmp->mx, mtmp->my) > 90) /*if (!m_next2u(mtmp))*/
251.             impossible("monst %u: leashed but not next to you (%d)",
252.                        mtmp->m_id, distu(mtmp->mx, mtmp->my));
253. #endif
254.     }
255. }
256. 
257. void
258. mon_sanity_check(void)
259. {
260.     coordxy x, y;
261.     struct monst *mtmp, *m;
262. 
263.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
264.         /* dead monsters should still have sane data */
265.         sanity_check_single_mon(mtmp, TRUE, "fmon");
266.         if (DEADMONSTER(mtmp) && !mtmp->isgd)
267.             continue;
268. 
269.         x = mtmp->mx, y = mtmp->my;
270.         if (!isok(x, y) && !(mtmp->isgd && x == 0 && y == 0)) {
271.             impossible("mon (%s) claims to be at <%d,%d>?",
272.                        fmt_ptr((genericptr_t) mtmp), x, y);
273.         } else if (mtmp == u.usteed) {
274.             /* steed is in fmon list but not on the map; its
275.                <mx,my> coordinates should match hero's location */
276.             if (x != u.ux || y != u.uy)
277.                 impossible("steed (%s) claims to be at <%d,%d>?",
278.                            fmt_ptr((genericptr_t) mtmp), x, y);
279.         } else if (svl.level.monsters[x][y] != mtmp) {
280.             impossible("mon (%s) at <%d,%d> is not there!",
281.                        fmt_ptr((genericptr_t) mtmp), x, y);
282.         } else if (mtmp->wormno) {
283.             sanity_check_worm(mtmp);
284. 
285.         /* some temp mstate bits can be expected for a mon on fmon, as part of
286.            removing it, but DEADMONSTER check above should skip those. */
287.         } else if (mon_offmap(mtmp)) {
288.             impossible("floor mon (%s) with mstate set to 0x%08lx",
289.                        fmt_ptr((genericptr_t) mtmp), mtmp->mstate);
290.         }
291.     }
292. 
293.     for (x = 1; x < COLNO; x++)
294.         for (y = 0; y < ROWNO; y++)
295.             if ((mtmp = svl.level.monsters[x][y]) != 0) {
296.                 for (m = fmon; m; m = m->nmon)
297.                     if (m == mtmp)
298.                         break;
299.                 if (!m)
300.                     impossible("map mon (%s) at <%d,%d> not in fmon list!",
301.                                fmt_ptr((genericptr_t) mtmp), x, y);
302.                 else if (mtmp == u.usteed)
303.                     impossible("steed (%s) is on the map at <%d,%d>!",
304.                                fmt_ptr((genericptr_t) mtmp), x, y);
305.                 else if ((mtmp->mx != x || mtmp->my != y)
306.                          && mtmp->data != &mons[PM_LONG_WORM])
307.                     impossible("map mon (%s) at <%d,%d> is found at <%d,%d>?",
308.                                fmt_ptr((genericptr_t) mtmp),
309.                                mtmp->mx, mtmp->my, x, y);
310.             }
311. 
312.     for (mtmp = gm.migrating_mons; mtmp; mtmp = mtmp->nmon) {
313.         sanity_check_single_mon(mtmp, FALSE, "migr");
314. 
315.         if ((mtmp->mstate
316.              & ~(MON_MIGRATING | MON_LIMBO | MON_ENDGAME_MIGR | MON_OFFMAP))
317.             != 0L
318.             || !(mtmp->mstate & MON_MIGRATING))
319.             impossible("migrating mon (%s) with mstate set to 0x%08lx",
320.                        fmt_ptr((genericptr_t) mtmp), mtmp->mstate);
321.     }
322. 
323.     wormno_sanity_check(); /* test for bogus worm tail */
324. }
325. 
326. /* Would monster be OK with poison gas? */
327. /* Does not check for actual poison gas at the location. */
328. /* Returns one of M_POISONGAS_foo */
329. int
330. m_poisongas_ok(struct monst *mtmp)
331. {
332.     int px, py;
333.     boolean is_you = (mtmp == &gy.youmonst);
334. 
335.     /* Non living, non breathing, immune monsters are not concerned */
336.     if (nonliving(mtmp->data) || is_vampshifter(mtmp)
337.         || breathless(mtmp->data) || immune_poisongas(mtmp->data))
338.         return M_POISONGAS_OK;
339.     /* not is_swimmer(); assume that non-fish are swimming on
340.        the surface and breathing the air above it periodically
341.        unless located at water spot on plane of water */
342.     px = is_you ? u.ux : mtmp->mx;
343.     py = is_you ? u.uy : mtmp->my;
344.     if ((mtmp->data->mlet == S_EEL || Is_waterlevel(&u.uz))
345.         && is_pool(px, py))
346.         return M_POISONGAS_OK;
347.     /* exclude monsters with poison gas breath attack:
348.        adult green dragon and Chromatic Dragon (and iron golem,
349.        but nonliving() and breathless() tests also catch that) */
350.     if (attacktype_fordmg(mtmp->data, AT_BREA, AD_DRST)
351.         || attacktype_fordmg(mtmp->data, AT_BREA, AD_RBRE))
352.         return M_POISONGAS_OK;
353.     if (is_you && (u.uinvulnerable || Breathless || Underwater))
354.         return M_POISONGAS_OK;
355.     if (is_you ? Poison_resistance : resists_poison(mtmp))
356.         return M_POISONGAS_MINOR;
357.     return M_POISONGAS_BAD;
358. }
359. 
360. /* return True if mon is capable of converting other monsters into zombies */
361. boolean
362. zombie_maker(struct monst *mon)
363. {
364.     struct permonst *pm = mon->data;
365. 
366.     if (mon->mcan)
367.         return FALSE;
368. 
369.     switch (pm->mlet) {
370.     case S_ZOMBIE:
371.         /* Z-class monsters that aren't actually zombies go here */
372.         if (pm == &mons[PM_GHOUL] || pm == &mons[PM_SKELETON])
373.             return FALSE;
374.         return TRUE;
375.     case S_LICH:
376.         /* all liches will create zombies as well */
377.         return TRUE;
378.     }
379.     return FALSE;
380. }
381. 
382. /* Return monster index of zombie monster which this monster could
383.    be turned into, or NON_PM if it doesn't have a direct counterpart.
384.    Sort of the zombie-specific inverse of undead_to_corpse. */
385. int
386. zombie_form(struct permonst *pm)
387. {
388.     switch (pm->mlet) {
389.     case S_ZOMBIE: /* when already a zombie/ghoul/skeleton, will stay as is */
390.         return NON_PM;
391.     case S_KOBOLD:
392.         return PM_KOBOLD_ZOMBIE;
393.     case S_ORC:
394.         return PM_ORC_ZOMBIE;
395.     case S_GIANT:
396.         if (pm == &mons[PM_ETTIN])
397.             return PM_ETTIN_ZOMBIE;
398.         return PM_GIANT_ZOMBIE;
399.     case S_HUMAN:
400.     case S_KOP:
401.         if (is_elf(pm))
402.             return PM_ELF_ZOMBIE;
403.         return PM_HUMAN_ZOMBIE;
404.     case S_HUMANOID:
405.         if (is_dwarf(pm))
406.             return PM_DWARF_ZOMBIE;
407.         else
408.             break;
409.     case S_GNOME:
410.         return PM_GNOME_ZOMBIE;
411.     }
412.     return NON_PM;
413. }
414. 
415. /* convert the monster index of an undead to its living counterpart */
416. int
417. undead_to_corpse(int mndx)
418. {
419.     switch (mndx) {
420.     case PM_KOBOLD_ZOMBIE:
421.     case PM_KOBOLD_MUMMY:
422.         mndx = PM_KOBOLD;
423.         break;
424.     case PM_DWARF_ZOMBIE:
425.     case PM_DWARF_MUMMY:
426.         mndx = PM_DWARF;
427.         break;
428.     case PM_GNOME_ZOMBIE:
429.     case PM_GNOME_MUMMY:
430.         mndx = PM_GNOME;
431.         break;
432.     case PM_ORC_ZOMBIE:
433.     case PM_ORC_MUMMY:
434.         mndx = PM_ORC;
435.         break;
436.     case PM_ELF_ZOMBIE:
437.     case PM_ELF_MUMMY:
438.         mndx = PM_ELF;
439.         break;
440.     case PM_VAMPIRE:
441.     case PM_VAMPIRE_LEADER:
442. #if 0 /* DEFERRED */
443.     case PM_VAMPIRE_MAGE:
444. #endif
445.     case PM_HUMAN_ZOMBIE:
446.     case PM_HUMAN_MUMMY:
447.         mndx = PM_HUMAN;
448.         break;
449.     case PM_GIANT_ZOMBIE:
450.     case PM_GIANT_MUMMY:
451.         mndx = PM_GIANT;
452.         break;
453.     case PM_ETTIN_ZOMBIE:
454.     case PM_ETTIN_MUMMY:
455.         mndx = PM_ETTIN;
456.         break;
457.     default:
458.         break;
459.     }
460.     return mndx;
461. }
462. 
463. /* Convert the monster index of some monsters (such as quest guardians)
464.  * to their generic species type.
465.  *
466.  * Return associated character class monster, rather than species
467.  * if mode is 1.
468.  */
469. int
470. genus(int mndx, int mode)
471. {
472.     switch (mndx) {
473.     /* Quest guardians */
474.     case PM_STUDENT:
475.         mndx = mode ? PM_ARCHEOLOGIST : PM_HUMAN;
476.         break;
477.     case PM_CHIEFTAIN:
478.         mndx = mode ? PM_BARBARIAN : PM_HUMAN;
479.         break;
480.     case PM_NEANDERTHAL:
481.         mndx = mode ? PM_CAVE_DWELLER : PM_HUMAN;
482.         break;
483.     case PM_ATTENDANT:
484.         mndx = mode ? PM_HEALER : PM_HUMAN;
485.         break;
486.     case PM_PAGE:
487.         mndx = mode ? PM_KNIGHT : PM_HUMAN;
488.         break;
489.     case PM_ABBOT:
490.         mndx = mode ? PM_MONK : PM_HUMAN;
491.         break;
492.     case PM_ACOLYTE:
493.         mndx = mode ? PM_CLERIC : PM_HUMAN;
494.         break;
495.     case PM_HUNTER:
496.         mndx = mode ? PM_RANGER : PM_HUMAN;
497.         break;
498.     case PM_THUG:
499.         mndx = mode ? PM_ROGUE : PM_HUMAN;
500.         break;
501.     case PM_ROSHI:
502.         mndx = mode ? PM_SAMURAI : PM_HUMAN;
503.         break;
504.     case PM_GUIDE:
505.         mndx = mode ? PM_TOURIST : PM_HUMAN;
506.         break;
507.     case PM_APPRENTICE:
508.         mndx = mode ? PM_WIZARD : PM_HUMAN;
509.         break;
510.     case PM_WARRIOR:
511.         mndx = mode ? PM_VALKYRIE : PM_HUMAN;
512.         break;
513.     default:
514.         if (ismnum(mndx)) {
515.             struct permonst *ptr = &mons[mndx];
516. 
517.             if (is_human(ptr))
518.                 mndx = PM_HUMAN;
519.             else if (is_elf(ptr))
520.                 mndx = PM_ELF;
521.             else if (is_dwarf(ptr))
522.                 mndx = PM_DWARF;
523.             else if (is_gnome(ptr))
524.                 mndx = PM_GNOME;
525.             else if (is_orc(ptr))
526.                 mndx = PM_ORC;
527.         }
528.         break;
529.     }
530.     return mndx;
531. }
532. 
533. /* return monster index if chameleon, or NON_PM if not */
534. int
535. pm_to_cham(int mndx)
536. {
537.     int mcham = NON_PM;
538. 
539.     /*
540.      * As of 3.6.0 we just check M2_SHAPESHIFTER instead of having a
541.      * big switch statement with hardcoded shapeshifter types here.
542.      */
543.     if (ismnum(mndx) && is_shapeshifter(&mons[mndx]))
544.         mcham = mndx;
545.     return mcham;
546. }
547. 
548. /* for deciding whether corpse will carry along full monster data */
549. #define KEEPTRAITS(mon)                                                  \
550.     ((mon)->isshk || (mon)->mtame || unique_corpstat((mon)->data)        \
551.      || is_reviver((mon)->data)                                          \
552.         /* normally quest leader will be unique, */                      \
553.         /* but he or she might have been polymorphed  */                 \
554.      || (mon)->m_id == svq.quest_status.leader_m_id                       \
555.         /* special cancellation handling for these */                    \
556.      || (dmgtype((mon)->data, AD_SEDU) || dmgtype((mon)->data, AD_SSEX)))
557. 
558. /* Creates a monster corpse, a "special" corpse, or nothing if it doesn't
559.  * leave corpses.  Monsters which leave "special" corpses should have
560.  * G_NOCORPSE set in order to prevent wishing for one, finding tins of one,
561.  * etc....
562.  */
563. staticfn struct obj *
564. make_corpse(struct monst *mtmp, unsigned int corpseflags)
565. {
566.     struct permonst *mdat = mtmp->data;
567.     int num;
568.     struct obj *obj = (struct obj *) 0;
569.     struct obj *otmp = (struct obj *) 0;
570.     coordxy x = mtmp->mx, y = mtmp->my;
571. /*    int mndx = monsndx(mdat); */
572.     enum monnums mndx = monsndx(mdat);
573.     unsigned corpstatflags = corpseflags;
574.     boolean burythem = ((corpstatflags & CORPSTAT_BURIED) != 0);
575. 
576.     if (mtmp->female)
577.         corpstatflags |= CORPSTAT_FEMALE;
578.     else if (!is_neuter(mtmp->data))
579.         corpstatflags |= CORPSTAT_MALE;
580. 
581.     switch (mndx) {
582.     case PM_GRAY_DRAGON:
583.     case PM_GOLD_DRAGON:
584.     case PM_SILVER_DRAGON:
585. #if 0 /* DEFERRED */
586.     case PM_SHIMMERING_DRAGON:
587. #endif
588.     case PM_RED_DRAGON:
589.     case PM_ORANGE_DRAGON:
590.     case PM_WHITE_DRAGON:
591.     case PM_BLACK_DRAGON:
592.     case PM_BLUE_DRAGON:
593.     case PM_GREEN_DRAGON:
594.     case PM_YELLOW_DRAGON:
595.         /* Make dragon scales.  This assumes that the order of the
596.            dragons is the same as the order of the scales. */
597.         if (!rn2(mtmp->mrevived ? 20 : 3)) {
598.             num = GRAY_DRAGON_SCALES + monsndx(mdat) - PM_GRAY_DRAGON;
599.             obj = mksobj_at(num, x, y, FALSE, FALSE);
600.             obj->spe = 0;
601.             obj->cursed = obj->blessed = FALSE;
602.         }
603.         goto default_1;
604.     case PM_WHITE_UNICORN:
605.     case PM_GRAY_UNICORN:
606.     case PM_BLACK_UNICORN:
607.         if (mtmp->mrevived && rn2(2)) {
608.             if (canseemon(mtmp))
609.                 pline_mon(mtmp,
610.                       "%s recently regrown horn crumbles to dust.",
611.                       s_suffix(Monnam(mtmp)));
612.         } else {
613.             obj = mksobj_at(UNICORN_HORN, x, y, TRUE, FALSE);
614.             if (obj && mtmp->mrevived)
615.                 obj->degraded_horn = 1;
616.         }
617.         goto default_1;
618.     case PM_LONG_WORM:
619.         (void) mksobj_at(WORM_TOOTH, x, y, TRUE, FALSE);
620.         goto default_1;
621.     case PM_VAMPIRE:
622.     case PM_VAMPIRE_LEADER:
623.         /* include mtmp in the mkcorpstat() call */
624.         num = undead_to_corpse(mndx);
625.         corpstatflags |= CORPSTAT_INIT;
626.         obj = mkcorpstat(CORPSE, mtmp, &mons[num], x, y, corpstatflags);
627.         obj->age -= (TAINT_AGE + 1); /* this is an *OLD* corpse */
628.         break;
629.     case PM_KOBOLD_MUMMY:
630.     case PM_DWARF_MUMMY:
631.     case PM_GNOME_MUMMY:
632.     case PM_ORC_MUMMY:
633.     case PM_ELF_MUMMY:
634.     case PM_HUMAN_MUMMY:
635.     case PM_GIANT_MUMMY:
636.     case PM_ETTIN_MUMMY:
637.     case PM_KOBOLD_ZOMBIE:
638.     case PM_DWARF_ZOMBIE:
639.     case PM_GNOME_ZOMBIE:
640.     case PM_ORC_ZOMBIE:
641.     case PM_ELF_ZOMBIE:
642.     case PM_HUMAN_ZOMBIE:
643.     case PM_GIANT_ZOMBIE:
644.     case PM_ETTIN_ZOMBIE:
645.         num = undead_to_corpse(mndx);
646.         corpstatflags |= CORPSTAT_INIT;
647.         obj = mkcorpstat(CORPSE, mtmp, &mons[num], x, y, corpstatflags);
648.         obj->age -= (TAINT_AGE + 1); /* this is an *OLD* corpse */
649.         break;
650.     case PM_IRON_GOLEM:
651.         num = d(2, 6);
652.         while (num--)
653.             obj = mksobj_at(IRON_CHAIN, x, y, TRUE, FALSE);
654.         free_mgivenname(mtmp); /* don't christen obj */
655.         break;
656.     case PM_GLASS_GOLEM:
657.         num = d(2, 4); /* very low chance of creating all glass gems */
658.         while (num--)
659.             obj = mksobj_at(FIRST_GLASS_GEM + rn2(NUM_GLASS_GEMS),
660.                             x, y, TRUE, FALSE);
661.         free_mgivenname(mtmp);
662.         break;
663.     case PM_CLAY_GOLEM:
664.         obj = mksobj_at(ROCK, x, y, FALSE, FALSE);
665.         obj->quan = (long) (rn2(20) + 50);
666.         obj->owt = weight(obj);
667.         free_mgivenname(mtmp);
668.         break;
669.     case PM_STONE_GOLEM:
670.         corpstatflags &= ~CORPSTAT_INIT;
671.         obj = mkcorpstat(STATUE, (struct monst *) 0, mdat, x, y,
672.                          corpstatflags);
673.         break;
674.     case PM_WOOD_GOLEM:
675.         num = d(2, 4);
676.         while (num--) {
677.             obj = mksobj_at(
678.                             rn2(2) ? QUARTERSTAFF
679.                             : rn2(3) ? SMALL_SHIELD
680.                             : rn2(3) ? CLUB
681.                             : rn2(3) ? ELVEN_SPEAR : BOOMERANG,
682.                             x, y, TRUE, FALSE);
683.         }
684.         free_mgivenname(mtmp);
685.         break;
686.     case PM_ROPE_GOLEM:
687.         num = rn2(3);
688.         while (num-- > 0) {
689.             obj = mksobj_at(rn2(2) ? LEASH
690.                             : rn2(3) ? BULLWHIP : GRAPPLING_HOOK,
691.                             x, y, TRUE, FALSE);
692.         }
693.         free_mgivenname(mtmp);
694.         break;
695.     case PM_LEATHER_GOLEM:
696.         num = d(2, 4);
697.         while (num--)
698.             obj = mksobj_at(rn2(4) ? LEATHER_ARMOR
699.                             : rn2(3) ? LEATHER_CLOAK : SADDLE,
700.                             x, y, TRUE, FALSE);
701.         free_mgivenname(mtmp);
702.         break;
703.     case PM_GOLD_GOLEM:
704.         /* Good luck gives more coins */
705.         obj = mkgold((long) (200 - rnl(101)), x, y);
706.         free_mgivenname(mtmp);
707.         break;
708.     case PM_PAPER_GOLEM:
709.         num = rnd(4);
710.         while (num--)
711.             obj = mksobj_at(SCR_BLANK_PAPER, x, y, TRUE, FALSE);
712.         free_mgivenname(mtmp);
713.         break;
714.     /* expired puddings will congeal into a large blob;
715.        like dragons, relies on the order remaining consistent */
716.     case PM_GRAY_OOZE:
717.     case PM_BROWN_PUDDING:
718.     case PM_GREEN_SLIME:
719.     case PM_BLACK_PUDDING:
720.         /* we have to do this here because most other places
721.            expect there to be an object coming back; not this one */
722.         obj = mksobj_at(GLOB_OF_BLACK_PUDDING - (PM_BLACK_PUDDING - mndx),
723.                         x, y, TRUE, FALSE);
724. 
725.         while (obj && (otmp = obj_nexto(obj)) != (struct obj *) 0) {
726.             pudding_merge_message(obj, otmp);
727.             obj = obj_meld(&obj, &otmp);
728.         }
729.         free_mgivenname(mtmp);
730.         newsym(x, y);
731.         return obj;
732.     case NON_PM: case LEAVESTATUE: case NUMMONS: /* never use as index */
733.         break;
734. 
735. #if (NH_DEVEL_STATUS != NH_STATUS_RELEASED)
736.     case PM_GIANT_ANT: case PM_KILLER_BEE: case PM_SOLDIER_ANT:
737.     case PM_FIRE_ANT: case PM_GIANT_BEETLE: case PM_QUEEN_BEE:
738. 
739.     case PM_QUIVERING_BLOB: case PM_ACID_BLOB: case PM_GELATINOUS_CUBE:
740.     case PM_CHICKATRICE: case PM_COCKATRICE: case PM_PYROLISK:
741. 
742.     case PM_JACKAL: case PM_FOX: case PM_COYOTE: case PM_WEREJACKAL:
743.     case PM_LITTLE_DOG: case PM_DINGO: case PM_DOG: case PM_LARGE_DOG:
744.     case PM_WOLF: case PM_WEREWOLF: case PM_WINTER_WOLF_CUB:
745.     case PM_WARG: case PM_WINTER_WOLF: case PM_HELL_HOUND_PUP:
746.     case PM_HELL_HOUND:
747. 
748.     case PM_GAS_SPORE: case PM_FLOATING_EYE: case PM_FREEZING_SPHERE:
749.     case PM_FLAMING_SPHERE: case PM_SHOCKING_SPHERE:
750. 
751.     case PM_KITTEN: case PM_HOUSECAT: case PM_JAGUAR: case PM_LYNX:
752.     case PM_PANTHER: case PM_LARGE_CAT:  case PM_TIGER:
753. 
754.     case PM_DISPLACER_BEAST: case PM_GREMLIN:
755.     case PM_GARGOYLE: case PM_WINGED_GARGOYLE:
756. 
757.     case PM_HOBBIT: case PM_DWARF: case PM_BUGBEAR: case PM_DWARF_LEADER:
758.     case PM_DWARF_RULER:
759.     case PM_MIND_FLAYER: case PM_MASTER_MIND_FLAYER: case PM_MANES:
760.     case PM_HOMUNCULUS: case PM_IMP: case PM_LEMURE: case PM_QUASIT:
761.     case PM_TENGU: case PM_BLUE_JELLY: case PM_SPOTTED_JELLY:
762.     case PM_OCHRE_JELLY: case PM_KOBOLD: case PM_LARGE_KOBOLD:
763.     case PM_KOBOLD_LEADER: case PM_KOBOLD_SHAMAN: case PM_LEPRECHAUN:
764.     case PM_SMALL_MIMIC: case PM_LARGE_MIMIC: case PM_GIANT_MIMIC:
765.     case PM_WOOD_NYMPH: case PM_WATER_NYMPH: case PM_MOUNTAIN_NYMPH:
766.     case PM_GOBLIN: case PM_HOBGOBLIN: case PM_ORC: case PM_HILL_ORC:
767.     case PM_MORDOR_ORC: case PM_URUK_HAI: case PM_ORC_SHAMAN:
768.     case PM_ORC_CAPTAIN:
769.     case PM_ROCK_PIERCER: case PM_IRON_PIERCER: case PM_GLASS_PIERCER:
770.     case PM_ROTHE: case PM_MUMAK: case PM_LEOCROTTA: case PM_WUMPUS:
771.     case PM_TITANOTHERE: case PM_BALUCHITHERIUM: case PM_MASTODON:
772.     case PM_SEWER_RAT: case PM_GIANT_RAT: case PM_RABID_RAT:
773.     case PM_WERERAT:
774. 
775.     case PM_ROCK_MOLE: case PM_WOODCHUCK:
776.     case PM_CAVE_SPIDER: case PM_CENTIPEDE: case PM_GIANT_SPIDER:
777.     case PM_SCORPION:
778.     case PM_LURKER_ABOVE: case PM_TRAPPER:
779.     case PM_PONY: case PM_HORSE: case PM_WARHORSE:
780.     case PM_FOG_CLOUD: case PM_DUST_VORTEX: case PM_ICE_VORTEX:
781.     case PM_ENERGY_VORTEX: case PM_STEAM_VORTEX: case PM_FIRE_VORTEX:
782. 
783.     case PM_BABY_LONG_WORM: case PM_BABY_PURPLE_WORM:
784.     case PM_PURPLE_WORM:
785. 
786.     case PM_GRID_BUG: case PM_XAN: case PM_YELLOW_LIGHT: case PM_BLACK_LIGHT:
787.     case PM_ZRUTY: case PM_COUATL: case PM_ALEAX: case PM_ANGEL:
788.     case PM_KI_RIN: case PM_ARCHON:
789. 
790.     case PM_BAT: case PM_GIANT_BAT: case PM_RAVEN: case PM_VAMPIRE_BAT:
791.     case PM_PLAINS_CENTAUR: case PM_FOREST_CENTAUR: case PM_MOUNTAIN_CENTAUR:
792. 
793.     case PM_BABY_GRAY_DRAGON: case PM_BABY_GOLD_DRAGON:
794.     case PM_BABY_SILVER_DRAGON: case PM_BABY_RED_DRAGON:
795.     case PM_BABY_WHITE_DRAGON: case PM_BABY_ORANGE_DRAGON:
796.     case PM_BABY_BLACK_DRAGON: case PM_BABY_BLUE_DRAGON:
797.     case PM_BABY_GREEN_DRAGON: case PM_BABY_YELLOW_DRAGON:
798. 
799.     case PM_STALKER: case PM_AIR_ELEMENTAL: case PM_FIRE_ELEMENTAL:
800.     case PM_EARTH_ELEMENTAL: case PM_WATER_ELEMENTAL:
801. 
802.     case PM_LICHEN: case PM_BROWN_MOLD: case PM_YELLOW_MOLD:
803.     case PM_GREEN_MOLD: case PM_RED_MOLD: case PM_SHRIEKER:
804.     case PM_VIOLET_FUNGUS:
805. 
806.     case PM_GNOME: case PM_GNOME_LEADER: case PM_GNOMISH_WIZARD:
807.     case PM_GNOME_RULER:
808.     case PM_GIANT: case PM_STONE_GIANT: case PM_HILL_GIANT:
809.     case PM_FIRE_GIANT: case PM_FROST_GIANT: case PM_ETTIN:
810.     case PM_STORM_GIANT: case PM_TITAN:
811. 
812.     case PM_MINOTAUR: case PM_JABBERWOCK: case PM_KEYSTONE_KOP:
813.     case PM_KOP_SERGEANT: case PM_KOP_LIEUTENANT: case PM_KOP_KAPTAIN:
814.     case PM_LICH: case PM_DEMILICH:
815.     case PM_MASTER_LICH: case PM_ARCH_LICH:
816. 
817.     case PM_RED_NAGA_HATCHLING: case PM_BLACK_NAGA_HATCHLING:
818.     case PM_GOLDEN_NAGA_HATCHLING: case PM_GUARDIAN_NAGA_HATCHLING:
819.     case PM_RED_NAGA: case PM_BLACK_NAGA: case PM_GOLDEN_NAGA:
820.     case PM_GUARDIAN_NAGA:
821. 
822.     case PM_OGRE: case PM_OGRE_LEADER: case PM_OGRE_TYRANT:
823. 
824.     case PM_QUANTUM_MECHANIC: case PM_GENETIC_ENGINEER:
825.     case PM_RUST_MONSTER: case PM_DISENCHANTER:
826. 
827.     case PM_GARTER_SNAKE: case PM_SNAKE: case PM_WATER_MOCCASIN:
828.     case PM_PYTHON: case PM_PIT_VIPER: case PM_COBRA:
829. 
830.     case PM_TROLL: case PM_ICE_TROLL: case PM_ROCK_TROLL: case PM_WATER_TROLL:
831.     case PM_OLOG_HAI: case PM_UMBER_HULK:
832. 
833.     case PM_VLAD_THE_IMPALER:
834. 
835.     case PM_BARROW_WIGHT: case PM_WRAITH: case PM_NAZGUL:
836.     case PM_XORN: case PM_MONKEY: case PM_APE: case PM_OWLBEAR:
837.     case PM_YETI: case PM_CARNIVOROUS_APE: case PM_SASQUATCH:
838. 
839.     case PM_GHOUL: case PM_SKELETON:
840. 
841.     case PM_STRAW_GOLEM: case PM_FLESH_GOLEM:
842. 
843.     case PM_HUMAN: case PM_HUMAN_WERERAT: case PM_HUMAN_WEREJACKAL:
844.     case PM_HUMAN_WEREWOLF: case PM_ELF: case PM_WOODLAND_ELF:
845.     case PM_GREEN_ELF: case PM_GREY_ELF: case PM_ELF_NOBLE:
846.     case PM_ELVEN_MONARCH:
847.     case PM_DOPPELGANGER: case PM_SHOPKEEPER:
848.     case PM_GUARD: case PM_PRISONER: case PM_ORACLE:
849.     case PM_ALIGNED_CLERIC: case PM_HIGH_CLERIC:
850.     case PM_SOLDIER: case PM_SERGEANT: case PM_NURSE:
851.     case PM_LIEUTENANT: case PM_CAPTAIN: case PM_WATCHMAN:
852.     case PM_WATCH_CAPTAIN:
853. 
854.     case PM_MEDUSA: case PM_WIZARD_OF_YENDOR: case PM_CROESUS:
855.     case PM_GHOST: case PM_SHADE: case PM_WATER_DEMON:
856.     case PM_AMOROUS_DEMON: case PM_HORNED_DEVIL:
857.     case PM_ERINYS: case PM_BARBED_DEVIL: case PM_MARILITH: case PM_VROCK:
858.     case PM_HEZROU: case PM_BONE_DEVIL: case PM_ICE_DEVIL: case PM_NALFESHNEE:
859.     case PM_PIT_FIEND: case PM_SANDESTIN: case PM_BALROG: case PM_JUIBLEX:
860.     case PM_YEENOGHU: case PM_ORCUS: case PM_GERYON: case PM_DISPATER:
861.     case PM_BAALZEBUB: case PM_ASMODEUS: case PM_DEMOGORGON:
862.     case PM_DEATH: case PM_PESTILENCE: case PM_FAMINE:
863.     case PM_MAIL_DAEMON: case PM_DJINNI:
864. 
865.     case PM_JELLYFISH: case PM_PIRANHA: case PM_SHARK: case PM_GIANT_EEL:
866.     case PM_ELECTRIC_EEL: case PM_KRAKEN:
867.     case PM_NEWT: case PM_GECKO: case PM_IGUANA: case PM_BABY_CROCODILE:
868.     case PM_LIZARD: case PM_CHAMELEON: case PM_CROCODILE:
869.     case PM_SALAMANDER: case PM_LONG_WORM_TAIL:
870. 
871.     case PM_ARCHEOLOGIST: case PM_BARBARIAN: case PM_CAVE_DWELLER:
872.     case PM_HEALER: case PM_KNIGHT: case PM_MONK: case PM_CLERIC:
873.     case PM_RANGER: case PM_ROGUE: case PM_SAMURAI: case PM_TOURIST:
874.     case PM_VALKYRIE: case PM_WIZARD:
875. 
876.     case PM_LORD_CARNARVON: case PM_PELIAS: case PM_SHAMAN_KARNOV:
877.     case PM_HIPPOCRATES: case PM_KING_ARTHUR: case PM_GRAND_MASTER:
878.     case PM_ARCH_PRIEST: case PM_ORION: case PM_MASTER_OF_THIEVES:
879.     case PM_LORD_SATO: case PM_TWOFLOWER: case PM_NORN:
880.     case PM_NEFERET_THE_GREEN: case PM_MINION_OF_HUHETOTL:
881.     case PM_THOTH_AMON: case PM_CHROMATIC_DRAGON: case PM_CYCLOPS:
882.     case PM_IXOTH: case PM_MASTER_KAEN: case PM_NALZOK:
883.     case PM_SCORPIUS: case PM_MASTER_ASSASSIN: case PM_ASHIKAGA_TAKAUJI:
884.     case PM_LORD_SURTUR: case PM_DARK_ONE: case PM_STUDENT:
885.     case PM_CHIEFTAIN: case PM_NEANDERTHAL: case PM_ATTENDANT:
886.     case PM_PAGE: case PM_ABBOT: case PM_ACOLYTE: case PM_HUNTER:
887.     case PM_THUG: case PM_NINJA: case PM_ROSHI: case PM_GUIDE:
888.     case PM_WARRIOR: case PM_APPRENTICE:
889. #else
890.     default:
891. #endif
892.  default_1:
893.         if (svm.mvitals[mndx].mvflags & G_NOCORPSE) {
894.             return (struct obj *) 0;
895.         } else {
896.             corpstatflags |= CORPSTAT_INIT;
897.             /* preserve the unique traits of some creatures */
898.             obj = mkcorpstat(CORPSE, KEEPTRAITS(mtmp) ? mtmp : 0,
899.                              mdat, x, y, corpstatflags);
900.             if (burythem) {
901.                 boolean dealloc;
902. 
903.                 (void) bury_an_obj(obj, &dealloc);
904.                 newsym(x, y);
905.                 return dealloc ? (struct obj *) 0 : obj;
906.             }
907.         }
908.         break;
909.     }
910.     /* All special cases should precede the G_NOCORPSE check */
911. 
912.     if (!obj)
913.         return (struct obj *) 0;
914. 
915.     /* if polymorph or undead turning has killed this monster,
916.        prevent the same attack beam from hitting its corpse */
917.     if (svc.context.bypasses)
918.         bypass_obj(obj);
919. 
920.     if (has_mgivenname(mtmp))
921.         obj = oname(obj, MGIVENNAME(mtmp), ONAME_NO_FLAGS);
922. 
923.     /*  Avoid "It was hidden under a green mold corpse!"
924.      *  during Blind combat. An unseen monster referred to as "it"
925.      *  could be killed and leave a corpse.  If a hider then hid
926.      *  underneath it, you could be told the corpse type of a
927.      *  monster that you never knew was there without this.
928.      *  The code in hitmu() substitutes the word "something"
929.      *  if the corpse's obj->dknown is 0.
930.      */
931.     if (Blind && !sensemon(mtmp))
932.         clear_dknown(obj); /* obj->dknown = 0; */
933. 
934.     stackobj(obj); /* 'obj' remains valid if stacking happens */
935.     newsym(x, y);
936.     /* in case the corpse was placed at a different spot from where
937.        the monster was (not expected to happen) */
938.     if (obj->ox != x || obj->oy != y)
939.         newsym(obj->ox, obj->oy);
940.     return obj;
941. }
942. 
943. #undef KEEPTRAITS
944. 
945. /* check mtmp and water/lava for compatibility, 0 (survived), 1 (died) */
946. int
947. minliquid(struct monst *mtmp)
948. {
949.     int res;
950. 
951.     /* set up flag for mondead() and xkilled() */
952.     iflags.sad_feeling = (mtmp->mtame && !canseemon(mtmp));
953.     res = minliquid_core(mtmp);
954.     /* always clear the flag */
955.     iflags.sad_feeling = FALSE;
956.     return res;
957. }
958. 
959. /* guts of minliquid() */
960. staticfn int
961. minliquid_core(struct monst *mtmp)
962. {
963.     boolean inpool, inlava, infountain;
964.     boolean waterwall = is_waterwall(mtmp->mx,mtmp->my);
965. 
966.     /* [ceiling clingers are handled below] */
967.     inpool = (is_pool(mtmp->mx, mtmp->my)
968.               && (!(is_flyer(mtmp->data) || is_floater(mtmp->data))
969.                   /* there's no "above the surface" on the plane of water */
970.                   || Is_waterlevel(&u.uz)));
971.     inlava = (is_lava(mtmp->mx, mtmp->my)
972.               && !(is_flyer(mtmp->data) || is_floater(mtmp->data)));
973.     infountain = IS_FOUNTAIN(levl[mtmp->mx][mtmp->my].typ);
974. 
975.     /* Flying and levitation keeps our steed out of the liquid
976.        (but not water-walking or swimming; note: if hero is in a
977.        water location on the Plane of Water, flight and levitating
978.        are blocked so this (Flying || Levitation) test fails there
979.        and steed will be subject to water effects, as intended) */
980.     if (mtmp == u.usteed && (Flying || Levitation) && !waterwall)
981.         return 0;
982. 
983.     /* Gremlin multiplying won't go on forever since the hit points
984.      * keep going down, and when it gets to 1 hit point the clone
985.      * function will fail.
986.      */
987.     if (mtmp->data == &mons[PM_GREMLIN] && (inpool || infountain) && rn2(3)) {
988.         if (split_mon(mtmp, (struct monst *) 0))
989.             dryup(mtmp->mx, mtmp->my, FALSE);
990.         if (inpool)
991.             water_damage_chain(mtmp->minvent, FALSE);
992.         return 0;
993.     } else if (mtmp->data == &mons[PM_IRON_GOLEM] && inpool && !rn2(5)) {
994.         int dam = d(2, 6);
995. 
996.         if (cansee(mtmp->mx, mtmp->my))
997.             pline_mon(mtmp, "%s rusts.", Monnam(mtmp));
998.         mtmp->mhp -= dam;
999.         if (mtmp->mhpmax > dam)
1000.             mtmp->mhpmax -= dam;
1001.         if (DEADMONSTER(mtmp)) {
1002.             mondied(mtmp);
1003.             if (DEADMONSTER(mtmp))
1004.                 return 1;
1005.         }
1006.         water_damage_chain(mtmp->minvent, FALSE);
1007.         return 0;
1008.     }
1009. 
1010.     if (inlava) {
1011.         /*
1012.          * Lava effects much as water effects. Lava likers are able to
1013.          * protect their stuff. Fire resistant monsters can only protect
1014.          * themselves  --ALI
1015.          */
1016.         if (!is_clinger(mtmp->data) && !likes_lava(mtmp->data)) {
1017.             /* not fair...?  hero doesn't automatically teleport away
1018.                from lava, just from water */
1019.             if (can_teleport(mtmp->data) && !tele_restrict(mtmp)) {
1020.                 if (rloc(mtmp, RLOC_MSG))
1021.                     return 0;
1022.             }
1023.             if (!resists_fire(mtmp)) {
1024.                 if (cansee(mtmp->mx, mtmp->my)) {
1025.                     struct attack *dummy = &mtmp->data->mattk[0];
1026.                     const char *how = on_fire(mtmp->data, dummy);
1027. 
1028.                     pline_mon(mtmp, "%s %s.", Monnam(mtmp),
1029.                           !strcmp(how, "boiling") ? "boils away"
1030.                              : !strcmp(how, "melting") ? "melts away"
1031.                                 : "burns to a crisp");
1032.                 }
1033.                 /* unlike fire -> melt ice -> pool, there's no way for the
1034.                    hero to create lava beneath a monster, so the !mon_moving
1035.                    case is not expected to happen (and we haven't made a
1036.                    player-against-monster variation of the message above) */
1037.                 if (svc.context.mon_moving)
1038.                     mondead(mtmp); /* no corpse */
1039.                 else
1040.                     xkilled(mtmp, XKILL_NOMSG);
1041.             } else {
1042.                 mtmp->mhp -= 1;
1043.                 if (DEADMONSTER(mtmp)) {
1044.                     if (cansee(mtmp->mx, mtmp->my))
1045.                         pline_mon(mtmp, "%s surrenders to the fire.",
1046.                                   Monnam(mtmp));
1047.                     mondead(mtmp); /* no corpse */
1048.                 } else if (cansee(mtmp->mx, mtmp->my)) {
1049.                     pline_mon(mtmp, "%s burns slightly.", Monnam(mtmp));
1050.                 }
1051.             }
1052.             if (!DEADMONSTER(mtmp)) {
1053.                 if (m_in_air(mtmp)) {
1054.                     ; /* vampshifter in wolf form can revert to vampire lord
1055.                        * and become a flyer so not need to teleport */
1056.                 } else if (likes_lava(mtmp->data)) {
1057.                     ; /* likes_lava case is hypothetical */
1058.                 } else {
1059.                     (void) fire_damage_chain(mtmp->minvent, FALSE, FALSE,
1060.                                              mtmp->mx, mtmp->my);
1061.                     if (!rloc(mtmp, RLOC_MSG))
1062.                         deal_with_overcrowding(mtmp);
1063.                 }
1064.                 return 0;
1065.             }
1066.             return 1;
1067.         }
1068.     } else if (inpool || waterwall) {
1069.         /* Most monsters drown in pools.  flooreffects() will take care of
1070.          * water damage to dead monsters' inventory, but survivors need to
1071.          * be handled here.  Swimmers are able to protect their stuff...
1072.          */
1073.         if ((waterwall || !is_clinger(mtmp->data))
1074.             && !cant_drown(mtmp->data)) {
1075.             /* like hero with teleport intrinsic or spell, teleport away
1076.                if possible */
1077.             if (can_teleport(mtmp->data) && !tele_restrict(mtmp)) {
1078.                 if (rloc(mtmp, RLOC_MSG))
1079.                     return 0;
1080.             }
1081.             if (cansee(mtmp->mx, mtmp->my)) {
1082.                 if (svc.context.mon_moving)
1083.                     pline_mon(mtmp, "%s drowns.", Monnam(mtmp));
1084.                 else
1085.                     /* hero used fire to melt ice that monster was on */
1086.                     You("drown %s.", mon_nam(mtmp));
1087.             }
1088.             if (engulfing_u(mtmp)) {
1089.                 /* This can happen after a purple worm plucks you off a
1090.                    flying steed while you are over water. */
1091.                 pline("%s sinks as %s rushes in and flushes you out.",
1092.                       Monnam(mtmp), hliquid("water"));
1093.             }
1094.             if (svc.context.mon_moving)
1095.                 mondied(mtmp); /* ok to leave corpse despite water */
1096.             else
1097.                 xkilled(mtmp, XKILL_NOMSG);
1098.             if (!DEADMONSTER(mtmp)) {
1099.                 if (m_in_air(mtmp)) {
1100.                     ; /* vampshifter in wolf form can revert to vampire lord
1101.                        * and become a flyer so not need to teleport */
1102.                 } else {
1103.                     water_damage_chain(mtmp->minvent, FALSE);
1104.                     if (!rloc(mtmp, RLOC_NOMSG))
1105.                         deal_with_overcrowding(mtmp);
1106.                 }
1107.                 return 0;
1108.             }
1109.             return 1;
1110.         }
1111.     } else {
1112.         /* but eels have a difficult time outside */
1113.         if (mtmp->data->mlet == S_EEL && !Is_waterlevel(&u.uz)
1114.             && !breathless(mtmp->data)) {
1115.             /* as mhp gets lower, the rate of further loss slows down */
1116.             if (mtmp->mhp > 1 && rn2(mtmp->mhp) > rn2(8))
1117.                 mtmp->mhp--;
1118.             monflee(mtmp, 2, FALSE, FALSE);
1119.         }
1120.     }
1121.     return 0;
1122. }
1123. 
1124. /* calculate 'mon's movement for current turn; called from moveloop() */
1125. int
1126. mcalcmove(
1127.     struct monst *mon,
1128.     boolean m_moving) /* True: adjust for moving;
1129.                        * False: just adjust for speed */
1130. {
1131.     int mmove = mon->data->mmove;
1132.     int mmove_adj;
1133. 
1134.     /* Note: MSLOW's `+ 1' prevents slowed speed 1 getting reduced to 0;
1135.      *       MFAST's `+ 2' prevents hasted speed 1 from becoming a no-op;
1136.      *       both adjustments have negligible effect on higher speeds.
1137.      */
1138.     if (mon->mspeed == MSLOW) {
1139.         /* slow-monster effects work better against faster monsters: they
1140.            lose 1/3 of their speed below 12 but 2/3 of their speed above */
1141.         if (mmove < NORMAL_SPEED)
1142.             mmove = (2 * mmove + 1) / 3;
1143.         else
1144.             mmove = 4 + (mmove / 3);
1145.     } else if (mon->mspeed == MFAST)
1146.         mmove = (4 * mmove + 2) / 3;
1147. 
1148.     if (mon == u.usteed && u.ugallop && svc.context.mv) {
1149.         /* increase movement by a factor of 1.5; also increase variance of
1150.            movement speed (if it's naturally 24, we don't want it to always
1151.            become 36) */
1152.         mmove = ((rn2(2) ? 4 : 5) * mmove) / 3;
1153.     }
1154. 
1155.     if (m_moving) {
1156.         /* Randomly round the monster's speed to a multiple of NORMAL_SPEED.
1157.            This makes it impossible for the player to predict when they'll
1158.            get a free turn (thus preventing exploits like "melee kiting"),
1159.            while retaining guarantees about shopkeepers not being outsped
1160.            by a normal-speed player, normal-speed players being unable
1161.            to open up a gap when fleeing a normal-speed monster, etc. */
1162.         mmove_adj = mmove % NORMAL_SPEED;
1163.         mmove -= mmove_adj;
1164.         if (rn2(NORMAL_SPEED) < mmove_adj)
1165.             mmove += NORMAL_SPEED;
1166.     }
1167.     return mmove;
1168. }
1169. 
1170. /* actions that happen once per ``turn, regardless of each
1171.    individual monster's metabolism; some of these might need to
1172.    be reclassified to occur more in proportion with movement rate */
1173. void
1174. mcalcdistress(void)
1175. {
1176.     iter_mons(m_calcdistress);
1177. }
1178. 
1179. staticfn void
1180. m_calcdistress(struct monst *mtmp)
1181. {
1182.     /* must check non-moving monsters once/turn in case they managed
1183.        to end up in water or lava; note: when not in liquid they regen,
1184.        shape-shift, timeout temporary maladies just like other monsters */
1185.     if (mtmp->data->mmove == 0) {
1186.         if (gv.vision_full_recalc)
1187.             vision_recalc(0);
1188.         if (minliquid(mtmp))
1189.             return;
1190.     }
1191. 
1192.     /* regenerate hit points */
1193.     mon_regen(mtmp, FALSE);
1194. 
1195.     /* possibly polymorph shapechangers and lycanthropes */
1196.     if (ismnum(mtmp->cham))
1197.         decide_to_shapeshift(mtmp);
1198.     were_change(mtmp);
1199. 
1200.     /* gradually time out temporary problems */
1201.     if (mtmp->mblinded && !--mtmp->mblinded)
1202.         mtmp->mcansee = 1;
1203.     if (mtmp->mfrozen && !--mtmp->mfrozen)
1204.         mtmp->mcanmove = 1;
1205.     if (mtmp->mfleetim && !--mtmp->mfleetim)
1206.         mtmp->mflee = 0;
1207. 
1208.     /* FIXME: mtmp->mlstmv ought to be updated here */
1209. }
1210. 
1211. /* perform movement for a single monster.
1212.    meant to be used with iter_mons_safe. */
1213. boolean
1214. movemon_singlemon(struct monst *mtmp)
1215. {
1216.     /* end monster movement early if hero is flagged to leave the level */
1217.     if (u.utotype
1218. #ifdef SAFERHANGUP
1219.         /* or if the program has lost contact with the user */
1220.         || program_state.done_hup
1221. #endif
1222.         ) {
1223.         gs.somebody_can_move = FALSE;
1224.         return TRUE;
1225.     }
1226. 
1227.     /* one dead monster needs to perform a move after death: vault
1228.        guard whose temporary corridor is still on the map; live
1229.        guards who have led the hero back to civilization get moved
1230.        off the map too; gd_move() decides whether the temporary
1231.        corridor can be removed and guard discarded (via clearing
1232.        mon->isgd flag so that dmonsfree() will get rid of mon) */
1233.     if (mtmp->isgd && !mtmp->mx && !(mtmp->mstate & MON_MIGRATING)) {
1234.         /* parked at <0,0>; eventually isgd should get set to false */
1235.         if (svm.moves > mtmp->mlstmv) {
1236.             (void) gd_move(mtmp);
1237.             mtmp->mlstmv = svm.moves;
1238.         }
1239.         return FALSE;
1240.     }
1241.     if (DEADMONSTER(mtmp))
1242.         return FALSE;
1243. 
1244.     /* monster isn't on this map anymore */
1245.     if (mon_offmap(mtmp))
1246.         return FALSE;
1247. 
1248.     m_everyturn_effect(mtmp);
1249. 
1250.     /* Find a monster that we have not treated yet. */
1251.     if (mtmp->movement < NORMAL_SPEED)
1252.         return FALSE;
1253. 
1254.     mtmp->movement -= NORMAL_SPEED;
1255.     if (mtmp->movement >= NORMAL_SPEED)
1256.         gs.somebody_can_move = TRUE;
1257. 
1258.     if (gv.vision_full_recalc)
1259.         vision_recalc(0); /* vision! */
1260. 
1261.     /* reset obj bypasses before next monster moves */
1262.     if (svc.context.bypasses)
1263.         clear_bypasses();
1264.     clear_splitobjs();
1265.     if (minliquid(mtmp))
1266.         return FALSE;
1267. 
1268.     /* after losing equipment, try to put on replacement */
1269.     if (mtmp->misc_worn_check & I_SPECIAL) {
1270.         long oldworn;
1271. 
1272.         /* hostiles only try to equip things if they think hero isn't
1273.          * nearby; if they think hero is nearby, leave the flag intact so
1274.          * that it can be checked again on subsequent moves until the hero
1275.          * is perceived to be farther away. */
1276.         if (mtmp->mpeaceful || mtmp->mtame
1277.             || dist2(mtmp->mx, mtmp->my, mtmp->mux, mtmp->muy) > (3 * 3)) {
1278.             mtmp->misc_worn_check &= ~I_SPECIAL;
1279.             oldworn = mtmp->misc_worn_check;
1280.             m_dowear(mtmp, FALSE);
1281.             if (mtmp->misc_worn_check != oldworn || !mtmp->mcanmove)
1282.                 return FALSE; /* is spending this turn equipping */
1283.         }
1284.     }
1285. 
1286.     if (is_hider(mtmp->data)) {
1287.         /* unwatched mimics and piercers may hide again  [MRS] */
1288.         if (restrap(mtmp))
1289.             return FALSE;
1290.         if (M_AP_TYPE(mtmp) == M_AP_FURNITURE
1291.             || M_AP_TYPE(mtmp) == M_AP_OBJECT)
1292.             return FALSE;
1293.         if (mtmp->mundetected)
1294.             return FALSE;
1295.     } else if (mtmp->data->mlet == S_EEL && !mtmp->mundetected
1296.                && (mtmp->mflee || !m_next2u(mtmp))
1297.                && !canseemon(mtmp) && !rn2(4)) {
1298.         /* some eels end up stuck in isolated pools, where they
1299.            can't--or at least won't--move, so they never reach
1300.            their post-move chance to re-hide */
1301.         if (hideunder(mtmp))
1302.             return FALSE;
1303.     }
1304. 
1305.     /* continue if the monster died fighting */
1306.     if (Conflict && !mtmp->iswiz && m_canseeu(mtmp)) {
1307.         /* Note:
1308.          *  Conflict does not take effect in the first round.
1309.          *  Therefore, A monster when stepping into the area will
1310.          *  get to swing at you.
1311.          *
1312.          *  The call to fightm() must be _last_.  The monster might
1313.          *  have died if it returns 1.
1314.          */
1315.         if (cansee(mtmp->mx, mtmp->my)
1316.             && (mdistu(mtmp) <= BOLT_LIM * BOLT_LIM)
1317.             && fightm(mtmp))
1318.             return FALSE; /* mon might have died */
1319.     }
1320.     (void) dochugw(mtmp, TRUE); /* otherwise just move the monster */
1321.     return FALSE;
1322. }
1323. 
1324. /* perform movement for all monsters */
1325. int
1326. movemon(void)
1327. {
1328.     gs.somebody_can_move = FALSE;
1329. 
1330.     iter_mons_safe(movemon_singlemon);
1331. 
1332.     if (any_light_source())
1333.         gv.vision_full_recalc = 1; /* in case a mon moved w/ a light source */
1334.     /* reset obj bypasses after last monster has moved */
1335.     if (svc.context.bypasses)
1336.         clear_bypasses();
1337.     clear_splitobjs();
1338.     /* remove dead monsters; dead vault guard will be left at <0,0>
1339.        if temporary corridor out of vault hasn't been removed yet */
1340.     dmonsfree();
1341. 
1342.     /* a monster may have levteleported player -dlc */
1343.     if (u.utotype) {
1344.         deferred_goto();
1345.         /* changed levels, so these monsters are dormant */
1346.         gs.somebody_can_move = FALSE;
1347.     }
1348. 
1349.     return gs.somebody_can_move;
1350. }
1351. 
1352. /* dispose of contents of an eaten container; used for pets and other mons */
1353. void
1354. meatbox(struct monst *mon, struct obj *otmp)
1355. {
1356.     boolean engulf_contents = (mon->data == &mons[PM_GELATINOUS_CUBE]);
1357.     int x = mon->mx, y = mon->my;
1358.     struct obj *cobj;
1359. 
1360.     if (!Has_contents(otmp) || !isok(x, y))
1361.         return;
1362. 
1363.     /* contents of eaten containers become engulfed or dropped onto
1364.       the floor; this is arbitrary, but otherwise g-cubes are too
1365.       powerful */
1366.     if (!engulf_contents && cansee(x, y)) {
1367.         pline("%s contents spill out onto the %s.",
1368.               s_suffix(The(distant_name(otmp, xname))),
1369.               surface(x, y));
1370.     }
1371.     while ((cobj = otmp->cobj) != 0) {
1372.         obj_extract_self(cobj);
1373.         if (otmp->otyp == ICE_BOX)
1374.             removed_from_icebox(cobj);
1375.         if (engulf_contents) {
1376.             (void) mpickobj(mon, cobj);
1377.         } else {
1378.             if (!flooreffects(cobj, x, y, ""))
1379.                 place_object(cobj, x, y);
1380.         }
1381.     }
1382. }
1383. 
1384. #define mstoning(obj) \
1385.     (ofood(obj) && ismnum(obj->corpsenm)      \
1386.      && flesh_petrifies(&mons[obj->corpsenm]))
1387. 
1388. /* Monster mtmp consumes an object.
1389.    Monster may die, polymorph, grow up, heal, etc; meating is not changed.
1390.    Object is extracted from any linked list and freed. */
1391. void
1392. m_consume_obj(struct monst *mtmp, struct obj *otmp)
1393. {
1394.     boolean ispet = mtmp->mtame;
1395. 
1396.     /* non-pet: Heal up to the object's weight in hp */
1397.     if (!ispet && mtmp->mhp < mtmp->mhpmax) {
1398.         healmon(mtmp, objects[otmp->otyp].oc_weight, 0);
1399.     }
1400.     if (Has_contents(otmp))
1401.         meatbox(mtmp, otmp);
1402.     if (otmp == uball) {
1403.         unpunish();
1404.         delobj(otmp);
1405.     } else if (otmp == uchain) {
1406.         unpunish(); /* frees uchain */
1407.     } else {
1408.         boolean deadmimic, slimer;
1409.         int poly, grow, heal, eyes, mstone, vis = canseemon(mtmp);
1410.         int corpsenm = (otmp->otyp == CORPSE ? otmp->corpsenm : NON_PM);
1411. 
1412.         deadmimic = (otmp->otyp == CORPSE && (corpsenm == PM_SMALL_MIMIC
1413.                                               || corpsenm == PM_LARGE_MIMIC
1414.                                               || corpsenm == PM_GIANT_MIMIC));
1415.         slimer = (otmp->otyp == GLOB_OF_GREEN_SLIME);
1416.         poly = polyfood(otmp);
1417.         grow = mlevelgain(otmp);
1418.         heal = mhealup(otmp);
1419.         eyes = (otmp->otyp == CARROT);
1420.         mstone = mstoning(otmp);
1421.         delobj(otmp); /* munch */
1422.         if (poly || slimer) {
1423.             struct permonst *ptr = slimer ? &mons[PM_GREEN_SLIME] : 0;
1424. 
1425.             (void) newcham(mtmp, ptr, vis ? NC_SHOW_MSG : NO_NC_FLAGS);
1426.         }
1427.         if (grow) {
1428.             if ((ispet && (int) mtmp->m_lev < (int) mtmp->data->mlevel + 15)
1429.                 || !ispet)
1430.                 (void) grow_up(mtmp, (struct monst *) 0);
1431.         }
1432.         if (mstone) {
1433.             if (poly_when_stoned(mtmp->data)) {
1434.                 mon_to_stone(mtmp);
1435.             } else if (!resists_ston(mtmp)) {
1436.                 if (vis)
1437.                     pline_mon(mtmp, "%s turns to stone!",
1438.                               Monnam(mtmp));
1439.                 monstone(mtmp);
1440.             }
1441.         }
1442.         if (heal)
1443.             healmon(mtmp, mtmp->mhpmax, 0);
1444.         if ((eyes || heal) && !mtmp->mcansee)
1445.             mcureblindness(mtmp, canseemon(mtmp));
1446.         if (ispet && deadmimic)
1447.             quickmimic(mtmp);
1448.         if (otmp->otyp == EGG && corpsenm == PM_PYROLISK)
1449.             explode(mtmp->mx, mtmp->my, -11, d(3, 6), 0, EXPL_FIERY);
1450.         if (corpsenm != NON_PM)
1451.             mon_givit(mtmp, &mons[corpsenm]);
1452.     }
1453. }
1454. 
1455. /*
1456.  * Maybe eat a metallic object (not just gold).
1457.  * Return value: 0 => nothing happened, 1 => monster ate something,
1458.  * 2 => monster died (it must have grown into a genocided form, but
1459.  * that can't happen at present because nothing which eats objects
1460.  * has young and old forms).
1461.  */
1462. int
1463. meatmetal(struct monst *mtmp)
1464. {
1465.     struct obj *otmp;
1466.     char *otmpname;
1467.     int vis = canseemon(mtmp);
1468. 
1469.     /* If a pet, eating is handled separately, in dog.c */
1470.     if (mtmp->mtame)
1471.         return 0;
1472. 
1473.     /* Eats topmost metal object if it is there */
1474.     for (otmp = svl.level.objects[mtmp->mx][mtmp->my]; otmp;
1475.          otmp = otmp->nexthere) {
1476.         /* Don't eat indigestible/choking/inappropriate objects */
1477.         if ((mtmp->data == &mons[PM_RUST_MONSTER] && !is_rustprone(otmp))
1478.             || (otmp->otyp == AMULET_OF_STRANGULATION
1479.                 || otmp->otyp == RIN_SLOW_DIGESTION)
1480.             || (otmp->opoisoned && !resists_poison(mtmp)))
1481.             continue;
1482.         if (is_metallic(otmp) && !obj_resists(otmp, 5, 95)
1483.             && touch_artifact(otmp, mtmp)) {
1484.             if (mtmp->data == &mons[PM_RUST_MONSTER] && otmp->oerodeproof) {
1485.                 if (vis) {
1486.                     /* call distant_name() for its side-effects even when
1487.                        !verbose so won't be printed */
1488.                     otmpname = distant_name(otmp, doname);
1489.                     if (flags.verbose)
1490.                         pline_mon(mtmp, "%s eats %s!",
1491.                                   Monnam(mtmp), otmpname);
1492.                 }
1493.                 /* The object's rustproofing is gone now */
1494.                 otmp->oerodeproof = 0;
1495.                 mtmp->mstun = 1;
1496.                 if (vis) {
1497.                     /* (see above; format even if it won't be printed) */
1498.                     otmpname = distant_name(otmp, doname);
1499.                     if (flags.verbose)
1500.                         pline_mon(mtmp, "%s spits %s out in disgust!",
1501.                               Monnam(mtmp), otmpname);
1502.                 }
1503.             } else {
1504.                 if (cansee(mtmp->mx, mtmp->my)) {
1505.                     /* (see above; format even if it won't be printed) */
1506.                     otmpname = distant_name(otmp, doname);
1507.                     if (flags.verbose)
1508.                         pline_mon(mtmp, "%s eats %s!",
1509.                                   Monnam(mtmp), otmpname);
1510.                 } else {
1511.                     if (flags.verbose) {
1512.                         Soundeffect(se_crunching_sound, 50);
1513.                         You_hear("a crunching sound.");
1514.                     }
1515.                 }
1516.                 mtmp->meating = otmp->owt / 2 + 1;
1517.                 m_consume_obj(mtmp, otmp);
1518.                 if (DEADMONSTER(mtmp))
1519.                     return 2;
1520.                 /* Left behind a pile? */
1521.                 if (rnd(25) < 3)
1522.                     (void) mksobj_at(ROCK, mtmp->mx, mtmp->my, TRUE, FALSE);
1523.                 newsym(mtmp->mx, mtmp->my);
1524.                 return 1;
1525.             }
1526.         }
1527.     }
1528.     return 0;
1529. }
1530. 
1531. /* monster eats a pile of objects */
1532. int
1533. meatobj(struct monst *mtmp) /* for gelatinous cubes */
1534. {
1535.     struct obj *otmp, *otmp2;
1536.     struct permonst *ptr, *original_ptr = mtmp->data;
1537.     int count = 0, ecount = 0;
1538.     char buf[BUFSZ], *otmpname;
1539. 
1540.     buf[0] = '\0';
1541.     /* If a pet, eating is handled separately, in dog.c */
1542.     if (mtmp->mtame)
1543.         return 0;
1544. 
1545.     /* eat organic objects, including cloth and wood, if present;
1546.        engulf others, except huge rocks and metal attached to player
1547.        [despite comment at top, doesn't assume that eater is a g-cube] */
1548.     for (otmp = svl.level.objects[mtmp->mx][mtmp->my]; otmp; otmp = otmp2) {
1549.         otmp2 = otmp->nexthere;
1550. 
1551.         /* avoid special items; once hero picks them up, they'll cease
1552.            being special, becoming eligible for engulf and devore if
1553.            dropped again */
1554.         if (is_mines_prize(otmp) || is_soko_prize(otmp))
1555.             continue;
1556. 
1557.         /* touch sensitive items */
1558.         if (otmp->otyp == CORPSE && is_rider(&mons[otmp->corpsenm])) {
1559.             int ox = otmp->ox, oy = otmp->oy;
1560.             boolean revived_it = revive_corpse(otmp);
1561. 
1562.             newsym(ox, oy);
1563.             /* Rider corpse isn't just inedible; can't engulf it either */
1564.             if (!revived_it)
1565.                 continue;
1566.             /* [should check whether revival forced 'mtmp' off the level
1567.                and return 3 in that situation (if possible...)] */
1568.             break;
1569. 
1570.         /* untouchable (or inaccessible) items */
1571.         } else if ((otmp->otyp == CORPSE
1572.                     && touch_petrifies(&mons[otmp->corpsenm])
1573.                     && !resists_ston(mtmp))
1574.                    /* don't engulf boulders and statues or ball&chain */
1575.                    || otmp->oclass == ROCK_CLASS
1576.                    || otmp == uball || otmp == uchain
1577.                    /* normally mtmp won't have stepped onto scare monster
1578.                       scroll, but if it does, don't eat or engulf that
1579.                       (note: scrolls inside eaten containers will still
1580.                       become engulfed) */
1581.                    || otmp->otyp == SCR_SCARE_MONSTER) {
1582.             /* do nothing--neither eaten nor engulfed */
1583.             continue;
1584. 
1585.         /* inedible items -- engulf these */
1586.         } else if (!is_organic(otmp) || obj_resists(otmp, 5, 95)
1587.                    || !touch_artifact(otmp, mtmp)
1588.                    /* redundant due to non-organic composition but
1589.                       included for emphasis */
1590.                    || (otmp->otyp == AMULET_OF_STRANGULATION
1591.                        || otmp->otyp == RIN_SLOW_DIGESTION)
1592.                    || (otmp->opoisoned && !resists_poison(mtmp))
1593.                    /* cockatrice corpses handled above; this
1594.                       touch_petrifies() check catches eggs */
1595.                    || (mstoning(otmp) && !resists_ston(mtmp))
1596.                    || (otmp->otyp == GLOB_OF_GREEN_SLIME
1597.                        && !slimeproof(mtmp->data))) {
1598.             /* engulf */
1599.             ++ecount;
1600.             /* call distant_name() for its possible side-effects even if
1601.                the result won't be printed */
1602.             otmpname = distant_name(otmp, doname);
1603.             if (ecount == 1)
1604.                 Sprintf(buf, "%s engulfs %s.", Monnam(mtmp), otmpname);
1605.             else if (ecount == 2)
1606.                 Sprintf(buf, "%s engulfs several objects.", Monnam(mtmp));
1607.             obj_extract_self(otmp);
1608.             (void) mpickobj(mtmp, otmp); /* slurp */
1609. 
1610.         /* lastly, edible items; yum! */
1611.         } else {
1612.             /* devour */
1613.             ++count;
1614.             if (cansee(mtmp->mx, mtmp->my)) {
1615.                 /* (see above; distant_name() sometimes has side-effects */
1616.                 otmpname = distant_name(otmp, doname);
1617.                 if (flags.verbose)
1618.                     pline_mon(mtmp, "%s eats %s!",
1619.                               Monnam(mtmp), otmpname);
1620.                 /* give this one even if !verbose */
1621.                 if (otmp->oclass == SCROLL_CLASS
1622.                     && objdescr_is(otmp, "YUM YUM"))
1623.                     pline("Yum%c", otmp->blessed ? '!' : '.');
1624.             } else {
1625.                 Soundeffect(se_slurping_sound, 30);
1626.                 if (flags.verbose)
1627.                     You_hear("a slurping sound.");
1628.             }
1629.             m_consume_obj(mtmp, otmp);
1630.             /* in case it polymorphed or died */
1631.             ptr = mtmp->data;
1632.             if (ptr != original_ptr)
1633.                 return !ptr ? 2 : 1;
1634.         }
1635. 
1636.         /* Engulf & devour is instant, so don't set meating */
1637.         if (mtmp->minvis)
1638.             newsym(mtmp->mx, mtmp->my);
1639.     }
1640. 
1641.     if (ecount > 0) {
1642.         if (cansee(mtmp->mx, mtmp->my) && flags.verbose && buf[0])
1643.             pline1(buf);
1644.         else if (flags.verbose)
1645.             You_hear("%s slurping sound%s.",
1646.                      (ecount == 1) ? "a" : "several", plur(ecount));
1647.     }
1648.     return (count > 0 || ecount > 0) ? 1 : 0;
1649. }
1650. 
1651. #undef mstoning
1652. 
1653. /* Monster eats a corpse off the ground.
1654.    Return value is 0 = nothing eaten, 1 = ate a corpse, 2 = died. */
1655. int
1656. meatcorpse(
1657.     struct monst *mtmp) /* for purple worms and other voracious monsters */
1658. {
1659.     struct obj *otmp;
1660.     struct permonst *ptr, *original_ptr = mtmp->data, *corpsepm;
1661.     coordxy x = mtmp->mx, y = mtmp->my;
1662. 
1663.     /* if a pet, eating is handled separately, in dog.c */
1664.     if (mtmp->mtame)
1665.         return 0;
1666. 
1667.     /* skips past any globs */
1668.     for (otmp = sobj_at(CORPSE, x, y); otmp;
1669.          /* won't get back here if otmp is split or gets used up */
1670.          otmp = nxtobj(otmp, CORPSE, TRUE)) {
1671. 
1672.         corpsepm = &mons[otmp->corpsenm];
1673.         /* skip some corpses */
1674.         if (vegan(corpsepm) /* ignore veggy corpse even if omnivorous */
1675.             /* don't eat harmful corpses */
1676.             || (flesh_petrifies(corpsepm) && !resists_ston(mtmp)))
1677.             continue;
1678.         if (is_rider(corpsepm)) {
1679.             boolean revived_it = revive_corpse(otmp);
1680. 
1681.             newsym(x, y); /* corpse is gone; mtmp might be too so do this now
1682.                              since we're bypassing the bottom of the loop */
1683.             if (!revived_it)
1684.                 continue; /* revival failed? if so, corpse is gone */
1685.             /* Successful Rider revival; unlike skipped corpses, don't
1686.                just move on to next corpse as if nothing has happened.
1687.                [Can Rider revival bump 'mtmp' off level when it's full?
1688.                We ought to return 3 if that happens.] */
1689.             break;
1690.         }
1691. 
1692.         if (otmp->quan > 1)
1693.             otmp = splitobj(otmp, 1L);
1694. 
1695.         if (cansee(x, y) && canseemon(mtmp)) {
1696.             /* call distant_name() for its possible side-effects even if
1697.                the result won't be printed */
1698.             char *otmpname = distant_name(otmp, doname);
1699. 
1700.             if (flags.verbose)
1701.                 pline_mon(mtmp, "%s eats %s!",
1702.                           Monnam(mtmp), otmpname);
1703.         } else {
1704.             Soundeffect(se_masticating_sound, 50);
1705.             if (flags.verbose)
1706.                 You_hear("a masticating sound.");
1707.         }
1708. 
1709.         m_consume_obj(mtmp, otmp);
1710.         /* in case it polymorphed or died */
1711.         ptr = mtmp->data;
1712.         if (ptr != original_ptr)
1713.             return !ptr ? 2 : 1;
1714. 
1715.         /* Engulf & devour is instant, so don't set meating */
1716.         if (mtmp->minvis)
1717.             newsym(x, y);
1718. 
1719.         return 1;
1720.     }
1721.     return 0;
1722. }
1723. 
1724. /* give monster property prop */
1725. void
1726. mon_give_prop(struct monst *mtmp, int prop)
1727. {
1728.     const char *msg = NULL;
1729.     unsigned short intrinsic = 0; /* MR_* constant */
1730. 
1731.     /* Pets don't have all the fields that the hero does, so they can't get
1732.        all the same intrinsics.  If it happens to choose strength gain or
1733.        teleport control or whatever, ignore it. */
1734.     switch (prop) {
1735.     case FIRE_RES:
1736.         msg = "%s shivers slightly.";
1737.         break;
1738.     case COLD_RES:
1739.         msg = "%s looks quite warm.";
1740.         break;
1741.     case SLEEP_RES:
1742.         msg = "%s looks wide awake.";
1743.         break;
1744.     case DISINT_RES:
1745.         msg = "%s looks very firm.";
1746.         break;
1747.     case SHOCK_RES:
1748.         msg = "%s crackles with static electricity.";
1749.         break;
1750.     case POISON_RES:
1751.         msg = "%s looks healthy.";
1752.         break;
1753.     default:
1754.         return; /* can't give it */
1755.         break;
1756.     }
1757.     intrinsic = res_to_mr(prop);
1758. 
1759.     /* Don't give message if it already had this property intrinsically, but
1760.        still do grant the intrinsic if it only had it from mresists.
1761.        Do print the message if it only had this property extrinsically, which
1762.        is why mon_resistancebits isn't used here. */
1763.     if ((mtmp->data->mresists | mtmp->mintrinsics) & intrinsic)
1764.         msg = (const char *) 0;
1765. 
1766.     if (intrinsic)
1767.         mtmp->mintrinsics |= intrinsic;
1768. 
1769.     if (canseemon(mtmp) && msg) {
1770.         DISABLE_WARNING_FORMAT_NONLITERAL
1771.         pline_mon(mtmp, msg, Monnam(mtmp));
1772.         RESTORE_WARNING_FORMAT_NONLITERAL
1773.     }
1774. }
1775. 
1776. /* Maybe give an intrinsic to monster from eating corpse that confers it. */
1777. void
1778. mon_givit(struct monst *mtmp, struct permonst *ptr)
1779. {
1780.     int prop = corpse_intrinsic(ptr);
1781.     boolean vis = canseemon(mtmp);
1782. 
1783.     if (DEADMONSTER(mtmp))
1784.         return;
1785. 
1786.     if (ptr == &mons[PM_STALKER]) {
1787.         /*
1788.          * Invisible stalker isn't flagged as conferring invisibility
1789.          * so prop is 0.  For hero, eating a stalker corpse confers
1790.          * temporary invisibility if hero is visible.  When already
1791.          * invisible, if confers permanent invisibility and also
1792.          * permanent see invisible.  For monsters, only permanent
1793.          * invisibility is possible; temporary invisibility and see
1794.          * invisible aren't implemented for them.
1795.          *
1796.          * A monster being invisible gains no benefit against other
1797.          * monsters, and an invisible pet when hero can't see invisible
1798.          * is a nuisance at best, so this is probably detrimental.
1799.          * Players will just have to live with it if they want to be
1800.          * able to have pets gain intrinsics from eating corpses.
1801.          */
1802.         if (!mtmp->perminvis || mtmp->invis_blkd) {
1803.             char mtmpbuf[BUFSZ];
1804. 
1805.             Strcpy(mtmpbuf, Monnam(mtmp));
1806.             mon_set_minvis(mtmp, FALSE);
1807.             if (vis)
1808.                 pline_mon(mtmp, "%s %s.", mtmpbuf,
1809.                       !canspotmon(mtmp) ? "vanishes"
1810.                       : mtmp->invis_blkd ? "seems to flicker"
1811.                         : "becomes invisible");
1812.         }
1813.         mtmp->mstun = 1; /* no timeout but will eventually wear off */
1814.         return;
1815.     }
1816. 
1817.     if (prop == 0)
1818.         return; /* no intrinsic from this corpse */
1819. 
1820.     if (!should_givit(prop, ptr))
1821.         return; /* failed die roll */
1822. 
1823.     mon_give_prop(mtmp, prop);
1824. }
1825. 
1826. void
1827. mpickgold(struct monst *mtmp)
1828. {
1829.     struct obj *gold;
1830.     int mat_idx;
1831. 
1832.     if ((gold = g_at(mtmp->mx, mtmp->my)) != 0) {
1833.         mat_idx = objects[gold->otyp].oc_material;
1834.         obj_extract_self(gold);
1835.         add_to_minv(mtmp, gold);
1836.         if (cansee(mtmp->mx, mtmp->my)) {
1837.             if (flags.verbose && !mtmp->isgd)
1838.                 pline_mon(mtmp, "%s picks up some %s.", Monnam(mtmp),
1839.                          mat_idx == GOLD ? "gold" : "money");
1840.             newsym(mtmp->mx, mtmp->my);
1841.         }
1842.     }
1843. }
1844. 
1845. /* monster picks up one item stack from the map location they are at */
1846. boolean
1847. mpickstuff(struct monst *mtmp)
1848. {
1849.     struct obj *otmp, *otmp2, *otmp3;
1850.     int carryamt = 0;
1851. 
1852.     /* prevent shopkeepers from leaving the door of their shop */
1853.     if (mtmp->isshk && inhishop(mtmp))
1854.         return FALSE;
1855. 
1856.     /* non-tame monsters normally don't go shopping */
1857.     if (!mtmp->mtame && *in_rooms(mtmp->mx, mtmp->my, SHOPBASE) && rn2(25))
1858.         return FALSE;
1859. 
1860.     /* item in a pool, but monster can't swim */
1861.     if (!could_reach_item(mtmp, mtmp->mx, mtmp->my))
1862.         return FALSE;
1863. 
1864.     for (otmp = svl.level.objects[mtmp->mx][mtmp->my]; otmp; otmp = otmp2) {
1865.         otmp2 = otmp->nexthere;
1866. 
1867.         /* avoid special items; once hero picks them up, they'll cease
1868.            being special, becoming eligible for normal pickup */
1869.         if (is_mines_prize(otmp) || is_soko_prize(otmp))
1870.             continue;
1871. 
1872.         /* Nymphs take everything.  Most monsters don't pick up corpses. */
1873.         if (mon_would_take_item(mtmp, otmp)) {
1874. 
1875.             if (otmp->otyp == CORPSE && mtmp->data->mlet != S_NYMPH
1876.                 /* let a handful of corpse types thru to can_carry() */
1877.                 && !touch_petrifies(&mons[otmp->corpsenm])
1878.                 && otmp->corpsenm != PM_LIZARD
1879.                 && !acidic(&mons[otmp->corpsenm]))
1880.                 continue;
1881.             if (!can_touch_safely(mtmp, otmp))
1882.                 continue;
1883.             carryamt = can_carry(mtmp, otmp);
1884.             if (carryamt == 0)
1885.                 continue;
1886.             /* handle cases where the critter can only get some */
1887.             otmp3 = otmp;
1888.             if (carryamt != otmp->quan) {
1889.                 otmp3 = splitobj(otmp, carryamt);
1890.             }
1891.             if (cansee(mtmp->mx, mtmp->my)) {
1892.                 /* call distant_name() for its possible side-effects even
1893.                    if the result won't be printed; do it before the extract
1894.                    from floor and subsequent pickup by mtmp */
1895.                 char *otmpname = distant_name(otmp, doname);
1896. 
1897.                 if (flags.verbose)
1898.                     pline_mon(mtmp, "%s picks up %s.",
1899.                               Monnam(mtmp), otmpname);
1900.             }
1901.             obj_extract_self(otmp3);      /* remove from floor */
1902.             (void) mpickobj(mtmp, otmp3); /* may merge and free otmp3 */
1903.             /* let them try to equip it on the next turn */
1904.             check_gear_next_turn(mtmp);
1905.             newsym(mtmp->mx, mtmp->my);
1906.             return TRUE; /* pick only one object */
1907.         }
1908.     }
1909.     return FALSE;
1910. }
1911. 
1912. int
1913. curr_mon_load(struct monst *mtmp)
1914. {
1915.     int curload = 0;
1916.     struct obj *obj;
1917. 
1918.     for (obj = mtmp->minvent; obj; obj = obj->nobj) {
1919.         if (obj->otyp != BOULDER || !throws_rocks(mtmp->data))
1920.             curload += obj->owt;
1921.     }
1922. 
1923.     return curload;
1924. }
1925. 
1926. int
1927. max_mon_load(struct monst *mtmp)
1928. {
1929.     long maxload;
1930. 
1931.     /* Base monster carrying capacity is equal to human maximum
1932.      * carrying capacity, or half human maximum if not strong.
1933.      * (for a polymorphed player, the value used would be the
1934.      * non-polymorphed carrying capacity instead of max/half max).
1935.      * This is then modified by the ratio between the monster weights
1936.      * and human weights.  Corpseless monsters are given a capacity
1937.      * proportional to their size instead of weight.
1938.      */
1939.     if (!mtmp->data->cwt)
1940.         maxload = (MAX_CARR_CAP * (long) mtmp->data->msize) / MZ_HUMAN;
1941.     else if (!strongmonst(mtmp->data)
1942.              || (strongmonst(mtmp->data) && (mtmp->data->cwt > WT_HUMAN)))
1943.         maxload = (MAX_CARR_CAP * (long) mtmp->data->cwt) / WT_HUMAN;
1944.     else
1945.         maxload = MAX_CARR_CAP; /*strong monsters w/cwt <= WT_HUMAN*/
1946. 
1947.     if (!strongmonst(mtmp->data))
1948.         maxload /= 2;
1949. 
1950.     if (maxload < 1)
1951.         maxload = 1;
1952. 
1953.     return (int) maxload;
1954. }
1955. 
1956. /* can monster touch object safely? */
1957. boolean
1958. can_touch_safely(struct monst *mtmp, struct obj *otmp)
1959. {
1960.     int otyp = otmp->otyp;
1961.     struct permonst *mdat = mtmp->data;
1962. 
1963.     if (otyp == CORPSE && touch_petrifies(&mons[otmp->corpsenm])
1964.         && !(mtmp->misc_worn_check & W_ARMG) && !resists_ston(mtmp))
1965.         return FALSE;
1966.     if (otyp == CORPSE && is_rider(&mons[otmp->corpsenm]))
1967.         return FALSE;
1968.     if (objects[otyp].oc_material == SILVER && mon_hates_silver(mtmp)
1969.         && (otyp != BELL_OF_OPENING || !is_covetous(mdat)))
1970.         return FALSE;
1971.     if (!touch_artifact(otmp, mtmp))
1972.         return FALSE;
1973.     return TRUE;
1974. }
1975. 
1976. /* for restricting monsters' object-pickup.
1977.  *
1978.  * to support the new pet behavior, this now returns the max # of objects
1979.  * that a given monster could pick up from a pile. frequently this will be
1980.  * otmp->quan, but special cases for 'only one' now exist.
1981.  *
1982.  * this will probably cause very amusing behavior with pets and gold coins.
1983.  *
1984.  * TODO: allow picking up 2-N objects from a pile of N based on weight.
1985.  *       Change from 'int' to 'long' to accommodate big stacks of gold.
1986.  *       Right now we fake it by reporting a partial quantity, but the
1987.  *       likesgold handling m_move results in picking up the whole stack.
1988.  */
1989. int
1990. can_carry(struct monst *mtmp, struct obj *otmp)
1991. {
1992.     int iquan, otyp = otmp->otyp, newload = otmp->owt;
1993.     struct permonst *mdat = mtmp->data;
1994.     short nattk = 0;
1995. 
1996.     if (notake(mdat))
1997.         return 0; /* can't carry anything */
1998. 
1999.     if (!can_touch_safely(mtmp, otmp))
2000.         return 0;
2001. 
2002.     /* hostile monsters who like gold will pick up the whole stack;
2003.        tame monsters with hands will pick up the partial stack */
2004.     iquan = (otmp->quan > (long) LARGEST_INT)
2005.                ? 20000 + rn2(LARGEST_INT - 20000 + 1)
2006.                : (int) otmp->quan;
2007. 
2008.     /* monsters without hands can't pick up multiple objects at once
2009.      * unless they have an engulfing attack
2010.      *
2011.      * ...dragons, of course, can always carry gold pieces and gems somehow
2012.      */
2013.     if (iquan > 1) {
2014.         boolean glomper = FALSE;
2015. 
2016.         if (mtmp->data->mlet == S_DRAGON
2017.             && (otmp->oclass == COIN_CLASS
2018.                 || otmp->oclass == GEM_CLASS))
2019.             glomper = TRUE;
2020.         else
2021.             for (nattk = 0; nattk < NATTK; nattk++)
2022.                 if (mtmp->data->mattk[nattk].aatyp == AT_ENGL) {
2023.                     glomper = TRUE;
2024.                     break;
2025.                 }
2026.         if ((mtmp->data->mflags1 & M1_NOHANDS) && !glomper)
2027.             return 1;
2028.     }
2029. 
2030.     /* steeds don't pick up stuff (to avoid shop abuse) */
2031.     if (mtmp == u.usteed)
2032.         return 0;
2033.     if (mtmp->isshk)
2034.         return iquan; /* no limit */
2035.     if (mtmp->mpeaceful && !mtmp->mtame)
2036.         return 0;
2037.     /* otherwise players might find themselves obligated to violate
2038.      * their alignment if the monster takes something they need
2039.      */
2040. 
2041.     /* special--boulder throwers carry unlimited amounts of boulders */
2042.     if (throws_rocks(mdat) && otyp == BOULDER)
2043.         return iquan;
2044. 
2045.     /* nymphs deal in stolen merchandise, but not boulders or statues */
2046.     if (mdat->mlet == S_NYMPH)
2047.         return (otmp->oclass == ROCK_CLASS) ? 0 : iquan;
2048. 
2049.     if (curr_mon_load(mtmp) + newload > max_mon_load(mtmp))
2050.         return 0;
2051. 
2052.     return iquan;
2053. }
2054. 
2055. /* is <nx,ny> in direct line with where 'mon' thinks hero is? */
2056. staticfn boolean
2057. monlineu(struct monst *mon, int nx, int ny)
2058. {
2059.     return online2(nx, ny, mon->mux, mon->muy);
2060. }
2061. 
2062. /* return flags based on monster data, for mfndpos() */
2063. long
2064. mon_allowflags(struct monst *mtmp)
2065. {
2066.     long allowflags = 0L;
2067.     boolean can_open = !(nohands(mtmp->data) || verysmall(mtmp->data));
2068.     boolean can_unlock = ((can_open && monhaskey(mtmp, TRUE))
2069.                           || mtmp->iswiz || is_rider(mtmp->data));
2070.     boolean doorbuster = is_giant(mtmp->data);
2071.     /* don't tunnel if on rogue level or if hostile and close enough
2072.        to prefer a weapon; same criteria as in m_move() */
2073.     boolean can_tunnel = (tunnels(mtmp->data) && !Is_rogue_level(&u.uz));
2074. 
2075.     if (can_tunnel && needspick(mtmp->data)
2076.         && ((!mtmp->mpeaceful || Conflict)
2077.             && dist2(mtmp->mx, mtmp->my, mtmp->mux, mtmp->muy) <= 8))
2078.         can_tunnel = FALSE;
2079. 
2080.     if (mtmp->mtame)
2081.         allowflags |= ALLOW_M | ALLOW_TRAPS | ALLOW_SANCT | ALLOW_SSM;
2082.     else if (mtmp->mpeaceful)
2083.         allowflags |= ALLOW_SANCT | ALLOW_SSM;
2084.     else
2085.         allowflags |= ALLOW_U;
2086.     if (Conflict && !resist_conflict(mtmp))
2087.         allowflags |= ALLOW_U;
2088.     if (mtmp->isshk)
2089.         allowflags |= ALLOW_SSM;
2090.     if (mtmp->ispriest)
2091.         allowflags |= ALLOW_SSM | ALLOW_SANCT;
2092.     if (passes_walls(mtmp->data))
2093.         allowflags |= (ALLOW_ROCK | ALLOW_WALL);
2094.     if (throws_rocks(mtmp->data) || m_can_break_boulder(mtmp))
2095.         allowflags |= ALLOW_ROCK;
2096.     if (can_tunnel)
2097.         allowflags |= ALLOW_DIG;
2098.     if (doorbuster)
2099.         allowflags |= BUSTDOOR;
2100.     if (can_open)
2101.         allowflags |= OPENDOOR;
2102.     if (can_unlock)
2103.         allowflags |= UNLOCKDOOR;
2104.     if (passes_bars(mtmp->data)
2105.         /* restrict engulfer or holder who might try to pass iron bars while
2106.            carrying hero; accept small subset for poly'd hero passes_bars() */
2107.         && (mtmp != u.ustuck || (unsolid(gy.youmonst.data)
2108.                                  || verysmall(gy.youmonst.data))))
2109.         allowflags |= ALLOW_BARS;
2110. #if 0   /* can't do this here; leave it for mfndpos() */
2111.     if (is_displacer(mtmp->data))
2112.         allowflags |= ALLOW_MDISP;
2113. #endif
2114.     if (is_minion(mtmp->data) || is_rider(mtmp->data))
2115.         allowflags |= ALLOW_SANCT;
2116.     /* unicorn may not be able to avoid hero on a noteleport level */
2117.     if (is_unicorn(mtmp->data) && !noteleport_level(mtmp))
2118.         allowflags |= NOTONL;
2119.     if (is_human(mtmp->data) || mtmp->data == &mons[PM_MINOTAUR])
2120.         allowflags |= ALLOW_SSM;
2121.     if ((is_undead(mtmp->data) && mtmp->data->mlet != S_GHOST)
2122.         || is_vampshifter(mtmp))
2123.         allowflags |= NOGARLIC;
2124. 
2125.     return allowflags;
2126. }
2127. 
2128. /* return TRUE if monster is up in the air/on the ceiling */
2129. boolean
2130. m_in_air(struct monst *mtmp)
2131. {
2132.     return (is_flyer(mtmp->data)
2133.             || is_floater(mtmp->data)
2134.             || (is_clinger(mtmp->data)
2135.                 && has_ceiling(&u.uz) && mtmp->mundetected));
2136. }
2137. 
2138. /* return number of acceptable neighbour positions */
2139. int
2140. mfndpos(
2141.     struct monst *mon,
2142.     struct mfndposdata *data,
2143.     long flag)
2144. {
2145.     struct permonst *mdat = mon->data;
2146.     struct trap *ttmp;
2147.     coordxy x, y, nx, ny;
2148.     int cnt = 0;
2149.     uchar ntyp;
2150.     uchar nowtyp;
2151.     boolean wantpool, poolok, lavaok, nodiag;
2152.     boolean rockok = FALSE, treeok = FALSE, thrudoor;
2153.     int maxx, maxy;
2154.     boolean poisongas_ok, in_poisongas;
2155.     NhRegion *gas_reg;
2156.     int gas_glyph = cmap_to_glyph(S_poisoncloud);
2157. 
2158.     x = mon->mx;
2159.     y = mon->my;
2160.     nowtyp = levl[x][y].typ;
2161. 
2162.     (void)memset((genericptr_t) data, 0, sizeof(struct mfndposdata));
2163. 
2164.     nodiag = NODIAG(mdat - mons);
2165.     wantpool = (mdat->mlet == S_EEL);
2166.     poolok = ((!Is_waterlevel(&u.uz) && m_in_air(mon))
2167.               || (is_swimmer(mdat) && !wantpool));
2168.     lavaok = (m_in_air(mon) || likes_lava(mdat));
2169.     if (mdat == &mons[PM_FLOATING_EYE]) /* prefers to avoid heat */
2170.         lavaok = FALSE;
2171.     thrudoor = ((flag & (ALLOW_WALL | BUSTDOOR)) != 0L);
2172.     poisongas_ok = (m_poisongas_ok(mon) == M_POISONGAS_OK);
2173.     in_poisongas = ((gas_reg = visible_region_at(x,y)) != 0
2174.                     && gas_reg->glyph == gas_glyph);
2175. 
2176.     if (flag & ALLOW_DIG) {
2177.         struct obj *mw_tmp;
2178. 
2179.         /* need to be specific about what can currently be dug */
2180.         if (!needspick(mdat)) {
2181.             rockok = treeok = TRUE;
2182.         } else if ((mw_tmp = MON_WEP(mon)) && mw_tmp->cursed
2183.                    && mon->weapon_check == NO_WEAPON_WANTED) {
2184.             rockok = is_pick(mw_tmp);
2185.             treeok = is_axe(mw_tmp);
2186.         } else {
2187.             rockok = (m_carrying(mon, PICK_AXE)
2188.                       || (m_carrying(mon, DWARVISH_MATTOCK)
2189.                           && !which_armor(mon, W_ARMS)));
2190.             treeok = (m_carrying(mon, AXE) || (m_carrying(mon, BATTLE_AXE)
2191.                                                && !which_armor(mon, W_ARMS)));
2192.         }
2193.         if (rockok || treeok)
2194.             thrudoor = TRUE;
2195.     }
2196. 
2197.  nexttry: /* eels prefer the water, but if there is no water nearby,
2198.              they will crawl over land */
2199.     if (mon->mconf) {
2200.         flag |= ALLOW_ALL;
2201.         flag &= ~NOTONL;
2202.     }
2203.     if (!mon->mcansee)
2204.         flag |= ALLOW_SSM;
2205.     maxx = min(x + 1, COLNO - 1);
2206.     maxy = min(y + 1, ROWNO - 1);
2207.     for (nx = max(1, x - 1); nx <= maxx; nx++)
2208.         for (ny = max(0, y - 1); ny <= maxy; ny++) {
2209.             if (nx == x && ny == y)
2210.                 continue;
2211.             ntyp = levl[nx][ny].typ;
2212.             if (IS_OBSTRUCTED(ntyp)
2213.                 && !((flag & ALLOW_WALL) && may_passwall(nx, ny))
2214.                 && !((IS_TREE(ntyp) ? treeok : rockok) && may_dig(nx, ny)))
2215.                 continue;
2216.             /* intelligent peacefuls avoid digging shop/temple walls */
2217.             if (IS_OBSTRUCTED(ntyp) && rockok
2218.                 && !mindless(mon->data) && (mon->mpeaceful || mon->mtame)
2219.                 && (*in_rooms(nx, ny, TEMPLE) || *in_rooms(nx, ny, SHOPBASE))
2220.                 && !(*in_rooms(x, y, TEMPLE) || *in_rooms(x, y, SHOPBASE)))
2221.                 continue;
2222.             if (IS_WATERWALL(ntyp) && !is_swimmer(mdat))
2223.                 continue;
2224.             /* KMH -- Added iron bars */
2225.             if (ntyp == IRONBARS
2226.                 && (!(flag & ALLOW_BARS)
2227.                     || ((levl[nx][ny].wall_info & W_NONDIGGABLE)
2228.                         && (dmgtype(mdat, AD_RUST)
2229.                             || dmgtype(mdat, AD_CORR)))))
2230.                 continue;
2231.             if (IS_DOOR(ntyp)
2232.                 /* an amorphous creature can only move under/through a
2233.                    closed door if it doesn't currently have hero engulfed */
2234.                 && !((amorphous(mdat) || can_fog(mon)) && !engulfing_u(mon))
2235.                 && (((levl[nx][ny].doormask & D_CLOSED) && !(flag & OPENDOOR))
2236.                     || ((levl[nx][ny].doormask & D_LOCKED)
2237.                         && !(flag & UNLOCKDOOR))) && !thrudoor)
2238.                 continue;
2239.             /* avoid poison gas? */
2240.             if (!poisongas_ok && !in_poisongas
2241.                 && (gas_reg = visible_region_at(nx,ny)) != 0
2242.                 && gas_reg->glyph == gas_glyph)
2243.                 continue;
2244.             /* first diagonal checks (tight squeezes handled below) */
2245.             if (nx != x && ny != y
2246.                 && (nodiag
2247.                     || (IS_DOOR(nowtyp) && (levl[x][y].doormask & ~D_BROKEN))
2248.                     || (IS_DOOR(ntyp) && (levl[nx][ny].doormask & ~D_BROKEN))
2249.                     || ((IS_DOOR(nowtyp) || IS_DOOR(ntyp))
2250.                         && Is_rogue_level(&u.uz))
2251.                     /* mustn't pass between adjacent long worm segments,
2252.                        but can attack that way */
2253.                     || (m_at(x, ny) && m_at(nx, y) && worm_cross(x, y, nx, ny)
2254.                         && !m_at(nx, ny) && (nx != u.ux || ny != u.uy))))
2255.                 continue;
2256.             if ((!lavaok || !(flag & ALLOW_WALL)) && ntyp == LAVAWALL)
2257.                 continue;
2258.             if ((poolok || is_pool(nx, ny) == wantpool)
2259.                 && (lavaok || !is_lava(nx, ny))) {
2260.                 int dispx, dispy;
2261.                 boolean monseeu = (mon->mcansee
2262.                                    && (!Invis || perceives(mdat)));
2263.                 boolean checkobj = OBJ_AT(nx, ny);
2264. 
2265.                 /* Displacement also displaces the Elbereth/scare monster,
2266.                  * as long as you are visible.
2267.                  */
2268.                 if (Displaced && monseeu
2269.                     && mon->mux == nx && mon->muy == ny) {
2270.                     dispx = u.ux;
2271.                     dispy = u.uy;
2272.                 } else {
2273.                     dispx = nx;
2274.                     dispy = ny;
2275.                 }
2276. 
2277.                 data->info[cnt] = 0;
2278.                 if (onscary(dispx, dispy, mon)) {
2279.                     if (!(flag & ALLOW_SSM))
2280.                         continue;
2281.                     data->info[cnt] |= ALLOW_SSM;
2282.                 }
2283.                 if (u_at(nx, ny)
2284.                     || (nx == mon->mux && ny == mon->muy)) {
2285.                     if (u_at(nx, ny)) {
2286.                         /* If it's right next to you, it found you,
2287.                          * displaced or no.  We must set mux and muy
2288.                          * right now, so when we return we can tell
2289.                          * that the ALLOW_U means to attack _you_ and
2290.                          * not the image.
2291.                          */
2292.                         mon->mux = u.ux;
2293.                         mon->muy = u.uy;
2294.                     }
2295.                     if (!(flag & ALLOW_U))
2296.                         continue;
2297.                     data->info[cnt] |= ALLOW_U;
2298.                 } else {
2299.                     if (MON_AT(nx, ny)) {
2300.                         struct monst *mtmp2 = m_at(nx, ny);
2301.                         long mmflag = flag | mm_aggression(mon, mtmp2);
2302. 
2303.                         if (mmflag & ALLOW_M) {
2304.                             data->info[cnt] |= ALLOW_M;
2305.                             if (mtmp2->mtame) {
2306.                                 if (!(mmflag & ALLOW_TM))
2307.                                     continue;
2308.                                 data->info[cnt] |= ALLOW_TM;
2309.                             }
2310.                         } else {
2311.                             flag &= ~ALLOW_MDISP; /* depends upon defender */
2312.                             mmflag = flag | mm_displacement(mon, mtmp2);
2313.                             if (!(mmflag & ALLOW_MDISP))
2314.                                 continue;
2315.                             data->info[cnt] |= ALLOW_MDISP;
2316.                         }
2317.                     }
2318.                     /* Note: ALLOW_SANCT only prevents movement, not
2319.                        attack, into a temple. */
2320.                     if (svl.level.flags.has_temple
2321.                         && *in_rooms(nx, ny, TEMPLE)
2322.                         && !*in_rooms(x, y, TEMPLE)
2323.                         && in_your_sanctuary((struct monst *) 0, nx, ny)) {
2324.                         if (!(flag & ALLOW_SANCT))
2325.                             continue;
2326.                         data->info[cnt] |= ALLOW_SANCT;
2327.                     }
2328.                 }
2329.                 if (checkobj && sobj_at(CLOVE_OF_GARLIC, nx, ny)) {
2330.                     if (flag & NOGARLIC)
2331.                         continue;
2332.                     data->info[cnt] |= NOGARLIC;
2333.                 }
2334.                 if (checkobj && sobj_at(BOULDER, nx, ny)) {
2335.                     if (!(flag & ALLOW_ROCK))
2336.                         continue;
2337.                     data->info[cnt] |= ALLOW_ROCK;
2338.                 }
2339.                 if (monseeu && monlineu(mon, nx, ny)) {
2340.                     if (flag & NOTONL)
2341.                         continue;
2342.                     data->info[cnt] |= NOTONL;
2343.                 }
2344.                 /* check for diagonal tight squeeze */
2345.                 if (nx != x && ny != y && bad_rock(mdat, x, ny)
2346.                     && bad_rock(mdat, nx, y) && cant_squeeze_thru(mon))
2347.                     continue;
2348.                 /* The monster avoids a particular type of trap if it's
2349.                  * familiar with the trap type.  Pets get ALLOW_TRAPS
2350.                  * and checking is done in dogmove.c.  In either case,
2351.                  * "harmless" traps are neither avoided nor marked in info[].
2352.                  */
2353.                 if ((ttmp = t_at(nx, ny)) != 0) {
2354.                     if (ttmp->ttyp >= TRAPNUM || ttmp->ttyp == 0) {
2355.                         impossible("A monster looked at a very strange trap"
2356.                                    " of type %d.",
2357.                                    ttmp->ttyp);
2358.                             continue;
2359.                     }
2360.                     /* fixed-destination teleport trap, was used by hero */
2361.                     if (fixed_tele_trap(ttmp) && hastrack(nx, ny))
2362.                         data->info[cnt] |= ALLOW_TRAPS;
2363.                     else if (!m_harmless_trap(mon, ttmp)) {
2364.                         if (!(flag & ALLOW_TRAPS)) {
2365.                             if (mon_knows_traps(mon, ttmp->ttyp))
2366.                                 continue;
2367.                         }
2368.                         data->info[cnt] |= ALLOW_TRAPS;
2369.                     }
2370.                 }
2371.                 data->poss[cnt].x = nx;
2372.                 data->poss[cnt].y = ny;
2373.                 cnt++;
2374.             }
2375.         }
2376.     if (!cnt && wantpool && !is_pool(x, y)) {
2377.         wantpool = FALSE;
2378.         goto nexttry;
2379.     }
2380.     data->cnt = cnt;
2381.     return cnt;
2382. }
2383. 
2384. /* Part of mm_aggression that represents two-way aggression.  To avoid
2385.    having to code each case twice, this function contains those cases that
2386.    ought to happen twice, and mm_aggression will call it twice. */
2387. staticfn long
2388. mm_2way_aggression(struct monst *magr, struct monst *mdef)
2389. {
2390.     if (On_W_tower_level(&u.uz)) {
2391.         /* treat inside the Wizard's tower as if it were a separate level
2392.            from outside so when hero is inside Wizard's tower, both monsters
2393.            need to be too; when outside, the monsters need to be too */
2394.         if (In_W_tower(u.ux, u.uy, &u.uz)
2395.             ? (!In_W_tower(magr->mx, magr->my, &u.uz)
2396.                || !In_W_tower(mdef->mx, mdef->my, &u.uz))
2397.             : (In_W_tower(magr->mx, magr->my, &u.uz)
2398.                || In_W_tower(mdef->mx, mdef->my, &u.uz)))
2399.             return 0L;
2400.     }
2401.     /* liches/zombies vs things that can be zombified
2402. 
2403.        Note: avoid this on the Castle level, partly for balance reasons
2404.        (the monster-versus-monster fights clear out significant portions of
2405.        the Castle and make it easier than it should be), partly for flavor
2406.        reasons (monsters who attacked other monsters to zombify them would
2407.        have been counterattacked to death long before the hero arrived).
2408. 
2409.        Also don't include unique monsters in this, otherwise it leads to
2410.        them waking up early (e.g. because a zombie decided to attack the
2411.        Wizard of Yendor). */
2412.     if (zombie_maker(magr) && zombie_form(mdef->data) != NON_PM) {
2413.         if (magr->mgenmklev && mdef->mgenmklev)
2414.             return 0L;
2415.         if (!Is_stronghold(&u.uz)
2416.             && !unique_corpstat(magr->data) && !unique_corpstat(mdef->data))
2417.             return (ALLOW_M | ALLOW_TM);
2418.     }
2419.     return 0L;
2420. }
2421. 
2422. /* Monster against monster special attacks; for the specified monster
2423.    combinations, this allows one monster to attack another adjacent one
2424.    in the absence of Conflict.  There is no provision for targeting
2425.    other monsters; just hand to hand fighting when they happen to be
2426.    next to each other. */
2427. staticfn long
2428. mm_aggression(
2429.     struct monst *magr, /* monster that is currently deciding where to move */
2430.     struct monst *mdef) /* another monster which is next to it */
2431. {
2432.     int mndx = monsndx(magr->data);
2433. 
2434.     /* don't allow pets to fight each other */
2435.     if (magr->mtame && mdef->mtame)
2436.         return 0L;
2437. 
2438.     /* supposedly purple worms are attracted to shrieking because they
2439.        like to eat shriekers, so attack the latter when feasible */
2440.     if ((mndx == PM_PURPLE_WORM || mndx == PM_BABY_PURPLE_WORM)
2441.         && mdef->data == &mons[PM_SHRIEKER])
2442.         return ALLOW_M | ALLOW_TM;
2443.     /* Various other combinations such as dog vs cat, cat vs rat, and
2444.        elf vs orc have been suggested.  For the time being we don't
2445.        support those. */
2446.     return (mm_2way_aggression(magr, mdef) | mm_2way_aggression(mdef, magr));
2447. }
2448. 
2449. /* Monster displacing another monster out of the way */
2450. staticfn long
2451. mm_displacement(
2452.     struct monst *magr, /* monster that is currently deciding where to move */
2453.     struct monst *mdef) /* another monster which is next to it */
2454. {
2455.     struct permonst *pa = magr->data, *pd = mdef->data;
2456. 
2457.     /* if attacker can't barge through, there's nothing to do;
2458.        or if defender can barge through too and has a level at least
2459.        as high as the attacker, don't let attacker do so, otherwise
2460.        they might just end up swapping places again when defender
2461.        gets its chance to move */
2462.     if (is_displacer(pa) && (!is_displacer(pd) || magr->m_lev > mdef->m_lev)
2463.         /* no displacing grid bugs diagonally */
2464.         && !(magr->mx != mdef->mx && magr->my != mdef->my
2465.              && NODIAG(monsndx(pd)))
2466.         /* no displacing trapped monsters or multi-location longworms */
2467.         && !mdef->mtrapped && (!mdef->wormno || !count_wsegs(mdef))
2468.         /* riders can move anything; others, same size or smaller only */
2469.         && (is_rider(pa) || pa->msize >= pd->msize))
2470.         return ALLOW_MDISP;
2471.     return 0L;
2472. }
2473. 
2474. /* Is the square close enough for the monster to move or attack into? */
2475. boolean
2476. monnear(struct monst *mon, coordxy x, coordxy y)
2477. {
2478.     int distance = dist2(mon->mx, mon->my, x, y);
2479. 
2480.     if (distance == 2 && NODIAG(mon->data - mons))
2481.         return 0;
2482.     return (boolean) (distance < 3);
2483. }
2484. 
2485. /* really free dead monsters */
2486. void
2487. dmonsfree(void)
2488. {
2489.     struct monst **mtmp, *freetmp;
2490.     int count = 0;
2491.     char buf[QBUFSZ];
2492. 
2493.     buf[0] = '\0';
2494.     for (mtmp = &fmon; *mtmp; ) {
2495.         freetmp = *mtmp;
2496.         if (DEADMONSTER(freetmp) && !freetmp->isgd) {
2497.             *mtmp = freetmp->nmon;
2498.             freetmp->nmon = NULL;
2499.             dealloc_monst(freetmp);
2500.             count++;
2501.         } else
2502.             mtmp = &(freetmp->nmon);
2503.     }
2504. 
2505.     if (count != iflags.purge_monsters) {
2506.         describe_level(buf, 2);
2507.         impossible("dmonsfree: %d removed doesn't match %d pending on %s",
2508.                    count, iflags.purge_monsters, buf);
2509.     }
2510.     iflags.purge_monsters = 0;
2511. }
2512. 
2513. /* called when monster is moved to larger structure */
2514. void
2515. replmon(struct monst *mtmp, struct monst *mtmp2)
2516. {
2517.     struct obj *otmp;
2518. 
2519.     /* transfer the monster's inventory */
2520.     for (otmp = mtmp2->minvent; otmp; otmp = otmp->nobj) {
2521.         if (otmp->where != OBJ_MINVENT || otmp->ocarry != mtmp)
2522.             impossible("replmon: minvent inconsistency");
2523.         otmp->ocarry = mtmp2;
2524.     }
2525.     mtmp->minvent = 0;
2526.     /* before relmon(mtmp), because it could clear polearm.hitmon */
2527.     if (svc.context.polearm.hitmon == mtmp)
2528.         svc.context.polearm.hitmon = mtmp2;
2529. 
2530.     /* remove the old monster from the map and from `fmon' list */
2531.     relmon(mtmp, (struct monst **) 0);
2532. 
2533.     /* finish adding its replacement */
2534.     if (mtmp != u.usteed) /* don't place steed onto the map */
2535.         place_monster(mtmp2, mtmp2->mx, mtmp2->my);
2536.     if (mtmp2->wormno)      /* update level.monsters[wseg->wx][wseg->wy] */
2537.         place_wsegs(mtmp2, mtmp); /* locations to mtmp2 not mtmp. */
2538.     if (emits_light(mtmp2->data)) {
2539.         /* since this is so rare, we don't have any `mon_move_light_source' */
2540.         new_light_source(mtmp2->mx, mtmp2->my, emits_light(mtmp2->data),
2541.                          LS_MONSTER, monst_to_any(mtmp2));
2542.         /* here we rely on fact that `mtmp' hasn't actually been deleted */
2543.         del_light_source(LS_MONSTER, monst_to_any(mtmp));
2544.     }
2545.     mtmp2->nmon = fmon;
2546.     fmon = mtmp2;
2547.     if (u.ustuck == mtmp)
2548.         set_ustuck(mtmp2);
2549.     if (u.usteed == mtmp)
2550.         u.usteed = mtmp2;
2551.     if (mtmp2->isshk)
2552.         replshk(mtmp, mtmp2);
2553. 
2554.     /* discard the old monster */
2555.     dealloc_monst(mtmp);
2556. }
2557. 
2558. /* release mon from the display and the map's monster list,
2559.    maybe transfer it to one of the other monster lists */
2560. void
2561. relmon(
2562.     struct monst *mon,
2563.     struct monst **monst_list) /* &gm.migrating_mons or &gm.mydogs or null */
2564. {
2565.     if (!fmon)
2566.         panic("relmon: no fmon available.");
2567. 
2568.     /* take 'mon' off the map */
2569.     mon_leaving_level(mon);
2570. 
2571.     /* remove 'mon' from the 'fmon' list */
2572.     if (mon == fmon) {
2573.         fmon = fmon->nmon;
2574.     } else {
2575.         struct monst *mtmp;
2576. 
2577.         for (mtmp = fmon; mtmp; mtmp = mtmp->nmon)
2578.             if (mtmp->nmon == mon) {
2579.                 mtmp->nmon = mon->nmon;
2580.                 break;
2581.             }
2582.         if (!mtmp)
2583.             panic("relmon: mon not in list.");
2584.     }
2585. 
2586.     if (monst_list) {
2587.         /* insert into gm.mydogs or gm.migrating_mons */
2588.         mon->nmon = *monst_list;
2589.         *monst_list = mon;
2590.     } else {
2591.         /* orphan has no next monster */
2592.         mon->nmon = 0;
2593.     }
2594. }
2595. 
2596. void
2597. copy_mextra(struct monst *mtmp2, struct monst *mtmp1)
2598. {
2599.     if (!mtmp2 || !mtmp1 || !mtmp1->mextra)
2600.         return;
2601. 
2602.     if (!mtmp2->mextra)
2603.         mtmp2->mextra = newmextra();
2604.     if (MGIVENNAME(mtmp1)) {
2605.         new_mgivenname(mtmp2, (int) strlen(MGIVENNAME(mtmp1)) + 1);
2606.         Strcpy(MGIVENNAME(mtmp2), MGIVENNAME(mtmp1));
2607.     }
2608.     if (EGD(mtmp1)) {
2609.         if (!EGD(mtmp2))
2610.             newegd(mtmp2);
2611.         assert(has_egd(mtmp2));
2612.         *EGD(mtmp2) = *EGD(mtmp1);
2613.     }
2614.     if (EPRI(mtmp1)) {
2615.         if (!EPRI(mtmp2))
2616.             newepri(mtmp2);
2617.         assert(has_epri(mtmp2));
2618.         *EPRI(mtmp2) = *EPRI(mtmp1);
2619.     }
2620.     if (ESHK(mtmp1)) {
2621.         if (!ESHK(mtmp2))
2622.             neweshk(mtmp2);
2623.         assert(has_eshk(mtmp2));
2624.         *ESHK(mtmp2) = *ESHK(mtmp1);
2625.     }
2626.     if (EMIN(mtmp1)) {
2627.         if (!EMIN(mtmp2))
2628.             newemin(mtmp2);
2629.         assert(has_emin(mtmp2));
2630.         *EMIN(mtmp2) = *EMIN(mtmp1);
2631.     }
2632.     if (EDOG(mtmp1)) {
2633.         if (!EDOG(mtmp2))
2634.             newedog(mtmp2);
2635.         assert(has_edog(mtmp2));
2636.         *EDOG(mtmp2) = *EDOG(mtmp1);
2637.     }
2638.     if (EBONES(mtmp1)) {
2639.         if (!EBONES(mtmp2))
2640.             newebones(mtmp2);
2641.         assert(has_ebones(mtmp2));
2642.         *EBONES(mtmp2) = *EBONES(mtmp1);
2643.     }
2644.     if (has_mcorpsenm(mtmp1))
2645.         MCORPSENM(mtmp2) = MCORPSENM(mtmp1);
2646. }
2647. 
2648. void
2649. dealloc_mextra(struct monst *m)
2650. {
2651.     struct mextra *x = m->mextra;
2652. 
2653.     if (x) {
2654.         if (x->mgivenname)
2655.             free((genericptr_t) x->mgivenname), x->mgivenname = 0;
2656.         if (x->egd)
2657.             free((genericptr_t) x->egd), x->egd = 0;
2658.         if (x->epri)
2659.             free((genericptr_t) x->epri), x->epri = 0;
2660.         if (x->eshk)
2661.             free((genericptr_t) x->eshk), x->eshk = 0;
2662.         if (x->emin)
2663.             free((genericptr_t) x->emin), x->emin = 0;
2664.         if (x->edog)
2665.             free((genericptr_t) x->edog), x->edog = 0;
2666.         if (x->ebones)
2667.             free((genericptr_t) x->ebones), x->ebones = 0;
2668.         x->mcorpsenm = NON_PM; /* no allocation to release */
2669. 
2670.         free((genericptr_t) x);
2671.         m->mextra = (struct mextra *) 0;
2672.     }
2673. }
2674. 
2675. void
2676. dealloc_monst(struct monst *mon)
2677. {
2678.     char buf[QBUFSZ];
2679. 
2680.     buf[0] = '\0';
2681.     if (mon->nmon) {
2682.         describe_level(buf, 2);
2683.         panic("dealloc_monst with nmon on %s", buf);
2684.     }
2685.     if (mon->mextra)
2686.         dealloc_mextra(mon);
2687.     /* clear out of date information contained in the about-to-become
2688.        stale memory; see dealloc_obj() */
2689.     *mon = cg.zeromonst;
2690.     free((genericptr_t) mon);
2691. }
2692. 
2693. /* 'mon' is being removed from level due to migration [relmon from keepdogs
2694.    or migrate_to_level] or due to death [m_detach from mondead or mongone] */
2695. staticfn void
2696. mon_leaving_level(struct monst *mon)
2697. {
2698.     coordxy mx = mon->mx, my = mon->my;
2699.     boolean onmap = (isok(mx, my) && svl.level.monsters[mx][my] == mon);
2700. 
2701.     /* to prevent an infinite relobj-flooreffects-hmon-killed loop */
2702.     mon->mtrapped = 0;
2703.     unstuck(mon); /* mon is not swallowing or holding you nor held by you */
2704. 
2705.     /* vault guard might be at <0,0> */
2706.     if (onmap || mon == svl.level.monsters[0][0]) {
2707.         if (mon->wormno)
2708.             remove_worm(mon);
2709.         else
2710.             remove_monster(mx, my);
2711. 
2712. #if 0   /* mustn't do this; too many places assume that the stale
2713.          * monst->mx,my values are still valid */
2714.         mon->mx = mon->my = 0; /* off normal map */
2715. #endif
2716.     }
2717.     if (onmap) {
2718.         mon->mundetected = 0; /* for migration; doesn't matter for death */
2719.         /* unhide mimic in case its shape has been blocking line of sight
2720.            or it is accompanying the hero to another level */
2721.         if (M_AP_TYPE(mon) != M_AP_NOTHING && M_AP_TYPE(mon) != M_AP_MONSTER)
2722.             seemimic(mon);
2723.         /* if mon is pinned by a boulder, removing mon lets boulder drop */
2724.         fill_pit(mx, my);
2725.         newsym(mx, my);
2726.     }
2727.     /* if mon is a remembered target, forget it since it isn't here anymore */
2728.     if (mon == svc.context.polearm.hitmon)
2729.         svc.context.polearm.hitmon = (struct monst *) 0;
2730. }
2731. 
2732. /* 'mtmp' is going away; remove effects of mtmp from other data structures */
2733. staticfn void
2734. m_detach(
2735.     struct monst *mtmp,
2736.     struct permonst *mptr, /* reflects mtmp->data _prior_ to mtmp's death */
2737.     boolean due_to_death)
2738. {
2739.     coordxy mx = mtmp->mx, my = mtmp->my;
2740. 
2741.     if (mtmp->mleashed)
2742.         m_unleash(mtmp, FALSE);
2743. 
2744.     if (mx > 0 && emits_light(mptr))
2745.         del_light_source(LS_MONSTER, monst_to_any(mtmp));
2746. 
2747.     /*
2748.      * Take mtmp off map but not out of fmon list yet (dmonsfree does that).
2749.      *
2750.      * Sequencing issue:  mtmp's inventory should be dropped before taking
2751.      * it off the map but if that includes a boulder and mtmp is at a pit
2752.      * location, dropping minvent ought to be deferred until its corpse
2753.      * gets placed.  We compromise and just make sure mtmp is off the map
2754.      * before dropping its former belongings.
2755.      */
2756.     mon_leaving_level(mtmp);
2757. 
2758.     mtmp->mhp = 0; /* simplify some tests: force mhp to 0 */
2759.     /* death handling for the Wizard needs to take place even if he is
2760.        leaving the dungeon alive rather than dying */
2761.     if (mtmp->iswiz)
2762.         wizdeadorgone();
2763.     /* foodead() might give quest feedback for foo having died; skip that
2764.        if we're called for mongone() rather than mondead(); saving bones
2765.        or wizard mode genocide of "*" can result in special monsters going
2766.        away without having been killed */
2767.     if (due_to_death) {
2768.         if (mtmp->data->msound == MS_NEMESIS) {
2769.             nemdead();
2770.             /* The Archeologist, Caveman, and Priest quest texts describe
2771.                the nemesis's body creating noxious fumes/gas when killed. */
2772.             if (stinky_nemesis(mtmp))
2773.                 nemesis_stinks(mx, my);
2774.         }
2775.         if (mtmp->data->msound == MS_LEADER)
2776.             leaddead();
2777.         /* release (drop onto map) all objects carried by mtmp; assumes that
2778.            mtmp->mx,my contains the appropriate location */
2779.         relobj(mtmp, 1, FALSE); /* drop mtmp->minvent, issue newsym(mx,my) */
2780.     }
2781. 
2782.     if (mtmp->m_id == gs.stealmid)
2783.         thiefdead(); /* reset theft-in-progress data */
2784.     if (mtmp->isshk)
2785.         shkgone(mtmp);
2786.     if (mtmp->wormno)
2787.         wormgone(mtmp);
2788.     if (In_endgame(&u.uz))
2789.         mtmp->mstate |= MON_ENDGAME_FREE;
2790. 
2791.     if ((mtmp->mstate & MON_DETACH) != 0) {
2792.         impossible("m_detach: %s is already detached?",
2793.                    minimal_monnam(mtmp, FALSE));
2794.     } else {
2795.         mtmp->mstate |= MON_DETACH;
2796.         iflags.purge_monsters++;
2797.     }
2798. 
2799.     /* hero is thrown from his steed when it dies or gets genocided */
2800.     if (mtmp == u.usteed)
2801.         dismount_steed(DISMOUNT_GENERIC);
2802.     return;
2803. }
2804. 
2805. /* give a life-saved monster a reasonable mhpmax value in case it has
2806.    been the victim of excessive life draining */
2807. staticfn void
2808. set_mon_min_mhpmax(
2809.     struct monst *mon,
2810.     int minimum_mhpmax) /* monster life-saving has traditionally used 10 */
2811. {
2812.     /* can't be less than m_lev+1 (if we just used m_lev itself, level 0
2813.        monsters would end up allowing a minimum of 0); since life draining
2814.        reduces m_lev, this usually won't give the monster much of a boost */
2815.     if (mon->mhpmax < (int) mon->m_lev + 1)
2816.         mon->mhpmax = (int) mon->m_lev + 1;
2817.     /* caller can specify an alternate minimum; we'll honor it iff it is
2818.        greater than m_lev+1; the traditional arbitrary value of 10 always
2819.        gives level 0 and level 1 monsters a boost and has a moderate
2820.        chance of doing so for level 2, a tiny chance for levels 3..9 */
2821.     if (mon->mhpmax < minimum_mhpmax)
2822.         mon->mhpmax = minimum_mhpmax;
2823. }
2824. 
2825. /* find the worn amulet of life saving which will save a monster */
2826. struct obj *
2827. mlifesaver(struct monst *mon)
2828. {
2829.     if (!nonliving(mon->data) || is_vampshifter(mon)) {
2830.         struct obj *otmp = which_armor(mon, W_AMUL);
2831. 
2832.         if (otmp && otmp->otyp == AMULET_OF_LIFE_SAVING)
2833.             return otmp;
2834.     }
2835.     return (struct obj *) 0;
2836. }
2837. 
2838. staticfn void
2839. lifesaved_monster(struct monst *mtmp)
2840. {
2841.     boolean surviver;
2842.     struct obj *lifesave = mlifesaver(mtmp);
2843. 
2844.     if (lifesave) {
2845.         /* not canseemon; amulets are on the head, so you don't want
2846.          * to show this for a long worm with only a tail visible.
2847.          * Nor do you check invisibility, because glowing and
2848.          * disintegrating amulets are always visible. */
2849.         if (cansee(mtmp->mx, mtmp->my)) {
2850.             pline("But wait...");
2851.             pline("%s medallion begins to glow!", s_suffix(Monnam(mtmp)));
2852.             makeknown(AMULET_OF_LIFE_SAVING);
2853.             /* amulet is visible, but monster might not be */
2854.             if (canseemon(mtmp)) {
2855.                 if (attacktype(mtmp->data, AT_EXPL)
2856.                     || attacktype(mtmp->data, AT_BOOM))
2857.                     pline("%s reconstitutes!", Monnam(mtmp));
2858.                 else
2859.                     pline("%s looks much better!", Monnam(mtmp));
2860.             }
2861.             pline_The("medallion crumbles to dust!");
2862.         }
2863.         m_useup(mtmp, lifesave);
2864.         /* equip replacement amulet, if any, on next move */
2865.         check_gear_next_turn(mtmp);
2866. 
2867.         surviver = !(svm.mvitals[monsndx(mtmp->data)].mvflags & G_GENOD);
2868.         mtmp->mcanmove = 1;
2869.         mtmp->mfrozen = 0;
2870.         if (mtmp->mtame && !mtmp->isminion) {
2871.             wary_dog(mtmp, !surviver);
2872.         }
2873.         set_mon_min_mhpmax(mtmp, 10); /* mtmp->mhpmax=max(mtmp->m_lev+1,10) */
2874.         mtmp->mhp = mtmp->mhpmax;
2875. 
2876.         if (!surviver) {
2877.             /* genocided monster can't be life-saved */
2878.             if (cansee(mtmp->mx, mtmp->my))
2879.                 pline("Unfortunately, %s is still genocided...",
2880.                       mon_nam(mtmp));
2881.             mtmp->mhp = 0;
2882.         }
2883.     }
2884. }
2885. 
2886. /* when a shape-shifted vampire is killed, it reverts to base form instead
2887.    of dying; returns True if mtmp successfully revives, False otherwise;
2888.    "successfully revived" vampire might be killed by a booby trapped door */
2889. staticfn boolean
2890. vamprises(struct monst *mtmp)
2891. {
2892.     int mndx = mtmp->cham;
2893. 
2894.     /*
2895.      * Protection from shape changers protects against this because
2896.      * the vampire will always be in normal form instead of shifted.
2897.      * So there's no need to check for that attribute being active.
2898.      */
2899.     if (ismnum(mndx) && mndx != monsndx(mtmp->data)
2900.         && !(svm.mvitals[mndx].mvflags & G_GENOD)) {
2901.         char action[BUFSZ];
2902.         /* alternate message phrasing for some monster types */
2903.         boolean spec_mon = (nonliving(mtmp->data)
2904.                             || noncorporeal(mtmp->data)
2905.                             || amorphous(mtmp->data)),
2906.                 spec_death = (gd.disintegested /* disintegrated/digested */
2907.                               || noncorporeal(mtmp->data)
2908.                               || amorphous(mtmp->data));
2909.         coordxy x = mtmp->mx, y = mtmp->my;
2910. 
2911.         /* construct a 'before' argument to pass to pline(); this used
2912.            to construct a dynamic format string but that's overkill */
2913.         Snprintf(action, sizeof action, "%s%s %s%s and rises as",
2914.                  Unaware ? "you dream that " : "",
2915.                  x_monnam(mtmp, ARTICLE_THE,
2916.                           spec_mon ? (char *) 0 : "seemingly dead",
2917.                           (SUPPRESS_INVISIBLE | AUGMENT_IT), FALSE),
2918.                  Unaware ? "" : "suddenly ",
2919.                  spec_death ? "reconstitutes" : "transforms");
2920.         mtmp->mcanmove = 1;
2921.         mtmp->mfrozen = 0;
2922.         set_mon_min_mhpmax(mtmp, 10); /* mtmp->mhpmax=max(m_lev+1,10) */
2923.         mtmp->mhp = mtmp->mhpmax;
2924.         /* mtmp==u.ustuck can happen if previously a fog cloud or if
2925.            poly'd hero is hugging a vampire bat */
2926.         if (mtmp == u.ustuck) {
2927.             if (u.uswallow)
2928.                 expels(mtmp, mtmp->data, FALSE);
2929.             else
2930.                 uunstick();
2931.         }
2932. 
2933.         if (!newcham(mtmp, &mons[mndx], NO_NC_FLAGS))
2934.             return !DEADMONSTER(mtmp);
2935.         mtmp->cham = (mtmp->data == &mons[mndx]) ? NON_PM : mndx;
2936. 
2937.         if (canspotmon(mtmp)) {
2938.             /* 3.6.0 used a_monnam(mtmp); that was weird if mtmp was
2939.                named: "Dracula suddenly transforms and rises as Dracula";
2940.                3.6.1 used mtmp->data->mname; that ignored hallucination */
2941.             pline_mon(mtmp, "%s %s!", upstart(action),
2942.                       x_monnam(mtmp, ARTICLE_A, (char *) 0,
2943.                            (SUPPRESS_NAME | SUPPRESS_IT | SUPPRESS_INVISIBLE),
2944.                                FALSE));
2945.             gv.vamp_rise_msg = TRUE;
2946.         }
2947.         /* revived vampire is in normal shape, so can't be amorphous; if on
2948.            a closed door spot, destroy the door and if trapped, blow it up */
2949.         if (closed_door(x, y)) {
2950.             static const char
2951.                 door_smashed[] = "a door being smashed",
2952.                 door_go_boom[] = "a door exploding";
2953.             struct rm *door = &levl[x][y];
2954.             boolean trapped = (door->doormask & D_TRAPPED) != 0,
2955.                     seeit = cansee(x, y);
2956. 
2957.             set_msg_xy(x, y); /* You()/pline() will reset this */
2958.             if (!seeit)
2959.                 You_hear("%s.", trapped ? "an explosion" : door_smashed);
2960.             else if (!canspotmon(mtmp))
2961.                 You_see("%s.", trapped ? door_go_boom : door_smashed);
2962.             else if (!Unaware)
2963.                 pline_The("door is smashed%s",
2964.                           trapped ? " and it explodes!" : ".");
2965.             set_msg_xy(0, 0); /* in case none of the messages was delivered */
2966. 
2967.             door->doormask = D_NODOOR;
2968.             recalc_block_point(x, y);
2969.             if (trapped) {
2970.                 boolean trap_killed, save_verbose = flags.verbose;
2971. 
2972.                 flags.verbose = FALSE; /* suppress mb_trapped() messages
2973.                                         * (that makes the 'seeit' arg moot) */
2974.                 trap_killed = mb_trapped(mtmp, seeit);
2975.                 flags.verbose = save_verbose;
2976.                 /* if the booby trap has killed the monster, mondied() will
2977.                    have been called but no message about its death given yet;
2978.                    mtmp was a vampire so use unconditional "destroyed" */
2979.                 if (trap_killed && canspotmon(mtmp) && !Unaware)
2980.                     pline_mon(mtmp, "%s is destroyed!", Monnam(mtmp));
2981.             }
2982.         }
2983.         newsym(x, y);
2984.         return TRUE;
2985.     }
2986.     return FALSE;
2987. }
2988. 
2989. /* specific combination of x_monnam flags for livelogging; show what was
2990.    actually killed even when unseen or hallucinated to be something else */
2991. #define livelog_mon_nam(mtmp) \
2992.     x_monnam(mtmp, ARTICLE_THE, (char *) 0, EXACT_NAME, FALSE)
2993. 
2994. /* when a mon has died, maybe record an achievement or issue livelog message;
2995.    moved into separate routine to unclutter mondead() */
2996. staticfn void
2997. logdeadmon(struct monst *mtmp, int mndx)
2998. {
2999.     int howmany = svm.mvitals[mndx].died;
3000. 
3001.     if (mndx == PM_MEDUSA && howmany == 1) {
3002.         record_achievement(ACH_MEDU); /* also generates a livelog event */
3003.     } else if ((unique_corpstat(mtmp->data)
3004.                 && (mndx != PM_HIGH_CLERIC || !mtmp->mrevived))
3005.                || (mtmp->isshk && !mtmp->mrevived)) {
3006.         char shkdetail[QBUFSZ];
3007.         const char *mkilled;
3008.         boolean herodidit = !svc.context.mon_moving;
3009. 
3010.         /*
3011.          * livelog event; unique_corpstat() includes the Wizard and
3012.          * any High Priest even though they aren't actually unique.
3013.          *
3014.          * Shopkeeper kills are logged, but only the first time per
3015.          * shopkeeper, since their shared kill counter wouldn't work
3016.          * for this purpose (and it wouldn't account for polymorphed
3017.          * shopkeepers either).
3018.          */
3019.         shkdetail[0] = '\0';
3020.         if (mtmp->isshk) {
3021.             howmany = 1;
3022.             /* ", the <shoptype> proprietor" needs a trailing comma for
3023.                the alternate phrasing "<shk>, shkdetails, has been killed"
3024.                when hero isn't directly responsible */
3025.             Snprintf(shkdetail, sizeof shkdetail, ", the %s %s%s",
3026.                      shtypes[ESHK(mtmp)->shoptype - SHOPBASE].name,
3027.                      /* in case shk name doesn't include Mr or Ms honorific */
3028.                      mtmp->female ? "proprietrix" : "proprietor",
3029.                      herodidit ? "" : ",");
3030.         } else if (mndx == PM_HIGH_CLERIC) {
3031.             /* the high priest[ess] monster is not unique; we know that
3032.                this is the first death for this particular high priest
3033.                (because of the !mtmp->mrevived test above) */
3034.             howmany = 1;
3035.         }
3036. 
3037.         /* killing a unique more than once doesn't get logged every time;
3038.            the Wizard and the Riders can be killed more than once
3039.            "naturally", others require deliberate player action such as
3040.            use of undead turning to revive a corpse or petrification plus
3041.            stone-to-flesh to create and revive a statue */
3042.         if (howmany <= 3 || howmany == 5 || howmany == 10 || howmany == 25
3043.             || (howmany % 50) == 0) { /* 50, 100, 150, 200, 250 */
3044.             char xtra[40]; /* space for " (Nth time)" when N > 1 */
3045.             long llevent_type = LL_UMONST;
3046. 
3047.             /* the first kill of any unique monster is a major event;
3048.                all kills of the Wizard and the Riders are major when
3049.                they're logged but they still don't get logged every time */
3050.             if (howmany == 1 || mtmp->iswiz || is_rider(mtmp->data))
3051.                 llevent_type |= LL_ACHIEVE;
3052.             xtra[0] = '\0';
3053.             if (howmany > 1) /* "(2nd time)" or "(50th time)" */
3054.                 Sprintf(xtra, " (%d%s time)", howmany, ordin(howmany));
3055. 
3056.             mkilled = nonliving(mtmp->data) ? "destroyed" : "killed";
3057.             /* hero is responsible: "killed <monst>" */
3058.             if (herodidit)
3059.                 livelog_printf(llevent_type, "%s %s%s%s",
3060.                                mkilled,
3061.                                livelog_mon_nam(mtmp), shkdetail, xtra);
3062.             else /* trap, pet, conflict:  "<monst> has been killed" */
3063.                 livelog_printf(llevent_type, "%s%s has been %s%s",
3064.                                livelog_mon_nam(mtmp), shkdetail,
3065.                                mkilled, xtra);
3066.         }
3067.     }
3068. }
3069. 
3070. /* anger all the quest guards on the level */
3071. staticfn void
3072. anger_quest_guardians(struct monst *mtmp)
3073. {
3074.     if (mtmp->data == &mons[gu.urole.guardnum])
3075.         setmangry(mtmp, TRUE);
3076. }
3077. 
3078. /* monster 'mtmp' has died; maybe life-save, otherwise unshapeshift and
3079.    update vanquished stats and update map */
3080. void
3081. mondead(struct monst *mtmp)
3082. {
3083.     struct permonst *mptr;
3084.     boolean be_sad;
3085.     int mndx;
3086. 
3087.     /* potential pet message; always clear global flag */
3088.     be_sad = iflags.sad_feeling;
3089.     iflags.sad_feeling = FALSE;
3090. 
3091.     mtmp->mhp = 0; /* in case caller hasn't done this */
3092.     lifesaved_monster(mtmp);
3093.     if (!DEADMONSTER(mtmp))
3094.         return;
3095. 
3096.     /* vampire in bat/fog/wolf form reverts to vampire instead of dying */
3097.     if (is_vampshifter(mtmp) && vamprises(mtmp))
3098.         return;
3099. 
3100.     if (be_sad)
3101.         You("have a sad feeling for a moment, then it passes.");
3102. 
3103.     if (mtmp->data == &mons[PM_STEAM_VORTEX])
3104.         create_gas_cloud(mtmp->mx, mtmp->my, rn2(10) + 5, 0); /* harmless */
3105. 
3106.     /* dead vault guard is actually kept at coordinate <0,0> until
3107.        his temporary corridor to/from the vault has been removed;
3108.        need to do this after life-saving and before m_detach() */
3109.     if (mtmp->isgd && !grddead(mtmp))
3110.         return;
3111. 
3112.     mptr = mtmp->data; /* save this for m_detach() */
3113.     /* restore chameleon, lycanthropes to true form at death */
3114.     if (ismnum(mtmp->cham)) {
3115.         set_mon_data(mtmp, &mons[mtmp->cham]);
3116.         mtmp->cham = NON_PM;
3117.     } else if (mtmp->data == &mons[PM_WEREJACKAL])
3118.         set_mon_data(mtmp, &mons[PM_HUMAN_WEREJACKAL]);
3119.     else if (mtmp->data == &mons[PM_WEREWOLF])
3120.         set_mon_data(mtmp, &mons[PM_HUMAN_WEREWOLF]);
3121.     else if (mtmp->data == &mons[PM_WERERAT])
3122.         set_mon_data(mtmp, &mons[PM_HUMAN_WERERAT]);
3123. 
3124.     /*
3125.      * svm.mvitals[].died does double duty as total number of dead monsters
3126.      * and as experience factor for the player killing more monsters.
3127.      * this means that a dragon dying by other means reduces the
3128.      * experience the player gets for killing a dragon directly; this
3129.      * is probably not too bad, since the player likely finagled the
3130.      * first dead dragon via ring of conflict or pets, and extinguishing
3131.      * based on only player kills probably opens more avenues of abuse
3132.      * for rings of conflict and such.
3133.      */
3134.     mndx = monsndx(mtmp->data);
3135.     if (svm.mvitals[mndx].died < 255)
3136.         svm.mvitals[mndx].died++;
3137. 
3138.     /* if it's a (possibly polymorphed) quest leader, mark him as dead */
3139.     if (mtmp->m_id == svq.quest_status.leader_m_id)
3140.         svq.quest_status.leader_is_dead = TRUE;
3141. #ifdef MAIL_STRUCTURES
3142.     /* if the mail daemon dies, no more mail delivery.  -3. */
3143.     if (mndx == PM_MAIL_DAEMON)
3144.         svm.mvitals[mndx].mvflags |= G_GENOD;
3145. #endif
3146. 
3147.     if (mtmp->data->mlet == S_KOP) {
3148.         stairway *stway = stairway_find_type_dir(FALSE, FALSE);
3149. 
3150.         /* Dead Kops may come back. */
3151.         switch (rnd(5)) {
3152.         case 1: /* returns near the stairs */
3153.             if (stway) {
3154.                 (void) makemon(mtmp->data, stway->sx, stway->sy, NO_MM_FLAGS);
3155.                 break;
3156.             }
3157.             FALLTHROUGH;
3158.             /* FALLTHRU */
3159.         case 2: /* randomly */
3160.             (void) makemon(mtmp->data, 0, 0, NO_MM_FLAGS);
3161.             break;
3162.         default:
3163.             break;
3164.         }
3165.     }
3166. 
3167.     /* achievement and/or livelog */
3168.     logdeadmon(mtmp, mndx);
3169. 
3170.     if (glyph_is_invisible(levl[mtmp->mx][mtmp->my].glyph))
3171.         unmap_object(mtmp->mx, mtmp->my);
3172. 
3173.     /* remove 'mtmp' from play; it will stay on the fmon list until end of
3174.        current move, then dmonsfree() will get rid of it */
3175.     m_detach(mtmp, mptr, TRUE);
3176.     return;
3177. }
3178. 
3179. /* TRUE if corpse might be dropped, magr may die if mon was swallowed */
3180. boolean
3181. corpse_chance(
3182.     struct monst *mon,
3183.     struct monst *magr,    /* killer, if swallowed */
3184.     boolean was_swallowed) /* digestion */
3185. {
3186.     struct permonst *mdat = mon->data;
3187.     int i, tmp;
3188. 
3189.     if (!magr && gm.mswallower && attacktype(gm.mswallower->data, AT_ENGL))
3190.         magr = gm.mswallower, was_swallowed = TRUE; /* for gas spore boom */
3191. 
3192.     if (mdat == &mons[PM_VLAD_THE_IMPALER] || mdat->mlet == S_LICH) {
3193.         if (cansee(mon->mx, mon->my) && !was_swallowed)
3194.             pline_mon(mon, "%s body crumbles into dust.",
3195.                       s_suffix(Monnam(mon)));
3196.         return FALSE;
3197.     }
3198. 
3199.     /* Gas spores always explode upon death */
3200.     for (i = 0; i < NATTK; i++) {
3201.         if (mdat->mattk[i].aatyp == AT_BOOM) {
3202.             if (mdat->mattk[i].damn)
3203.                 tmp = d((int) mdat->mattk[i].damn, (int) mdat->mattk[i].damd);
3204.             else if (mdat->mattk[i].damd)
3205.                 tmp = d((int) mdat->mlevel + 1, (int) mdat->mattk[i].damd);
3206.             else
3207.                 tmp = 0;
3208. 
3209.             if (was_swallowed && magr) {
3210.                 /* mdef is a gas spore (AT_BOOM) that is exploding inside an
3211.                    engulfer; suppress usual explosion since it's contained */
3212.                 if (magr == &gy.youmonst) {
3213.                     There("is an explosion in your %s!", body_part(STOMACH));
3214.                     Sprintf(svk.killer.name, "%s explosion",
3215.                             s_suffix(pmname(mdat, Mgender(mon))));
3216.                     losehp(Maybe_Half_Phys(tmp), svk.killer.name,
3217.                            KILLED_BY_AN);
3218.                 } else {
3219.                     You_hear("an explosion.");
3220.                     magr->mhp -= tmp;
3221.                     if (DEADMONSTER(magr))
3222.                         mondied(magr);
3223.                     if (DEADMONSTER(magr)) { /* maybe lifesaved */
3224.                         if (canspotmon(magr))
3225.                             pline_mon(magr, "%s rips open!", Monnam(magr));
3226.                     } else if (canseemon(magr))
3227.                         pline_mon(magr, "%s seems to have indigestion.",
3228.                                   Monnam(magr));
3229.                 }
3230.                 return FALSE;
3231.             }
3232. 
3233.             mon_explodes(mon, &mdat->mattk[i]);
3234.             return FALSE;
3235.         }
3236.     }
3237. 
3238.     /* must duplicate this below check in xkilled() since it results in
3239.      * creating no objects as well as no corpse
3240.      */
3241.     if (LEVEL_SPECIFIC_NOCORPSE(mdat))
3242.         return FALSE;
3243. 
3244.     if (((bigmonst(mdat) || mdat == &mons[PM_LIZARD]) && !mon->mcloned)
3245.         || is_golem(mdat) || is_mplayer(mdat) || is_rider(mdat) || mon->isshk)
3246.         return TRUE;
3247.     tmp = 2 + ((mdat->geno & G_FREQ) < 2) + verysmall(mdat);
3248.     return (boolean) !rn2(tmp);
3249. }
3250. 
3251. /* drop (perhaps) a cadaver and remove monster */
3252. void
3253. mondied(struct monst *mdef)
3254. {
3255.     mondead(mdef);
3256.     if (!DEADMONSTER(mdef))
3257.         return; /* lifesaved */
3258. 
3259.     /* this assumes that the dead monster's map coordinates remain accurate */
3260.     if (corpse_chance(mdef, (struct monst *) 0, FALSE)
3261.         && (accessible(mdef->mx, mdef->my) || is_pool(mdef->mx, mdef->my)))
3262.         (void) make_corpse(mdef, CORPSTAT_NONE);
3263. }
3264. 
3265. /* monster disappears, not dies */
3266. void
3267. mongone(struct monst *mdef)
3268. {
3269.     mdef->mhp = 0; /* can skip some inventory bookkeeping */
3270. 
3271.     /* dead vault guard is actually kept at coordinate <0,0> until
3272.        his temporary corridor to/from the vault has been removed */
3273.     if (mdef->isgd && !grddead(mdef))
3274.         return;
3275.     /* stuck to you? release */
3276.     unstuck(mdef);
3277.     /* drop special items like the Amulet so that a dismissed Kop or nurse
3278.        can't remove them from the game */
3279.     mdrop_special_objs(mdef);
3280.     /* release rest of monster's inventory--it is removed from game */
3281.     discard_minvent(mdef, FALSE);
3282.     m_detach(mdef, mdef->data, FALSE);
3283. }
3284. 
3285. /* drop a statue or rock and remove monster */
3286. void
3287. monstone(struct monst *mdef)
3288. {
3289.     struct obj *otmp, *obj, *oldminvent;
3290.     coordxy x = mdef->mx, y = mdef->my;
3291.     boolean wasinside = FALSE;
3292. 
3293.     /* vampshifter reverts to vampire;
3294.        3.6.3: also used to unshift shape-changed sandestin */
3295.     if (!vamp_stone(mdef))
3296.         return;
3297. 
3298.     /* we have to make the statue before calling mondead, to be able to
3299.      * put inventory in it, and we have to check for lifesaving before
3300.      * making the statue....
3301.      */
3302.     mdef->mhp = 0; /* in case caller hasn't done this */
3303.     lifesaved_monster(mdef);
3304.     if (!DEADMONSTER(mdef))
3305.         return;
3306. 
3307.     mdef->mtrapped = 0; /* (see m_detach) */
3308. 
3309.     if ((int) mdef->data->msize > MZ_TINY
3310.         || !rn2(2 + ((int) (mdef->data->geno & G_FREQ) > 2))) {
3311.         unsigned corpstatflags = CORPSTAT_NONE;
3312. 
3313.         oldminvent = 0;
3314.         /* some objects may end up outside the statue */
3315.         while ((obj = mdef->minvent) != 0) {
3316.             extract_from_minvent(mdef, obj, TRUE, TRUE);
3317.             if (obj->otyp == BOULDER
3318. #if 0 /* monsters don't carry statues */
3319.                 ||  (obj->otyp == STATUE
3320.                      && mons[obj->corpsenm].msize >= mdef->data->msize)
3321. #endif
3322.                 /* invocation tools resist even with 0% resistance */
3323.                 || obj_resists(obj, 0, 0)) {
3324.                 if (flooreffects(obj, x, y, "fall"))
3325.                     continue;
3326.                 place_object(obj, x, y);
3327.             } else {
3328.                 if (obj->lamplit)
3329.                     end_burn(obj, TRUE);
3330.                 obj->nobj = oldminvent;
3331.                 oldminvent = obj;
3332.             }
3333.         }
3334.         /* defer statue creation until after inventory removal
3335.            so that saved monster traits won't retain any stale
3336.            item-conferred attributes */
3337.         if (mdef->female)
3338.             corpstatflags |= CORPSTAT_FEMALE;
3339.         else if (!is_neuter(mdef->data))
3340.             corpstatflags |= CORPSTAT_MALE;
3341.         /* Archeologists should not break unique statues */
3342.         if (mdef->data->geno & G_UNIQ)
3343.             corpstatflags |= CORPSTAT_HISTORIC;
3344.         otmp = mkcorpstat(STATUE, mdef, mdef->data, x, y, corpstatflags);
3345.         if (has_mgivenname(mdef))
3346.             otmp = oname(otmp, MGIVENNAME(mdef), ONAME_NO_FLAGS);
3347.         while ((obj = oldminvent) != 0) {
3348.             oldminvent = obj->nobj;
3349.             obj->nobj = 0; /* avoid merged-> obfree-> dealloc_obj-> panic */
3350.             (void) add_to_container(otmp, obj);
3351.         }
3352.         otmp->owt = weight(otmp);
3353.     } else
3354.         otmp = mksobj_at(ROCK, x, y, TRUE, FALSE);
3355. 
3356.     stackobj(otmp);
3357.     /* mondead() already does this, but we must do it before the newsym */
3358.     if (glyph_is_invisible(levl[x][y].glyph))
3359.         unmap_object(x, y);
3360.     if (cansee(x, y))
3361.         newsym(x, y);
3362.     /* we don't currently trap the hero in the statue in this case but we
3363.        could */
3364.     if (engulfing_u(mdef))
3365.         wasinside = TRUE;
3366.     mondead(mdef);
3367.     if (wasinside) {
3368.         if (digests(mdef->data))
3369.             You("%s through an opening in the new %s.",
3370.                 u_locomotion("jump"), xname(otmp));
3371.     }
3372.     return;
3373. }
3374. 
3375. /* another monster has killed the monster mdef */
3376. void
3377. monkilled(
3378.     struct monst *mdef,
3379.     const char *fltxt,
3380.     int how)
3381. {
3382.     struct permonst *mptr = mdef->data;
3383. 
3384.     if (fltxt && (mdef->wormno ? worm_known(mdef)
3385.                                : cansee(mdef->mx, mdef->my)))
3386.         pline_mon(mdef, "%s is %s%s%s!", Monnam(mdef),
3387.               nonliving(mptr) ? "destroyed" : "killed",
3388.               *fltxt ? " by the " : "", fltxt);
3389.     else
3390.         /* sad feeling is deferred until after potential life-saving */
3391.         iflags.sad_feeling = mdef->mtame ? TRUE : FALSE;
3392. 
3393.     /* no corpse if digested or disintegrated or flammable golem burnt up;
3394.        no corpse for a paper golem means no scrolls; golems that rust or
3395.        rot completely are described as "falling to pieces" so they do
3396.        leave a corpse (which means staves for wood golem, leather armor for
3397.        leather golem, iron chains for iron golem, not a regular corpse) */
3398.     gd.disintegested = (how == AD_DGST || how == -AD_RBRE
3399.                        || (how == AD_FIRE && completelyburns(mptr)));
3400.     if (gd.disintegested)
3401.         mondead(mdef); /* never leaves a corpse */
3402.     else
3403.         mondied(mdef); /* calls mondead() and maybe leaves a corpse */
3404. 
3405.     if (!DEADMONSTER(mdef))
3406.         return; /* life-saved */
3407.     /* extra message if pet golem is completely destroyed;
3408.        if not visible, this will follow "you have a sad feeling" */
3409.     if (mdef->mtame) {
3410.         const char *rxt = (how == AD_FIRE && completelyburns(mptr)) ? "roast"
3411.                           : (how == AD_RUST && completelyrusts(mptr)) ? "rust"
3412.                             : (how == AD_DCAY && completelyrots(mptr)) ? "rot"
3413.                               :  0;
3414.         if (rxt)
3415.             pline("May %s %s in peace.", noit_mon_nam(mdef), rxt);
3416.     }
3417.     return;
3418. }
3419. 
3420. void
3421. set_ustuck(struct monst *mtmp)
3422. {
3423.     if (iflags.sanity_check || iflags.debug_fuzzer) {
3424.         if (mtmp && !m_next2u(mtmp))
3425.             impossible("Sticking to %s at distu %d?",
3426.                        mon_nam(mtmp), mdistu(mtmp));
3427.     }
3428. 
3429.     disp.botl = TRUE;
3430.     u.ustuck = mtmp;
3431.     if (!u.ustuck) {
3432.         u.uswallow = 0;
3433.         u.uswldtim = 0;
3434.     }
3435. }
3436. 
3437. void
3438. unstuck(struct monst *mtmp)
3439. {
3440.     if (u.ustuck == mtmp) {
3441.         struct permonst *ptr = mtmp->data;
3442.         unsigned swallowed = u.uswallow;
3443. 
3444.         /* do this first so that docrt()'s botl update is accurate;
3445.            clears u.uswallow as well as setting u.ustuck to Null */
3446.         set_ustuck((struct monst *) 0);
3447. 
3448.         if (swallowed) {
3449.             gm.mswallower = (struct monst *) 0;
3450.             u.ux = mtmp->mx;
3451.             u.uy = mtmp->my;
3452.             if (Punished && uchain->where != OBJ_FLOOR)
3453.                 placebc();
3454.             gv.vision_full_recalc = 1;
3455.             docrt();
3456.         }
3457. 
3458.         /* prevent holder/engulfer from immediately re-holding/re-engulfing
3459.            [note: this call to unstuck() might be because u.ustuck has just
3460.            changed shape and doesn't have a holding attack any more, hence
3461.            don't set mspec_used unconditionally] */
3462.         if (!mtmp->mspec_used && (dmgtype(ptr, AD_STCK)
3463.                                   || attacktype(ptr, AT_ENGL)
3464.                                   || attacktype(ptr, AT_HUGS)))
3465.             mtmp->mspec_used = rnd(2);
3466.     }
3467. }
3468. 
3469. void
3470. killed(struct monst *mtmp)
3471. {
3472.     xkilled(mtmp, XKILL_GIVEMSG);
3473. }
3474. 
3475. /* the player has killed the monster mtmp */
3476. void
3477. xkilled(
3478.     struct monst *mtmp,
3479.     int xkill_flags) /* 1: suppress mesg, 2: suppress corpse, 4: pacifist */
3480. {
3481.     int tmp, mndx;
3482.     coordxy x = mtmp->mx, y = mtmp->my;
3483.     struct monst museum = cg.zeromonst;
3484.     struct permonst *mdat;
3485.     struct obj *otmp;
3486.     struct trap *t;
3487.     boolean be_sad;
3488.     boolean wasinside = engulfing_u(mtmp),
3489.             burycorpse = FALSE,
3490.             nomsg = (xkill_flags & XKILL_NOMSG) != 0,
3491.             nocorpse = (xkill_flags & XKILL_NOCORPSE) != 0,
3492.             noconduct = (xkill_flags & XKILL_NOCONDUCT) != 0;
3493. 
3494.     /* potential pet message; always clear global flag */
3495.     be_sad = iflags.sad_feeling;
3496.     iflags.sad_feeling = FALSE;
3497. 
3498.     mtmp->mhp = 0; /* caller will usually have already done this */
3499.     if (!noconduct) { /* KMH, conduct */
3500.         if (!u.uconduct.killer++)
3501.             livelog_printf(LL_CONDUCT, "killed for the first time");
3502.     }
3503.     if (!nomsg) {
3504.         boolean namedpet = has_mgivenname(mtmp) && !Hallucination;
3505. 
3506.         You("%s %s!",
3507.             nonliving(mtmp->data) ? "destroy" : "kill",
3508.             !(wasinside || canspotmon(mtmp)) ? "it"
3509.               : !mtmp->mtame ? mon_nam(mtmp)
3510.                 : x_monnam(mtmp, namedpet ? ARTICLE_NONE : ARTICLE_THE,
3511.                            "poor", namedpet ? SUPPRESS_SADDLE : 0, FALSE));
3512.     }
3513. 
3514.     if (mtmp->mtrapped && (t = t_at(x, y)) != 0 && is_pit(t->ttyp)) {
3515.         if (sobj_at(BOULDER, x, y))
3516.             nocorpse = TRUE; /* Prevent corpses/treasure being created
3517.                               * "on top" of boulder that is about to fall in.
3518.                               * This is out of order, but cannot be helped
3519.                               * unless this whole routine is rearranged. */
3520.         if (m_carrying(mtmp, BOULDER))
3521.             burycorpse = TRUE;
3522.     }
3523. 
3524.     /* your pet knows who just killed it...watch out */
3525.     if (mtmp->mtame && !mtmp->isminion)
3526.         EDOG(mtmp)->killed_by_u = 1;
3527. 
3528.     if (wasinside && gt.thrownobj && gt.thrownobj != uball
3529.         /* don't give to mon if missile is going to be destroyed */
3530.         && gt.thrownobj->oclass != POTION_CLASS
3531.         /* don't give to mon if missile is going to return to hero */
3532.         && gt.thrownobj != (struct obj *) iflags.returning_missile) {
3533.         /* thrown object has killed hero's engulfer; add it to mon's
3534.            inventory now so that it will be placed with mon's other
3535.            stuff prior to lookhere/autopickup when hero is expelled
3536.            below (as a side-effect, this missile has immunity from
3537.            being consumed [for this shot/throw only]) */
3538.         mpickobj(mtmp, gt.thrownobj);
3539.         /* let throwing code know that missile has been disposed of */
3540.         gt.thrownobj = 0;
3541.     }
3542. 
3543.     gv.vamp_rise_msg = FALSE; /* might get set in mondead(); checked below */
3544.     gd.disintegested = nocorpse; /* alternate vamp_rise mesg needed if true */
3545.     /* dispose of monster and make cadaver */
3546.     if (gs.stoned)
3547.         monstone(mtmp);
3548.     else
3549.         mondead(mtmp);
3550.     gd.disintegested = FALSE; /* reset */
3551. 
3552.     if (!DEADMONSTER(mtmp)) { /* monster lifesaved */
3553.         /* Cannot put the non-visible lifesaving message in
3554.          * lifesaved_monster() since the message appears only when _you_
3555.          * kill it (as opposed to visible lifesaving which always appears).
3556.          */
3557.         gs.stoned = FALSE;
3558.         if (!cansee(x, y) && !gv.vamp_rise_msg)
3559.             pline("Maybe not...");
3560.         return;
3561.     }
3562. 
3563.     if (be_sad)
3564.         You("have a sad feeling for a moment, then it passes.");
3565. 
3566.     mdat = mtmp->data; /* note: mondead can change mtmp->data */
3567.     mndx = monsndx(mdat);
3568. 
3569.     if (gs.stoned) {
3570.         gs.stoned = FALSE;
3571.         goto cleanup;
3572.     }
3573. 
3574.     if (nocorpse || LEVEL_SPECIFIC_NOCORPSE(mdat))
3575.         goto cleanup;
3576. 
3577. #ifdef MAIL_STRUCTURES
3578.     if (mdat == &mons[PM_MAIL_DAEMON]) {
3579.         stackobj(mksobj_at(SCR_MAIL, x, y, FALSE, FALSE));
3580.     }
3581. #endif
3582.     if (accessible(x, y) || is_pool(x, y)) {
3583.         struct obj *cadaver;
3584.         int otyp;
3585. 
3586.         /* illogical but traditional "treasure drop" */
3587.         if (!rn2(6) && !(svm.mvitals[mndx].mvflags & G_NOCORPSE)
3588.             /* no extra item from swallower or steed */
3589.             && (x != u.ux || y != u.uy)
3590.             /* no extra item from kops--too easy to abuse */
3591.             && mdat->mlet != S_KOP
3592.             /* no items from cloned monsters */
3593.             && !mtmp->mcloned) {
3594.             otmp = mkobj(RANDOM_CLASS, TRUE);
3595.             /* don't create large objects from small monsters */
3596.             otyp = otmp->otyp;
3597.             if (otmp->oclass == FOOD_CLASS && !(mdat->mflags2 & M2_COLLECT)
3598.                 && !otmp->oartifact) {
3599.                 /* don't drop newly created permafood from kills, unless
3600.                    the monster collects food; it creates too much nutrition
3601.                    in the late game and encourages grinding in the early
3602.                    game; oartifact check is paranoia and will be redundant
3603.                    until an artifact comestible is added */
3604.                 delobj(otmp);
3605.             } else if (mdat->msize < MZ_HUMAN && otyp != FIGURINE
3606.                 /* oc_big is also oc_bimanual and oc_bulky */
3607.                 && (otmp->owt > 30 || objects[otyp].oc_big)) {
3608.                 if (otmp->oartifact) /* un-create */
3609.                     artifact_exists(otmp, safe_oname(otmp), FALSE,
3610.                                     ONAME_NO_FLAGS);
3611.                 delobj(otmp);
3612.             } else if (!flooreffects(otmp, x, y, nomsg ? "" : "fall")) {
3613.                 place_object(otmp, x, y);
3614.                 stackobj(otmp);
3615.             }
3616.         }
3617.         /* corpse--none if hero was inside the monster */
3618.         if (!wasinside && corpse_chance(mtmp, (struct monst *) 0, FALSE)) {
3619.             gz.zombify = (!gt.thrownobj && !gs.stoned && !uwep
3620.                          && zombie_maker(&gy.youmonst)
3621.                          && zombie_form(mtmp->data) != NON_PM);
3622.             cadaver = make_corpse(mtmp, burycorpse ? CORPSTAT_BURIED
3623.                                                    : CORPSTAT_NONE);
3624.             gz.zombify = FALSE; /* reset */
3625.             if (burycorpse && cadaver && cansee(x, y) && !mtmp->minvis
3626.                 && cadaver->where == OBJ_BURIED && !nomsg) {
3627.                 pline("%s corpse ends up buried.", s_suffix(Monnam(mtmp)));
3628.             }
3629.         }
3630.     }
3631. 
3632.     if (wasinside) {
3633.         /* spoteffects() can end up clearing level of monsters; grab a copy */
3634.         museum = *mtmp;
3635.         museum.nmon = 0;
3636.         museum.minvent = 0;
3637.         museum.mextra = 0;
3638.         spoteffects(TRUE); /* poor man's expels() */
3639.         mtmp = &museum; /* use the reference copy now */
3640.     }
3641.     /* monster is gone, corpse or other object might now be visible */
3642.     newsym(x, y);
3643. 
3644.  cleanup:
3645.     /*
3646.      * Punish bad behavior.
3647.      */
3648.     if (is_human(mdat)
3649.         && (!always_hostile(mdat) && mtmp->malign <= 0)
3650.         /* exclude role monsters */
3651.         && (mndx < PM_ARCHEOLOGIST || mndx > PM_WIZARD)
3652.         /* exclude plain "human", which isn't flagged as always hostile;
3653.            it is rare and most likely to occur as the result of resurrecting
3654.            a corpse or animating a statue and usually will be hostile */
3655.         && mndx != PM_HUMAN
3656.         /* only applicable if hero is lawful or neutral */
3657.         && u.ualign.type != A_CHAOTIC) {
3658.         HTelepat &= ~INTRINSIC;
3659.         change_luck(-2);
3660.         You("murderer!");
3661.         if (Blind && !Blind_telepat)
3662.             see_monsters(); /* Can't sense monsters any more. */
3663.     }
3664.     if ((mtmp->mpeaceful && !rn2(2)) || mtmp->mtame)
3665.         change_luck(-1);
3666.     if (is_unicorn(mdat) && sgn(u.ualign.type) == sgn(mdat->maligntyp)) {
3667.         change_luck(-5);
3668.         You_feel("guilty...");
3669.     }
3670. 
3671.     /* give experience points */
3672.     tmp = experience(mtmp, (int) svm.mvitals[mndx].died);
3673.     more_experienced(tmp, 0);
3674.     newexplevel(); /* will decide if you go up */
3675. 
3676.     /* adjust alignment points */
3677.     if (mtmp->m_id == svq.quest_status.leader_m_id) { /* REAL BAD! */
3678.         adjalign(-(u.ualign.record + (int) ALIGNLIM / 2));
3679.         u.ugangr += 7; /* instantly become "extremely" angry */
3680.         change_luck(-20);
3681.         pline("That was %sa bad idea...",
3682.               u.uevent.qcompleted ? "probably " : "");
3683.         if (!svc.context.mon_moving)
3684.             iter_mons(anger_quest_guardians);
3685.     } else if (mdat->msound == MS_NEMESIS) { /* Real good! */
3686.         if (!svq.quest_status.killed_leader)
3687.             adjalign((int) (ALIGNLIM / 4));
3688.     } else if (mdat->msound == MS_GUARDIAN) { /* Bad */
3689.         adjalign(-(int) (ALIGNLIM / 8));
3690.         u.ugangr++;
3691.         change_luck(-4);
3692.         if (!Hallucination)
3693.             pline("That was probably a bad idea...");
3694.         else
3695.             pline("Whoopsie-daisy!");
3696.     } else if (mtmp->ispriest) {
3697.         adjalign((p_coaligned(mtmp)) ? -2 : 2);
3698.         /* cancel divine protection for killing your priest */
3699.         if (p_coaligned(mtmp))
3700.             u.ublessed = 0;
3701.         if (mdat->maligntyp == A_NONE)
3702.             adjalign((int) (ALIGNLIM / 4)); /* BIG bonus */
3703.     } else if (mtmp->mtame) {
3704.         adjalign(-15); /* bad!! */
3705.         /* your god is mighty displeased... */
3706.         if (!Hallucination) {
3707.             Soundeffect(se_distant_thunder, 40);
3708.             You_hear("the rumble of distant thunder...");
3709.         } else {
3710.             Soundeffect(se_applause, 40);
3711.             You_hear("the studio audience applaud!");
3712.         }
3713.         if (!unique_corpstat(mdat)) {
3714.             boolean mname = has_mgivenname(mtmp);
3715. 
3716.             livelog_printf(LL_KILLEDPET, "murdered %s%s%s faithful %s",
3717.                            mname ? MGIVENNAME(mtmp) : "",
3718.                            mname ? ", " : "",
3719.                            uhis(), pmname(mdat, Mgender(mtmp)));
3720.         }
3721.     } else if (mtmp->mpeaceful)
3722.         adjalign(-5);
3723. 
3724.     /* malign was already adjusted for u.ualign.type and randomization */
3725.     adjalign(mtmp->malign);
3726. 
3727. #if 0  /* HARDFOUGHT-only at present */
3728. #ifdef LIVELOG
3729.     if (has_ebones(mtmp)) {
3730.         livelog_printf(LL_UMONST, "destroyed %s, %s former %s",
3731.                        livelog_mon_nam(mtmp),
3732.                        (mtmp->data == &mons[PM_GHOST]) ? "the" : "and",
3733.                        rank_of(EBONES(mtmp)->deathlevel,
3734.                                EBONES(mtmp)->mnum,
3735.                                EBONES(mtmp)->female));
3736.     }
3737. #endif  /* LIVELOG */
3738. #endif
3739.     return;
3740. }
3741. 
3742. #undef LEVEL_SPECIFIC_NOCORPSE
3743. #undef livelog_mon_nam
3744. 
3745. /* changes the monster into a stone monster of the same type
3746.    this should only be called when poly_when_stoned() is true */
3747. void
3748. mon_to_stone(struct monst *mtmp)
3749. {
3750.     if (mtmp->data->mlet == S_GOLEM) {
3751.         /* it's a golem, and not a stone golem */
3752.         if (canseemon(mtmp))
3753.             pline_mon(mtmp, "%s solidifies...", Monnam(mtmp));
3754.         if (newcham(mtmp, &mons[PM_STONE_GOLEM], NO_NC_FLAGS)) {
3755.             if (canseemon(mtmp))
3756.                 pline("Now it's %s.", an(pmname(mtmp->data, Mgender(mtmp))));
3757.         } else {
3758.             if (canseemon(mtmp))
3759.                 pline("... and returns to normal.");
3760.         }
3761.     } else
3762.         impossible("Can't polystone %s!", a_monnam(mtmp));
3763. }
3764. 
3765. boolean
3766. vamp_stone(struct monst *mtmp)
3767. {
3768.     if (is_vampshifter(mtmp)) {
3769.         int mndx = mtmp->cham;
3770.         coordxy x = mtmp->mx, y = mtmp->my;
3771. 
3772.         /* this only happens if shapeshifted */
3773.         if (mndx >= LOW_PM && mndx != monsndx(mtmp->data)
3774.             && !(svm.mvitals[mndx].mvflags & G_GENOD)) {
3775.             char buf[BUFSZ];
3776. 
3777.             /* construct a format string before transformation */
3778.             Sprintf(buf, "The lapidifying %s %s %s",
3779.                     x_monnam(mtmp, ARTICLE_NONE, (char *) 0,
3780.                              (SUPPRESS_SADDLE | SUPPRESS_HALLUCINATION
3781.                               | SUPPRESS_INVISIBLE | SUPPRESS_IT), FALSE),
3782.                     amorphous(mtmp->data) ? "coalesces on the"
3783.                        : is_flyer(mtmp->data) ? "drops to the"
3784.                           : "writhes on the",
3785.                     surface(x, y));
3786.             mtmp->mcanmove = 1;
3787.             mtmp->mfrozen = 0;
3788.             set_mon_min_mhpmax(mtmp, 10); /* mtmp->mhpmax=max(m_lev+1,10) */
3789.             mtmp->mhp = mtmp->mhpmax;
3790.             /* this can happen if previously a fog cloud */
3791.             if (engulfing_u(mtmp))
3792.                 expels(mtmp, mtmp->data, FALSE);
3793.             if (amorphous(mtmp->data) && closed_door(mtmp->mx, mtmp->my)) {
3794.                 coord new_xy;
3795. 
3796.                 if (enexto(&new_xy, mtmp->mx, mtmp->my, &mons[mndx])) {
3797.                     rloc_to(mtmp, new_xy.x, new_xy.y);
3798.                 }
3799.             }
3800.             if (canspotmon(mtmp)) {
3801.                 pline_mon(mtmp, "%s!", buf);
3802.                 display_nhwindow(WIN_MESSAGE, FALSE);
3803.             }
3804.             (void) newcham(mtmp, &mons[mndx], NO_NC_FLAGS);
3805.             if (mtmp->data == &mons[mndx])
3806.                 mtmp->cham = NON_PM;
3807.             else
3808.                 mtmp->cham = mndx;
3809.             if (canspotmon(mtmp)) {
3810.                 pline_mon(mtmp,
3811.                       "%s rises from the %s with renewed agility!",
3812.                       Amonnam(mtmp), surface(mtmp->mx, mtmp->my));
3813.             }
3814.             newsym(mtmp->mx, mtmp->my);
3815.             return FALSE;   /* didn't petrify */
3816.         }
3817.     } else if (ismnum(mtmp->cham)
3818.                && (mons[mtmp->cham].mresists & MR_STONE)) {
3819.         /* sandestins are stoning-immune so if hit by stoning damage
3820.            they revert to innate shape rather than become a statue */
3821.         mtmp->mcanmove = 1;
3822.         mtmp->mfrozen = 0;
3823.         set_mon_min_mhpmax(mtmp, 10); /* mtmp->mhpmax=max(mtmp->m_lev+1,10) */
3824.         mtmp->mhp = mtmp->mhpmax;
3825.         (void) newcham(mtmp, &mons[mtmp->cham], NC_SHOW_MSG);
3826.         newsym(mtmp->mx, mtmp->my);
3827.         return FALSE;   /* didn't petrify */
3828.     }
3829.     return TRUE;
3830. }
3831. 
3832. /* drop monster into "limbo" - that is, migrate to the current level */
3833. void
3834. m_into_limbo(struct monst *mtmp)
3835. {
3836.     xint16 target_lev = ledger_no(&u.uz), xyloc = MIGR_APPROX_XY;
3837. 
3838.     mtmp->mstate |= MON_LIMBO;
3839.     migrate_mon(mtmp, target_lev, xyloc);
3840. }
3841. 
3842. void
3843. migrate_mon(
3844.     struct monst *mtmp,
3845.     xint16 target_lev, /* destination level */
3846.     xint16 xyloc)      /* MIGR_xxx flag for location within destination */
3847. {
3848.     /*
3849.      * If mtmp->mx is zero, this was a failed arrival attempt from a
3850.      * prior migration and mtmp isn't on the map.  In that situation
3851.      * it can't be engulfing or holding the hero or held by same and
3852.      * should have dropped any special objects during that earlier
3853.      * migration back when it had a valid map location.  So only
3854.      * perform some actions when mx is non-zero.
3855.      */
3856.     if (mtmp->mx) {
3857.         unstuck(mtmp);
3858.         mdrop_special_objs(mtmp);
3859.     }
3860.     migrate_to_level(mtmp, target_lev, xyloc, (coord *) 0);
3861. }
3862. 
3863. staticfn boolean
3864. ok_to_obliterate(struct monst *mtmp)
3865. {
3866.     /*
3867.      * Add checks for monsters that should not be obliterated
3868.      * here (return FALSE).
3869.      */
3870.     if (mtmp->data == &mons[PM_WIZARD_OF_YENDOR] || is_rider(mtmp->data)
3871.         || has_emin(mtmp) || has_epri(mtmp) || has_eshk(mtmp)
3872.         || mtmp == u.ustuck || mtmp == u.usteed)
3873.         return FALSE;
3874.     return TRUE;
3875. }
3876. 
3877. void
3878. elemental_clog(struct monst *mon)
3879. {
3880.     static long msgmv = 0L;
3881.     int m_lev = 0;
3882.     struct monst *mtmp, *m1, *m2, *m3, *m4, *m5, *zm;
3883. 
3884.     if (In_endgame(&u.uz)) {
3885.         m1 = m2 = m3 = m4 = m5 = zm = (struct monst *) 0;
3886.         if (!msgmv || (svm.moves - msgmv) > 200L) {
3887.             if (!msgmv || rn2(2))
3888.                 You_feel("besieged.");
3889.             msgmv = svm.moves;
3890.         }
3891.         /*
3892.          * m1 an elemental from another plane.
3893.          * m2 an elemental from this plane.
3894.          * m3 the least powerful monst encountered in loop so far.
3895.          * m4 some other non-tame monster.
3896.          * m5 a pet.
3897.          */
3898.         for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
3899.             if (DEADMONSTER(mtmp) || mtmp == mon)
3900.                 continue;
3901.             if (mtmp->mx == 0 && mtmp->my == 0)
3902.                 continue;
3903.             if (mon_has_amulet(mtmp) || !ok_to_obliterate(mtmp))
3904.                 continue;
3905.             if (mtmp->data->mlet == S_ELEMENTAL) {
3906.                 if (!is_home_elemental(mtmp->data)) {
3907.                     if (!m1)
3908.                         m1 = mtmp;
3909.                 } else {
3910.                     if (!m2)
3911.                         m2 = mtmp;
3912.                 }
3913.             } else {
3914.                 if (!mtmp->mtame) {
3915.                     if (!m_lev || mtmp->m_lev < m_lev) {
3916.                         m_lev = mtmp->m_lev;
3917.                         m3 = mtmp;
3918.                     } else if (!m4) {
3919.                         m4 = mtmp;
3920.                     }
3921.                 } else {
3922.                     if (!m5)
3923.                         m5 = mtmp;
3924.                     break;
3925.                 }
3926.             }
3927.         }
3928.         mtmp = m1 ? m1 : m2 ? m2 : m3 ? m3 : m4 ? m4 : m5 ? m5 : zm;
3929.         if (mtmp) {
3930.             int mx = mtmp->mx, my = mtmp->my;
3931. 
3932.             mtmp->mstate |= MON_OBLITERATE;
3933.             mongone(mtmp);
3934.             /* places in the code might still reference mtmp->mx, mtmp->my */
3935.             /* mtmp->mx = mtmp->my = 0; */
3936.             rloc_to(mon, mx, my);           /* note: mon, not mtmp */
3937. 
3938.         /* last resort - migrate mon to the next plane */
3939.         } else if (!Is_astralevel(&u.uz)) {
3940.             d_level dest;
3941.             coordxy target_lev;
3942. 
3943.             dest = u.uz;
3944.             dest.dlevel--;
3945.             target_lev = ledger_no(&dest);
3946.             mon->mstate |= MON_ENDGAME_MIGR;
3947.             migrate_mon(mon, target_lev, MIGR_RANDOM);
3948.         }
3949.     }
3950. }
3951. 
3952. /* make monster mtmp next to you (if possible);
3953.    might place monst on far side of a wall or boulder */
3954. void
3955. mnexto(struct monst *mtmp, unsigned int rlocflags)
3956. {
3957.     coord mm;
3958. 
3959.     if (mtmp == u.usteed) {
3960.         /* Keep your steed in sync with you instead */
3961.         mtmp->mx = u.ux;
3962.         mtmp->my = u.uy;
3963.         return;
3964.     }
3965. 
3966.     if (!enexto(&mm, u.ux, u.uy, mtmp->data) || !isok(mm.x, mm.y)) {
3967.         deal_with_overcrowding(mtmp);
3968.         return;
3969.     }
3970.     /* wizard-mode player can choose destination by setting 'montelecontrol'
3971.        option; enexto()'s value for 'mm' will be the default; 'savemm' is
3972.        used to make sure player doesn't choose hero's location and then
3973.        answer 'y' to the 'override invalid spot' prompt */
3974.     if (iflags.mon_telecontrol) {
3975.         coord savemm = mm;
3976. 
3977.         if (!control_mon_tele(mtmp, &mm, rlocflags, FALSE))
3978.             mm = savemm;
3979.     }
3980. 
3981.     rloc_to_flag(mtmp, mm.x, mm.y, rlocflags);
3982.     return;
3983. }
3984. 
3985. void
3986. deal_with_overcrowding(struct monst *mtmp)
3987. {
3988.     if (In_endgame(&u.uz)) {
3989.         debugpline1("overcrowding: elemental_clog on %s", m_monnam(mtmp));
3990.         elemental_clog(mtmp);
3991.     } else {
3992.         debugpline1("overcrowding: sending %s into limbo", m_monnam(mtmp));
3993.         m_into_limbo(mtmp);
3994.     }
3995. }
3996. 
3997. /* like mnexto() but requires destination to be directly accessible */
3998. void
3999. maybe_mnexto(struct monst *mtmp)
4000. {
4001.     coord mm;
4002.     struct permonst *ptr = mtmp->data;
4003.     boolean diagok = !NODIAG(ptr - mons);
4004.     int tryct = 20;
4005. 
4006.     do {
4007.         if (!enexto(&mm, u.ux, u.uy, ptr))
4008.             return;
4009.         if (couldsee(mm.x, mm.y)
4010.             /* don't move grid bugs diagonally */
4011.             && (diagok || mm.x == mtmp->mx || mm.y == mtmp->my)) {
4012.             /* [this doesn't honor the 'montelecontrol' option] */
4013.             rloc_to(mtmp, mm.x, mm.y);
4014.             return;
4015.         }
4016.     } while (--tryct > 0);
4017. }
4018. 
4019. /* mnearto()
4020.  * Put monster near (or at) location if possible.
4021.  * Returns:
4022.  *  2 if another monster was moved out of this one's way;
4023.  *  1 if relocation was successful (without moving another one);
4024.  *  0 otherwise.
4025.  * Note: if already at the target spot, result is 1 rather than 0.
4026.  *
4027.  * Might be called recursively if 'move_other' is True; if so, that argument
4028.  * will be False on the nested call so there won't be any further recursion.
4029.  */
4030. int
4031. mnearto(
4032.     struct monst *mtmp,
4033.     coordxy x,
4034.     coordxy y,
4035.     boolean move_other, /* make sure mtmp gets to x, y! so move m_at(x, y) */
4036.     unsigned int rlocflags)
4037. {
4038.     struct monst *othermon = (struct monst *) 0;
4039.     coordxy newx, newy;
4040.     coord mm;
4041.     int res = 1;
4042. 
4043.     if (mtmp->mx == x && mtmp->my == y && m_at(x, y) == mtmp)
4044.         return res;
4045. 
4046.     if (move_other && (othermon = m_at(x, y)) != 0) {
4047.         /* take othermon off the map; it might end up immediately returning
4048.            but for the moment it is leaving */
4049.         mon_leaving_level(othermon);
4050.         othermon->mx = othermon->my = 0; /* 'othermon' is not on the map */
4051.         othermon->mstate |= MON_OFFMAP;
4052.     }
4053. 
4054.     newx = x;
4055.     newy = y;
4056.     if (!goodpos(newx, newy, mtmp, 0)) {
4057.         /* Actually we have real problems if enexto ever fails.
4058.          * Migrating_mons that need to be placed will cause
4059.          * no end of trouble.
4060.          */
4061.         if (!enexto(&mm, newx, newy, mtmp->data) || !isok(mm.x, mm.y)) {
4062.             if (othermon) {
4063.                 /* othermon already had its mx, my set to 0 above
4064.                  * and this would shortly cause a sanity check to fail
4065.                  * if we just return 0 here. The caller only possesses
4066.                  * awareness of mtmp, not othermon. */
4067.                 deal_with_overcrowding(othermon);
4068.             }
4069.             return 0;
4070.         }
4071.         newx = mm.x;
4072.         newy = mm.y;
4073.     }
4074.     /* [this doesn't honor the 'montelecontrol' option] */
4075.     rloc_to_flag(mtmp, newx, newy, rlocflags);
4076. 
4077.     if (move_other && othermon) {
4078.         res = 2; /* moving another monster out of the way */
4079.         /* 'move_other'==FALSE this time; fail rather than recurse */
4080.         if (!mnearto(othermon, x, y, FALSE, rlocflags))
4081.             deal_with_overcrowding(othermon);
4082.     }
4083. 
4084.     return res;
4085. }
4086. 
4087. /* shrieker special action: shriek, maybe summon monster, aggravate */
4088. staticfn void
4089. m_respond_shrieker(struct monst *mtmp)
4090. {
4091.     if (!Deaf) {
4092.         pline("%s shrieks.", Monnam(mtmp));
4093.         stop_occupation();
4094.     }
4095.     if (!rn2(10)) { /* 1/10 chance per shriek to create a monster */
4096.         /* new monster has a 1/13 chance to be a purple worm, random
4097.            otherwise; baby purple worm if adult is too difficult */
4098.         (void) makemon(rn2(13) ? (struct permonst *) 0
4099.                        : &mons[montoostrong(PM_PURPLE_WORM,
4100.                                             monmax_difficulty_lev())
4101.                                ? PM_BABY_PURPLE_WORM : PM_PURPLE_WORM],
4102.                        0, 0, NO_MM_FLAGS);
4103.     }
4104.     aggravate();
4105. }
4106. 
4107. /* medusa special action: gaze at hero */
4108. staticfn void
4109. m_respond_medusa(struct monst *mtmp)
4110. {
4111.     int i;
4112. 
4113.     for (i = 0; i < NATTK; i++)
4114.         if (mtmp->data->mattk[i].aatyp == AT_GAZE) {
4115.             (void) gazemu(mtmp, &mtmp->data->mattk[i]);
4116.             break;
4117.         }
4118. }
4119. 
4120. /* monster responds to player action; not the same as a passive attack */
4121. void
4122. m_respond(struct monst *mtmp)
4123. {
4124.     if (mtmp->data->msound == MS_SHRIEK && !um_dist(mtmp->mx, mtmp->my, 1))
4125.         m_respond_shrieker(mtmp);
4126.     if (mtmp->data == &mons[PM_MEDUSA] && couldsee(mtmp->mx, mtmp->my))
4127.         m_respond_medusa(mtmp);
4128.     /* Erinyes will inform surrounding monsters of your crimes */
4129.     if (mtmp->data == &mons[PM_ERINYS] && !mtmp->mpeaceful && m_canseeu(mtmp))
4130.         aggravate();
4131. }
4132. 
4133. /* how quest guardians respond when you attack the quest leader */
4134. staticfn void
4135. qst_guardians_respond(void)
4136. {
4137.     struct monst *mon;
4138.     struct permonst *q_guardian = &mons[quest_info(MS_GUARDIAN)];
4139.     int got_mad = 0;
4140. 
4141.     /* guardians will sense this attack even if they can't see it */
4142.     for (mon = fmon; mon; mon = mon->nmon) {
4143.         if (DEADMONSTER(mon))
4144.             continue;
4145.         if (mon->data == q_guardian && mon->mpeaceful) {
4146.             mon->mpeaceful = 0;
4147.             if (canseemon(mon))
4148.                 ++got_mad;
4149.         }
4150.     }
4151.     if (got_mad && !Hallucination) {
4152.         const char *who = q_guardian->pmnames[NEUTRAL];
4153. 
4154.         if (got_mad > 1)
4155.             who = makeplural(who);
4156.         pline_The("%s %s to be angry too...",
4157.                   who, vtense(who, "appear"));
4158.     }
4159. }
4160. 
4161. /* how other peacefuls react when you attack monster */
4162. staticfn void
4163. peacefuls_respond(struct monst *mtmp)
4164. {
4165.     struct monst *mon;
4166.     int mndx = monsndx(mtmp->data);
4167. 
4168.     for (mon = fmon; mon; mon = mon->nmon) {
4169.         if (DEADMONSTER(mon))
4170.             continue;
4171.         if (mon == mtmp) /* the mpeaceful test catches this since mtmp */
4172.             continue;    /* is no longer peaceful, but be explicit...  */
4173. 
4174.         if (!mindless(mon->data) && mon->mpeaceful
4175.             && couldsee(mon->mx, mon->my) && !mon->msleeping
4176.             && mon->mcansee && m_canseeu(mon)) {
4177.             char buf[BUFSZ];
4178.             boolean exclaimed = FALSE, needpunct = FALSE, alreadyfleeing;
4179. 
4180.             buf[0] = '\0';
4181.             if (humanoid(mon->data) || mon->isshk || mon->ispriest) {
4182.                 if (is_watch(mon->data)) {
4183.                     SetVoice(mon, 0, 80, 0);
4184.                     verbalize("Halt!  You're under arrest!");
4185.                     (void) angry_guards(!!Deaf);
4186.                 } else {
4187.                     if (!Deaf && !rn2(5)) {
4188.                         const char *gasp = maybe_gasp(mon);
4189. 
4190.                         if (gasp) {
4191.                             if (!strncmpi(gasp, "gasp", 4)) {
4192.                                 Sprintf(buf, "%s gasps", Monnam(mon));
4193.                                 needpunct = TRUE;
4194.                             } else {
4195.                                 Sprintf(buf, "%s exclaims \"%s\"",
4196.                                         Monnam(mon), gasp);
4197.                             }
4198.                             exclaimed = TRUE;
4199.                         }
4200.                     }
4201.                     /* shopkeepers and temple priests might gasp in
4202.                        surprise, but they won't become angry here;
4203.                        quest leader will only get angry if hero attacks
4204.                        own quest guardians */
4205.                     if (mon->isshk || mon->ispriest
4206.                         || (mon->data == &mons[quest_info(MS_LEADER)]
4207.                             && mtmp->data != &mons[gu.urole.guardnum])) {
4208.                         if (exclaimed)
4209.                             pline_mon(mon, "%s%s", buf, " then shrugs.");
4210.                         continue;
4211.                     }
4212. 
4213.                     if (mon->data->mlevel < rn2(10)
4214.                         /* don't have quest guardians turn to flee */
4215.                         && (mon->data != &mons[gu.urole.guardnum])) {
4216.                         alreadyfleeing = (mon->mflee || mon->mfleetim);
4217.                         monflee(mon, rn2(50) + 25, TRUE, !exclaimed);
4218.                         if (exclaimed) {
4219.                             if (flags.verbose && !alreadyfleeing) {
4220.                                 Strcat(buf, " and then turns to flee.");
4221.                                 needpunct = FALSE;
4222.                             }
4223.                         } else
4224.                             exclaimed = TRUE; /* got msg from monflee() */
4225.                     }
4226.                     if (*buf)
4227.                         pline_mon(mon, "%s%s", buf, needpunct ? "." : "");
4228.                     if (mon->mtame) {
4229.                         ; /* mustn't set mpeaceful to 0 as below;
4230.                            * perhaps reduce tameness? */
4231.                     } else {
4232.                         mon->mpeaceful = 0;
4233.                         mon->mstrategy &= ~STRAT_WAITMASK;
4234.                         adjalign(-1);
4235.                         if (!exclaimed)
4236.                             pline_mon(mon, "%s gets angry!", Monnam(mon));
4237.                     }
4238.                 }
4239.             } else if (mon->data->mlet == mtmp->data->mlet
4240.                        && big_little_match(mndx, monsndx(mon->data))
4241.                        && !rn2(3)) {
4242.                 if (!rn2(4)) {
4243.                     growl(mon);
4244.                     exclaimed = (iflags.last_msg == PLNMSG_GROWL);
4245.                 }
4246.                 if (rn2(6)) {
4247.                     alreadyfleeing = (mon->mflee || mon->mfleetim);
4248.                     monflee(mon, rn2(25) + 15, TRUE, !exclaimed);
4249.                     if (exclaimed && !alreadyfleeing)
4250.                         /* word like a separate sentence so that we
4251.                            don't have to poke around inside growl() */
4252.                         pline("And then starts to flee.");
4253.                 }
4254.             }
4255.         }
4256.     }
4257. }
4258. 
4259. /* Called whenever the player attacks mtmp; also called in other situations
4260.    where mtmp gets annoyed at the player. Handles mtmp getting annoyed at the
4261.    attack and any ramifications that might have. Useful also in situations
4262.    where mtmp was already hostile; it checks for situations where the player
4263.    shouldn't be attacking and any ramifications /that/ might have. */
4264. void
4265. setmangry(struct monst *mtmp, boolean via_attack)
4266. {
4267.     if (via_attack && sengr_at("Elbereth", u.ux, u.uy, TRUE)
4268.         /* only hypocritical if monster is vulnerable to Elbereth (or
4269.            peaceful--not vulnerable but attacking it is hypocritical) */
4270.         && (onscary(u.ux, u.uy, mtmp) || mtmp->mpeaceful)) {
4271.         You_feel("like a hypocrite.");
4272.         /* AIS: Yes, I know alignment penalties and bonuses aren't balanced
4273.            at the moment. This is about correct relative to other "small"
4274.            penalties; it should be fairly large, as attacking while standing
4275.            on an Elbereth means that you're requesting peace and then
4276.            violating your own request. I know 5 isn't actually large, but
4277.            it's intentionally larger than the 1s and 2s that are normally
4278.            given for this sort of thing. */
4279.         /* reduce to 3 (average) when alignment is already very low */
4280.         adjalign((u.ualign.record > 5) ? -5 : -rnd(5));
4281. 
4282.         if (!Blind)
4283.             pline("The engraving beneath you fades.");
4284.         del_engr_at(u.ux, u.uy);
4285.     }
4286. 
4287.     /* AIS: Should this be in both places, or just in wakeup()? */
4288.     mtmp->mstrategy &= ~STRAT_WAITMASK;
4289.     if (!mtmp->mpeaceful)
4290.         return;
4291.     /* [FIXME: this logic seems wrong; peaceful humanoids gasp or exclaim
4292.        when they see you attack a peaceful monster but they just casually
4293.        look the other way when you attack a pet?] */
4294.     if (mtmp->mtame)
4295.         return;
4296.     mtmp->mpeaceful = 0;
4297.     if (mtmp->ispriest) {
4298.         if (p_coaligned(mtmp))
4299.             adjalign(-5); /* very bad */
4300.         else
4301.             adjalign(2);
4302.     } else
4303.         adjalign(-1); /* attacking peaceful monsters is bad */
4304.     if (humanoid(mtmp->data) || mtmp->isshk || mtmp->isgd) {
4305.         if (couldsee(mtmp->mx, mtmp->my))
4306.             pline_mon(mtmp, "%s gets angry!", Monnam(mtmp));
4307.     } else {
4308.         growl(mtmp);
4309.     }
4310. 
4311.     /* attacking your own quest leader will anger his or her guardians */
4312.     if (mtmp->data == &mons[quest_info(MS_LEADER)])
4313.         qst_guardians_respond();
4314. 
4315.     /* make other peaceful monsters react */
4316.     if (!svc.context.mon_moving)
4317.         peacefuls_respond(mtmp);
4318. }
4319. 
4320. /* Indicate via message that a monster has awoken. */
4321. void
4322. wake_msg(struct monst *mtmp, boolean interesting)
4323. {
4324.     if (mtmp->msleeping && canseemon(mtmp)) {
4325.         pline_mon(mtmp, "%s wakes up%s%s",
4326.               Monnam(mtmp), interesting ? "!" : ".",
4327.               mtmp->data == &mons[PM_FLESH_GOLEM] ? " It's alive!" : "");
4328.     }
4329. }
4330. 
4331. /* wake up a monster, possibly making it angry in the process */
4332. void
4333. wakeup(struct monst *mtmp, boolean via_attack)
4334. {
4335.     boolean was_sleeping = mtmp->msleeping;
4336. 
4337.     wake_msg(mtmp, via_attack);
4338.     mtmp->msleeping = 0;
4339.     if (M_AP_TYPE(mtmp) != M_AP_NOTHING) {
4340.         /* mimics come out of hiding, but disguised Wizard doesn't
4341.            have to lose his disguise */
4342.         if (M_AP_TYPE(mtmp) != M_AP_MONSTER)
4343.             seemimic(mtmp);
4344.     } else if (svc.context.forcefight && !svc.context.mon_moving
4345.                && mtmp->mundetected) {
4346.         mtmp->mundetected = 0;
4347.         newsym(mtmp->mx, mtmp->my);
4348.     }
4349.     finish_meating(mtmp);
4350.     if (via_attack) {
4351.         boolean was_peaceful = mtmp->mpeaceful;
4352. 
4353.         if (was_sleeping)
4354.             growl(mtmp);
4355.         setmangry(mtmp, TRUE);
4356.         if (was_peaceful) {
4357.             if (mtmp->ispriest && *in_rooms(mtmp->mx, mtmp->my, TEMPLE))
4358.                 ghod_hitsu(mtmp);
4359.             if (mtmp->isshk && !*u.ushops)
4360.                 hot_pursuit(mtmp);
4361.         }
4362.     }
4363. }
4364. 
4365. /* Wake up nearby monsters without angering them. */
4366. void
4367. wake_nearby(boolean petcall)
4368. {
4369.     wake_nearto_core(u.ux, u.uy, u.ulevel * 20, petcall);
4370. }
4371. 
4372. /* Wake up monsters near some particular location. */
4373. staticfn void
4374. wake_nearto_core(coordxy x, coordxy y, int distance, boolean petcall)
4375. {
4376.     struct monst *mtmp;
4377. 
4378.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
4379.         if (DEADMONSTER(mtmp))
4380.             continue;
4381.         if (distance == 0 || dist2(mtmp->mx, mtmp->my, x, y) < distance) {
4382.             /* sleep for N turns uses mtmp->mfrozen, but so does paralysis
4383.                so we leave mfrozen monsters alone */
4384.             wake_msg(mtmp, FALSE);
4385.             mtmp->msleeping = 0; /* wake indeterminate sleep */
4386.             if (!(mtmp->data->geno & G_UNIQ))
4387.                 mtmp->mstrategy &= ~STRAT_WAITMASK; /* wake 'meditation' */
4388.             if (svc.context.mon_moving || !petcall)
4389.                 continue;
4390.             if (mtmp->mtame) {
4391.                 if (!mtmp->isminion)
4392.                     EDOG(mtmp)->whistletime = svm.moves;
4393.                 /* Fix up a pet who is stuck "fleeing" its master */
4394.                 mon_track_clear(mtmp);
4395.             }
4396.         }
4397.     }
4398.     disturb_buried_zombies(x, y);
4399. }
4400. 
4401. void
4402. wake_nearto(coordxy x, coordxy y, int distance)
4403. {
4404.     wake_nearto_core(x, y, distance, FALSE);
4405. }
4406. 
4407. /* NOTE: we must check for mimicry before calling this routine */
4408. void
4409. seemimic(struct monst *mtmp)
4410. {
4411.     boolean is_blocker_appear = (is_lightblocker_mappear(mtmp));
4412. 
4413.     if (has_mcorpsenm(mtmp))
4414.         freemcorpsenm(mtmp);
4415. 
4416.     mtmp->m_ap_type = M_AP_NOTHING;
4417.     mtmp->mappearance = 0;
4418. 
4419.     /*
4420.      *  Discovered mimics don't block light.
4421.      */
4422.     if (is_blocker_appear
4423.         && !does_block(mtmp->mx, mtmp->my, &levl[mtmp->mx][mtmp->my]))
4424.         unblock_point(mtmp->mx, mtmp->my);
4425. 
4426.     newsym(mtmp->mx, mtmp->my);
4427. }
4428. 
4429. /* [taken out of rescham() in order to be shared by restore_cham()] */
4430. void
4431. normal_shape(struct monst *mon)
4432. {
4433.     int mcham = (int) mon->cham;
4434. 
4435.     if (ismnum(mcham)) {
4436.         unsigned mcan = mon->mcan;
4437. 
4438.         (void) newcham(mon, &mons[mcham], NC_SHOW_MSG);
4439.         mon->cham = NON_PM;
4440.         /* newcham() may uncancel a polymorphing monster; override that */
4441.         if (mcan)
4442.             mon->mcan = 1;
4443.         newsym(mon->mx, mon->my);
4444.     }
4445.     if (is_were(mon->data) && mon->data->mlet != S_HUMAN) {
4446.         new_were(mon);
4447.     }
4448.     if (M_AP_TYPE(mon) != M_AP_NOTHING) {
4449.         /* this used to include a cansee() check but Protection_from_
4450.            _shape_changers shouldn't be trumped by being unseen */
4451.         if (!mon->meating) {
4452.             /* make revealed mimic fall asleep in lieu of shape change */
4453.             if (M_AP_TYPE(mon) != M_AP_MONSTER)
4454.                 mon->msleeping = 1;
4455.             seemimic(mon);
4456.         } else {
4457.             /* quickmimic: pet is midst of eating a mimic corpse;
4458.                this terminates the meal early */
4459.             finish_meating(mon);
4460.         }
4461.     }
4462. }
4463. 
4464. /* freed by freedynamicdata() when game ends; doesn't need to be struct g */
4465. static struct monst **itermonarr = NULL;
4466. static unsigned itermonsiz = 0; /* size in 'monst *' pointers */
4467. 
4468. /* manage itermonarr; it used to be allocated and freed every time the
4469.    monster movement loop ran; now, keep it around most of the time */
4470. void
4471. alloc_itermonarr(unsigned count)
4472. {
4473.     /* if count is 0 or bigger than itermonsiz or much smaller than
4474.        itermonsiz, release itermonarr (and reset itermonsiz to 0) */
4475.     if (!count || count > itermonsiz || count + 40 < itermonsiz) {
4476.         if (itermonarr)
4477.             free((genericptr_t) itermonarr), itermonarr = NULL;
4478.         itermonsiz = 0;
4479.     }
4480.     /* when count is more than itermonsiz (including when that just
4481.        got reset to 0), allocate a new instance of itermonarr;
4482.        implies that count is greater than 0 */
4483.     if (count > itermonsiz) {
4484.         /* overallocate to reduce free/alloc-again thrashing when the
4485.            number of monsters varies from turn to turn */
4486.         itermonsiz = count + 20;
4487.         itermonarr = (struct monst **) alloc(
4488.                                         itermonsiz * sizeof (struct monst *));
4489.     }
4490. }
4491. 
4492. /* Iterate all monsters on the level, even dead or off-map ones, calling
4493.    bfunc() for each monster.  If bfunc() returns TRUE, stop iterating.
4494.    If the game ends during the call to bfunc(), then freedynamicdata()
4495.    will free 'itermonarr'.
4496. 
4497.    Safe for list deletions and insertions, and guarantees calling bfunc()
4498.    once per monster in fmon unless it returns TRUE (or game ends). */
4499. void
4500. iter_mons_safe(boolean (*bfunc)(struct monst *))
4501. {
4502.     struct monst *mtmp;
4503.     unsigned i, nmons;
4504. 
4505.     for (nmons = 0, mtmp = fmon; mtmp; mtmp = mtmp->nmon)
4506.         nmons++;
4507. 
4508.     /* make sure itermonarr[] is big enough to hold nmons entries */
4509.     alloc_itermonarr(nmons);
4510. 
4511.     if (nmons) {
4512.         for (i = 0, mtmp = fmon; mtmp; mtmp = mtmp->nmon)
4513.             itermonarr[i++] = mtmp;
4514. 
4515.         for (i = 0; i < nmons; i++) {
4516.             mtmp = itermonarr[i];
4517.             if ((*bfunc)(mtmp))
4518.                 break;
4519.         }
4520.     }
4521.     return;
4522. }
4523. 
4524. 
4525. /* iterate all living monsters on current level, calling vfunc for each. */
4526. void
4527. iter_mons(void (*vfunc)(struct monst *))
4528. {
4529.     struct monst *mtmp, *mtmp2;
4530. 
4531.     for (mtmp = fmon; mtmp; mtmp = mtmp2) {
4532.         mtmp2 = mtmp->nmon;
4533.         if (DEADMONSTER(mtmp) || mon_offmap(mtmp))
4534.             continue;
4535.         (*vfunc)(mtmp);
4536.     }
4537.     return;
4538. }
4539. 
4540. 
4541. /* iterate all living monsters on current level, calling bfunc for each.
4542.    if bfunc returns TRUE, stop and return that monster. */
4543. struct monst *
4544. get_iter_mons(boolean (*bfunc)(struct monst *))
4545. {
4546.     struct monst *mtmp, *mtmp2;
4547. 
4548.     for (mtmp = fmon; mtmp; mtmp = mtmp2) {
4549.         mtmp2 = mtmp->nmon;
4550.         if (DEADMONSTER(mtmp) || mon_offmap(mtmp))
4551.             continue;
4552.         if ((*bfunc)(mtmp))
4553.             break;
4554.     }
4555.     return mtmp;
4556. }
4557. 
4558. /* iterate all living monsters on current level, calling bfunc for each,
4559.    passing x,y to the function.
4560.    if bfunc returns TRUE, stop and return that monster. */
4561. struct monst *
4562. get_iter_mons_xy(
4563.     boolean (*bfunc)(struct monst *, coordxy, coordxy),
4564.     coordxy x, coordxy y)
4565. {
4566.     struct monst *mtmp, *mtmp2;
4567. 
4568.     for (mtmp = fmon; mtmp; mtmp = mtmp2) {
4569.         mtmp2 = mtmp->nmon;
4570.         if (DEADMONSTER(mtmp) || mon_offmap(mtmp))
4571.             continue;
4572.         if ((*bfunc)(mtmp, x, y))
4573.             break;
4574.     }
4575.     return mtmp;
4576. }
4577. 
4578. 
4579. /* Heal the given monster by amt hitpoints, unless it is somehow prevented
4580.    from healing. "overheal" is the maximum amount by which the max HP will
4581.    increase to allow for the healing (the resulting HP caps at max HP +
4582.    overheal, and the max HP stays the some unless it needs to increase to
4583.    accommodate the new HP). Overhealing the player is not currently
4584.    implemented by this method.
4585. 
4586.    This function should only be used for situations which are conceptually
4587.    heals, rather than other situations where a monster's HP is set, so that
4588.    "prevent healing" effects work correctly. In particular, it should not
4589.    be used for cases where a monster's HP is restored upon revival, or when
4590.    a monster is created. It also shouldn't be used for lifesaving, which
4591.    overrides "cannot heal" effects.
4592. 
4593.    amt and overheal must not be negative (0 is allowed, and a very common
4594.    amount for overheal). Returns the number of hitpoints healed. */
4595. int
4596. healmon(struct monst *mtmp, int amt, int overheal)
4597. {
4598.     if (mtmp == &gy.youmonst) {
4599.         int oldhp = Upolyd ? u.mh : u.uhp;
4600.         healup(amt, 0, 0, 0);
4601.         return (Upolyd ? u.mh : u.uhp) - oldhp;
4602.     } else {
4603.         int oldhp = mtmp->mhp;
4604.         if (mtmp->mhp + amt > mtmp->mhpmax + overheal) {
4605.             mtmp->mhpmax += overheal;
4606.             mtmp->mhp = mtmp->mhpmax;
4607.         } else {
4608.             mtmp->mhp += amt;
4609.             if (mtmp->mhp > mtmp->mhpmax)
4610.                 mtmp->mhpmax = mtmp->mhp;
4611.         }
4612.         return mtmp->mhp - oldhp;
4613.     }
4614. }
4615. 
4616. 
4617. /* force all chameleons and mimics to become themselves and werecreatures
4618.    to revert to human form; called when Protection_from_shape_changers gets
4619.    activated via wearing or eating ring or via #wizintrinsic */
4620. void
4621. rescham(void)
4622. {
4623.     iter_mons(normal_shape);
4624. }
4625. 
4626. staticfn void
4627. m_restartcham(struct monst *mtmp)
4628. {
4629.     if (!mtmp->mcan)
4630.         mtmp->cham = pm_to_cham(monsndx(mtmp->data));
4631.     if (mtmp->data->mlet == S_MIMIC && mtmp->msleeping) {
4632.         set_mimic_sym(mtmp);
4633.         newsym(mtmp->mx, mtmp->my);
4634.     }
4635. }
4636. 
4637. /* let chameleons change and mimics hide again; called when taking off
4638.    ring of protection from shape changers */
4639. void
4640. restartcham(void)
4641. {
4642.     iter_mons(m_restartcham);
4643. }
4644. 
4645. /* called when restoring a monster from a saved level; protection
4646.    against shape-changing might be different now than it was at the
4647.    time the level was saved. */
4648. void
4649. restore_cham(struct monst *mon)
4650. {
4651.     if (Protection_from_shape_changers || mon->mcan) {
4652.         /* force chameleon or mimic to revert to its natural shape */
4653.         normal_shape(mon);
4654.     } else if (mon->cham == NON_PM) {
4655.         /* chameleon doesn't change shape here, just gets allowed to do so */
4656.         mon->cham = pm_to_cham(monsndx(mon->data));
4657.     }
4658. }
4659. 
4660. /* unwatched hiders may hide again; if so, returns True */
4661. staticfn boolean
4662. restrap(struct monst *mtmp)
4663. {
4664.     struct trap *t;
4665. 
4666.     if (mtmp->mcan || M_AP_TYPE(mtmp) || cansee(mtmp->mx, mtmp->my)
4667.         || rn2(3) || mtmp == u.ustuck
4668.         /* can't hide while trapped except in pits */
4669.         || (mtmp->mtrapped && (t = t_at(mtmp->mx, mtmp->my)) != 0
4670.             && !is_pit(t->ttyp))
4671.         /* can't hide on ceiling if there isn't one */
4672.         || (ceiling_hider(mtmp->data) && !has_ceiling(&u.uz))
4673.         /* won't hide when adjacent to hero */
4674.         || (sensemon(mtmp) && m_next2u(mtmp)))
4675.         return FALSE;
4676. 
4677.     if (mtmp->data->mlet == S_MIMIC) {
4678.         if (mtmp->msleeping || mtmp->mfrozen) {
4679.         /*
4680.          * The mimic needs to be awake to disguise itself
4681.          * as something else.
4682.          */
4683.             return FALSE;
4684.         }
4685.         set_mimic_sym(mtmp);
4686.         return TRUE;
4687.     } else if (levl[mtmp->mx][mtmp->my].typ == ROOM) {
4688.         mtmp->mundetected = 1;
4689.         return TRUE;
4690.     }
4691. 
4692.     return FALSE;
4693. }
4694. 
4695. /* reveal a hiding monster at x,y, either under nonexistent object,
4696.    or an eel out of water. */
4697. void
4698. maybe_unhide_at(coordxy x, coordxy y)
4699. {
4700.     struct monst *mtmp;
4701.     boolean undetected = FALSE, trapped = FALSE;
4702. 
4703.     if ((mtmp = m_at(x, y)) != (struct monst *) 0) {
4704.         undetected = mtmp->mundetected;
4705.         trapped = mtmp->mtrapped;
4706.     } else if (u_at(x, y)) {
4707.         mtmp = &gy.youmonst;
4708.         undetected = u.uundetected;
4709.         trapped = u.utrap;
4710.     } else {
4711.         return;
4712.     }
4713. 
4714.     if (undetected
4715.         && ((hides_under(mtmp->data)
4716.              && (!OBJ_AT(x, y) || trapped
4717.                  || !can_hide_under_obj(svl.level.objects[x][y])))
4718.             || (mtmp->data->mlet == S_EEL && !is_pool(x, y))))
4719.         (void) hideunder(mtmp);
4720. }
4721. 
4722. /* monster/hero tries to hide under something at the current location;
4723.    if used by monster creation, should only happen during level
4724.    creation, otherwise there will be message sequencing issues */
4725. boolean
4726. hideunder(struct monst *mtmp)
4727. {
4728.     struct trap *t;
4729.     struct obj *otmp;
4730.     const char *seenmon = (char *) 0, *seenobj = (char *) 0,
4731.                *locomo = (char *) 0;
4732.     int seeit = gi.in_mklev ? 0 : canseemon(mtmp);
4733.     boolean oldundetctd, undetected = FALSE, is_u = (mtmp == &gy.youmonst);
4734.     coordxy x = is_u ? u.ux : mtmp->mx, y = is_u ? u.uy : mtmp->my;
4735. 
4736.     if (mtmp == u.ustuck) {
4737.         ; /* undetected==FALSE; can't hide if holding you or held by you */
4738.     } else if ((is_u ? u.utrap : mtmp->mtrapped)
4739.                || ((t = t_at(x, y)) != 0 && !is_pit(t->ttyp))) {
4740.         ; /* undetected==FALSE; can't hide while trapped or on/in/under
4741.              any non-pit trap when not trapped */
4742.     } else if (mtmp->data->mlet == S_EEL) {
4743.         /* aquatic creatures only hide under water, not under objects;
4744.            they don't do so on the Plane of Water or when hero is also
4745.            under water unless some obstacle blocks line-of-sight */
4746.         undetected = (is_pool(x, y) && !Is_waterlevel(&u.uz)
4747.                       && (!Underwater || !couldsee(x, y)));
4748.         if (seeit) {
4749.             seenobj = "the water";
4750.             locomo = "dive";
4751.         }
4752.     } else if (hides_under(mtmp->data)
4753.                /* hider-underers only hide under objects */
4754.                && (otmp = svl.level.objects[x][y]) != 0
4755.                /* most things can be hidden under, but not all */
4756.                && can_hide_under_obj(otmp)
4757.                /* pets won't hide under a cursed item or an item of any BUC
4758.                   state that shares a pile with one or more cursed items */
4759.                && (!mtmp->mtame || !cursed_object_at(x, y))
4760.                /* aquatic creatures don't reach here; other swimmers
4761.                   shouldn't hide beneath underwater objects */
4762.                && !is_pool_or_lava(x, y)) {
4763.         if (seeit) /*&& (!is_pool(x, y) || (Underwater && distu(x, y) <= 2))*/
4764.             seenobj = ansimpleoname(otmp);
4765.         /* most monsters won't hide under a cockatrice corpse but they
4766.            can hide under a pile containing more than just such corpses */
4767.         if (is_u ? !Stone_resistance : !resists_ston(mtmp))
4768.             while (otmp && otmp->otyp == CORPSE
4769.                    && touch_petrifies(&mons[otmp->corpsenm]))
4770.                 otmp = otmp->nexthere;
4771.         if (otmp)
4772.             undetected = TRUE;
4773.     }
4774. 
4775.     if (is_u) {
4776.         oldundetctd = u.uundetected != 0;
4777.         u.uundetected = undetected ? 1 : 0;
4778. #if 0   /* feedback handled via #monster */
4779.         if (undetected && !oldundeteced && seenobj)
4780.             You("hide under %s.", seenobj);
4781. #endif
4782.     } else {
4783.         if (seeit)
4784.             seenmon = y_monnam(mtmp);
4785.         oldundetctd = mtmp->mundetected != 0;
4786.         mtmp->mundetected = undetected ? 1 : 0;
4787.         /* the "you see" message won't be shown for monster hiding during
4788.            level creation because 'seeit' will be 0 so 'seenmon' and 'seenobj'
4789.            will be Null */
4790.         if (undetected && seenmon && seenobj) {
4791.             if (!locomo)
4792.                 locomo = locomotion(mtmp->data, "hide");
4793.             set_msg_xy(mtmp->mx, mtmp->my); /* pline() will reset this */
4794.             You_see("%s %s under %s.", seenmon, locomo, seenobj);
4795.             iflags.last_msg = PLNMSG_HIDE_UNDER;
4796.             gl.last_hider = mtmp->m_id;
4797.         }
4798.     }
4799.     if (undetected != oldundetctd)
4800.         newsym(x, y);
4801.     return undetected;
4802. }
4803. 
4804. /* called when returning to a previously visited level */
4805. void
4806. hide_monst(struct monst *mon)
4807. {
4808.     boolean hider_under = hides_under(mon->data) || mon->data->mlet == S_EEL;
4809. 
4810.     if ((is_hider(mon->data) || hider_under)
4811.         && !(mon->mundetected || M_AP_TYPE(mon))) {
4812.         coordxy x = mon->mx, y = mon->my;
4813.         char save_viz = gv.viz_array[y][x];
4814. 
4815.         /* override vision, forcing hero to be unable to see monster's spot */
4816.         gv.viz_array[y][x] &= ~(IN_SIGHT | COULD_SEE);
4817.         if (is_hider(mon->data))
4818.             (void) restrap(mon);
4819.         /* try again if mimic missed its 1/3 chance to hide */
4820.         if (mon->data->mlet == S_MIMIC && !M_AP_TYPE(mon))
4821.             (void) restrap(mon);
4822.         gv.viz_array[y][x] = save_viz;
4823.         if (hider_under)
4824.             (void) hideunder(mon);
4825.     }
4826. }
4827. 
4828. void
4829. mon_animal_list(boolean construct)
4830. {
4831.     if (construct) {
4832.         short animal_temp[SPECIAL_PM];
4833.         int i, n;
4834. 
4835.         /* if (animal_list) impossible("animal_list already exists"); */
4836. 
4837.         for (n = 0, i = LOW_PM; i < SPECIAL_PM; i++)
4838.             if (is_animal(&mons[i]))
4839.                 animal_temp[n++] = i;
4840.         /* if (n == 0) animal_temp[n++] = NON_PM; */
4841. 
4842.         ga.animal_list = (short *) alloc(n * sizeof *ga.animal_list);
4843.         (void) memcpy((genericptr_t) ga.animal_list,
4844.                       (genericptr_t) animal_temp,
4845.                       n * sizeof *ga.animal_list);
4846.         ga.animal_list_count = n;
4847.     } else { /* release */
4848.         if (ga.animal_list)
4849.             free((genericptr_t) ga.animal_list), ga.animal_list = 0;
4850.         ga.animal_list_count = 0;
4851.     }
4852. }
4853. 
4854. staticfn int
4855. pick_animal(void)
4856. {
4857.     int res;
4858. 
4859.     if (!ga.animal_list)
4860.         mon_animal_list(TRUE);
4861.     assert(ga.animal_list != 0);
4862.     res = ga.animal_list[rn2(ga.animal_list_count)];
4863.     /* rogue level should use monsters represented by uppercase letters
4864.        only, but since chameleons aren't generated there (not uppercase!)
4865.        we don't perform a lot of retries */
4866.     if (Is_rogue_level(&u.uz) && !isupper(monsym(&mons[res])))
4867.         res = ga.animal_list[rn2(ga.animal_list_count)];
4868.     return res;
4869. }
4870. 
4871. void
4872. decide_to_shapeshift(struct monst *mon)
4873. {
4874.     struct permonst *ptr = 0;
4875.     int mndx;
4876.     unsigned was_female = mon->female;
4877.     boolean dochng = FALSE;
4878. 
4879.     if (!is_vampshifter(mon)) {
4880.         /* regular shapeshifter; 'ptr' is Null */
4881.         if (!mon->mspec_used && !rn2(6)) {
4882.             dochng = TRUE;
4883.             mon->mspec_used = 3 + rn2(10);
4884.         }
4885.     } else if (!(mon->mstrategy & STRAT_WAITFORU)) {
4886.         /* The vampire has to be in good health (mhp) to maintain
4887.          * its shifted form.
4888.          *
4889.          * If we're shifted and getting low on hp, maybe shift back, or
4890.          * if we're a fog cloud at full hp, maybe pick a different shape.
4891.          * If we're not already shifted and in good health, maybe shift.
4892.          */
4893.         if (mon->data->mlet != S_VAMPIRE) {
4894.             if ((mon->mhp <= (mon->mhpmax + 5) / 6) && rn2(4)
4895.                 && ismnum(mon->cham)) {
4896.                 ptr = &mons[mon->cham];
4897.                 dochng = TRUE;
4898.             } else if (mon->data == &mons[PM_FOG_CLOUD]
4899.                        && mon->mhp == mon->mhpmax && !rn2(4)
4900.                        && (!canseemon(mon)
4901.                            || mdistu(mon) > BOLT_LIM * BOLT_LIM)) {
4902.                 /* if a fog cloud, maybe change to wolf or vampire bat;
4903.                    those are more likely to take damage--at least when
4904.                    tame--and then switch back to vampire; they'll also
4905.                    switch to fog cloud if they encounter a closed door */
4906.                 mndx = pickvampshape(mon);
4907.                 if (ismnum(mndx)) {
4908.                     ptr = &mons[mndx];
4909.                     dochng = (ptr != mon->data);
4910.                 }
4911.             }
4912.             if (dochng && amorphous(mon->data)
4913.                 && closed_door(mon->mx, mon->my)) {
4914.                 coord new_xy;
4915. 
4916.                 if (enexto(&new_xy, mon->mx, mon->my, ptr)) {
4917.                     rloc_to(mon, new_xy.x, new_xy.y);
4918.                 }
4919.             }
4920.         } else {
4921.             if (mon->mhp >= 9 * mon->mhpmax / 10 && !rn2(6)
4922.                 && (!canseemon(mon)
4923.                     || mdistu(mon) > BOLT_LIM * BOLT_LIM))
4924.                 dochng = TRUE; /* 'ptr' stays Null */
4925.         }
4926.     }
4927.     if (dochng) {
4928.         if (newcham(mon, ptr, NC_SHOW_MSG)) {
4929.             /* for vampshift, override the 10% chance for sex change
4930.                (by forcing original gender in case that occurred) */
4931.             if (is_vampshifter(mon)) {
4932.                 ptr = mon->data;
4933.                 if (!is_male(ptr) && !is_female(ptr) && !is_neuter(ptr))
4934.                     mon->female = was_female;
4935.             }
4936.         }
4937.     }
4938. }
4939. 
4940. staticfn int
4941. pickvampshape(struct monst *mon)
4942. {
4943.     int mndx = mon->cham, wolfchance = 10;
4944.     /* avoid picking monsters with lowercase display symbols ('d' for wolf
4945.        and 'v' for fog cloud) on rogue level*/
4946.     boolean uppercase_only = Is_rogue_level(&u.uz);
4947. 
4948.     switch (mndx) {
4949.     case PM_VLAD_THE_IMPALER:
4950.         /* ensure Vlad can keep carrying the Candelabrum */
4951.         if (mon_has_special(mon))
4952.             break; /* leave mndx as is */
4953.         wolfchance = 3;
4954.         FALLTHROUGH;
4955.     /*FALLTHRU*/
4956.     case PM_VAMPIRE_LEADER: /* vampire lord or Vlad can become wolf */
4957.         if (!rn2(wolfchance) && !uppercase_only
4958.             /* don't pick a walking form if that would lead to immediate
4959.                drowning or immolation and reversion to vampire form */
4960.             && !is_pool_or_lava(mon->mx, mon->my)) {
4961.             mndx = PM_WOLF;
4962.             break;
4963.         }
4964.         FALLTHROUGH;
4965.     /*FALLTHRU*/
4966.     case PM_VAMPIRE: /* any vampire can become fog or bat */
4967.         mndx = (!rn2(4) && !uppercase_only) ? PM_FOG_CLOUD : PM_VAMPIRE_BAT;
4968.         break;
4969.     }
4970. 
4971.     /* return to base form if chosen poly target has been genocided
4972.        or randomly if already in an alternate form (to prevent always
4973.        switching back and forth between bat and fog) */
4974.     if ((svm.mvitals[mndx].mvflags & G_GENOD) != 0
4975.         || (mon->data != &mons[mon->cham] && !rn2(4)))
4976.         return mon->cham;
4977. 
4978.     return mndx;
4979. }
4980. 
4981. /* nonshapechangers who warrant special polymorph handling */
4982. staticfn boolean
4983. isspecmon(struct monst *mon)
4984. {
4985.     return (mon->isshk || mon->ispriest || mon->isgd
4986.             || mon->m_id == svq.quest_status.leader_m_id);
4987. }
4988. 
4989. /* restrict certain special monsters (shopkeepers, aligned priests,
4990.    vault guards) to forms that allow them to behave sensibly (catching
4991.    gold, speaking?) so that they don't need too much extra code */
4992. staticfn boolean
4993. validspecmon(struct monst *mon, int mndx)
4994. {
4995.     if (mndx == NON_PM)
4996.         return TRUE; /* caller wants random */
4997. 
4998.     if (!accept_newcham_form(mon, mndx))
4999.         return FALSE; /* geno'd or !polyok */
5000. 
5001.     if (isspecmon(mon)) {
5002.         struct permonst *ptr = &mons[mndx];
5003. 
5004.         /* reject notake because object manipulation is expected
5005.            and nohead because speech capability is expected */
5006.         if (notake(ptr) || !has_head(ptr))
5007.             return FALSE;
5008.         /* [should we check ptr->msound here too?] */
5009.     }
5010.     return TRUE; /* potential new form is ok */
5011. }
5012. 
5013. /* used for hero polyself handling */
5014. boolean
5015. valid_vampshiftform(int base, int form)
5016. {
5017.     if (base >= LOW_PM && is_vampire(&mons[base])) {
5018.         if (form == PM_VAMPIRE_BAT || form == PM_FOG_CLOUD
5019.             || (form == PM_WOLF && base != PM_VAMPIRE))
5020.             return TRUE;
5021.     }
5022.     return FALSE;
5023. }
5024. 
5025. /* prevent wizard mode user from specifying invalid vampshifter shape
5026.    when using monpolycontrol to assign a new form to a vampshifter */
5027. boolean
5028. validvamp(struct monst *mon, int *mndx_p, int monclass)
5029. {
5030.     /* simplify caller's usage */
5031.     if (!is_vampshifter(mon))
5032.         return validspecmon(mon, *mndx_p);
5033. 
5034.     if (mon->cham == PM_VLAD_THE_IMPALER && mon_has_special(mon)) {
5035.         /* Vlad with Candelabrum; override choice, then accept it */
5036.         *mndx_p = PM_VLAD_THE_IMPALER;
5037.         return TRUE;
5038.     }
5039.     if (ismnum(*mndx_p) && is_shapeshifter(&mons[*mndx_p])) {
5040.         /* player picked some type of shapeshifter; use mon's self
5041.            (vampire or chameleon) */
5042.         *mndx_p = mon->cham;
5043.         return TRUE;
5044.     }
5045.     /* basic vampires can't become wolves; any can become fog or bat
5046.        (we don't enforce upper-case only for rogue level here) */
5047.     if (*mndx_p == PM_WOLF)
5048.         return (boolean) (mon->cham != PM_VAMPIRE);
5049.     if (*mndx_p == PM_FOG_CLOUD || *mndx_p == PM_VAMPIRE_BAT)
5050.         return TRUE;
5051. 
5052.     /* if we get here, specific type was no good; try by class */
5053.     switch (monclass) {
5054.     case S_VAMPIRE:
5055.         *mndx_p = mon->cham;
5056.         break;
5057.     case S_BAT:
5058.         *mndx_p = PM_VAMPIRE_BAT;
5059.         break;
5060.     case S_VORTEX:
5061.         *mndx_p = PM_FOG_CLOUD;
5062.         break;
5063.     case S_DOG:
5064.         if (mon->cham != PM_VAMPIRE) {
5065.             *mndx_p = PM_WOLF;
5066.             break;
5067.         }
5068.         FALLTHROUGH;
5069.         /*FALLTHRU*/
5070.     default:
5071.         *mndx_p = NON_PM;
5072.         break;
5073.     }
5074.     return (boolean) (*mndx_p != NON_PM);
5075. }
5076. 
5077. staticfn int
5078. wiz_force_cham_form(struct monst *mon)
5079. {
5080.     char pprompt[BUFSZ], parttwo[QBUFSZ], buf[BUFSZ], prevbuf[BUFSZ];
5081.     int monclass, len, tryct, mndx = NON_PM;
5082. 
5083.     /* construct prompt in pieces */
5084.     Sprintf(pprompt, "Change %s", noit_mon_nam(mon));
5085.     Sprintf(parttwo, " @ %s into what?",
5086.             coord_desc((int) mon->mx, (int) mon->my, buf,
5087.                        (iflags.getpos_coords != GPCOORDS_NONE)
5088.                        ? iflags.getpos_coords : GPCOORDS_MAP));
5089.     /* combine the two parts, not exceeding QBUFSZ-1 in overall length;
5090.        if combined length is too long it has to be due to monster's
5091.        name so we'll chop enough of that off to fit the second part */
5092.     if ((len = (int) strlen(pprompt) + (int) strlen(parttwo)) >= QBUFSZ)
5093.         /* strlen(parttwo) is less than QBUFSZ/2 so strlen(pprompt) is
5094.            more than QBUFSZ/2 and excess amount being truncated can't
5095.            exceed pprompt's length and back up to before &pprompt[0]) */
5096.         *(eos(pprompt) - (len - (QBUFSZ - 1))) = '\0';
5097.     Strcat(pprompt, parttwo);
5098. 
5099.     buf[0] = prevbuf[0] = '\0'; /* clear buffer for EDIT_GETLIN */
5100. #define TRYLIMIT 5
5101.     tryct = TRYLIMIT;
5102.     do {
5103.         if (tryct == TRYLIMIT - 1) { /* first retry */
5104.             /* change "into what?" to "into what kind of monster?" */
5105.             if (strlen(pprompt) + sizeof " kind of monster" - 1 < QBUFSZ)
5106.                 Strcpy(eos(pprompt) - 1, " kind of monster?");
5107.         }
5108. #undef TRYLIMIT
5109.         monclass = 0;
5110.         getlin(pprompt, buf);
5111.         mungspaces(buf);
5112.         /* for ESC, take form selected above (might be NON_PM) */
5113.         if (*buf == '\033')
5114.             break;
5115.         /* for "*", use NON_PM to pick an arbitrary shape below */
5116.         if (!strcmp(buf, "*") || !strcmpi(buf, "random")) {
5117.             mndx = NON_PM;
5118.             break;
5119.         }
5120.         mndx = name_to_mon(buf, (int *) 0);
5121.         if (mndx == NON_PM) {
5122.             /* didn't get a type, so check whether it's a class
5123.                (single letter or text match with def_monsyms[]) */
5124.             monclass = name_to_monclass(buf, &mndx);
5125.             if (monclass && mndx == NON_PM)
5126.                 mndx = mkclass_poly(monclass);
5127.         }
5128.         if (ismnum(mndx)) {
5129.             /* got a specific type of monster; use it if we can */
5130.             if (validvamp(mon, &mndx, monclass))
5131.                 break;
5132.             /* can't; revert to random in case we exhaust tryct */
5133.             mndx = NON_PM;
5134.         }
5135. 
5136.         pline("It can't become that.");
5137. #ifdef EDIT_GETLIN
5138.         /* EDIT_GETLIN preloads the input buffer with the previous
5139.            response but we shouldn't just keep repeating that if player
5140.            leaves it unchanged; affects retry for empty input too */
5141.         if (!strcmp(buf, prevbuf))
5142.             Strcpy(buf, "random");
5143.         Strcpy(prevbuf, buf);
5144. #else
5145.         nhUse(prevbuf);
5146. #endif
5147.     } while (--tryct > 0);
5148. 
5149.     if (!tryct)
5150.         pline1(thats_enough_tries);
5151.     if (is_vampshifter(mon) && !validvamp(mon, &mndx, monclass))
5152.         mndx = pickvampshape(mon); /* don't resort to arbitrary */
5153.     return mndx;
5154. }
5155. 
5156. int
5157. select_newcham_form(struct monst *mon)
5158. {
5159.     int mndx = NON_PM, tryct;
5160. 
5161.     switch (mon->cham) {
5162.     case PM_SANDESTIN:
5163.         if (rn2(7))
5164.             mndx = pick_nasty(mons[PM_ARCHON].difficulty - 1);
5165.         break;
5166.     case PM_DOPPELGANGER:
5167.         if (!rn2(7)) {
5168.             mndx = pick_nasty(mons[PM_JABBERWOCK].difficulty - 1);
5169.         } else if (rn2(3)) { /* role monsters */
5170.             mndx = tt_doppel(mon);
5171.         } else if (!rn2(3)) { /* quest guardians */
5172.             mndx = rn1(PM_APPRENTICE - PM_STUDENT + 1, PM_STUDENT);
5173.             /* avoid own role's guardian */
5174.             if (mndx == gu.urole.guardnum)
5175.                 mndx = NON_PM;
5176.         } else { /* general humanoids */
5177.             tryct = 5;
5178.             do {
5179.                 mndx = rn1(SPECIAL_PM - LOW_PM, LOW_PM);
5180.                 /* assert(ismnum(mndx)); */
5181.                 if (humanoid(&mons[mndx]) && polyok(&mons[mndx]))
5182.                     break;
5183.             } while (--tryct > 0);
5184.             if (!tryct)
5185.                 mndx = NON_PM;
5186.         }
5187.         break;
5188.     case PM_CHAMELEON:
5189.         if (!rn2(3))
5190.             mndx = pick_animal();
5191.         break;
5192.     case PM_VLAD_THE_IMPALER:
5193.     case PM_VAMPIRE_LEADER:
5194.     case PM_VAMPIRE:
5195.         mndx = pickvampshape(mon);
5196.         break;
5197.     case NON_PM: /* ordinary */
5198.       {
5199.         struct obj *m_armr = which_armor(mon, W_ARM);
5200. 
5201.         if (m_armr && Is_dragon_scales(m_armr))
5202.             mndx = (int) (Dragon_scales_to_pm(m_armr) - mons);
5203.         else if (m_armr && Is_dragon_mail(m_armr))
5204.             mndx = (int) (Dragon_mail_to_pm(m_armr) - mons);
5205.       }
5206.         break;
5207.     }
5208. 
5209.     /* for debugging: allow control of polymorphed monster */
5210.     if (wizard && iflags.mon_polycontrol)
5211.         mndx = wiz_force_cham_form(mon);
5212. 
5213.     /* if no form was specified above, pick one at random now */
5214.     if (mndx == NON_PM) {
5215.         tryct = 50;
5216.         do {
5217.             mndx = rn1(SPECIAL_PM - LOW_PM, LOW_PM);
5218.             /* assert(ismnum(mndx); */
5219.         } while (--tryct > 0 && !validspecmon(mon, mndx)
5220.                  /* try harder to select uppercase monster on rogue level */
5221.                  && (tryct > 40 && Is_rogue_level(&u.uz)
5222.                      && !isupper(monsym(&mons[mndx]))));
5223.     }
5224.     return mndx;
5225. }
5226. 
5227. /* this used to be inline within newcham() but monpolycontrol needs it too */
5228. staticfn struct permonst *
5229. accept_newcham_form(struct monst *mon, int mndx)
5230. {
5231.     struct permonst *mdat;
5232. 
5233.     if (mndx == NON_PM)
5234.         return 0;
5235.     mdat = &mons[mndx];
5236.     if ((svm.mvitals[mndx].mvflags & G_GENOD) != 0)
5237.         return 0;
5238.     if (is_placeholder(mdat))
5239.         return 0;
5240.     /* select_newcham_form() might deliberately pick a player
5241.        character type (random selection never does) which
5242.        polyok() rejects, so we need a special case here */
5243.     if (is_mplayer(mdat))
5244.         return mdat;
5245.     /* shapeshifters are rejected by polyok() but allow a shapeshifter
5246.        to take on its 'natural' form */
5247.     if (is_shapeshifter(mdat)
5248.         && ismnum(mon->cham) && mdat == &mons[mon->cham])
5249.         return mdat;
5250.     /* polyok() rules out M2_PNAME, M2_WERE, and all humans except Kops */
5251.     return polyok(mdat) ? mdat : 0;
5252. }
5253. 
5254. /* shapechanger might take on a shape that forces gender change */
5255. void
5256. mgender_from_permonst(
5257.     struct monst *mtmp,
5258.     struct permonst *mdat)
5259. {
5260.     if (is_male(mdat)) {
5261.         mtmp->female = FALSE;
5262.     } else if (is_female(mdat)) {
5263.         mtmp->female = TRUE;
5264.     } else if (!is_neuter(mdat)) {
5265.         /* usually leave as-is; same chance to change as polymorphing hero;
5266.            vampires use controlled shapechange (from their perspective, even
5267.            if it is random from the player's perspective) and don't undergo
5268.            gender change */
5269.         if (!rn2(10) && !(is_vampire(mdat) || is_vampshifter(mtmp)))
5270.             mtmp->female = !mtmp->female;
5271.     }
5272. }
5273. 
5274. /* make a chameleon take on another shape, or a polymorph target
5275.    (possibly self-inflicted) become a different monster;
5276.    returns 1 if it actually changes form */
5277. int
5278. newcham(
5279.     struct monst *mtmp,
5280.     struct permonst *mdat,
5281.     unsigned ncflags)
5282. {
5283.     boolean polyspot = ((ncflags & NC_VIA_WAND_OR_SPELL) !=0),
5284.             /* "The oldmon turns into a newmon!" */
5285.             msg = ((ncflags & NC_SHOW_MSG) != 0),
5286.             seenorsensed = canspotmon(mtmp);
5287.     int hpn, hpd, mndx, tryct;
5288.     struct permonst *olddata = mtmp->data;
5289.     char *p, oldname[BUFSZ], l_oldname[BUFSZ];
5290. 
5291.     /* Riders are immune to polymorph and green slime
5292.        (but apparent Rider might actually be a doppelganger) */
5293.     if (mtmp->cham == NON_PM) { /* not a shapechanger */
5294.         if (is_rider(olddata))
5295.             return 0;
5296.         /* make Nazgul and erinyes immune too, to reduce chance of
5297.            anomalous extinction feedback during final disclosure */
5298.         if (mbirth_limit(monsndx(olddata)) < MAXMONNO)
5299.             return 0;
5300.         /* cancelled shapechangers become uncancelled prior
5301.            to being given a new shape */
5302.         if (mtmp->mcan && !Protection_from_shape_changers) {
5303.             mtmp->cham = pm_to_cham(monsndx(mtmp->data));
5304.             if (mtmp->cham != NON_PM)
5305.                 mtmp->mcan = 0;
5306.         }
5307.     }
5308. 
5309.     if (msg) {
5310.         Strcpy(oldname,
5311.                /* like YMonnam() but never mention saddle */
5312.                x_monnam(mtmp, mtmp->mtame ? ARTICLE_YOUR : ARTICLE_THE,
5313.                         (char *) 0, SUPPRESS_SADDLE, FALSE));
5314.         oldname[0] = highc(oldname[0]);
5315.     }
5316.     /* we need this one whether msg is true or not */
5317.     Strcpy(l_oldname, x_monnam(mtmp, ARTICLE_THE, (char *) 0,
5318.                                has_mgivenname(mtmp) ? SUPPRESS_SADDLE : 0,
5319.                                FALSE));
5320. 
5321.     /* mdat = 0 -> caller wants a random monster shape */
5322.     if (mdat == 0) {
5323.         /* select_newcham_form() loops when resorting to random but
5324.            it doesn't always pick that so we still retry here too */
5325.         tryct = 20;
5326.         do {
5327.             mndx = select_newcham_form(mtmp);
5328.             mdat = accept_newcham_form(mtmp, mndx);
5329.             /* for the first several tries we require upper-case on
5330.                the rogue level (after that, we take whatever we get) */
5331.             if (tryct > 15 && Is_rogue_level(&u.uz)
5332.                 && mdat && !isupper(monsym(mdat)))
5333.                 mdat = 0;
5334.             if (mdat)
5335.                 break;
5336.         } while (--tryct > 0);
5337.         if (!tryct)
5338.             return 0;
5339.     } else if (svm.mvitals[monsndx(mdat)].mvflags & G_GENOD)
5340.         return 0; /* passed in mdat is genocided */
5341. 
5342.     if (mdat == olddata)
5343.         return 0; /* still the same monster */
5344. 
5345.     mgender_from_permonst(mtmp, mdat);
5346.     /* Endgame mplayers start out as "Foo the Bar", but some of the
5347.      * titles are inappropriate when polymorphed, particularly into
5348.      * the opposite sex.  Player characters don't use ranks when
5349.      * polymorphed, so dropping rank for mplayers seems reasonable.
5350.      */
5351.     if (In_endgame(&u.uz) && is_mplayer(olddata)
5352.         && has_mgivenname(mtmp)
5353.         && (p = strstr(MGIVENNAME(mtmp), " the ")) != 0)
5354.         *p = '\0';
5355. 
5356.     if (mtmp->wormno) { /* throw tail away */
5357.         coordxy mx = mtmp->mx, my = mtmp->my;
5358. 
5359.         wormgone(mtmp); /* discards tail segments, takes head off the map */
5360.         /* put the head back; it will morph into mtmp's new form */
5361.         place_monster(mtmp, mx, my);
5362.     }
5363.     if (M_AP_TYPE(mtmp) && mdat->mlet != S_MIMIC)
5364.         seemimic(mtmp); /* revert to normal monster */
5365. 
5366.     /* (this code used to try to adjust the monster's health based on
5367.        a normal one of its type but there are too many special cases
5368.        which need to be handled in order to do that correctly, so just
5369.        give the new form the same proportion of HP as its old one had) */
5370.     hpn = mtmp->mhp;
5371.     hpd = mtmp->mhpmax;
5372.     /* set level and hit points */
5373.     newmonhp(mtmp, monsndx(mdat));
5374.     /* new hp: same fraction of max as before */
5375.     mtmp->mhp = (int) (((long) hpn * (long) mtmp->mhp) / (long) hpd);
5376.     /* sanity check (potential overflow) */
5377.     if (mtmp->mhp < 0 || mtmp->mhp > mtmp->mhpmax)
5378.         mtmp->mhp = mtmp->mhpmax;
5379.     /* unlikely but not impossible; a 1HD creature with 1HP that changes
5380.        into a 0HD creature will require this statement */
5381.     if (!mtmp->mhp)
5382.         mtmp->mhp = 1;
5383. 
5384.     /* take on the new form... */
5385.     set_mon_data(mtmp, mdat);
5386. 
5387.     if (mtmp->mleashed) {
5388.         if (!leashable(mtmp))
5389.             m_unleash(mtmp, TRUE);
5390.         else
5391.             /* if leashed, persistent inventory window needs updating
5392.                (really only when mon_nam() is going to yield "a frog"
5393.                rather than "Kermit" but no need to micromanage here) */
5394.             update_inventory(); /* x - leash (attached to a <mon>) */
5395.     }
5396. 
5397.     if (emits_light(olddata) != emits_light(mtmp->data)) {
5398.         /* used to give light, now doesn't, or vice versa,
5399.            or light's range has changed */
5400.         if (emits_light(olddata))
5401.             del_light_source(LS_MONSTER, monst_to_any(mtmp));
5402.         if (emits_light(mtmp->data))
5403.             new_light_source(mtmp->mx, mtmp->my, emits_light(mtmp->data),
5404.                              LS_MONSTER, monst_to_any(mtmp));
5405.     }
5406.     if (!mtmp->perminvis || pm_invisible(olddata))
5407.         mtmp->perminvis = pm_invisible(mdat);
5408.     mtmp->minvis = mtmp->invis_blkd ? 0 : mtmp->perminvis;
5409.     if (mtmp->mundetected)
5410.         (void) hideunder(mtmp);
5411.     if (u.ustuck == mtmp) {
5412.         if (u.uswallow) {
5413.             if (!attacktype(mdat, AT_ENGL)) {
5414.                 /* Does mdat care? */
5415.                 if (!noncorporeal(mdat) && !is_whirly(mdat)
5416.                     && !(amorphous(mdat) || mdat->mlet == S_LIGHT)) {
5417.                     char msgtrail[BUFSZ];
5418. 
5419.                     if (is_vampshifter(mtmp)) {
5420.                         Sprintf(msgtrail, " which was a shapeshifted %s",
5421.                                 noname_monnam(mtmp, ARTICLE_NONE));
5422.                     } else if (digests(mdat)) {
5423.                         Strcpy(msgtrail, "'s stomach");
5424.                     } else {
5425.                         msgtrail[0] = '\0';
5426.                     }
5427.                     /* Do this even if msg is FALSE */
5428.                     You("%s %s%s!",
5429.                         (amorphous(olddata) || is_whirly(olddata))
5430.                             ? "emerge from" : "break out of",
5431.                         l_oldname, msgtrail);
5432.                     msg = FALSE; /* message has been given */
5433.                     mtmp->mhp = 1; /* almost dead */
5434.                 }
5435.                 expels(mtmp, olddata, FALSE);
5436.             } else {
5437.                 /* update swallow glyphs for new monster */
5438.                 swallowed(0);
5439.             }
5440.         } else if ((!sticks(mdat) && !sticks(gy.youmonst.data))
5441.                    /* sticky hero can't continue to hold mtmp if it has
5442.                       turned into a non-solid creature; we don't use
5443.                       uunstick() for that because its message would be
5444.                       shown out of sequence [before 'if (msg)' below];
5445.                       unstuck() doesn't issue any messages */
5446.                    || unsolid(mdat)) {
5447.             unstuck(mtmp);
5448.         }
5449.     }
5450. 
5451.     if (mdat == &mons[PM_LONG_WORM] && (mtmp->wormno = get_wormno()) != 0) {
5452.         initworm(mtmp, rn2(5));
5453.         place_worm_tail_randomly(mtmp, mtmp->mx, mtmp->my);
5454.     }
5455. 
5456.     mtmp->meverseen = 0; /* never seen mon in present shape; newsym() ->
5457.                           * display_monster() may change it right back */
5458.     newsym(mtmp->mx, mtmp->my);
5459. 
5460.     if (msg) {
5461.         /* oldname is capitalized and might be an assigned name */
5462.         if (!canspotmon(mtmp)) { /* can't see or sense it now */
5463.             if (seenorsensed) /* could see or sense it before */
5464.                 pline_mon(mtmp, "%s disappears!", oldname);
5465.             (void) usmellmon(mdat);
5466.         } else if (!seenorsensed) { /* couldn't see/sense before, can now */
5467.             char *mnm = x_monnam(mtmp, mtmp->mtame ? ARTICLE_YOUR : ARTICLE_A,
5468.                                  (char *) 0, 0, FALSE);
5469. 
5470.             pline_mon(mtmp, "%s appears!", upstart(mnm));
5471.         } else { /* saw/sensed it before, still see/sense it now */
5472.             pline_mon(mtmp, "%s turns into %s!", oldname,
5473.                       /* "a <monster type>" even if it has a name assigned */
5474.                       noname_monnam(mtmp, ARTICLE_A));
5475.         }
5476.     }
5477. 
5478.     /* when polymorph trap/wand/potion produces a vampire, turn in into
5479.        a full-fledged vampshifter unless shape-changing is blocked */
5480.     if (mtmp->cham == NON_PM && mdat->mlet == S_VAMPIRE
5481.         && !Protection_from_shape_changers)
5482.         mtmp->cham = pm_to_cham(monsndx(mdat));
5483. 
5484.     possibly_unwield(mtmp, polyspot); /* might lose use of weapon */
5485.     mon_break_armor(mtmp, polyspot);
5486.     if (!(mtmp->misc_worn_check & W_ARMG))
5487.         mselftouch(mtmp, "No longer petrify-resistant, ",
5488.                    !svc.context.mon_moving);
5489.     check_gear_next_turn(mtmp);
5490. 
5491.     /* This ought to re-test can_carry() on each item in the inventory
5492.      * rather than just checking ex-giants & boulders, but that'd be
5493.      * pretty expensive to perform.  If implemented, then perhaps
5494.      * minvent should be sorted in order to drop heaviest items first.
5495.      */
5496.     /* former giants can't continue carrying boulders */
5497.     if (mtmp->minvent && !throws_rocks(mdat)) {
5498.         struct obj *otmp, *otmp2;
5499. 
5500.         /* DEADMONSTER(): it is possible for flooreffects() to kill mtmp;
5501.            the rest of its inventory would be dropped making otmp2 stale */
5502.         for (otmp = mtmp->minvent; otmp && !DEADMONSTER(mtmp); otmp = otmp2) {
5503.             otmp2 = otmp->nobj;
5504.             if (otmp->otyp == BOULDER) {
5505.                 /* this keeps otmp from being polymorphed in the
5506.                    same zap that the monster that held it is polymorphed */
5507.                 if (polyspot)
5508.                     bypass_obj(otmp);
5509.                 obj_extract_self(otmp);
5510.                 /* probably ought to give some "drop" message here */
5511.                 if (flooreffects(otmp, mtmp->mx, mtmp->my, ""))
5512.                     continue;
5513.                 place_object(otmp, mtmp->mx, mtmp->my);
5514.             }
5515.         }
5516.     }
5517.     if (mtmp == u.usteed)
5518.         poly_steed(mtmp, olddata);
5519. 
5520.     /* old form might not have been affected by Elbereth but perhaps the
5521.        new form is */
5522.     if (svc.context.mon_moving) {
5523.         /* give 'mtmp' a new chance to pinpoint hero's location */
5524.         if (!u_at(mtmp->mux, mtmp->muy))
5525.             set_apparxy(mtmp);
5526.         /* if hero is on Elbereth or scare monster, mtmp in new form might
5527.            become scared */
5528.         if (!mtmp->mpeaceful
5529.             && onscary(mtmp->mux, mtmp->muy, mtmp)
5530.             && monnear(mtmp, mtmp->mux, mtmp->muy))
5531.             monflee(mtmp, rn1(9, 2), TRUE, TRUE); /* 2..10 turns */
5532.     }
5533. 
5534.     return 1;
5535. }
5536. 
5537. /* sometimes an egg will be special */
5538. #define BREEDER_EGG (!rn2(77))
5539. 
5540. /*
5541.  * Determine if the given monster number can be hatched from an egg.
5542.  * Return the monster number to use as the egg's corpsenm.  Return
5543.  * NON_PM if the given monster can't be hatched.
5544.  */
5545. int
5546. can_be_hatched(int mnum)
5547. {
5548.     /* ranger quest nemesis has the oviparous bit set, making it
5549.        be possible to wish for eggs of that unique monster; turn
5550.        such into ordinary eggs rather than forbidding them outright */
5551.     if (mnum == PM_SCORPIUS)
5552.         mnum = PM_SCORPION;
5553. 
5554.     mnum = little_to_big(mnum);
5555.     /*
5556.      * Queen bees lay killer bee eggs (usually), but killer bees don't
5557.      * grow into queen bees.  Ditto for [winged-]gargoyles.
5558.      */
5559.     if (mnum == PM_KILLER_BEE || mnum == PM_GARGOYLE
5560.         || (lays_eggs(&mons[mnum])
5561.             && (BREEDER_EGG
5562.                 || (mnum != PM_QUEEN_BEE && mnum != PM_WINGED_GARGOYLE))))
5563.         return mnum;
5564.     return NON_PM;
5565. }
5566. 
5567. /* type of egg laid by #sit; usually matches parent */
5568. int
5569. egg_type_from_parent(
5570.     int mnum, /* parent monster; caller must handle lays_eggs() check */
5571.     boolean force_ordinary)
5572. {
5573.     if (force_ordinary || !BREEDER_EGG) {
5574.         if (mnum == PM_QUEEN_BEE)
5575.             mnum = PM_KILLER_BEE;
5576.         else if (mnum == PM_WINGED_GARGOYLE)
5577.             mnum = PM_GARGOYLE;
5578.     }
5579.     return mnum;
5580. }
5581. 
5582. #undef BREEDER_EGG
5583. 
5584. /* decide whether an egg of the indicated monster type is viable;
5585.    also used to determine whether an egg or tin can be created... */
5586. boolean
5587. dead_species(int m_idx, boolean egg)
5588. {
5589.     int alt_idx;
5590. 
5591.     /* generic eggs are unhatchable and have corpsenm of NON_PM */
5592.     if (m_idx < LOW_PM)
5593.         return TRUE;
5594.     /*
5595.      * For monsters with both baby and adult forms, genociding either
5596.      * form kills all eggs of that monster.  Monsters with more than
5597.      * two forms (small->large->giant mimics) are more or less ignored;
5598.      * fortunately, none of them have eggs.  Species extinction due to
5599.      * overpopulation does not kill eggs.
5600.      */
5601.     /* assert(ismnum(m_idx)); */
5602.     alt_idx = egg ? big_to_little(m_idx) : m_idx;
5603.     return (boolean) ((svm.mvitals[m_idx].mvflags & G_GENOD) != 0
5604.                       || (svm.mvitals[alt_idx].mvflags & G_GENOD) != 0);
5605. }
5606. 
5607. /* kill off any eggs of genocided monsters */
5608. staticfn void
5609. kill_eggs(struct obj *obj_list)
5610. {
5611.     struct obj *otmp;
5612. 
5613.     for (otmp = obj_list; otmp; otmp = otmp->nobj)
5614.         if (otmp->otyp == EGG) {
5615.             if (dead_species(otmp->corpsenm, TRUE)) {
5616.                 /*
5617.                  * It seems we could also just catch this when
5618.                  * it attempted to hatch, so we wouldn't have to
5619.                  * search all of the objlists.. or stop all
5620.                  * hatch timers based on a corpsenm.
5621.                  */
5622.                 kill_egg(otmp);
5623.             }
5624. #if 0 /* not used */
5625.         } else if (otmp->otyp == TIN) {
5626.             if (dead_species(otmp->corpsenm, FALSE))
5627.                 otmp->corpsenm = NON_PM; /* empty tin */
5628.         } else if (otmp->otyp == CORPSE) {
5629.             if (dead_species(otmp->corpsenm, FALSE))
5630.                 ; /* not yet implemented... */
5631. #endif
5632.         } else if (Has_contents(otmp)) {
5633.             kill_eggs(otmp->cobj);
5634.         }
5635. }
5636. 
5637. /* kill all members of genocided species */
5638. void
5639. kill_genocided_monsters(void)
5640. {
5641.     struct monst *mtmp, *mtmp2;
5642.     boolean kill_cham;
5643.     int mndx;
5644. 
5645.     /*
5646.      * Called during genocide, and again upon level change.  The latter
5647.      * catches up with any migrating monsters as they finally arrive at
5648.      * their intended destinations, so possessions get deposited there.
5649.      *
5650.      * Chameleon handling:
5651.      *  1) if chameleons have been genocided, destroy them
5652.      *     regardless of current form;
5653.      *  2) otherwise, force every chameleon which is imitating
5654.      *     any genocided species to take on a new form.
5655.      */
5656.     for (mtmp = fmon; mtmp; mtmp = mtmp2) {
5657.         mtmp2 = mtmp->nmon;
5658.         if (DEADMONSTER(mtmp))
5659.             continue;
5660.         mndx = monsndx(mtmp->data);
5661.         kill_cham = (ismnum(mtmp->cham)
5662.                      && (svm.mvitals[mtmp->cham].mvflags & G_GENOD));
5663.         if ((svm.mvitals[mndx].mvflags & G_GENOD) || kill_cham) {
5664.             if (ismnum(mtmp->cham) && !kill_cham)
5665.                 (void) newcham(mtmp, (struct permonst *) 0, NC_SHOW_MSG);
5666.             else
5667.                 mondead(mtmp);
5668.         }
5669.         if (mtmp->minvent)
5670.             kill_eggs(mtmp->minvent);
5671.     }
5672. 
5673.     kill_eggs(gi.invent);
5674.     kill_eggs(fobj);
5675.     kill_eggs(gm.migrating_objs);
5676.     kill_eggs(svl.level.buriedobjlist);
5677. }
5678. 
5679. void
5680. golemeffects(struct monst *mon, int damtype, int dam)
5681. {
5682.     int heal = 0, slow = 0;
5683. 
5684.     if (mon->data == &mons[PM_FLESH_GOLEM]) {
5685.         if (damtype == AD_ELEC)
5686.             heal = (dam + 5) / 6;
5687.         else if (damtype == AD_FIRE || damtype == AD_COLD)
5688.             slow = 1;
5689.     } else if (mon->data == &mons[PM_IRON_GOLEM]) {
5690.         if (damtype == AD_ELEC)
5691.             slow = 1;
5692.         else if (damtype == AD_FIRE)
5693.             heal = dam;
5694.     } else {
5695.         return;
5696.     }
5697.     if (slow) {
5698.         if (mon->mspeed != MSLOW)
5699.             mon_adjust_speed(mon, -1, (struct obj *) 0);
5700.     }
5701.     if (heal) {
5702.         if (healmon(mon, heal, 0)) {
5703.             if (cansee(mon->mx, mon->my))
5704.                 pline_mon(mon, "%s seems healthier.", Monnam(mon));
5705.         }
5706.     }
5707. }
5708. 
5709. /* anger the Minetown watch */
5710. boolean
5711. angry_guards(boolean silent)
5712. {
5713.     struct monst *mtmp;
5714.     int ct = 0, nct = 0, sct = 0, slct = 0;
5715. 
5716.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
5717.         if (DEADMONSTER(mtmp))
5718.             continue;
5719.         if (is_watch(mtmp->data) && mtmp->mpeaceful) {
5720.             ct++;
5721.             if (canspotmon(mtmp) && mtmp->mcanmove) {
5722.                 if (m_next2u(mtmp))
5723.                     nct++;
5724.                 else
5725.                     sct++;
5726.             }
5727.             if (mtmp->msleeping || mtmp->mfrozen) {
5728.                 slct++;
5729.                 mtmp->msleeping = mtmp->mfrozen = 0;
5730.             }
5731.             mtmp->mpeaceful = 0;
5732.         }
5733.     }
5734.     if (ct) {
5735.         if (!silent) { /* do we want pline msgs? */
5736.             char buf[BUFSZ];
5737. 
5738.             if (slct) { /* sleeping guard(s) */
5739.                 Sprintf(buf, "guard%s", plur(slct));
5740.                 pline_The("%s %s up.", buf, vtense(buf, "wake"));
5741.             }
5742. 
5743.             if (nct) { /* seen/sensed adjacent guard(s) */
5744.                 Sprintf(buf, "guard%s", plur(nct));
5745.                 pline_The("%s %s angry!", buf, vtense(buf, "get"));
5746.             } else if (sct) { /* seen/sensed non-adjacent guard(s) */
5747.                 Sprintf(buf, "guard%s", plur(sct));
5748.                 pline("%s %s %s approaching!",
5749.                       (sct == 1) ? "An angry" : "Angry",
5750.                       buf, vtense(buf, "are"));
5751.             } else {
5752.                 Strcpy(buf, (ct == 1) ? "a guard's" : "guards'");
5753.                 Soundeffect(se_shrill_whistle, 100);
5754.                 You_hear("the shrill sound of %s whistle%s.", buf, plur(ct));
5755.             }
5756.         }
5757.         return TRUE;
5758.     }
5759.     return FALSE;
5760. }
5761. 
5762. staticfn void
5763. pacify_guard(struct monst *mtmp)
5764. {
5765.     if (is_watch(mtmp->data))
5766.         mtmp->mpeaceful = 1;
5767. }
5768. 
5769. void
5770. pacify_guards(void)
5771. {
5772.     iter_mons(pacify_guard);
5773. }
5774. 
5775. void
5776. mimic_hit_msg(struct monst *mtmp, short otyp)
5777. {
5778.     short ap = mtmp->mappearance;
5779. 
5780.     switch (M_AP_TYPE(mtmp)) {
5781.     case M_AP_NOTHING:
5782.     case M_AP_FURNITURE:
5783.     case M_AP_MONSTER:
5784.         break;
5785.     case M_AP_OBJECT:
5786.         if (otyp == SPE_HEALING || otyp == SPE_EXTRA_HEALING) {
5787.             pline_mon(mtmp, "%s seems a more vivid %s than before.",
5788.                   The(simple_typename(ap)),
5789.                   c_obj_colors[objects[ap].oc_color]);
5790.         }
5791.         break;
5792.     }
5793. }
5794. 
5795. boolean
5796. usmellmon(struct permonst *mdat)
5797. {
5798.     int mndx;
5799.     boolean nonspecific = FALSE;
5800.     boolean msg_given = FALSE;
5801. 
5802.     if (mdat) {
5803.         if (!olfaction(gy.youmonst.data))
5804.             return FALSE;
5805.         mndx = monsndx(mdat);
5806.         switch (mndx) {
5807.         case PM_ROTHE:
5808.         case PM_MINOTAUR:
5809.             You("notice a bovine smell.");
5810.             msg_given = TRUE;
5811.             break;
5812.         case PM_CAVE_DWELLER:
5813.         case PM_BARBARIAN:
5814.         case PM_NEANDERTHAL:
5815.             You("smell body odor.");
5816.             msg_given = TRUE;
5817.             break;
5818.         /*
5819.         case PM_PESTILENCE:
5820.         case PM_FAMINE:
5821.         case PM_DEATH:
5822.             break;
5823.         */
5824.         case PM_HORNED_DEVIL:
5825.         case PM_BALROG:
5826.         case PM_ASMODEUS:
5827.         case PM_DISPATER:
5828.         case PM_YEENOGHU:
5829.         case PM_ORCUS:
5830.             break;
5831.         case PM_HUMAN_WEREJACKAL:
5832.         case PM_HUMAN_WERERAT:
5833.         case PM_HUMAN_WEREWOLF:
5834.         case PM_WEREJACKAL:
5835.         case PM_WERERAT:
5836.         case PM_WEREWOLF:
5837.         case PM_OWLBEAR:
5838.             You("detect an odor reminiscent of an animal's den.");
5839.             msg_given = TRUE;
5840.             break;
5841.         /*
5842.         case PM_PURPLE_WORM:
5843.             break;
5844.         */
5845.         case PM_STEAM_VORTEX:
5846.             You("smell steam.");
5847.             msg_given = TRUE;
5848.             break;
5849.         case PM_GREEN_SLIME:
5850.             pline("%s stinks.", Something);
5851.             msg_given = TRUE;
5852.             break;
5853.         case PM_VIOLET_FUNGUS:
5854.         case PM_SHRIEKER:
5855.             You("smell mushrooms.");
5856.             msg_given = TRUE;
5857.             break;
5858.         /* These are here to avoid triggering the
5859.            nonspecific treatment through the default case below*/
5860.         case PM_WHITE_UNICORN:
5861.         case PM_GRAY_UNICORN:
5862.         case PM_BLACK_UNICORN:
5863.         case PM_JELLYFISH:
5864.             break;
5865.         default:
5866.             nonspecific = TRUE;
5867.             break;
5868.         }
5869. 
5870.         if (nonspecific)
5871.             switch (mdat->mlet) {
5872.             case S_DOG:
5873.                 You("notice a dog smell.");
5874.                 msg_given = TRUE;
5875.                 break;
5876.             case S_DRAGON:
5877.                 You("smell a dragon!");
5878.                 msg_given = TRUE;
5879.                 break;
5880.             case S_FUNGUS:
5881.                 pline("%s smells moldy.", Something);
5882.                 msg_given = TRUE;
5883.                 break;
5884.             case S_UNICORN:
5885.                 You("detect a%s odor reminiscent of a stable.",
5886.                     (mndx == PM_PONY) ? "n" : " strong");
5887.                 msg_given = TRUE;
5888.                 break;
5889.             case S_ZOMBIE:
5890.                 You("smell rotting flesh.");
5891.                 msg_given = TRUE;
5892.                 break;
5893.             case S_EEL:
5894.                 You("smell fish.");
5895.                 msg_given = TRUE;
5896.                 break;
5897.             case S_ORC:
5898.                 if (maybe_polyd(is_orc(gy.youmonst.data), Race_if(PM_ORC)))
5899.                     You("notice an attractive smell.");
5900.                 else
5901.                     pline("A foul stench makes you feel a little nauseated.");
5902.                 msg_given = TRUE;
5903.                 break;
5904.             default:
5905.                 break;
5906.             }
5907.     }
5908.     return msg_given ? TRUE : FALSE;
5909. }
5910. 
5911. /* setting misc_worn_check's I_SPECIAL bit flags a monster to reassess
5912.    and potentially re-equip gear at the start of its next move;
5913.    this hides the details of that */
5914. void
5915. check_gear_next_turn(struct monst *mon)
5916. {
5917.     mon->misc_worn_check |= I_SPECIAL;
5918. }
5919. 
5920. /* make erinyes more dangerous based on your alignment abuse */
5921. void
5922. adj_erinys(unsigned abuse)
5923. {
5924.     struct permonst *pm = &mons[PM_ERINYS];
5925. 
5926.     if (abuse > 5L) {
5927.         pm->mflags1 |= M1_SEE_INVIS;
5928.     }
5929.     if (abuse > 10L) {
5930.         pm->mflags1 |= M1_AMPHIBIOUS;
5931.     }
5932.     if (abuse > 15L) {
5933.         pm->mflags1 |= M1_FLY;
5934.     }
5935.     if (abuse > 20L) {
5936.         /* more powerful attack */
5937.         pm->mattk[0].damn = 3;
5938.     }
5939.     if (abuse > 25L) {
5940.         pm->mflags1 |= M1_REGEN;
5941.     }
5942.     if (abuse > 30L) {
5943.         pm->mflags1 |= M1_TPORT_CNTRL;
5944.     }
5945.     if (abuse > 35L) {
5946.         /* second attack */
5947.         pm->mattk[1].aatyp = AT_WEAP;
5948.         pm->mattk[1].adtyp = AD_DRST;
5949.         pm->mattk[1].damn = 3;
5950.         pm->mattk[1].damd = 4;
5951.     }
5952.     if (abuse > 40L) {
5953.         pm->mflags1 |= M1_TPORT;
5954.     }
5955.     if (abuse > 50L) {
5956.         /* third (spellcasting) attack */
5957.         pm->mattk[2].aatyp = AT_MAGC;
5958.         pm->mattk[2].adtyp = AD_SPEL;
5959.         pm->mattk[2].damn = 3;
5960.         pm->mattk[2].damd = 4;
5961.     }
5962. 
5963.     /* also adjust level and difficulty */
5964.     pm->mlevel = min(7 + u.ualign.abuse, 50);
5965.     pm->difficulty = min(10 + (u.ualign.abuse / 3), 25);
5966. }
5967. 
5968. /* mark individual monster type as seen from close-up,
5969.    if we haven't seen it nearby before */
5970. void
5971. see_monster_closeup(struct monst *mtmp, boolean photo)
5972. {
5973.     int mndx;
5974. 
5975.     if (Hallucination || (Blind && !Blind_telepat))
5976.         return;
5977. 
5978.     mndx = monsndx(mtmp->data);
5979.     if (M_AP_TYPE(mtmp) == M_AP_MONSTER && !sensemon(mtmp))
5980.         mndx = mtmp->mappearance;
5981.     if (mndx == PM_LONG_WORM && gn.notonhead)
5982.         mndx = PM_LONG_WORM_TAIL;
5983. 
5984.     if (!svm.mvitals[mndx].seen_close) {
5985.         svm.mvitals[mndx].seen_close = 1;
5986.         svc.context.lifelist.total_seen_upclose++;
5987.     }
5988. 
5989.     /* hallucinatory monsters don't reach here--they're not recorded;
5990.        being able to see invisible doesn't make invisible monsters show up
5991.        on photos; likewise, telepathy allows hero to see hidden monsters
5992.        but doesn't cause them to appear on photos */
5993.     if (photo && !mtmp->minvis && !mtmp->mundetected
5994.         && (M_AP_TYPE(mtmp) == M_AP_NOTHING
5995.             || M_AP_TYPE(mtmp) == M_AP_MONSTER)) {
5996.         if (M_AP_TYPE(mtmp) == M_AP_MONSTER) /* cloned Wizard of Yendor */
5997.             mndx = mtmp->mappearance;
5998. 
5999.         if (!svm.mvitals[mndx].photographed) {
6000.             svm.mvitals[mndx].photographed = 1;
6001.             svc.context.lifelist.total_photographed++;
6002. 
6003.             /* tourist earns points (toward EXP but not final score) for
6004.                the first instance of each type of monster photographed;
6005.                worm tail can be photographed but yields no EXP bonus */
6006.             if (Role_if(PM_TOURIST)
6007.                 /* suppress extra points for photographing the pet that hero
6008.                    started with (unless it has changed shape due to growing
6009.                    up or being polymorphed) */
6010.                 && (mtmp->m_id != svc.context.startingpet_mid
6011.                     || mndx != svc.context.startingpet_typ)
6012.                 /* monsndx() check covers worm tail and also disguised
6013.                    Wizard of Yendor; experienced() won't yield a reasonable
6014.                    value for those */
6015.                 && mndx == monsndx(mtmp->data)) {
6016.                 more_experienced(experience(mtmp, 0), 0);
6017.                 newexplevel();
6018.             }
6019.         }
6020.     }
6021. }
6022. 
6023. /* mark a monster type as seen close-up when we see it next to us */
6024. void
6025. see_nearby_monsters(void)
6026. {
6027.     struct monst *mtmp;
6028.     int mndx;
6029.     coordxy x, y;
6030. 
6031.     if (Hallucination || (Blind && !Blind_telepat))
6032.         return;
6033. 
6034.     for (x = u.ux - 1; x <= u.ux + 1; x++)
6035.         for (y = u.uy - 1; y <= u.uy + 1; y++) {
6036.             if (!isok(x, y))
6037.                 continue;
6038.             if (!(mtmp = m_at(x, y)))
6039.                 continue;
6040.             mndx = monsndx(mtmp->data);
6041.             if (M_AP_TYPE(mtmp) == M_AP_MONSTER)
6042.                 mndx = mtmp->mappearance;
6043.             /* skip closeup handling if this mon type has already been done */
6044.             if (svm.mvitals[mndx].seen_close)
6045.                 continue;
6046.             /* disguised mimics pass canseemon(); undetected hiders don't */
6047.             if (canseemon(mtmp) || (mtmp->mundetected && sensemon(mtmp))) {
6048.                 gb.bhitpos.x = x, gb.bhitpos.y = y;
6049.                 gn.notonhead = (x != mtmp->mx || y != mtmp->my);
6050.                 see_monster_closeup(mtmp, FALSE);
6051.             }
6052.         }
6053. }
6054. 
6055. /* monster resists something.
6056.    make a shield effect at monster's location and give a message */
6057. void
6058. shieldeff_mon(struct monst *mtmp)
6059. {
6060.     shieldeff(mtmp->mx, mtmp->my);
6061.     /* does not depend on seeing the monster; the shield effect is visible */
6062.     if (cansee(mtmp->mx, mtmp->my))
6063.         pline_mon(mtmp, "%s resists!", Monnam(mtmp));
6064. }
6065. 
6066. void
6067. flash_mon(struct monst *mtmp)
6068. {
6069.     coordxy mx = mtmp->mx, my = mtmp->my;
6070.     int count = couldsee(mx, my) ? 8 : 4;
6071.     char saveviz = gv.viz_array[my][mx];
6072. 
6073.     if (!flags.sparkle)
6074.         count /= 2;
6075.     gv.viz_array[my][mx] |= (IN_SIGHT | COULD_SEE);
6076.     flash_glyph_at(mx, my, mon_to_glyph(mtmp, newsym_rn2), count);
6077.     gv.viz_array[my][mx] = saveviz;
6078.     newsym(mx, my);
6079. }
6080. 
6081. /* cleanup for 'onefile' processing */
6082. #undef LEVEL_SPECIFIC_NOCORPSE
6083. #undef KEEPTRAITS
6084. #undef mstoning
6085. #undef livelog_mon_nam
6086. #undef BREEDER_EGG
6087. 
6088. /*mon.c*/