Source:NetHack 3.6.4/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 3.6.4. To link to a particular line, write [[Source:NetHack 3.6.4/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 3.6	mon.c	$NHDT-Date: 1569276991 2019/09/23 22:16:31 $  $NHDT-Branch: NetHack-3.6 $:$NHDT-Revision: 1.297 $ */
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. /* If you're using precompiled headers, you don't want this either */
7. #ifdef MICROPORT_BUG
8. #define MKROOM_H
9. #endif
10. 
11. #include "hack.h"
12. #include "mfndpos.h"
13. #include <ctype.h>
14. 
15. STATIC_VAR boolean vamp_rise_msg, disintegested;
16. 
17. STATIC_DCL void FDECL(sanity_check_single_mon, (struct monst *, BOOLEAN_P,
18.                                                 const char *));
19. STATIC_DCL boolean FDECL(restrap, (struct monst *));
20. STATIC_DCL long FDECL(mm_aggression, (struct monst *, struct monst *));
21. STATIC_DCL long FDECL(mm_displacement, (struct monst *, struct monst *));
22. STATIC_DCL int NDECL(pick_animal);
23. STATIC_DCL void FDECL(kill_eggs, (struct obj *));
24. STATIC_DCL int FDECL(pickvampshape, (struct monst *));
25. STATIC_DCL boolean FDECL(isspecmon, (struct monst *));
26. STATIC_DCL boolean FDECL(validspecmon, (struct monst *, int));
27. STATIC_DCL struct permonst *FDECL(accept_newcham_form, (struct monst *, int));
28. STATIC_DCL struct obj *FDECL(make_corpse, (struct monst *, unsigned));
29. STATIC_DCL void FDECL(m_detach, (struct monst *, struct permonst *));
30. STATIC_DCL void FDECL(lifesaved_monster, (struct monst *));
31. STATIC_DCL void FDECL(migrate_mon, (struct monst *, XCHAR_P, XCHAR_P));
32. STATIC_DCL boolean FDECL(ok_to_obliterate, (struct monst *));
33. STATIC_DCL void FDECL(deal_with_overcrowding, (struct monst *));
34. 
35. /* note: duplicated in dog.c */
36. #define LEVEL_SPECIFIC_NOCORPSE(mdat) \
37.     (Is_rogue_level(&u.uz)            \
38.      || (level.flags.graveyard && is_undead(mdat) && rn2(3)))
39. 
40. #if 0
41. /* part of the original warning code which was replaced in 3.3.1 */
42. const char *warnings[] = {
43.     "white", "pink", "red", "ruby", "purple", "black"
44. };
45. #endif /* 0 */
46. 
47. 
48. STATIC_OVL void
49. sanity_check_single_mon(mtmp, chk_geno, msg)
50. struct monst *mtmp;
51. boolean chk_geno;
52. const char *msg;
53. {
54.     if (mtmp->data < &mons[LOW_PM] || mtmp->data >= &mons[NUMMONS]) {
55.         impossible("illegal mon data %s; mnum=%d (%s)",
56.                    fmt_ptr((genericptr_t) mtmp->data), mtmp->mnum, msg);
57.     } else {
58.         int mndx = monsndx(mtmp->data);
59. 
60.         if (mtmp->mnum != mndx) {
61.             impossible("monster mnum=%d, monsndx=%d (%s)",
62.                        mtmp->mnum, mndx, msg);
63.             mtmp->mnum = mndx;
64.         }
65.         if (DEADMONSTER(mtmp)) {
66. #if 0
67.             /* bad if not fmons list or if not vault guard */
68.             if (strcmp(msg, "fmon") || !mtmp->isgd)
69.                 impossible("dead monster on %s; %s at <%d,%d>",
70.                            msg, mons[mndx].mname, mtmp->mx, mtmp->my);
71. #endif
72.             return;
73.         }
74.         if (chk_geno && (mvitals[mndx].mvflags & G_GENOD) != 0)
75.             impossible("genocided %s in play (%s)", mons[mndx].mname, msg);
76.     }
77.     if (mtmp->isshk && !has_eshk(mtmp))
78.         impossible("shk without eshk (%s)", msg);
79.     if (mtmp->ispriest && !has_epri(mtmp))
80.         impossible("priest without epri (%s)", msg);
81.     if (mtmp->isgd && !has_egd(mtmp))
82.         impossible("guard without egd (%s)", msg);
83.     if (mtmp->isminion && !has_emin(mtmp))
84.         impossible("minion without emin (%s)", msg);
85.     /* guardian angel on astral level is tame but has emin rather than edog */
86.     if (mtmp->mtame && !has_edog(mtmp) && !mtmp->isminion)
87.         impossible("pet without edog (%s)", msg);
88. }
89. 
90. void
91. mon_sanity_check()
92. {
93.     int x, y;
94.     struct monst *mtmp, *m;
95. 
96.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
97.         /* dead monsters should still have sane data */
98.         sanity_check_single_mon(mtmp, TRUE, "fmon");
99.         if (DEADMONSTER(mtmp) && !mtmp->isgd)
100.             continue;
101. 
102.         x = mtmp->mx, y = mtmp->my;
103.         if (!isok(x, y) && !(mtmp->isgd && x == 0 && y == 0)) {
104.             impossible("mon (%s) claims to be at <%d,%d>?",
105.                        fmt_ptr((genericptr_t) mtmp), x, y);
106.         } else if (mtmp == u.usteed) {
107.             /* steed is in fmon list but not on the map; its
108.                <mx,my> coordinates should match hero's location */
109.             if (x != u.ux || y != u.uy)
110.                 impossible("steed (%s) claims to be at <%d,%d>?",
111.                            fmt_ptr((genericptr_t) mtmp), x, y);
112.         } else if (level.monsters[x][y] != mtmp) {
113.             impossible("mon (%s) at <%d,%d> is not there!",
114.                        fmt_ptr((genericptr_t) mtmp), x, y);
115.         } else if (mtmp->wormno) {
116.             sanity_check_worm(mtmp);
117.         }
118.     }
119. 
120.     for (x = 1; x < COLNO; x++)
121.         for (y = 0; y < ROWNO; y++)
122.             if ((mtmp = level.monsters[x][y]) != 0) {
123.                 for (m = fmon; m; m = m->nmon)
124.                     if (m == mtmp)
125.                         break;
126.                 if (!m)
127.                     impossible("map mon (%s) at <%d,%d> not in fmon list!",
128.                                fmt_ptr((genericptr_t) mtmp), x, y);
129.                 else if (mtmp == u.usteed)
130.                     impossible("steed (%s) is on the map at <%d,%d>!",
131.                                fmt_ptr((genericptr_t) mtmp), x, y);
132.                 else if ((mtmp->mx != x || mtmp->my != y)
133.                          && mtmp->data != &mons[PM_LONG_WORM])
134.                     impossible("map mon (%s) at <%d,%d> is found at <%d,%d>?",
135.                                fmt_ptr((genericptr_t) mtmp),
136.                                mtmp->mx, mtmp->my, x, y);
137.             }
138. 
139.     for (mtmp = migrating_mons; mtmp; mtmp = mtmp->nmon) {
140.         sanity_check_single_mon(mtmp, FALSE, "migr");
141.     }
142. }
143. 
144. 
145. /* convert the monster index of an undead to its living counterpart */
146. int
147. undead_to_corpse(mndx)
148. int mndx;
149. {
150.     switch (mndx) {
151.     case PM_KOBOLD_ZOMBIE:
152.     case PM_KOBOLD_MUMMY:
153.         mndx = PM_KOBOLD;
154.         break;
155.     case PM_DWARF_ZOMBIE:
156.     case PM_DWARF_MUMMY:
157.         mndx = PM_DWARF;
158.         break;
159.     case PM_GNOME_ZOMBIE:
160.     case PM_GNOME_MUMMY:
161.         mndx = PM_GNOME;
162.         break;
163.     case PM_ORC_ZOMBIE:
164.     case PM_ORC_MUMMY:
165.         mndx = PM_ORC;
166.         break;
167.     case PM_ELF_ZOMBIE:
168.     case PM_ELF_MUMMY:
169.         mndx = PM_ELF;
170.         break;
171.     case PM_VAMPIRE:
172.     case PM_VAMPIRE_LORD:
173. #if 0 /* DEFERRED */
174.     case PM_VAMPIRE_MAGE:
175. #endif
176.     case PM_HUMAN_ZOMBIE:
177.     case PM_HUMAN_MUMMY:
178.         mndx = PM_HUMAN;
179.         break;
180.     case PM_GIANT_ZOMBIE:
181.     case PM_GIANT_MUMMY:
182.         mndx = PM_GIANT;
183.         break;
184.     case PM_ETTIN_ZOMBIE:
185.     case PM_ETTIN_MUMMY:
186.         mndx = PM_ETTIN;
187.         break;
188.     default:
189.         break;
190.     }
191.     return mndx;
192. }
193. 
194. /* Convert the monster index of some monsters (such as quest guardians)
195.  * to their generic species type.
196.  *
197.  * Return associated character class monster, rather than species
198.  * if mode is 1.
199.  */
200. int
201. genus(mndx, mode)
202. int mndx, mode;
203. {
204.     switch (mndx) {
205.     /* Quest guardians */
206.     case PM_STUDENT:
207.         mndx = mode ? PM_ARCHEOLOGIST : PM_HUMAN;
208.         break;
209.     case PM_CHIEFTAIN:
210.         mndx = mode ? PM_BARBARIAN : PM_HUMAN;
211.         break;
212.     case PM_NEANDERTHAL:
213.         mndx = mode ? PM_CAVEMAN : PM_HUMAN;
214.         break;
215.     case PM_ATTENDANT:
216.         mndx = mode ? PM_HEALER : PM_HUMAN;
217.         break;
218.     case PM_PAGE:
219.         mndx = mode ? PM_KNIGHT : PM_HUMAN;
220.         break;
221.     case PM_ABBOT:
222.         mndx = mode ? PM_MONK : PM_HUMAN;
223.         break;
224.     case PM_ACOLYTE:
225.         mndx = mode ? PM_PRIEST : PM_HUMAN;
226.         break;
227.     case PM_HUNTER:
228.         mndx = mode ? PM_RANGER : PM_HUMAN;
229.         break;
230.     case PM_THUG:
231.         mndx = mode ? PM_ROGUE : PM_HUMAN;
232.         break;
233.     case PM_ROSHI:
234.         mndx = mode ? PM_SAMURAI : PM_HUMAN;
235.         break;
236.     case PM_GUIDE:
237.         mndx = mode ? PM_TOURIST : PM_HUMAN;
238.         break;
239.     case PM_APPRENTICE:
240.         mndx = mode ? PM_WIZARD : PM_HUMAN;
241.         break;
242.     case PM_WARRIOR:
243.         mndx = mode ? PM_VALKYRIE : PM_HUMAN;
244.         break;
245.     default:
246.         if (mndx >= LOW_PM && mndx < NUMMONS) {
247.             struct permonst *ptr = &mons[mndx];
248. 
249.             if (is_human(ptr))
250.                 mndx = PM_HUMAN;
251.             else if (is_elf(ptr))
252.                 mndx = PM_ELF;
253.             else if (is_dwarf(ptr))
254.                 mndx = PM_DWARF;
255.             else if (is_gnome(ptr))
256.                 mndx = PM_GNOME;
257.             else if (is_orc(ptr))
258.                 mndx = PM_ORC;
259.         }
260.         break;
261.     }
262.     return mndx;
263. }
264. 
265. /* return monster index if chameleon, or NON_PM if not */
266. int
267. pm_to_cham(mndx)
268. int mndx;
269. {
270.     int mcham = NON_PM;
271. 
272.     /*
273.      * As of 3.6.0 we just check M2_SHAPESHIFTER instead of having a
274.      * big switch statement with hardcoded shapeshifter types here.
275.      */
276.     if (mndx >= LOW_PM && is_shapeshifter(&mons[mndx]))
277.         mcham = mndx;
278.     return mcham;
279. }
280. 
281. /* for deciding whether corpse will carry along full monster data */
282. #define KEEPTRAITS(mon)                                                 \
283.     ((mon)->isshk || (mon)->mtame || unique_corpstat((mon)->data)       \
284.      || is_reviver((mon)->data)                                         \
285.         /* normally quest leader will be unique, */                     \
286.         /* but he or she might have been polymorphed  */                \
287.      || (mon)->m_id == quest_status.leader_m_id                         \
288.         /* special cancellation handling for these */                   \
289.      || (dmgtype((mon)->data, AD_SEDU) || dmgtype((mon)->data, AD_SSEX)))
290. 
291. /* Creates a monster corpse, a "special" corpse, or nothing if it doesn't
292.  * leave corpses.  Monsters which leave "special" corpses should have
293.  * G_NOCORPSE set in order to prevent wishing for one, finding tins of one,
294.  * etc....
295.  */
296. STATIC_OVL struct obj *
297. make_corpse(mtmp, corpseflags)
298. register struct monst *mtmp;
299. unsigned corpseflags;
300. {
301.     register struct permonst *mdat = mtmp->data;
302.     int num;
303.     struct obj *obj = (struct obj *) 0;
304.     struct obj *otmp = (struct obj *) 0;
305.     int x = mtmp->mx, y = mtmp->my;
306.     int mndx = monsndx(mdat);
307.     unsigned corpstatflags = corpseflags;
308.     boolean burythem = ((corpstatflags & CORPSTAT_BURIED) != 0);
309. 
310.     switch (mndx) {
311.     case PM_GRAY_DRAGON:
312.     case PM_SILVER_DRAGON:
313. #if 0 /* DEFERRED */
314.     case PM_SHIMMERING_DRAGON:
315. #endif
316.     case PM_RED_DRAGON:
317.     case PM_ORANGE_DRAGON:
318.     case PM_WHITE_DRAGON:
319.     case PM_BLACK_DRAGON:
320.     case PM_BLUE_DRAGON:
321.     case PM_GREEN_DRAGON:
322.     case PM_YELLOW_DRAGON:
323.         /* Make dragon scales.  This assumes that the order of the
324.            dragons is the same as the order of the scales. */
325.         if (!rn2(mtmp->mrevived ? 20 : 3)) {
326.             num = GRAY_DRAGON_SCALES + monsndx(mdat) - PM_GRAY_DRAGON;
327.             obj = mksobj_at(num, x, y, FALSE, FALSE);
328.             obj->spe = 0;
329.             obj->cursed = obj->blessed = FALSE;
330.         }
331.         goto default_1;
332.     case PM_WHITE_UNICORN:
333.     case PM_GRAY_UNICORN:
334.     case PM_BLACK_UNICORN:
335.         if (mtmp->mrevived && rn2(2)) {
336.             if (canseemon(mtmp))
337.                 pline("%s recently regrown horn crumbles to dust.",
338.                       s_suffix(Monnam(mtmp)));
339.         } else {
340.             obj = mksobj_at(UNICORN_HORN, x, y, TRUE, FALSE);
341.             if (obj && mtmp->mrevived)
342.                 obj->degraded_horn = 1;
343.         }
344.         goto default_1;
345.     case PM_LONG_WORM:
346.         (void) mksobj_at(WORM_TOOTH, x, y, TRUE, FALSE);
347.         goto default_1;
348.     case PM_VAMPIRE:
349.     case PM_VAMPIRE_LORD:
350.         /* include mtmp in the mkcorpstat() call */
351.         num = undead_to_corpse(mndx);
352.         corpstatflags |= CORPSTAT_INIT;
353.         obj = mkcorpstat(CORPSE, mtmp, &mons[num], x, y, corpstatflags);
354.         obj->age -= 100; /* this is an *OLD* corpse */
355.         break;
356.     case PM_KOBOLD_MUMMY:
357.     case PM_DWARF_MUMMY:
358.     case PM_GNOME_MUMMY:
359.     case PM_ORC_MUMMY:
360.     case PM_ELF_MUMMY:
361.     case PM_HUMAN_MUMMY:
362.     case PM_GIANT_MUMMY:
363.     case PM_ETTIN_MUMMY:
364.     case PM_KOBOLD_ZOMBIE:
365.     case PM_DWARF_ZOMBIE:
366.     case PM_GNOME_ZOMBIE:
367.     case PM_ORC_ZOMBIE:
368.     case PM_ELF_ZOMBIE:
369.     case PM_HUMAN_ZOMBIE:
370.     case PM_GIANT_ZOMBIE:
371.     case PM_ETTIN_ZOMBIE:
372.         num = undead_to_corpse(mndx);
373.         corpstatflags |= CORPSTAT_INIT;
374.         obj = mkcorpstat(CORPSE, mtmp, &mons[num], x, y, corpstatflags);
375.         obj->age -= 100; /* this is an *OLD* corpse */
376.         break;
377.     case PM_IRON_GOLEM:
378.         num = d(2, 6);
379.         while (num--)
380.             obj = mksobj_at(IRON_CHAIN, x, y, TRUE, FALSE);
381.         free_mname(mtmp); /* don't christen obj */
382.         break;
383.     case PM_GLASS_GOLEM:
384.         num = d(2, 4); /* very low chance of creating all glass gems */
385.         while (num--)
386.             obj = mksobj_at((LAST_GEM + rnd(9)), x, y, TRUE, FALSE);
387.         free_mname(mtmp);
388.         break;
389.     case PM_CLAY_GOLEM:
390.         obj = mksobj_at(ROCK, x, y, FALSE, FALSE);
391.         obj->quan = (long) (rn2(20) + 50);
392.         obj->owt = weight(obj);
393.         free_mname(mtmp);
394.         break;
395.     case PM_STONE_GOLEM:
396.         corpstatflags &= ~CORPSTAT_INIT;
397.         obj =
398.             mkcorpstat(STATUE, (struct monst *) 0, mdat, x, y, corpstatflags);
399.         break;
400.     case PM_WOOD_GOLEM:
401.         num = d(2, 4);
402.         while (num--) {
403.             obj = mksobj_at(QUARTERSTAFF, x, y, TRUE, FALSE);
404.         }
405.         free_mname(mtmp);
406.         break;
407.     case PM_LEATHER_GOLEM:
408.         num = d(2, 4);
409.         while (num--)
410.             obj = mksobj_at(LEATHER_ARMOR, x, y, TRUE, FALSE);
411.         free_mname(mtmp);
412.         break;
413.     case PM_GOLD_GOLEM:
414.         /* Good luck gives more coins */
415.         obj = mkgold((long) (200 - rnl(101)), x, y);
416.         free_mname(mtmp);
417.         break;
418.     case PM_PAPER_GOLEM:
419.         num = rnd(4);
420.         while (num--)
421.             obj = mksobj_at(SCR_BLANK_PAPER, x, y, TRUE, FALSE);
422.         free_mname(mtmp);
423.         break;
424.     /* expired puddings will congeal into a large blob;
425.        like dragons, relies on the order remaining consistent */
426.     case PM_GRAY_OOZE:
427.     case PM_BROWN_PUDDING:
428.     case PM_GREEN_SLIME:
429.     case PM_BLACK_PUDDING:
430.         /* we have to do this here because most other places
431.            expect there to be an object coming back; not this one */
432.         obj = mksobj_at(GLOB_OF_BLACK_PUDDING - (PM_BLACK_PUDDING - mndx),
433.                         x, y, TRUE, FALSE);
434. 
435.         while (obj && (otmp = obj_nexto(obj)) != (struct obj *) 0) {
436.             pudding_merge_message(obj, otmp);
437.             obj = obj_meld(&obj, &otmp);
438.         }
439.         free_mname(mtmp);
440.         return obj;
441.     default_1:
442.     default:
443.         if (mvitals[mndx].mvflags & G_NOCORPSE) {
444.             return (struct obj *) 0;
445.         } else {
446.             corpstatflags |= CORPSTAT_INIT;
447.             /* preserve the unique traits of some creatures */
448.             obj = mkcorpstat(CORPSE, KEEPTRAITS(mtmp) ? mtmp : 0,
449.                              mdat, x, y, corpstatflags);
450.             if (burythem) {
451.                 boolean dealloc;
452. 
453.                 (void) bury_an_obj(obj, &dealloc);
454.                 newsym(x, y);
455.                 return dealloc ? (struct obj *) 0 : obj;
456.             }
457.         }
458.         break;
459.     }
460.     /* All special cases should precede the G_NOCORPSE check */
461. 
462.     if (!obj)
463.         return (struct obj *) 0;
464. 
465.     /* if polymorph or undead turning has killed this monster,
466.        prevent the same attack beam from hitting its corpse */
467.     if (context.bypasses)
468.         bypass_obj(obj);
469. 
470.     if (has_mname(mtmp))
471.         obj = oname(obj, MNAME(mtmp));
472. 
473.     /*  Avoid "It was hidden under a green mold corpse!"
474.      *  during Blind combat. An unseen monster referred to as "it"
475.      *  could be killed and leave a corpse.  If a hider then hid
476.      *  underneath it, you could be told the corpse type of a
477.      *  monster that you never knew was there without this.
478.      *  The code in hitmu() substitutes the word "something"
479.      *  if the corpse's obj->dknown is 0.
480.      */
481.     if (Blind && !sensemon(mtmp))
482.         obj->dknown = 0;
483. 
484.     stackobj(obj);
485.     newsym(x, y);
486.     return obj;
487. }
488. 
489. /* check mtmp and water/lava for compatibility, 0 (survived), 1 (died) */
490. int
491. minliquid(mtmp)
492. register struct monst *mtmp;
493. {
494.     boolean inpool, inlava, infountain;
495. 
496.     /* [ceiling clingers are handled below] */
497.     inpool = (is_pool(mtmp->mx, mtmp->my)
498.               && (!(is_flyer(mtmp->data) || is_floater(mtmp->data))
499.                   /* there's no "above the surface" on the plane of water */
500.                   || Is_waterlevel(&u.uz)));
501.     inlava = (is_lava(mtmp->mx, mtmp->my)
502.               && !(is_flyer(mtmp->data) || is_floater(mtmp->data)));
503.     infountain = IS_FOUNTAIN(levl[mtmp->mx][mtmp->my].typ);
504. 
505.     /* Flying and levitation keeps our steed out of the liquid
506.        (but not water-walking or swimming; note: if hero is in a
507.        water location on the Plane of Water, flight and levitating
508.        are blocked so this (Flying || Levitation) test fails there
509.        and steed will be subject to water effects, as intended) */
510.     if (mtmp == u.usteed && (Flying || Levitation))
511.         return 0;
512. 
513.     /* Gremlin multiplying won't go on forever since the hit points
514.      * keep going down, and when it gets to 1 hit point the clone
515.      * function will fail.
516.      */
517.     if (mtmp->data == &mons[PM_GREMLIN] && (inpool || infountain) && rn2(3)) {
518.         if (split_mon(mtmp, (struct monst *) 0))
519.             dryup(mtmp->mx, mtmp->my, FALSE);
520.         if (inpool)
521.             water_damage_chain(mtmp->minvent, FALSE);
522.         return 0;
523.     } else if (mtmp->data == &mons[PM_IRON_GOLEM] && inpool && !rn2(5)) {
524.         int dam = d(2, 6);
525. 
526.         if (cansee(mtmp->mx, mtmp->my))
527.             pline("%s rusts.", Monnam(mtmp));
528.         mtmp->mhp -= dam;
529.         if (mtmp->mhpmax > dam)
530.             mtmp->mhpmax -= dam;
531.         if (DEADMONSTER(mtmp)) {
532.             mondead(mtmp);
533.             if (DEADMONSTER(mtmp))
534.                 return 1;
535.         }
536.         water_damage_chain(mtmp->minvent, FALSE);
537.         return 0;
538.     }
539. 
540.     if (inlava) {
541.         /*
542.          * Lava effects much as water effects. Lava likers are able to
543.          * protect their stuff. Fire resistant monsters can only protect
544.          * themselves  --ALI
545.          */
546.         if (!is_clinger(mtmp->data) && !likes_lava(mtmp->data)) {
547.             /* not fair...?  hero doesn't automatically teleport away
548.                from lava, just from water */
549.             if (can_teleport(mtmp->data) && !tele_restrict(mtmp)) {
550.                 if (rloc(mtmp, TRUE))
551.                     return 0;
552.             }
553.             if (!resists_fire(mtmp)) {
554.                 if (cansee(mtmp->mx, mtmp->my)) {
555.                     struct attack *dummy = &mtmp->data->mattk[0];
556.                     const char *how = on_fire(mtmp->data, dummy);
557. 
558.                     pline("%s %s.", Monnam(mtmp),
559.                           !strcmp(how, "boiling") ? "boils away"
560.                              : !strcmp(how, "melting") ? "melts away"
561.                                 : "burns to a crisp");
562.                 }
563.                 /* unlike fire -> melt ice -> pool, there's no way for the
564.                    hero to create lava beneath a monster, so the !mon_moving
565.                    case is not expected to happen (and we haven't made a
566.                    player-against-monster variation of the message above) */
567.                 if (context.mon_moving)
568.                     mondead(mtmp);
569.                 else
570.                     xkilled(mtmp, XKILL_NOMSG);
571.             } else {
572.                 mtmp->mhp -= 1;
573.                 if (DEADMONSTER(mtmp)) {
574.                     if (cansee(mtmp->mx, mtmp->my))
575.                         pline("%s surrenders to the fire.", Monnam(mtmp));
576.                     mondead(mtmp);
577.                 } else if (cansee(mtmp->mx, mtmp->my))
578.                     pline("%s burns slightly.", Monnam(mtmp));
579.             }
580.             if (!DEADMONSTER(mtmp)) {
581.                 (void) fire_damage_chain(mtmp->minvent, FALSE, FALSE,
582.                                          mtmp->mx, mtmp->my);
583.                 (void) rloc(mtmp, FALSE);
584.                 return 0;
585.             }
586.             return 1;
587.         }
588.     } else if (inpool) {
589.         /* Most monsters drown in pools.  flooreffects() will take care of
590.          * water damage to dead monsters' inventory, but survivors need to
591.          * be handled here.  Swimmers are able to protect their stuff...
592.          */
593.         if (!is_clinger(mtmp->data) && !is_swimmer(mtmp->data)
594.             && !amphibious(mtmp->data)) {
595.             /* like hero with teleport intrinsic or spell, teleport away
596.                if possible */
597.             if (can_teleport(mtmp->data) && !tele_restrict(mtmp)) {
598.                 if (rloc(mtmp, TRUE))
599.                     return 0;
600.             }
601.             if (cansee(mtmp->mx, mtmp->my)) {
602.                 if (context.mon_moving)
603.                     pline("%s drowns.", Monnam(mtmp));
604.                 else
605.                     /* hero used fire to melt ice that monster was on */
606.                     You("drown %s.", mon_nam(mtmp));
607.             }
608.             if (u.ustuck && u.uswallow && u.ustuck == mtmp) {
609.                 /* This can happen after a purple worm plucks you off a
610.                    flying steed while you are over water. */
611.                 pline("%s sinks as %s rushes in and flushes you out.",
612.                       Monnam(mtmp), hliquid("water"));
613.             }
614.             if (context.mon_moving)
615.                 mondead(mtmp);
616.             else
617.                 xkilled(mtmp, XKILL_NOMSG);
618.             if (!DEADMONSTER(mtmp)) {
619.                 water_damage_chain(mtmp->minvent, FALSE);
620.                 if (!rloc(mtmp, TRUE))
621.                     deal_with_overcrowding(mtmp);
622.                 return 0;
623.             }
624.             return 1;
625.         }
626.     } else {
627.         /* but eels have a difficult time outside */
628.         if (mtmp->data->mlet == S_EEL && !Is_waterlevel(&u.uz)) {
629.             /* as mhp gets lower, the rate of further loss slows down */
630.             if (mtmp->mhp > 1 && rn2(mtmp->mhp) > rn2(8))
631.                 mtmp->mhp--;
632.             monflee(mtmp, 2, FALSE, FALSE);
633.         }
634.     }
635.     return 0;
636. }
637. 
638. int
639. mcalcmove(mon)
640. struct monst *mon;
641. {
642.     int mmove = mon->data->mmove;
643.     int mmove_adj;
644. 
645.     /* Note: MSLOW's `+ 1' prevents slowed speed 1 getting reduced to 0;
646.      *       MFAST's `+ 2' prevents hasted speed 1 from becoming a no-op;
647.      *       both adjustments have negligible effect on higher speeds.
648.      */
649.     if (mon->mspeed == MSLOW)
650.         mmove = (2 * mmove + 1) / 3;
651.     else if (mon->mspeed == MFAST)
652.         mmove = (4 * mmove + 2) / 3;
653. 
654.     if (mon == u.usteed && u.ugallop && context.mv) {
655.         /* increase movement by a factor of 1.5; also increase variance of
656.            movement speed (if it's naturally 24, we don't want it to always
657.            become 36) */
658.         mmove = ((rn2(2) ? 4 : 5) * mmove) / 3;
659.     }
660. 
661.     /* Randomly round the monster's speed to a multiple of NORMAL_SPEED.
662.        This makes it impossible for the player to predict when they'll get
663.        a free turn (thus preventing exploits like "melee kiting"), while
664.        retaining guarantees about shopkeepers not being outsped by a
665.        normal-speed player, normal-speed players being unable to open up
666.        a gap when fleeing a normal-speed monster, etc. */
667.     mmove_adj = mmove % NORMAL_SPEED;
668.     mmove -= mmove_adj;
669.     if (rn2(NORMAL_SPEED) < mmove_adj)
670.         mmove += NORMAL_SPEED;
671. 
672.     return mmove;
673. }
674. 
675. /* actions that happen once per ``turn, regardless of each
676.    individual monster's metabolism; some of these might need to
677.    be reclassified to occur more in proportion with movement rate */
678. void
679. mcalcdistress()
680. {
681.     struct monst *mtmp;
682. 
683.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
684.         if (DEADMONSTER(mtmp))
685.             continue;
686. 
687.         /* must check non-moving monsters once/turn in case they managed
688.            to end up in water or lava; note: when not in liquid they regen,
689.            shape-shift, timeout temporary maladies just like other monsters */
690.         if (mtmp->data->mmove == 0) {
691.             if (vision_full_recalc)
692.                 vision_recalc(0);
693.             if (minliquid(mtmp))
694.                 continue;
695.         }
696. 
697.         /* regenerate hit points */
698.         mon_regen(mtmp, FALSE);
699. 
700.         /* possibly polymorph shapechangers and lycanthropes */
701.         if (mtmp->cham >= LOW_PM)
702.             decide_to_shapeshift(mtmp, (canspotmon(mtmp)
703.                                         || (u.uswallow && mtmp == u.ustuck))
704.                                           ? SHIFT_MSG : 0);
705.         were_change(mtmp);
706. 
707.         /* gradually time out temporary problems */
708.         if (mtmp->mblinded && !--mtmp->mblinded)
709.             mtmp->mcansee = 1;
710.         if (mtmp->mfrozen && !--mtmp->mfrozen)
711.             mtmp->mcanmove = 1;
712.         if (mtmp->mfleetim && !--mtmp->mfleetim)
713.             mtmp->mflee = 0;
714. 
715.         /* FIXME: mtmp->mlstmv ought to be updated here */
716.     }
717. }
718. 
719. int
720. movemon()
721. {
722.     register struct monst *mtmp, *nmtmp;
723.     register boolean somebody_can_move = FALSE;
724. 
725.     /*
726.      * Some of you may remember the former assertion here that
727.      * because of deaths and other actions, a simple one-pass
728.      * algorithm wasn't possible for movemon.  Deaths are no longer
729.      * removed to the separate list fdmon; they are simply left in
730.      * the chain with hit points <= 0, to be cleaned up at the end
731.      * of the pass.
732.      *
733.      * The only other actions which cause monsters to be removed from
734.      * the chain are level migrations and losedogs().  I believe losedogs()
735.      * is a cleanup routine not associated with monster movements, and
736.      * monsters can only affect level migrations on themselves, not others
737.      * (hence the fetching of nmon before moving the monster).  Currently,
738.      * monsters can jump into traps, read cursed scrolls of teleportation,
739.      * and drink cursed potions of raise level to change levels.  These are
740.      * all reflexive at this point.  Should one monster be able to level
741.      * teleport another, this scheme would have problems.
742.      */
743. 
744.     for (mtmp = fmon; mtmp; mtmp = nmtmp) {
745.         /* end monster movement early if hero is flagged to leave the level */
746.         if (u.utotype
747. #ifdef SAFERHANGUP
748.             /* or if the program has lost contact with the user */
749.             || program_state.done_hup
750. #endif
751.             ) {
752.             somebody_can_move = FALSE;
753.             break;
754.         }
755.         nmtmp = mtmp->nmon;
756.         /* one dead monster needs to perform a move after death: vault
757.            guard whose temporary corridor is still on the map; live
758.            guards who have led the hero back to civilization get moved
759.            off the map too; gd_move() decides whether the temporary
760.            corridor can be removed and guard discarded (via clearing
761.            mon->isgd flag so that dmonsfree() will get rid of mon) */
762.         if (mtmp->isgd && !mtmp->mx) {
763.             /* parked at <0,0>; eventually isgd should get set to false */
764.             if (monstermoves > mtmp->mlstmv) {
765.                 (void) gd_move(mtmp);
766.                 mtmp->mlstmv = monstermoves;
767.             }
768.             continue;
769.         }
770.         if (DEADMONSTER(mtmp))
771.             continue;
772. 
773.         /* Find a monster that we have not treated yet. */
774.         if (mtmp->movement < NORMAL_SPEED)
775.             continue;
776. 
777.         mtmp->movement -= NORMAL_SPEED;
778.         if (mtmp->movement >= NORMAL_SPEED)
779.             somebody_can_move = TRUE;
780. 
781.         if (vision_full_recalc)
782.             vision_recalc(0); /* vision! */
783. 
784.         /* reset obj bypasses before next monster moves */
785.         if (context.bypasses)
786.             clear_bypasses();
787.         clear_splitobjs();
788.         if (minliquid(mtmp))
789.             continue;
790. 
791.         /* after losing equipment, try to put on replacement */
792.         if (mtmp->misc_worn_check & I_SPECIAL) {
793.             long oldworn;
794. 
795.             mtmp->misc_worn_check &= ~I_SPECIAL;
796.             oldworn = mtmp->misc_worn_check;
797.             m_dowear(mtmp, FALSE);
798.             if (mtmp->misc_worn_check != oldworn || !mtmp->mcanmove)
799.                 continue;
800.         }
801. 
802.         if (is_hider(mtmp->data)) {
803.             /* unwatched mimics and piercers may hide again  [MRS] */
804.             if (restrap(mtmp))
805.                 continue;
806.             if (M_AP_TYPE(mtmp) == M_AP_FURNITURE
807.                 || M_AP_TYPE(mtmp) == M_AP_OBJECT)
808.                 continue;
809.             if (mtmp->mundetected)
810.                 continue;
811.         } else if (mtmp->data->mlet == S_EEL && !mtmp->mundetected
812.                    && (mtmp->mflee || distu(mtmp->mx, mtmp->my) > 2)
813.                    && !canseemon(mtmp) && !rn2(4)) {
814.             /* some eels end up stuck in isolated pools, where they
815.                can't--or at least won't--move, so they never reach
816.                their post-move chance to re-hide */
817.             if (hideunder(mtmp))
818.                 continue;
819.         }
820. 
821.         /* continue if the monster died fighting */
822.         if (Conflict && !mtmp->iswiz && mtmp->mcansee) {
823.             /* Note:
824.              *  Conflict does not take effect in the first round.
825.              *  Therefore, A monster when stepping into the area will
826.              *  get to swing at you.
827.              *
828.              *  The call to fightm() must be _last_.  The monster might
829.              *  have died if it returns 1.
830.              */
831.             if (couldsee(mtmp->mx, mtmp->my)
832.                 && (distu(mtmp->mx, mtmp->my) <= BOLT_LIM * BOLT_LIM)
833.                 && fightm(mtmp))
834.                 continue; /* mon might have died */
835.         }
836.         if (dochugw(mtmp)) /* otherwise just move the monster */
837.             continue;
838.     }
839. 
840.     if (any_light_source())
841.         vision_full_recalc = 1; /* in case a mon moved with a light source */
842.     /* reset obj bypasses after last monster has moved */
843.     if (context.bypasses)
844.         clear_bypasses();
845.     clear_splitobjs();
846.     /* remove dead monsters; dead vault guard will be left at <0,0>
847.        if temporary corridor out of vault hasn't been removed yet */
848.     dmonsfree();
849. 
850.     /* a monster may have levteleported player -dlc */
851.     if (u.utotype) {
852.         deferred_goto();
853.         /* changed levels, so these monsters are dormant */
854.         somebody_can_move = FALSE;
855.     }
856. 
857.     return somebody_can_move;
858. }
859. 
860. #define mstoning(obj)                                       \
861.     (ofood(obj) && (touch_petrifies(&mons[(obj)->corpsenm]) \
862.                     || (obj)->corpsenm == PM_MEDUSA))
863. 
864. /*
865.  * Maybe eat a metallic object (not just gold).
866.  * Return value: 0 => nothing happened, 1 => monster ate something,
867.  * 2 => monster died (it must have grown into a genocided form, but
868.  * that can't happen at present because nothing which eats objects
869.  * has young and old forms).
870.  */
871. int
872. meatmetal(mtmp)
873. register struct monst *mtmp;
874. {
875.     register struct obj *otmp;
876.     struct permonst *ptr;
877.     int poly, grow, heal, mstone;
878. 
879.     /* If a pet, eating is handled separately, in dog.c */
880.     if (mtmp->mtame)
881.         return 0;
882. 
883.     /* Eats topmost metal object if it is there */
884.     for (otmp = level.objects[mtmp->mx][mtmp->my]; otmp;
885.          otmp = otmp->nexthere) {
886.         /* Don't eat indigestible/choking/inappropriate objects */
887.         if ((mtmp->data == &mons[PM_RUST_MONSTER] && !is_rustprone(otmp))
888.             || (otmp->otyp == AMULET_OF_STRANGULATION)
889.             || (otmp->otyp == RIN_SLOW_DIGESTION))
890.             continue;
891.         if (is_metallic(otmp) && !obj_resists(otmp, 5, 95)
892.             && touch_artifact(otmp, mtmp)) {
893.             if (mtmp->data == &mons[PM_RUST_MONSTER] && otmp->oerodeproof) {
894.                 if (canseemon(mtmp) && flags.verbose) {
895.                     pline("%s eats %s!", Monnam(mtmp),
896.                           distant_name(otmp, doname));
897.                 }
898.                 /* The object's rustproofing is gone now */
899.                 otmp->oerodeproof = 0;
900.                 mtmp->mstun = 1;
901.                 if (canseemon(mtmp) && flags.verbose) {
902.                     pline("%s spits %s out in disgust!", Monnam(mtmp),
903.                           distant_name(otmp, doname));
904.                 }
905.             } else {
906.                 if (cansee(mtmp->mx, mtmp->my) && flags.verbose)
907.                     pline("%s eats %s!", Monnam(mtmp),
908.                           distant_name(otmp, doname));
909.                 else if (flags.verbose)
910.                     You_hear("a crunching sound.");
911.                 mtmp->meating = otmp->owt / 2 + 1;
912.                 /* Heal up to the object's weight in hp */
913.                 if (mtmp->mhp < mtmp->mhpmax) {
914.                     mtmp->mhp += objects[otmp->otyp].oc_weight;
915.                     if (mtmp->mhp > mtmp->mhpmax)
916.                         mtmp->mhp = mtmp->mhpmax;
917.                 }
918.                 if (otmp == uball) {
919.                     unpunish();
920.                     delobj(otmp);
921.                 } else if (otmp == uchain) {
922.                     unpunish(); /* frees uchain */
923.                 } else {
924.                     poly = polyfodder(otmp);
925.                     grow = mlevelgain(otmp);
926.                     heal = mhealup(otmp);
927.                     mstone = mstoning(otmp);
928.                     delobj(otmp);
929.                     ptr = mtmp->data;
930.                     if (poly) {
931.                         if (newcham(mtmp, (struct permonst *) 0, FALSE, FALSE))
932.                             ptr = mtmp->data;
933.                     } else if (grow) {
934.                         ptr = grow_up(mtmp, (struct monst *) 0);
935.                     } else if (mstone) {
936.                         if (poly_when_stoned(ptr)) {
937.                             mon_to_stone(mtmp);
938.                             ptr = mtmp->data;
939.                         } else if (!resists_ston(mtmp)) {
940.                             if (canseemon(mtmp))
941.                                 pline("%s turns to stone!", Monnam(mtmp));
942.                             monstone(mtmp);
943.                             ptr = (struct permonst *) 0;
944.                         }
945.                     } else if (heal) {
946.                         mtmp->mhp = mtmp->mhpmax;
947.                     }
948.                     if (!ptr)
949.                         return 2; /* it died */
950.                 }
951.                 /* Left behind a pile? */
952.                 if (rnd(25) < 3)
953.                     (void) mksobj_at(ROCK, mtmp->mx, mtmp->my, TRUE, FALSE);
954.                 newsym(mtmp->mx, mtmp->my);
955.                 return 1;
956.             }
957.         }
958.     }
959.     return 0;
960. }
961. 
962. /* monster eats a pile of objects */
963. int
964. meatobj(mtmp) /* for gelatinous cubes */
965. struct monst *mtmp;
966. {
967.     struct obj *otmp, *otmp2;
968.     struct permonst *ptr, *original_ptr = mtmp->data;
969.     int poly, grow, heal, eyes, count = 0, ecount = 0;
970.     char buf[BUFSZ];
971. 
972.     buf[0] = '\0';
973.     /* If a pet, eating is handled separately, in dog.c */
974.     if (mtmp->mtame)
975.         return 0;
976. 
977.     /* eat organic objects, including cloth and wood, if present;
978.        engulf others, except huge rocks and metal attached to player
979.        [despite comment at top, doesn't assume that eater is a g.cube] */
980.     for (otmp = level.objects[mtmp->mx][mtmp->my]; otmp; otmp = otmp2) {
981.         otmp2 = otmp->nexthere;
982. 
983.         /* touch sensitive items */
984.         if (otmp->otyp == CORPSE && is_rider(&mons[otmp->corpsenm])) {
985.             /* Rider corpse isn't just inedible; can't engulf it either */
986.             (void) revive_corpse(otmp);
987. 
988.         /* untouchable (or inaccessible) items */
989.         } else if ((otmp->otyp == CORPSE
990.                     && touch_petrifies(&mons[otmp->corpsenm])
991.                     && !resists_ston(mtmp))
992.                    /* don't engulf boulders and statues or ball&chain */
993.                    || otmp->oclass == ROCK_CLASS
994.                    || otmp == uball || otmp == uchain
995.                    /* normally mtmp won't have stepped onto scare monster
996.                       scroll, but if it does, don't eat or engulf that
997.                       (note: scrolls inside eaten containers will still
998.                       become engulfed) */
999.                    || otmp->otyp == SCR_SCARE_MONSTER) {
1000.             /* do nothing--neither eaten nor engulfed */
1001.             continue;
1002. 
1003.         /* inedible items -- engulf these */
1004.         } else if (!is_organic(otmp) || obj_resists(otmp, 5, 95)
1005.                    || !touch_artifact(otmp, mtmp)
1006.                    /* redundant due to non-organic composition but
1007.                       included for emphasis */
1008.                    || (otmp->otyp == AMULET_OF_STRANGULATION
1009.                        || otmp->otyp == RIN_SLOW_DIGESTION)
1010.                    /* cockatrice corpses handled above; this
1011.                       touch_petrifies() check catches eggs */
1012.                    || ((otmp->otyp == CORPSE || otmp->otyp == EGG
1013.                         || otmp->globby)
1014.                        && ((touch_petrifies(&mons[otmp->corpsenm])
1015.                             && !resists_ston(mtmp))
1016.                            || (otmp->corpsenm == PM_GREEN_SLIME
1017.                                && !slimeproof(mtmp->data))))) {
1018.             /* engulf */
1019.             ++ecount;
1020.             if (ecount == 1)
1021.                 Sprintf(buf, "%s engulfs %s.", Monnam(mtmp),
1022.                         distant_name(otmp, doname));
1023.             else if (ecount == 2)
1024.                 Sprintf(buf, "%s engulfs several objects.", Monnam(mtmp));
1025.             obj_extract_self(otmp);
1026.             (void) mpickobj(mtmp, otmp); /* slurp */
1027. 
1028.         /* lastly, edible items; yum! */
1029.         } else {
1030.             /* devour */
1031.             ++count;
1032.             if (cansee(mtmp->mx, mtmp->my)) {
1033.                 if (flags.verbose)
1034.                     pline("%s eats %s!", Monnam(mtmp),
1035.                           distant_name(otmp, doname));
1036.                 /* give this one even if !verbose */
1037.                 if (otmp->oclass == SCROLL_CLASS
1038.                     && !strcmpi(OBJ_DESCR(objects[otmp->otyp]), "YUM YUM"))
1039.                     pline("Yum%c", otmp->blessed ? '!' : '.');
1040.             } else {
1041.                 if (flags.verbose)
1042.                     You_hear("a slurping sound.");
1043.             }
1044.             /* Heal up to the object's weight in hp */
1045.             if (mtmp->mhp < mtmp->mhpmax) {
1046.                 mtmp->mhp += objects[otmp->otyp].oc_weight;
1047.                 if (mtmp->mhp > mtmp->mhpmax)
1048.                     mtmp->mhp = mtmp->mhpmax;
1049.             }
1050.             if (Has_contents(otmp)) {
1051.                 register struct obj *otmp3;
1052. 
1053.                 /* contents of eaten containers become engulfed; this
1054.                    is arbitrary, but otherwise g.cubes are too powerful */
1055.                 while ((otmp3 = otmp->cobj) != 0) {
1056.                     obj_extract_self(otmp3);
1057.                     if (otmp->otyp == ICE_BOX && otmp3->otyp == CORPSE) {
1058.                         otmp3->age = monstermoves - otmp3->age;
1059.                         start_corpse_timeout(otmp3);
1060.                     }
1061.                     (void) mpickobj(mtmp, otmp3);
1062.                 }
1063.             }
1064.             poly = polyfodder(otmp);
1065.             grow = mlevelgain(otmp);
1066.             heal = mhealup(otmp);
1067.             eyes = (otmp->otyp == CARROT);
1068.             delobj(otmp); /* munch */
1069.             ptr = mtmp->data;
1070.             if (poly) {
1071.                 if (newcham(mtmp, (struct permonst *) 0, FALSE, FALSE))
1072.                     ptr = mtmp->data;
1073.             } else if (grow) {
1074.                 ptr = grow_up(mtmp, (struct monst *) 0);
1075.             } else if (heal) {
1076.                 mtmp->mhp = mtmp->mhpmax;
1077.             }
1078.             if ((eyes || heal) && !mtmp->mcansee)
1079.                 mcureblindness(mtmp, canseemon(mtmp));
1080.             /* in case it polymorphed or died */
1081.             if (ptr != original_ptr)
1082.                 return !ptr ? 2 : 1;
1083.         }
1084. 
1085.         /* Engulf & devour is instant, so don't set meating */
1086.         if (mtmp->minvis)
1087.             newsym(mtmp->mx, mtmp->my);
1088.     }
1089. 
1090.     if (ecount > 0) {
1091.         if (cansee(mtmp->mx, mtmp->my) && flags.verbose && buf[0])
1092.             pline1(buf);
1093.         else if (flags.verbose)
1094.             You_hear("%s slurping sound%s.",
1095.                      (ecount == 1) ? "a" : "several", plur(ecount));
1096.     }
1097.     return (count > 0 || ecount > 0) ? 1 : 0;
1098. }
1099. 
1100. void
1101. mpickgold(mtmp)
1102. register struct monst *mtmp;
1103. {
1104.     register struct obj *gold;
1105.     int mat_idx;
1106. 
1107.     if ((gold = g_at(mtmp->mx, mtmp->my)) != 0) {
1108.         mat_idx = objects[gold->otyp].oc_material;
1109.         obj_extract_self(gold);
1110.         add_to_minv(mtmp, gold);
1111.         if (cansee(mtmp->mx, mtmp->my)) {
1112.             if (flags.verbose && !mtmp->isgd)
1113.                 pline("%s picks up some %s.", Monnam(mtmp),
1114.                       mat_idx == GOLD ? "gold" : "money");
1115.             newsym(mtmp->mx, mtmp->my);
1116.         }
1117.     }
1118. }
1119. 
1120. boolean
1121. mpickstuff(mtmp, str)
1122. register struct monst *mtmp;
1123. register const char *str;
1124. {
1125.     register struct obj *otmp, *otmp2, *otmp3;
1126.     int carryamt = 0;
1127. 
1128.     /* prevent shopkeepers from leaving the door of their shop */
1129.     if (mtmp->isshk && inhishop(mtmp))
1130.         return FALSE;
1131. 
1132.     for (otmp = level.objects[mtmp->mx][mtmp->my]; otmp; otmp = otmp2) {
1133.         otmp2 = otmp->nexthere;
1134.         /* Nymphs take everything.  Most monsters don't pick up corpses. */
1135.         if (!str ? searches_for_item(mtmp, otmp)
1136.                  : !!(index(str, otmp->oclass))) {
1137.             if (otmp->otyp == CORPSE && mtmp->data->mlet != S_NYMPH
1138.                 /* let a handful of corpse types thru to can_carry() */
1139.                 && !touch_petrifies(&mons[otmp->corpsenm])
1140.                 && otmp->corpsenm != PM_LIZARD
1141.                 && !acidic(&mons[otmp->corpsenm]))
1142.                 continue;
1143.             if (!touch_artifact(otmp, mtmp))
1144.                 continue;
1145.             carryamt = can_carry(mtmp, otmp);
1146.             if (carryamt == 0)
1147.                 continue;
1148.             if (is_pool(mtmp->mx, mtmp->my))
1149.                 continue;
1150.             /* handle cases where the critter can only get some */
1151.             otmp3 = otmp;
1152.             if (carryamt != otmp->quan) {
1153.                 otmp3 = splitobj(otmp, carryamt);
1154.             }
1155.             if (cansee(mtmp->mx, mtmp->my) && flags.verbose)
1156.                 pline("%s picks up %s.", Monnam(mtmp),
1157.                       (distu(mtmp->mx, mtmp->my) <= 5)
1158.                           ? doname(otmp3)
1159.                           : distant_name(otmp3, doname));
1160.             obj_extract_self(otmp3);      /* remove from floor */
1161.             (void) mpickobj(mtmp, otmp3); /* may merge and free otmp3 */
1162.             m_dowear(mtmp, FALSE);
1163.             newsym(mtmp->mx, mtmp->my);
1164.             return TRUE; /* pick only one object */
1165.         }
1166.     }
1167.     return FALSE;
1168. }
1169. 
1170. int
1171. curr_mon_load(mtmp)
1172. struct monst *mtmp;
1173. {
1174.     int curload = 0;
1175.     struct obj *obj;
1176. 
1177.     for (obj = mtmp->minvent; obj; obj = obj->nobj) {
1178.         if (obj->otyp != BOULDER || !throws_rocks(mtmp->data))
1179.             curload += obj->owt;
1180.     }
1181. 
1182.     return curload;
1183. }
1184. 
1185. int
1186. max_mon_load(mtmp)
1187. struct monst *mtmp;
1188. {
1189.     long maxload;
1190. 
1191.     /* Base monster carrying capacity is equal to human maximum
1192.      * carrying capacity, or half human maximum if not strong.
1193.      * (for a polymorphed player, the value used would be the
1194.      * non-polymorphed carrying capacity instead of max/half max).
1195.      * This is then modified by the ratio between the monster weights
1196.      * and human weights.  Corpseless monsters are given a capacity
1197.      * proportional to their size instead of weight.
1198.      */
1199.     if (!mtmp->data->cwt)
1200.         maxload = (MAX_CARR_CAP * (long) mtmp->data->msize) / MZ_HUMAN;
1201.     else if (!strongmonst(mtmp->data)
1202.              || (strongmonst(mtmp->data) && (mtmp->data->cwt > WT_HUMAN)))
1203.         maxload = (MAX_CARR_CAP * (long) mtmp->data->cwt) / WT_HUMAN;
1204.     else
1205.         maxload = MAX_CARR_CAP; /*strong monsters w/cwt <= WT_HUMAN*/
1206. 
1207.     if (!strongmonst(mtmp->data))
1208.         maxload /= 2;
1209. 
1210.     if (maxload < 1)
1211.         maxload = 1;
1212. 
1213.     return (int) maxload;
1214. }
1215. 
1216. /* for restricting monsters' object-pickup.
1217.  *
1218.  * to support the new pet behavior, this now returns the max # of objects
1219.  * that a given monster could pick up from a pile. frequently this will be
1220.  * otmp->quan, but special cases for 'only one' now exist so.
1221.  *
1222.  * this will probably cause very amusing behavior with pets and gold coins.
1223.  *
1224.  * TODO: allow picking up 2-N objects from a pile of N based on weight.
1225.  *       Change from 'int' to 'long' to accomate big stacks of gold.
1226.  *       Right now we fake it by reporting a partial quantity, but the
1227.  *       likesgold handling m_move results in picking up the whole stack.
1228.  */
1229. int
1230. can_carry(mtmp, otmp)
1231. struct monst *mtmp;
1232. struct obj *otmp;
1233. {
1234.     int iquan, otyp = otmp->otyp, newload = otmp->owt;
1235.     struct permonst *mdat = mtmp->data;
1236.     short nattk = 0;
1237. 
1238.     if (notake(mdat))
1239.         return 0; /* can't carry anything */
1240. 
1241.     if (otyp == CORPSE && touch_petrifies(&mons[otmp->corpsenm])
1242.         && !(mtmp->misc_worn_check & W_ARMG) && !resists_ston(mtmp))
1243.         return 0;
1244.     if (otyp == CORPSE && is_rider(&mons[otmp->corpsenm]))
1245.         return 0;
1246.     if (objects[otyp].oc_material == SILVER && mon_hates_silver(mtmp)
1247.         && (otyp != BELL_OF_OPENING || !is_covetous(mdat)))
1248.         return 0;
1249. 
1250.     /* hostile monsters who like gold will pick up the whole stack;
1251.        tame mosnters with hands will pick up the partial stack */
1252.     iquan = (otmp->quan > (long) LARGEST_INT)
1253.                ? 20000 + rn2(LARGEST_INT - 20000 + 1)
1254.                : (int) otmp->quan;
1255. 
1256.     /* monsters without hands can't pick up multiple objects at once
1257.      * unless they have an engulfing attack
1258.      *
1259.      * ...dragons, of course, can always carry gold pieces and gems somehow
1260.      */
1261.     if (iquan > 1) {
1262.         boolean glomper = FALSE;
1263. 
1264.         if (mtmp->data->mlet == S_DRAGON
1265.             && (otmp->oclass == COIN_CLASS
1266.                 || otmp->oclass == GEM_CLASS))
1267.             glomper = TRUE;
1268.         else
1269.             for (nattk = 0; nattk < NATTK; nattk++)
1270.                 if (mtmp->data->mattk[nattk].aatyp == AT_ENGL) {
1271.                     glomper = TRUE;
1272.                     break;
1273.                 }
1274.         if ((mtmp->data->mflags1 & M1_NOHANDS) && !glomper)
1275.             return 1;
1276.     }
1277. 
1278.     /* steeds don't pick up stuff (to avoid shop abuse) */
1279.     if (mtmp == u.usteed)
1280.         return 0;
1281.     if (mtmp->isshk)
1282.         return iquan; /* no limit */
1283.     if (mtmp->mpeaceful && !mtmp->mtame)
1284.         return 0;
1285.     /* otherwise players might find themselves obligated to violate
1286.      * their alignment if the monster takes something they need
1287.      */
1288. 
1289.     /* special--boulder throwers carry unlimited amounts of boulders */
1290.     if (throws_rocks(mdat) && otyp == BOULDER)
1291.         return iquan;
1292. 
1293.     /* nymphs deal in stolen merchandise, but not boulders or statues */
1294.     if (mdat->mlet == S_NYMPH)
1295.         return (otmp->oclass == ROCK_CLASS) ? 0 : iquan;
1296. 
1297.     if (curr_mon_load(mtmp) + newload > max_mon_load(mtmp))
1298.         return 0;
1299. 
1300.     return iquan;
1301. }
1302. 
1303. /* return number of acceptable neighbour positions */
1304. int
1305. mfndpos(mon, poss, info, flag)
1306. struct monst *mon;
1307. coord *poss; /* coord poss[9] */
1308. long *info;  /* long info[9] */
1309. long flag;
1310. {
1311.     struct permonst *mdat = mon->data;
1312.     register struct trap *ttmp;
1313.     xchar x, y, nx, ny;
1314.     int cnt = 0;
1315.     uchar ntyp;
1316.     uchar nowtyp;
1317.     boolean wantpool, poolok, lavaok, nodiag;
1318.     boolean rockok = FALSE, treeok = FALSE, thrudoor;
1319.     int maxx, maxy;
1320.     boolean poisongas_ok, in_poisongas;
1321.     NhRegion *gas_reg;
1322.     int gas_glyph = cmap_to_glyph(S_poisoncloud);
1323. 
1324.     x = mon->mx;
1325.     y = mon->my;
1326.     nowtyp = levl[x][y].typ;
1327. 
1328.     nodiag = NODIAG(mdat - mons);
1329.     wantpool = (mdat->mlet == S_EEL);
1330.     poolok = ((!Is_waterlevel(&u.uz)
1331.                && (is_flyer(mdat) || is_floater(mdat) || is_clinger(mdat)))
1332.               || (is_swimmer(mdat) && !wantpool));
1333.     /* note: floating eye is the only is_floater() so this could be
1334.        simplified, but then adding another floater would be error prone */
1335.     lavaok = (is_flyer(mdat) || is_floater(mdat) || is_clinger(mdat)
1336.               || likes_lava(mdat));
1337.     if (mdat == &mons[PM_FLOATING_EYE]) /* prefers to avoid heat */
1338.         lavaok = FALSE;
1339.     thrudoor = ((flag & (ALLOW_WALL | BUSTDOOR)) != 0L);
1340.     poisongas_ok = ((nonliving(mdat) || is_vampshifter(mon)
1341.                      || breathless(mdat)) || resists_poison(mon));
1342.     in_poisongas = ((gas_reg = visible_region_at(x,y)) != 0
1343.                     && gas_reg->glyph == gas_glyph);
1344. 
1345.     if (flag & ALLOW_DIG) {
1346.         struct obj *mw_tmp;
1347. 
1348.         /* need to be specific about what can currently be dug */
1349.         if (!needspick(mdat)) {
1350.             rockok = treeok = TRUE;
1351.         } else if ((mw_tmp = MON_WEP(mon)) && mw_tmp->cursed
1352.                    && mon->weapon_check == NO_WEAPON_WANTED) {
1353.             rockok = is_pick(mw_tmp);
1354.             treeok = is_axe(mw_tmp);
1355.         } else {
1356.             rockok = (m_carrying(mon, PICK_AXE)
1357.                       || (m_carrying(mon, DWARVISH_MATTOCK)
1358.                           && !which_armor(mon, W_ARMS)));
1359.             treeok = (m_carrying(mon, AXE) || (m_carrying(mon, BATTLE_AXE)
1360.                                                && !which_armor(mon, W_ARMS)));
1361.         }
1362.         if (rockok || treeok)
1363.             thrudoor = TRUE;
1364.     }
1365. 
1366.  nexttry: /* eels prefer the water, but if there is no water nearby,
1367.              they will crawl over land */
1368.     if (mon->mconf) {
1369.         flag |= ALLOW_ALL;
1370.         flag &= ~NOTONL;
1371.     }
1372.     if (!mon->mcansee)
1373.         flag |= ALLOW_SSM;
1374.     maxx = min(x + 1, COLNO - 1);
1375.     maxy = min(y + 1, ROWNO - 1);
1376.     for (nx = max(1, x - 1); nx <= maxx; nx++)
1377.         for (ny = max(0, y - 1); ny <= maxy; ny++) {
1378.             if (nx == x && ny == y)
1379.                 continue;
1380.             ntyp = levl[nx][ny].typ;
1381.             if (IS_ROCK(ntyp)
1382.                 && !((flag & ALLOW_WALL) && may_passwall(nx, ny))
1383.                 && !((IS_TREE(ntyp) ? treeok : rockok) && may_dig(nx, ny)))
1384.                 continue;
1385.             /* KMH -- Added iron bars */
1386.             if (ntyp == IRONBARS
1387.                 && (!(flag & ALLOW_BARS)
1388.                     || ((levl[nx][ny].wall_info & W_NONDIGGABLE)
1389.                         && (dmgtype(mdat, AD_RUST)
1390.                             || dmgtype(mdat, AD_CORR)))))
1391.                 continue;
1392.             if (IS_DOOR(ntyp) && !(amorphous(mdat) || can_fog(mon))
1393.                 && (((levl[nx][ny].doormask & D_CLOSED) && !(flag & OPENDOOR))
1394.                     || ((levl[nx][ny].doormask & D_LOCKED)
1395.                         && !(flag & UNLOCKDOOR))) && !thrudoor)
1396.                 continue;
1397.             /* avoid poison gas? */
1398.             if (!poisongas_ok && !in_poisongas
1399.                 && (gas_reg = visible_region_at(nx,ny)) != 0
1400.                 && gas_reg->glyph == gas_glyph)
1401.                 continue;
1402.             /* first diagonal checks (tight squeezes handled below) */
1403.             if (nx != x && ny != y
1404.                 && (nodiag
1405.                     || (IS_DOOR(nowtyp) && (levl[x][y].doormask & ~D_BROKEN))
1406.                     || (IS_DOOR(ntyp) && (levl[nx][ny].doormask & ~D_BROKEN))
1407.                     || ((IS_DOOR(nowtyp) || IS_DOOR(ntyp))
1408.                         && Is_rogue_level(&u.uz))
1409.                     /* mustn't pass between adjacent long worm segments,
1410.                        but can attack that way */
1411.                     || (m_at(x, ny) && m_at(nx, y) && worm_cross(x, y, nx, ny)
1412.                         && !m_at(nx, ny) && (nx != u.ux || ny != u.uy))))
1413.                 continue;
1414.             if ((is_pool(nx, ny) == wantpool || poolok)
1415.                 && (lavaok || !is_lava(nx, ny))) {
1416.                 int dispx, dispy;
1417.                 boolean monseeu = (mon->mcansee
1418.                                    && (!Invis || perceives(mdat)));
1419.                 boolean checkobj = OBJ_AT(nx, ny);
1420. 
1421.                 /* Displacement also displaces the Elbereth/scare monster,
1422.                  * as long as you are visible.
1423.                  */
1424.                 if (Displaced && monseeu && mon->mux == nx && mon->muy == ny) {
1425.                     dispx = u.ux;
1426.                     dispy = u.uy;
1427.                 } else {
1428.                     dispx = nx;
1429.                     dispy = ny;
1430.                 }
1431. 
1432.                 info[cnt] = 0;
1433.                 if (onscary(dispx, dispy, mon)) {
1434.                     if (!(flag & ALLOW_SSM))
1435.                         continue;
1436.                     info[cnt] |= ALLOW_SSM;
1437.                 }
1438.                 if ((nx == u.ux && ny == u.uy)
1439.                     || (nx == mon->mux && ny == mon->muy)) {
1440.                     if (nx == u.ux && ny == u.uy) {
1441.                         /* If it's right next to you, it found you,
1442.                          * displaced or no.  We must set mux and muy
1443.                          * right now, so when we return we can tell
1444.                          * that the ALLOW_U means to attack _you_ and
1445.                          * not the image.
1446.                          */
1447.                         mon->mux = u.ux;
1448.                         mon->muy = u.uy;
1449.                     }
1450.                     if (!(flag & ALLOW_U))
1451.                         continue;
1452.                     info[cnt] |= ALLOW_U;
1453.                 } else {
1454.                     if (MON_AT(nx, ny)) {
1455.                         struct monst *mtmp2 = m_at(nx, ny);
1456.                         long mmflag = flag | mm_aggression(mon, mtmp2);
1457. 
1458.                         if (mmflag & ALLOW_M) {
1459.                             info[cnt] |= ALLOW_M;
1460.                             if (mtmp2->mtame) {
1461.                                 if (!(mmflag & ALLOW_TM))
1462.                                     continue;
1463.                                 info[cnt] |= ALLOW_TM;
1464.                             }
1465.                         } else {
1466.                             mmflag = flag | mm_displacement(mon, mtmp2);
1467.                             if (!(mmflag & ALLOW_MDISP))
1468.                                 continue;
1469.                             info[cnt] |= ALLOW_MDISP;
1470.                         }
1471.                     }
1472.                     /* Note: ALLOW_SANCT only prevents movement, not
1473.                        attack, into a temple. */
1474.                     if (level.flags.has_temple && *in_rooms(nx, ny, TEMPLE)
1475.                         && !*in_rooms(x, y, TEMPLE)
1476.                         && in_your_sanctuary((struct monst *) 0, nx, ny)) {
1477.                         if (!(flag & ALLOW_SANCT))
1478.                             continue;
1479.                         info[cnt] |= ALLOW_SANCT;
1480.                     }
1481.                 }
1482.                 if (checkobj && sobj_at(CLOVE_OF_GARLIC, nx, ny)) {
1483.                     if (flag & NOGARLIC)
1484.                         continue;
1485.                     info[cnt] |= NOGARLIC;
1486.                 }
1487.                 if (checkobj && sobj_at(BOULDER, nx, ny)) {
1488.                     if (!(flag & ALLOW_ROCK))
1489.                         continue;
1490.                     info[cnt] |= ALLOW_ROCK;
1491.                 }
1492.                 if (monseeu && onlineu(nx, ny)) {
1493.                     if (flag & NOTONL)
1494.                         continue;
1495.                     info[cnt] |= NOTONL;
1496.                 }
1497.                 /* check for diagonal tight squeeze */
1498.                 if (nx != x && ny != y && bad_rock(mdat, x, ny)
1499.                     && bad_rock(mdat, nx, y) && cant_squeeze_thru(mon))
1500.                     continue;
1501.                 /* The monster avoids a particular type of trap if it's
1502.                  * familiar with the trap type.  Pets get ALLOW_TRAPS
1503.                  * and checking is done in dogmove.c.  In either case,
1504.                  * "harmless" traps are neither avoided nor marked in info[].
1505.                  */
1506.                 if ((ttmp = t_at(nx, ny)) != 0) {
1507.                     if (ttmp->ttyp >= TRAPNUM || ttmp->ttyp == 0) {
1508.                         impossible(
1509.                          "A monster looked at a very strange trap of type %d.",
1510.                                    ttmp->ttyp);
1511.                             continue;
1512.                     }
1513.                     if ((ttmp->ttyp != RUST_TRAP
1514.                          || mdat == &mons[PM_IRON_GOLEM])
1515.                         && ttmp->ttyp != STATUE_TRAP
1516.                         && ttmp->ttyp != VIBRATING_SQUARE
1517.                         && ((!is_pit(ttmp->ttyp) && !is_hole(ttmp->ttyp))
1518.                             || (!is_flyer(mdat) && !is_floater(mdat)
1519.                                 && !is_clinger(mdat)) || Sokoban)
1520.                         && (ttmp->ttyp != SLP_GAS_TRAP || !resists_sleep(mon))
1521.                         && (ttmp->ttyp != BEAR_TRAP
1522.                             || (mdat->msize > MZ_SMALL && !amorphous(mdat)
1523.                                 && !is_flyer(mdat) && !is_floater(mdat)
1524.                                 && !is_whirly(mdat) && !unsolid(mdat)))
1525.                         && (ttmp->ttyp != FIRE_TRAP || !resists_fire(mon))
1526.                         && (ttmp->ttyp != SQKY_BOARD || !is_flyer(mdat))
1527.                         && (ttmp->ttyp != WEB
1528.                             || (!amorphous(mdat) && !webmaker(mdat)
1529.                                 && !is_whirly(mdat) && !unsolid(mdat)))
1530.                         && (ttmp->ttyp != ANTI_MAGIC || !resists_magm(mon))) {
1531.                         if (!(flag & ALLOW_TRAPS)) {
1532.                             if (mon->mtrapseen & (1L << (ttmp->ttyp - 1)))
1533.                                 continue;
1534.                         }
1535.                         info[cnt] |= ALLOW_TRAPS;
1536.                     }
1537.                 }
1538.                 poss[cnt].x = nx;
1539.                 poss[cnt].y = ny;
1540.                 cnt++;
1541.             }
1542.         }
1543.     if (!cnt && wantpool && !is_pool(x, y)) {
1544.         wantpool = FALSE;
1545.         goto nexttry;
1546.     }
1547.     return cnt;
1548. }
1549. 
1550. /* Monster against monster special attacks; for the specified monster
1551.    combinations, this allows one monster to attack another adjacent one
1552.    in the absence of Conflict.  There is no provision for targetting
1553.    other monsters; just hand to hand fighting when they happen to be
1554.    next to each other. */
1555. STATIC_OVL long
1556. mm_aggression(magr, mdef)
1557. struct monst *magr, /* monster that is currently deciding where to move */
1558.              *mdef; /* another monster which is next to it */
1559. {
1560.     /* supposedly purple worms are attracted to shrieking because they
1561.        like to eat shriekers, so attack the latter when feasible */
1562.     if (magr->data == &mons[PM_PURPLE_WORM]
1563.         && mdef->data == &mons[PM_SHRIEKER])
1564.         return ALLOW_M | ALLOW_TM;
1565.     /* Various other combinations such as dog vs cat, cat vs rat, and
1566.        elf vs orc have been suggested.  For the time being we don't
1567.        support those. */
1568.     return 0L;
1569. }
1570. 
1571. /* Monster displacing another monster out of the way */
1572. STATIC_OVL long
1573. mm_displacement(magr, mdef)
1574. struct monst *magr, /* monster that is currently deciding where to move */
1575.              *mdef; /* another monster which is next to it */
1576. {
1577.     struct permonst *pa = magr->data, *pd = mdef->data;
1578. 
1579.     /* if attacker can't barge through, there's nothing to do;
1580.        or if defender can barge through too, don't let attacker
1581.        do so, otherwise they might just end up swapping places
1582.        again when defender gets its chance to move */
1583.     if ((pa->mflags3 & M3_DISPLACES) != 0 && (pd->mflags3 & M3_DISPLACES) == 0
1584.         /* no displacing grid bugs diagonally */
1585.         && !(magr->mx != mdef->mx && magr->my != mdef->my
1586.              && NODIAG(monsndx(pd)))
1587.         /* no displacing trapped monsters or multi-location longworms */
1588.         && !mdef->mtrapped && (!mdef->wormno || !count_wsegs(mdef))
1589.         /* riders can move anything; others, same size or smaller only */
1590.         && (is_rider(pa) || pa->msize >= pd->msize))
1591.         return ALLOW_MDISP;
1592.     return 0L;
1593. }
1594. 
1595. /* Is the square close enough for the monster to move or attack into? */
1596. boolean
1597. monnear(mon, x, y)
1598. struct monst *mon;
1599. int x, y;
1600. {
1601.     int distance = dist2(mon->mx, mon->my, x, y);
1602. 
1603.     if (distance == 2 && NODIAG(mon->data - mons))
1604.         return 0;
1605.     return (boolean) (distance < 3);
1606. }
1607. 
1608. /* really free dead monsters */
1609. void
1610. dmonsfree()
1611. {
1612.     struct monst **mtmp, *freetmp;
1613.     int count = 0;
1614.     char buf[QBUFSZ];
1615. 
1616.     buf[0] = '\0';
1617.     for (mtmp = &fmon; *mtmp;) {
1618.         freetmp = *mtmp;
1619.         if (DEADMONSTER(freetmp) && !freetmp->isgd) {
1620.             *mtmp = freetmp->nmon;
1621.             freetmp->nmon = NULL;
1622.             dealloc_monst(freetmp);
1623.             count++;
1624.         } else
1625.             mtmp = &(freetmp->nmon);
1626.     }
1627. 
1628.     if (count != iflags.purge_monsters) {
1629.         describe_level(buf);
1630.         impossible("dmonsfree: %d removed doesn't match %d pending on %s",
1631.                    count, iflags.purge_monsters, buf);
1632.     }
1633.     iflags.purge_monsters = 0;
1634. }
1635. 
1636. /* called when monster is moved to larger structure */
1637. void
1638. replmon(mtmp, mtmp2)
1639. struct monst *mtmp, *mtmp2;
1640. {
1641.     struct obj *otmp;
1642. 
1643.     /* transfer the monster's inventory */
1644.     for (otmp = mtmp2->minvent; otmp; otmp = otmp->nobj) {
1645.         if (otmp->where != OBJ_MINVENT || otmp->ocarry != mtmp)
1646.             impossible("replmon: minvent inconsistency");
1647.         otmp->ocarry = mtmp2;
1648.     }
1649.     mtmp->minvent = 0;
1650. 
1651.     /* remove the old monster from the map and from `fmon' list */
1652.     relmon(mtmp, (struct monst **) 0);
1653. 
1654.     /* finish adding its replacement */
1655.     if (mtmp != u.usteed) /* don't place steed onto the map */
1656.         place_monster(mtmp2, mtmp2->mx, mtmp2->my);
1657.     if (mtmp2->wormno)      /* update level.monsters[wseg->wx][wseg->wy] */
1658.         place_wsegs(mtmp2, NULL); /* locations to mtmp2 not mtmp. */
1659.     if (emits_light(mtmp2->data)) {
1660.         /* since this is so rare, we don't have any `mon_move_light_source' */
1661.         new_light_source(mtmp2->mx, mtmp2->my, emits_light(mtmp2->data),
1662.                          LS_MONSTER, monst_to_any(mtmp2));
1663.         /* here we rely on fact that `mtmp' hasn't actually been deleted */
1664.         del_light_source(LS_MONSTER, monst_to_any(mtmp));
1665.     }
1666.     mtmp2->nmon = fmon;
1667.     fmon = mtmp2;
1668.     if (u.ustuck == mtmp)
1669.         u.ustuck = mtmp2;
1670.     if (u.usteed == mtmp)
1671.         u.usteed = mtmp2;
1672.     if (mtmp2->isshk)
1673.         replshk(mtmp, mtmp2);
1674. 
1675.     /* discard the old monster */
1676.     dealloc_monst(mtmp);
1677. }
1678. 
1679. /* release mon from the display and the map's monster list,
1680.    maybe transfer it to one of the other monster lists */
1681. void
1682. relmon(mon, monst_list)
1683. struct monst *mon;
1684. struct monst **monst_list; /* &migrating_mons or &mydogs or null */
1685. {
1686.     struct monst *mtmp;
1687.     int mx = mon->mx, my = mon->my;
1688.     boolean on_map = (m_at(mx, my) == mon),
1689.             unhide = (monst_list != 0);
1690. 
1691.     if (!fmon)
1692.         panic("relmon: no fmon available.");
1693. 
1694.     if (unhide) {
1695.         /* can't remain hidden across level changes (exception: wizard
1696.            clone can continue imitating some other monster form); also,
1697.            might be imitating a boulder so need line-of-sight unblocking */
1698.         mon->mundetected = 0;
1699.         if (M_AP_TYPE(mon) && M_AP_TYPE(mon) != M_AP_MONSTER)
1700.             seemimic(mon);
1701.     }
1702. 
1703.     if (on_map) {
1704.         mon->mtrapped = 0;
1705.         if (mon->wormno)
1706.             remove_worm(mon);
1707.         else
1708.             remove_monster(mx, my);
1709.     }
1710. 
1711.     if (mon == fmon) {
1712.         fmon = fmon->nmon;
1713.     } else {
1714.         for (mtmp = fmon; mtmp; mtmp = mtmp->nmon)
1715.             if (mtmp->nmon == mon)
1716.                 break;
1717. 
1718.         if (mtmp)
1719.             mtmp->nmon = mon->nmon;
1720.         else
1721.             panic("relmon: mon not in list.");
1722.     }
1723. 
1724.     if (unhide) {
1725.         if (on_map)
1726.             newsym(mx, my);
1727.         /* insert into mydogs or migrating_mons */
1728.         mon->nmon = *monst_list;
1729.         *monst_list = mon;
1730.     } else {
1731.         /* orphan has no next monster */
1732.         mon->nmon = 0;
1733.     }
1734. }
1735. 
1736. void
1737. copy_mextra(mtmp2, mtmp1)
1738. struct monst *mtmp2, *mtmp1;
1739. {
1740.     if (!mtmp2 || !mtmp1 || !mtmp1->mextra)
1741.         return;
1742. 
1743.     if (!mtmp2->mextra)
1744.         mtmp2->mextra = newmextra();
1745.     if (MNAME(mtmp1)) {
1746.         new_mname(mtmp2, (int) strlen(MNAME(mtmp1)) + 1);
1747.         Strcpy(MNAME(mtmp2), MNAME(mtmp1));
1748.     }
1749.     if (EGD(mtmp1)) {
1750.         if (!EGD(mtmp2))
1751.             newegd(mtmp2);
1752.         *EGD(mtmp2) = *EGD(mtmp1);
1753.     }
1754.     if (EPRI(mtmp1)) {
1755.         if (!EPRI(mtmp2))
1756.             newepri(mtmp2);
1757.         *EPRI(mtmp2) = *EPRI(mtmp1);
1758.     }
1759.     if (ESHK(mtmp1)) {
1760.         if (!ESHK(mtmp2))
1761.             neweshk(mtmp2);
1762.         *ESHK(mtmp2) = *ESHK(mtmp1);
1763.     }
1764.     if (EMIN(mtmp1)) {
1765.         if (!EMIN(mtmp2))
1766.             newemin(mtmp2);
1767.         *EMIN(mtmp2) = *EMIN(mtmp1);
1768.     }
1769.     if (EDOG(mtmp1)) {
1770.         if (!EDOG(mtmp2))
1771.             newedog(mtmp2);
1772.         *EDOG(mtmp2) = *EDOG(mtmp1);
1773.     }
1774.     if (has_mcorpsenm(mtmp1))
1775.         MCORPSENM(mtmp2) = MCORPSENM(mtmp1);
1776. }
1777. 
1778. void
1779. dealloc_mextra(m)
1780. struct monst *m;
1781. {
1782.     struct mextra *x = m->mextra;
1783. 
1784.     if (x) {
1785.         if (x->mname)
1786.             free((genericptr_t) x->mname);
1787.         if (x->egd)
1788.             free((genericptr_t) x->egd);
1789.         if (x->epri)
1790.             free((genericptr_t) x->epri);
1791.         if (x->eshk)
1792.             free((genericptr_t) x->eshk);
1793.         if (x->emin)
1794.             free((genericptr_t) x->emin);
1795.         if (x->edog)
1796.             free((genericptr_t) x->edog);
1797.         /* [no action needed for x->mcorpsenm] */
1798. 
1799.         free((genericptr_t) x);
1800.         m->mextra = (struct mextra *) 0;
1801.     }
1802. }
1803. 
1804. void
1805. dealloc_monst(mon)
1806. struct monst *mon;
1807. {
1808.     char buf[QBUFSZ];
1809. 
1810.     buf[0] = '\0';
1811.     if (mon->nmon) {
1812.         describe_level(buf);
1813.         panic("dealloc_monst with nmon on %s", buf);
1814.     }
1815.     if (mon->mextra)
1816.         dealloc_mextra(mon);
1817.     free((genericptr_t) mon);
1818. }
1819. 
1820. /* remove effects of mtmp from other data structures */
1821. STATIC_OVL void
1822. m_detach(mtmp, mptr)
1823. struct monst *mtmp;
1824. struct permonst *mptr; /* reflects mtmp->data _prior_ to mtmp's death */
1825. {
1826.     boolean onmap = (mtmp->mx > 0);
1827. 
1828.     if (mtmp == context.polearm.hitmon)
1829.         context.polearm.hitmon = 0;
1830.     if (mtmp->mleashed)
1831.         m_unleash(mtmp, FALSE);
1832.     /* to prevent an infinite relobj-flooreffects-hmon-killed loop */
1833.     mtmp->mtrapped = 0;
1834.     mtmp->mhp = 0; /* simplify some tests: force mhp to 0 */
1835.     relobj(mtmp, 0, FALSE);
1836.     if (onmap || mtmp == level.monsters[0][0]) {
1837.         if (mtmp->wormno)
1838.             remove_worm(mtmp);
1839.         else
1840.             remove_monster(mtmp->mx, mtmp->my);
1841.     }
1842.     if (emits_light(mptr))
1843.         del_light_source(LS_MONSTER, monst_to_any(mtmp));
1844.     if (M_AP_TYPE(mtmp))
1845.         seemimic(mtmp);
1846.     if (onmap)
1847.         newsym(mtmp->mx, mtmp->my);
1848.     unstuck(mtmp);
1849.     if (onmap)
1850.         fill_pit(mtmp->mx, mtmp->my);
1851. 
1852.     if (mtmp->isshk)
1853.         shkgone(mtmp);
1854.     if (mtmp->wormno)
1855.         wormgone(mtmp);
1856.     if (In_endgame(&u.uz))
1857.         mtmp->mstate |= MON_ENDGAME_FREE;
1858. 
1859.     mtmp->mstate |= MON_DETACH;
1860.     iflags.purge_monsters++;
1861. }
1862. 
1863. /* find the worn amulet of life saving which will save a monster */
1864. struct obj *
1865. mlifesaver(mon)
1866. struct monst *mon;
1867. {
1868.     if (!nonliving(mon->data) || is_vampshifter(mon)) {
1869.         struct obj *otmp = which_armor(mon, W_AMUL);
1870. 
1871.         if (otmp && otmp->otyp == AMULET_OF_LIFE_SAVING)
1872.             return otmp;
1873.     }
1874.     return (struct obj *) 0;
1875. }
1876. 
1877. STATIC_OVL void
1878. lifesaved_monster(mtmp)
1879. struct monst *mtmp;
1880. {
1881.     boolean surviver;
1882.     struct obj *lifesave = mlifesaver(mtmp);
1883. 
1884.     if (lifesave) {
1885.         /* not canseemon; amulets are on the head, so you don't want
1886.          * to show this for a long worm with only a tail visible.
1887.          * Nor do you check invisibility, because glowing and
1888.          * disintegrating amulets are always visible. */
1889.         if (cansee(mtmp->mx, mtmp->my)) {
1890.             pline("But wait...");
1891.             pline("%s medallion begins to glow!", s_suffix(Monnam(mtmp)));
1892.             makeknown(AMULET_OF_LIFE_SAVING);
1893.             /* amulet is visible, but monster might not be */
1894.             if (canseemon(mtmp)) {
1895.                 if (attacktype(mtmp->data, AT_EXPL)
1896.                     || attacktype(mtmp->data, AT_BOOM))
1897.                     pline("%s reconstitutes!", Monnam(mtmp));
1898.                 else
1899.                     pline("%s looks much better!", Monnam(mtmp));
1900.             }
1901.             pline_The("medallion crumbles to dust!");
1902.         }
1903.         m_useup(mtmp, lifesave);
1904.         /* equip replacement amulet, if any, on next move */
1905.         mtmp->misc_worn_check |= I_SPECIAL;
1906. 
1907.         surviver = !(mvitals[monsndx(mtmp->data)].mvflags & G_GENOD);
1908.         mtmp->mcanmove = 1;
1909.         mtmp->mfrozen = 0;
1910.         if (mtmp->mtame && !mtmp->isminion) {
1911.             wary_dog(mtmp, !surviver);
1912.         }
1913.         if (mtmp->mhpmax <= 0)
1914.             mtmp->mhpmax = 10;
1915.         mtmp->mhp = mtmp->mhpmax;
1916. 
1917.         if (!surviver) {
1918.             /* genocided monster can't be life-saved */
1919.             if (cansee(mtmp->mx, mtmp->my))
1920.                 pline("Unfortunately, %s is still genocided...",
1921.                       mon_nam(mtmp));
1922.             mtmp->mhp = 0;
1923.         }
1924.     }
1925. }
1926. 
1927. void
1928. mondead(mtmp)
1929. register struct monst *mtmp;
1930. {
1931.     struct permonst *mptr;
1932.     int tmp;
1933. 
1934.     mtmp->mhp = 0; /* in case caller hasn't done this */
1935.     lifesaved_monster(mtmp);
1936.     if (!DEADMONSTER(mtmp))
1937.         return;
1938. 
1939.     if (is_vampshifter(mtmp)) {
1940.         int mndx = mtmp->cham;
1941.         int x = mtmp->mx, y = mtmp->my;
1942. 
1943.         /* this only happens if shapeshifted */
1944.         if (mndx >= LOW_PM && mndx != monsndx(mtmp->data)
1945.             && !(mvitals[mndx].mvflags & G_GENOD)) {
1946.             char buf[BUFSZ];
1947.             boolean in_door = (amorphous(mtmp->data)
1948.                                && closed_door(mtmp->mx, mtmp->my)),
1949.                 /* alternate message phrasing for some monster types */
1950.                 spec_mon = (nonliving(mtmp->data)
1951.                             || noncorporeal(mtmp->data)
1952.                             || amorphous(mtmp->data)),
1953.                 spec_death = (disintegested /* disintegrated or digested */
1954.                               || noncorporeal(mtmp->data)
1955.                               || amorphous(mtmp->data));
1956. 
1957.             /* construct a format string before transformation;
1958.                will be capitalized when used, expects one %s arg */
1959.             Sprintf(buf, "%s suddenly %s and rises as %%s!",
1960.                     x_monnam(mtmp, ARTICLE_THE,
1961.                              spec_mon ? (char *) 0 : "seemingly dead",
1962.                              (SUPPRESS_INVISIBLE | SUPPRESS_IT), FALSE),
1963.                     spec_death ? "reconstitutes" : "transforms");
1964.             mtmp->mcanmove = 1;
1965.             mtmp->mfrozen = 0;
1966.             if (mtmp->mhpmax <= 0)
1967.                 mtmp->mhpmax = 10;
1968.             mtmp->mhp = mtmp->mhpmax;
1969.             /* mtmp==u.ustuck can happen if previously a fog cloud
1970.                or poly'd hero is hugging a vampire bat */
1971.             if (mtmp == u.ustuck) {
1972.                 if (u.uswallow)
1973.                     expels(mtmp, mtmp->data, FALSE);
1974.                 else
1975.                     uunstick();
1976.             }
1977.             if (in_door) {
1978.                 coord new_xy;
1979. 
1980.                 if (enexto(&new_xy, mtmp->mx, mtmp->my, &mons[mndx])) {
1981.                     rloc_to(mtmp, new_xy.x, new_xy.y);
1982.                 }
1983.             }
1984.             newcham(mtmp, &mons[mndx], FALSE, FALSE);
1985.             if (mtmp->data == &mons[mndx])
1986.                 mtmp->cham = NON_PM;
1987.             else
1988.                 mtmp->cham = mndx;
1989.             if (canspotmon(mtmp)) {
1990.                 /* 3.6.0 used a_monnam(mtmp); that was weird if mtmp was
1991.                    named: "Dracula suddenly transforms and rises as Dracula";
1992.                    3.6.1 used mtmp->data->mname; that ignored hallucination */
1993.                 pline(upstart(buf),
1994.                       x_monnam(mtmp, ARTICLE_A, (char *) 0,
1995.                                (SUPPRESS_NAME | SUPPRESS_IT
1996.                                 | SUPPRESS_INVISIBLE), FALSE));
1997.                 vamp_rise_msg = TRUE;
1998.             }
1999.             newsym(x, y);
2000.             return;
2001.         }
2002.     }
2003. 
2004.     /* dead vault guard is actually kept at coordinate <0,0> until
2005.        his temporary corridor to/from the vault has been removed;
2006.        need to do this after life-saving and before m_detach() */
2007.     if (mtmp->isgd && !grddead(mtmp))
2008.         return;
2009. 
2010.     /* Player is thrown from his steed when it dies */
2011.     if (mtmp == u.usteed)
2012.         dismount_steed(DISMOUNT_GENERIC);
2013. 
2014.     mptr = mtmp->data; /* save this for m_detach() */
2015.     /* restore chameleon, lycanthropes to true form at death */
2016.     if (mtmp->cham >= LOW_PM) {
2017.         set_mon_data(mtmp, &mons[mtmp->cham]);
2018.         mtmp->cham = NON_PM;
2019.     } else if (mtmp->data == &mons[PM_WEREJACKAL])
2020.         set_mon_data(mtmp, &mons[PM_HUMAN_WEREJACKAL]);
2021.     else if (mtmp->data == &mons[PM_WEREWOLF])
2022.         set_mon_data(mtmp, &mons[PM_HUMAN_WEREWOLF]);
2023.     else if (mtmp->data == &mons[PM_WERERAT])
2024.         set_mon_data(mtmp, &mons[PM_HUMAN_WERERAT]);
2025. 
2026.     /*
2027.      * mvitals[].died does double duty as total number of dead monsters
2028.      * and as experience factor for the player killing more monsters.
2029.      * this means that a dragon dying by other means reduces the
2030.      * experience the player gets for killing a dragon directly; this
2031.      * is probably not too bad, since the player likely finagled the
2032.      * first dead dragon via ring of conflict or pets, and extinguishing
2033.      * based on only player kills probably opens more avenues of abuse
2034.      * for rings of conflict and such.
2035.      */
2036.     tmp = monsndx(mtmp->data);
2037.     if (mvitals[tmp].died < 255)
2038.         mvitals[tmp].died++;
2039. 
2040.     /* if it's a (possibly polymorphed) quest leader, mark him as dead */
2041.     if (mtmp->m_id == quest_status.leader_m_id)
2042.         quest_status.leader_is_dead = TRUE;
2043. #ifdef MAIL
2044.     /* if the mail daemon dies, no more mail delivery.  -3. */
2045.     if (tmp == PM_MAIL_DAEMON)
2046.         mvitals[tmp].mvflags |= G_GENOD;
2047. #endif
2048. 
2049.     if (mtmp->data->mlet == S_KOP) {
2050.         /* Dead Kops may come back. */
2051.         switch (rnd(5)) {
2052.         case 1: /* returns near the stairs */
2053.             (void) makemon(mtmp->data, xdnstair, ydnstair, NO_MM_FLAGS);
2054.             break;
2055.         case 2: /* randomly */
2056.             (void) makemon(mtmp->data, 0, 0, NO_MM_FLAGS);
2057.             break;
2058.         default:
2059.             break;
2060.         }
2061.     }
2062.     if (mtmp->iswiz)
2063.         wizdead();
2064.     if (mtmp->data->msound == MS_NEMESIS)
2065.         nemdead();
2066.     if (mtmp->data == &mons[PM_MEDUSA])
2067.         u.uachieve.killed_medusa = 1;
2068.     if (glyph_is_invisible(levl[mtmp->mx][mtmp->my].glyph))
2069.         unmap_object(mtmp->mx, mtmp->my);
2070.     m_detach(mtmp, mptr);
2071. }
2072. 
2073. /* TRUE if corpse might be dropped, magr may die if mon was swallowed */
2074. boolean
2075. corpse_chance(mon, magr, was_swallowed)
2076. struct monst *mon;
2077. struct monst *magr;    /* killer, if swallowed */
2078. boolean was_swallowed; /* digestion */
2079. {
2080.     struct permonst *mdat = mon->data;
2081.     int i, tmp;
2082. 
2083.     if (mdat == &mons[PM_VLAD_THE_IMPALER] || mdat->mlet == S_LICH) {
2084.         if (cansee(mon->mx, mon->my) && !was_swallowed)
2085.             pline("%s body crumbles into dust.", s_suffix(Monnam(mon)));
2086.         return FALSE;
2087.     }
2088. 
2089.     /* Gas spores always explode upon death */
2090.     for (i = 0; i < NATTK; i++) {
2091.         if (mdat->mattk[i].aatyp == AT_BOOM) {
2092.             if (mdat->mattk[i].damn)
2093.                 tmp = d((int) mdat->mattk[i].damn, (int) mdat->mattk[i].damd);
2094.             else if (mdat->mattk[i].damd)
2095.                 tmp = d((int) mdat->mlevel + 1, (int) mdat->mattk[i].damd);
2096.             else
2097.                 tmp = 0;
2098.             if (was_swallowed && magr) {
2099.                 if (magr == &youmonst) {
2100.                     There("is an explosion in your %s!", body_part(STOMACH));
2101.                     Sprintf(killer.name, "%s explosion",
2102.                             s_suffix(mdat->mname));
2103.                     losehp(Maybe_Half_Phys(tmp), killer.name, KILLED_BY_AN);
2104.                 } else {
2105.                     You_hear("an explosion.");
2106.                     magr->mhp -= tmp;
2107.                     if (DEADMONSTER(magr))
2108.                         mondied(magr);
2109.                     if (DEADMONSTER(magr)) { /* maybe lifesaved */
2110.                         if (canspotmon(magr))
2111.                             pline("%s rips open!", Monnam(magr));
2112.                     } else if (canseemon(magr))
2113.                         pline("%s seems to have indigestion.", Monnam(magr));
2114.                 }
2115. 
2116.                 return FALSE;
2117.             }
2118. 
2119.             Sprintf(killer.name, "%s explosion", s_suffix(mdat->mname));
2120.             killer.format = KILLED_BY_AN;
2121.             explode(mon->mx, mon->my, -1, tmp, MON_EXPLODE, EXPL_NOXIOUS);
2122.             killer.name[0] = '\0';
2123.             killer.format = 0;
2124.             return FALSE;
2125.         }
2126.     }
2127. 
2128.     /* must duplicate this below check in xkilled() since it results in
2129.      * creating no objects as well as no corpse
2130.      */
2131.     if (LEVEL_SPECIFIC_NOCORPSE(mdat))
2132.         return FALSE;
2133. 
2134.     if (((bigmonst(mdat) || mdat == &mons[PM_LIZARD]) && !mon->mcloned)
2135.         || is_golem(mdat) || is_mplayer(mdat) || is_rider(mdat) || mon->isshk)
2136.         return TRUE;
2137.     tmp = 2 + ((mdat->geno & G_FREQ) < 2) + verysmall(mdat);
2138.     return (boolean) !rn2(tmp);
2139. }
2140. 
2141. /* drop (perhaps) a cadaver and remove monster */
2142. void
2143. mondied(mdef)
2144. register struct monst *mdef;
2145. {
2146.     mondead(mdef);
2147.     if (!DEADMONSTER(mdef))
2148.         return; /* lifesaved */
2149. 
2150.     if (corpse_chance(mdef, (struct monst *) 0, FALSE)
2151.         && (accessible(mdef->mx, mdef->my) || is_pool(mdef->mx, mdef->my)))
2152.         (void) make_corpse(mdef, CORPSTAT_NONE);
2153. }
2154. 
2155. /* monster disappears, not dies */
2156. void
2157. mongone(mdef)
2158. struct monst *mdef;
2159. {
2160.     mdef->mhp = 0; /* can skip some inventory bookkeeping */
2161. 
2162.     /* dead vault guard is actually kept at coordinate <0,0> until
2163.        his temporary corridor to/from the vault has been removed */
2164.     if (mdef->isgd && !grddead(mdef))
2165.         return;
2166.     /* hero is thrown from his steed when it disappears */
2167.     if (mdef == u.usteed)
2168.         dismount_steed(DISMOUNT_GENERIC);
2169.     /* stuck to you? release */
2170.     unstuck(mdef);
2171.     /* drop special items like the Amulet so that a dismissed Kop or nurse
2172.        can't remove them from the game */
2173.     mdrop_special_objs(mdef);
2174.     /* release rest of monster's inventory--it is removed from game */
2175.     discard_minvent(mdef);
2176.     m_detach(mdef, mdef->data);
2177. }
2178. 
2179. /* drop a statue or rock and remove monster */
2180. void
2181. monstone(mdef)
2182. struct monst *mdef;
2183. {
2184.     struct obj *otmp, *obj, *oldminvent;
2185.     xchar x = mdef->mx, y = mdef->my;
2186.     boolean wasinside = FALSE;
2187. 
2188.     /* vampshifter reverts to vampire;
2189.        3.6.3: also used to unshift shape-changed sandestin */
2190.     if (!vamp_stone(mdef))
2191.         return;
2192. 
2193.     /* we have to make the statue before calling mondead, to be able to
2194.      * put inventory in it, and we have to check for lifesaving before
2195.      * making the statue....
2196.      */
2197.     mdef->mhp = 0; /* in case caller hasn't done this */
2198.     lifesaved_monster(mdef);
2199.     if (!DEADMONSTER(mdef))
2200.         return;
2201. 
2202.     mdef->mtrapped = 0; /* (see m_detach) */
2203. 
2204.     if ((int) mdef->data->msize > MZ_TINY
2205.         || !rn2(2 + ((int) (mdef->data->geno & G_FREQ) > 2))) {
2206.         oldminvent = 0;
2207.         /* some objects may end up outside the statue */
2208.         while ((obj = mdef->minvent) != 0) {
2209.             obj_extract_self(obj);
2210.             if (obj->owornmask)
2211.                 update_mon_intrinsics(mdef, obj, FALSE, TRUE);
2212.             obj_no_longer_held(obj);
2213.             if (obj->owornmask & W_WEP)
2214.                 setmnotwielded(mdef, obj);
2215.             obj->owornmask = 0L;
2216.             if (obj->otyp == BOULDER
2217. #if 0 /* monsters don't carry statues */
2218.                 ||  (obj->otyp == STATUE
2219.                      && mons[obj->corpsenm].msize >= mdef->data->msize)
2220. #endif
2221.                 /* invocation tools resist even with 0% resistance */
2222.                 || obj_resists(obj, 0, 0)) {
2223.                 if (flooreffects(obj, x, y, "fall"))
2224.                     continue;
2225.                 place_object(obj, x, y);
2226.             } else {
2227.                 if (obj->lamplit)
2228.                     end_burn(obj, TRUE);
2229.                 obj->nobj = oldminvent;
2230.                 oldminvent = obj;
2231.             }
2232.         }
2233.         /* defer statue creation until after inventory removal
2234.            so that saved monster traits won't retain any stale
2235.            item-conferred attributes */
2236.         otmp = mkcorpstat(STATUE, mdef, mdef->data, x, y, CORPSTAT_NONE);
2237.         if (has_mname(mdef))
2238.             otmp = oname(otmp, MNAME(mdef));
2239.         while ((obj = oldminvent) != 0) {
2240.             oldminvent = obj->nobj;
2241.             obj->nobj = 0; /* avoid merged-> obfree-> dealloc_obj-> panic */
2242.             (void) add_to_container(otmp, obj);
2243.         }
2244.         /* Archeologists should not break unique statues */
2245.         if (mdef->data->geno & G_UNIQ)
2246.             otmp->spe = 1;
2247.         otmp->owt = weight(otmp);
2248.     } else
2249.         otmp = mksobj_at(ROCK, x, y, TRUE, FALSE);
2250. 
2251.     stackobj(otmp);
2252.     /* mondead() already does this, but we must do it before the newsym */
2253.     if (glyph_is_invisible(levl[x][y].glyph))
2254.         unmap_object(x, y);
2255.     if (cansee(x, y))
2256.         newsym(x, y);
2257.     /* We don't currently trap the hero in the statue in this case but we
2258.      * could */
2259.     if (u.uswallow && u.ustuck == mdef)
2260.         wasinside = TRUE;
2261.     mondead(mdef);
2262.     if (wasinside) {
2263.         if (is_animal(mdef->data))
2264.             You("%s through an opening in the new %s.",
2265.                 locomotion(youmonst.data, "jump"), xname(otmp));
2266.     }
2267. }
2268. 
2269. /* another monster has killed the monster mdef */
2270. void
2271. monkilled(mdef, fltxt, how)
2272. struct monst *mdef;
2273. const char *fltxt;
2274. int how;
2275. {
2276.     boolean be_sad = FALSE; /* true if unseen pet is killed */
2277. 
2278.     if ((mdef->wormno ? worm_known(mdef) : cansee(mdef->mx, mdef->my))
2279.         && fltxt)
2280.         pline("%s is %s%s%s!", Monnam(mdef),
2281.               nonliving(mdef->data) ? "destroyed" : "killed",
2282.               *fltxt ? " by the " : "", fltxt);
2283.     else
2284.         be_sad = (mdef->mtame != 0);
2285. 
2286.     /* no corpses if digested or disintegrated */
2287.     disintegested = (how == AD_DGST || how == -AD_RBRE);
2288.     if (disintegested)
2289.         mondead(mdef);
2290.     else
2291.         mondied(mdef);
2292. 
2293.     if (be_sad && DEADMONSTER(mdef))
2294.         You("have a sad feeling for a moment, then it passes.");
2295. }
2296. 
2297. void
2298. unstuck(mtmp)
2299. struct monst *mtmp;
2300. {
2301.     if (u.ustuck == mtmp) {
2302.         if (u.uswallow) {
2303.             u.ux = mtmp->mx;
2304.             u.uy = mtmp->my;
2305.             u.uswallow = 0;
2306.             u.uswldtim = 0;
2307.             if (Punished && uchain->where != OBJ_FLOOR)
2308.                 placebc();
2309.             vision_full_recalc = 1;
2310.             docrt();
2311.             /* prevent swallower (mtmp might have just poly'd into something
2312.                without an engulf attack) from immediately re-engulfing */
2313.             if (attacktype(mtmp->data, AT_ENGL) && !mtmp->mspec_used)
2314.                 mtmp->mspec_used = rnd(2);
2315.         }
2316.         u.ustuck = 0;
2317.     }
2318. }
2319. 
2320. void
2321. killed(mtmp)
2322. struct monst *mtmp;
2323. {
2324.     xkilled(mtmp, XKILL_GIVEMSG);
2325. }
2326. 
2327. /* the player has killed the monster mtmp */
2328. void
2329. xkilled(mtmp, xkill_flags)
2330. struct monst *mtmp;
2331. int xkill_flags; /* 1: suppress message, 2: suppress corpse, 4: pacifist */
2332. {
2333.     int tmp, mndx, x = mtmp->mx, y = mtmp->my;
2334.     struct permonst *mdat;
2335.     struct obj *otmp;
2336.     struct trap *t;
2337.     boolean wasinside = u.uswallow && (u.ustuck == mtmp),
2338.             burycorpse = FALSE,
2339.             nomsg = (xkill_flags & XKILL_NOMSG) != 0,
2340.             nocorpse = (xkill_flags & XKILL_NOCORPSE) != 0,
2341.             noconduct = (xkill_flags & XKILL_NOCONDUCT) != 0;
2342. 
2343.     mtmp->mhp = 0; /* caller will usually have already done this */
2344.     if (!noconduct) /* KMH, conduct */
2345.         u.uconduct.killer++;
2346. 
2347.     if (!nomsg) {
2348.         boolean namedpet = has_mname(mtmp) && !Hallucination;
2349. 
2350.         You("%s %s!",
2351.             nonliving(mtmp->data) ? "destroy" : "kill",
2352.             !(wasinside || canspotmon(mtmp)) ? "it"
2353.               : !mtmp->mtame ? mon_nam(mtmp)
2354.                 : x_monnam(mtmp, namedpet ? ARTICLE_NONE : ARTICLE_THE,
2355.                            "poor", namedpet ? SUPPRESS_SADDLE : 0, FALSE));
2356.     }
2357. 
2358.     if (mtmp->mtrapped && (t = t_at(x, y)) != 0
2359.         && is_pit(t->ttyp)) {
2360.         if (sobj_at(BOULDER, x, y))
2361.             nocorpse = TRUE; /* Prevent corpses/treasure being created
2362.                                 "on top" of boulder that is about to fall in.
2363.                                 This is out of order, but cannot be helped
2364.                                 unless this whole routine is rearranged. */
2365.         if (m_carrying(mtmp, BOULDER))
2366.             burycorpse = TRUE;
2367.     }
2368. 
2369.     /* your pet knows who just killed it...watch out */
2370.     if (mtmp->mtame && !mtmp->isminion)
2371.         EDOG(mtmp)->killed_by_u = 1;
2372. 
2373.     if (wasinside && thrownobj && thrownobj != uball
2374.         /* don't give to mon if missile is going to return to hero */
2375.         && thrownobj != (struct obj *) iflags.returning_missile) {
2376.         /* thrown object has killed hero's engulfer; add it to mon's
2377.            inventory now so that it will be placed with mon's other
2378.            stuff prior to lookhere/autopickup when hero is expelled
2379.            below (as a side-effect, this missile has immunity from
2380.            being consumed [for this shot/throw only]) */
2381.         mpickobj(mtmp, thrownobj);
2382.         /* let throwing code know that missile has been disposed of */
2383.         thrownobj = 0;
2384.     }
2385. 
2386.     vamp_rise_msg = FALSE; /* might get set in mondead(); only checked below */
2387.     disintegested = nocorpse; /* alternate vamp_rise message needed if true */
2388.     /* dispose of monster and make cadaver */
2389.     if (stoned)
2390.         monstone(mtmp);
2391.     else
2392.         mondead(mtmp);
2393.     disintegested = FALSE; /* reset */
2394. 
2395.     if (!DEADMONSTER(mtmp)) { /* monster lifesaved */
2396.         /* Cannot put the non-visible lifesaving message in
2397.          * lifesaved_monster() since the message appears only when _you_
2398.          * kill it (as opposed to visible lifesaving which always appears).
2399.          */
2400.         stoned = FALSE;
2401.         if (!cansee(x, y) && !vamp_rise_msg)
2402.             pline("Maybe not...");
2403.         return;
2404.     }
2405. 
2406.     mdat = mtmp->data; /* note: mondead can change mtmp->data */
2407.     mndx = monsndx(mdat);
2408. 
2409.     if (stoned) {
2410.         stoned = FALSE;
2411.         goto cleanup;
2412.     }
2413. 
2414.     if (nocorpse || LEVEL_SPECIFIC_NOCORPSE(mdat))
2415.         goto cleanup;
2416. 
2417. #ifdef MAIL
2418.     if (mdat == &mons[PM_MAIL_DAEMON]) {
2419.         stackobj(mksobj_at(SCR_MAIL, x, y, FALSE, FALSE));
2420.     }
2421. #endif
2422.     if (accessible(x, y) || is_pool(x, y)) {
2423.         struct obj *cadaver;
2424.         int otyp;
2425. 
2426.         /* illogical but traditional "treasure drop" */
2427.         if (!rn2(6) && !(mvitals[mndx].mvflags & G_NOCORPSE)
2428.             /* no extra item from swallower or steed */
2429.             && (x != u.ux || y != u.uy)
2430.             /* no extra item from kops--too easy to abuse */
2431.             && mdat->mlet != S_KOP
2432.             /* no items from cloned monsters */
2433.             && !mtmp->mcloned) {
2434.             otmp = mkobj(RANDOM_CLASS, TRUE);
2435.             /* don't create large objects from small monsters */
2436.             otyp = otmp->otyp;
2437.             if (mdat->msize < MZ_HUMAN && otyp != FIGURINE
2438.                 /* oc_big is also oc_bimanual and oc_bulky */
2439.                 && (otmp->owt > 30 || objects[otyp].oc_big)) {
2440.                 delobj(otmp);
2441.             } else if (!flooreffects(otmp, x, y, nomsg ? "" : "fall")) {
2442.                 place_object(otmp, x, y);
2443.                 stackobj(otmp);
2444.             }
2445.         }
2446.         /* corpse--none if hero was inside the monster */
2447.         if (!wasinside && corpse_chance(mtmp, (struct monst *) 0, FALSE)) {
2448.             cadaver = make_corpse(mtmp, burycorpse ? CORPSTAT_BURIED
2449.                                                    : CORPSTAT_NONE);
2450.             if (burycorpse && cadaver && cansee(x, y) && !mtmp->minvis
2451.                 && cadaver->where == OBJ_BURIED && !nomsg) {
2452.                 pline("%s corpse ends up buried.", s_suffix(Monnam(mtmp)));
2453.             }
2454.         }
2455.     }
2456.     if (wasinside)
2457.         spoteffects(TRUE); /* poor man's expels() */
2458.     /* monster is gone, corpse or other object might now be visible */
2459.     newsym(x, y);
2460. 
2461.  cleanup:
2462.     /* punish bad behaviour */
2463.     if (is_human(mdat)
2464.         && (!always_hostile(mdat) && mtmp->malign <= 0)
2465.         && (mndx < PM_ARCHEOLOGIST || mndx > PM_WIZARD)
2466.         && u.ualign.type != A_CHAOTIC) {
2467.         HTelepat &= ~INTRINSIC;
2468.         change_luck(-2);
2469.         You("murderer!");
2470.         if (Blind && !Blind_telepat)
2471.             see_monsters(); /* Can't sense monsters any more. */
2472.     }
2473.     if ((mtmp->mpeaceful && !rn2(2)) || mtmp->mtame)
2474.         change_luck(-1);
2475.     if (is_unicorn(mdat) && sgn(u.ualign.type) == sgn(mdat->maligntyp)) {
2476.         change_luck(-5);
2477.         You_feel("guilty...");
2478.     }
2479. 
2480.     /* give experience points */
2481.     tmp = experience(mtmp, (int) mvitals[mndx].died);
2482.     more_experienced(tmp, 0);
2483.     newexplevel(); /* will decide if you go up */
2484. 
2485.     /* adjust alignment points */
2486.     if (mtmp->m_id == quest_status.leader_m_id) { /* REAL BAD! */
2487.         adjalign(-(u.ualign.record + (int) ALIGNLIM / 2));
2488.         pline("That was %sa bad idea...",
2489.               u.uevent.qcompleted ? "probably " : "");
2490.     } else if (mdat->msound == MS_NEMESIS) { /* Real good! */
2491.         adjalign((int) (ALIGNLIM / 4));
2492.     } else if (mdat->msound == MS_GUARDIAN) { /* Bad */
2493.         adjalign(-(int) (ALIGNLIM / 8));
2494.         if (!Hallucination)
2495.             pline("That was probably a bad idea...");
2496.         else
2497.             pline("Whoopsie-daisy!");
2498.     } else if (mtmp->ispriest) {
2499.         adjalign((p_coaligned(mtmp)) ? -2 : 2);
2500.         /* cancel divine protection for killing your priest */
2501.         if (p_coaligned(mtmp))
2502.             u.ublessed = 0;
2503.         if (mdat->maligntyp == A_NONE)
2504.             adjalign((int) (ALIGNLIM / 4)); /* BIG bonus */
2505.     } else if (mtmp->mtame) {
2506.         adjalign(-15); /* bad!! */
2507.         /* your god is mighty displeased... */
2508.         if (!Hallucination)
2509.             You_hear("the rumble of distant thunder...");
2510.         else
2511.             You_hear("the studio audience applaud!");
2512.     } else if (mtmp->mpeaceful)
2513.         adjalign(-5);
2514. 
2515.     /* malign was already adjusted for u.ualign.type and randomization */
2516.     adjalign(mtmp->malign);
2517. }
2518. 
2519. /* changes the monster into a stone monster of the same type
2520.    this should only be called when poly_when_stoned() is true */
2521. void
2522. mon_to_stone(mtmp)
2523. struct monst *mtmp;
2524. {
2525.     if (mtmp->data->mlet == S_GOLEM) {
2526.         /* it's a golem, and not a stone golem */
2527.         if (canseemon(mtmp))
2528.             pline("%s solidifies...", Monnam(mtmp));
2529.         if (newcham(mtmp, &mons[PM_STONE_GOLEM], FALSE, FALSE)) {
2530.             if (canseemon(mtmp))
2531.                 pline("Now it's %s.", an(mtmp->data->mname));
2532.         } else {
2533.             if (canseemon(mtmp))
2534.                 pline("... and returns to normal.");
2535.         }
2536.     } else
2537.         impossible("Can't polystone %s!", a_monnam(mtmp));
2538. }
2539. 
2540. boolean
2541. vamp_stone(mtmp)
2542. struct monst *mtmp;
2543. {
2544.     if (is_vampshifter(mtmp)) {
2545.         int mndx = mtmp->cham;
2546.         int x = mtmp->mx, y = mtmp->my;
2547. 
2548.         /* this only happens if shapeshifted */
2549.         if (mndx >= LOW_PM && mndx != monsndx(mtmp->data)
2550.             && !(mvitals[mndx].mvflags & G_GENOD)) {
2551.             char buf[BUFSZ];
2552.             boolean in_door = (amorphous(mtmp->data)
2553.                                && closed_door(mtmp->mx, mtmp->my));
2554. 
2555.             /* construct a format string before transformation */
2556.             Sprintf(buf, "The lapidifying %s %s %s",
2557.                     x_monnam(mtmp, ARTICLE_NONE, (char *) 0,
2558.                              (SUPPRESS_SADDLE | SUPPRESS_HALLUCINATION
2559.                               | SUPPRESS_INVISIBLE | SUPPRESS_IT), FALSE),
2560.                     amorphous(mtmp->data) ? "coalesces on the"
2561.                        : is_flyer(mtmp->data) ? "drops to the"
2562.                           : "writhes on the",
2563.                     surface(x,y));
2564.             mtmp->mcanmove = 1;
2565.             mtmp->mfrozen = 0;
2566.             if (mtmp->mhpmax <= 0)
2567.                 mtmp->mhpmax = 10;
2568.             mtmp->mhp = mtmp->mhpmax;
2569.             /* this can happen if previously a fog cloud */
2570.             if (u.uswallow && (mtmp == u.ustuck))
2571.                 expels(mtmp, mtmp->data, FALSE);
2572.             if (in_door) {
2573.                 coord new_xy;
2574. 
2575.                 if (enexto(&new_xy, mtmp->mx, mtmp->my, &mons[mndx])) {
2576.                     rloc_to(mtmp, new_xy.x, new_xy.y);
2577.                 }
2578.             }
2579.             if (canspotmon(mtmp)) {
2580.                 pline("%s!", buf);
2581.                 display_nhwindow(WIN_MESSAGE, FALSE);
2582.             }
2583.             newcham(mtmp, &mons[mndx], FALSE, FALSE);
2584.             if (mtmp->data == &mons[mndx])
2585.                 mtmp->cham = NON_PM;
2586.             else
2587.                 mtmp->cham = mndx;
2588.             if (canspotmon(mtmp)) {
2589.                 pline("%s rises from the %s with renewed agility!",
2590.                       Amonnam(mtmp), surface(mtmp->mx, mtmp->my));
2591.             }
2592.             newsym(mtmp->mx, mtmp->my);
2593.             return FALSE;   /* didn't petrify */
2594.         }
2595.     } else if (mtmp->cham >= LOW_PM
2596.                && (mons[mtmp->cham].mresists & MR_STONE)) {
2597.         /* sandestins are stoning-immune so if hit by stoning damage
2598.            they revert to innate shape rather than become a statue */
2599.         mtmp->mcanmove = 1;
2600.         mtmp->mfrozen = 0;
2601.         if (mtmp->mhpmax <= 0)
2602.             mtmp->mhpmax = 10;
2603.         mtmp->mhp = mtmp->mhpmax;
2604.         (void) newcham(mtmp, &mons[mtmp->cham], FALSE, TRUE);
2605.         newsym(mtmp->mx, mtmp->my);
2606.         return FALSE;   /* didn't petrify */
2607.     }
2608.     return TRUE;
2609. }
2610. 
2611. /* drop monster into "limbo" - that is, migrate to the current level */
2612. void
2613. m_into_limbo(mtmp)
2614. struct monst *mtmp;
2615. {
2616.     xchar target_lev = ledger_no(&u.uz), xyloc = MIGR_APPROX_XY;
2617. 
2618.     mtmp->mstate |= MON_LIMBO;
2619.     migrate_mon(mtmp, target_lev, xyloc);
2620. }
2621. 
2622. STATIC_OVL void
2623. migrate_mon(mtmp, target_lev, xyloc)
2624. struct monst *mtmp;
2625. xchar target_lev, xyloc;
2626. {
2627.     unstuck(mtmp);
2628.     mdrop_special_objs(mtmp);
2629.     migrate_to_level(mtmp, target_lev, xyloc, (coord *) 0);
2630.     mtmp->mstate |= MON_MIGRATING;
2631. }
2632. 
2633. STATIC_OVL boolean
2634. ok_to_obliterate(mtmp)
2635. struct monst *mtmp;
2636. {
2637.     /*
2638.      * Add checks for monsters that should not be obliterated
2639.      * here (return FALSE).
2640.      */
2641.     if (mtmp->data == &mons[PM_WIZARD_OF_YENDOR] || is_rider(mtmp->data)
2642.         || has_emin(mtmp) || has_epri(mtmp) || has_eshk(mtmp)
2643.         || (u.ustuck == mtmp) || (u.usteed == mtmp))
2644.         return FALSE;
2645.     return TRUE;
2646. }
2647. 
2648. void
2649. elemental_clog(mon)
2650. struct monst *mon;
2651. {
2652.     int m_lev = 0;
2653.     static long msgmv = 0L;
2654.     struct monst *mtmp, *m1, *m2, *m3, *m4, *m5, *zm;
2655. 
2656.     if (In_endgame(&u.uz)) {
2657.         m1 = m2 = m3 = m4 = m5 = zm = (struct monst *) 0;
2658.         if (!msgmv || (moves - msgmv) > 200L) {
2659.             if (!msgmv || rn2(2))
2660.                 You_feel("besieged.");
2661.             msgmv = moves;
2662.         }
2663.         /*
2664.          * m1 an elemental from another plane.
2665.          * m2 an elemental from this plane.
2666.          * m3 the least powerful monst encountered in loop so far.
2667.          * m4 some other non-tame monster.
2668.          * m5 a pet.
2669.          */
2670.         for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
2671.             if (DEADMONSTER(mtmp) || mtmp == mon)
2672.                 continue;
2673.             if (mtmp->mx == 0 && mtmp->my == 0)
2674.                 continue;
2675.             if (mon_has_amulet(mtmp) || !ok_to_obliterate(mtmp))
2676.                 continue;
2677.             if (mtmp->data->mlet == S_ELEMENTAL) {
2678.                 if (!is_home_elemental(mtmp->data)) {
2679.                     if (!m1)
2680.                         m1 = mtmp;
2681.                 } else {
2682.                     if (!m2)
2683.                         m2 = mtmp;
2684.                 }
2685.             } else {
2686.                 if (!mtmp->mtame) {
2687.                     if (!m_lev || mtmp->m_lev < m_lev) {
2688.                         m_lev = mtmp->m_lev;
2689.                         m3 = mtmp;
2690.                     } else if (!m4) {
2691.                         m4 = mtmp;
2692.                     }
2693.                 } else {
2694.                     if (!m5)
2695.                         m5 = mtmp;
2696.                     break;
2697.                 }
2698.             }
2699.         }
2700.         mtmp = m1 ? m1 : m2 ? m2 : m3 ? m3 : m4 ? m4 : m5 ? m5 : zm;
2701.         if (mtmp) {
2702.             int mx = mtmp->mx, my = mtmp->my;
2703. 
2704.             mtmp->mstate |= MON_OBLITERATE;
2705.             mongone(mtmp);
2706.             /* places in the code might still reference mtmp->mx, mtmp->my */
2707.             /* mtmp->mx = mtmp->my = 0; */
2708.             rloc_to(mon, mx, my);           /* note: mon, not mtmp */
2709. 
2710.         /* last resort - migrate mon to the next plane */
2711.         } else if (!Is_astralevel(&u.uz)) {
2712.             d_level dest;
2713.             xchar target_lev;
2714. 
2715.             dest = u.uz;
2716.             dest.dlevel--;
2717.             target_lev = ledger_no(&dest);
2718.             mon->mstate |= MON_ENDGAME_MIGR;
2719.             migrate_mon(mon, target_lev, MIGR_RANDOM);
2720.         }
2721.     }
2722. }
2723. 
2724. /* make monster mtmp next to you (if possible);
2725.    might place monst on far side of a wall or boulder */
2726. void
2727. mnexto(mtmp)
2728. struct monst *mtmp;
2729. {
2730.     coord mm;
2731.     boolean couldspot = canspotmon(mtmp);
2732. 
2733.     if (mtmp == u.usteed) {
2734.         /* Keep your steed in sync with you instead */
2735.         mtmp->mx = u.ux;
2736.         mtmp->my = u.uy;
2737.         return;
2738.     }
2739. 
2740.     if (!enexto(&mm, u.ux, u.uy, mtmp->data) || !isok(mm.x, mm.y)) {
2741.         deal_with_overcrowding(mtmp);
2742.         return;
2743.     }
2744.     rloc_to(mtmp, mm.x, mm.y);
2745.     if (!in_mklev && (mtmp->mstrategy & STRAT_APPEARMSG)) {
2746.         mtmp->mstrategy &= ~STRAT_APPEARMSG; /* one chance only */
2747.         if (!couldspot && canspotmon(mtmp))
2748.             pline("%s suddenly %s!", Amonnam(mtmp),
2749.                   !Blind ? "appears" : "arrives");
2750.     }
2751.     return;
2752. }
2753. 
2754. STATIC_OVL void
2755. deal_with_overcrowding(mtmp)
2756. struct monst *mtmp;
2757. {
2758.     if (In_endgame(&u.uz)) {
2759.         debugpline1("overcrowding: elemental_clog on %s", m_monnam(mtmp));
2760.         elemental_clog(mtmp);
2761.     } else {
2762.         debugpline1("overcrowding: sending %s into limbo", m_monnam(mtmp));
2763.         m_into_limbo(mtmp);
2764.     }
2765. }
2766. 
2767. /* like mnexto() but requires destination to be directly accessible */
2768. void
2769. maybe_mnexto(mtmp)
2770. struct monst *mtmp;
2771. {
2772.     coord mm;
2773.     struct permonst *ptr = mtmp->data;
2774.     boolean diagok = !NODIAG(ptr - mons);
2775.     int tryct = 20;
2776. 
2777.     do {
2778.         if (!enexto(&mm, u.ux, u.uy, ptr))
2779.             return;
2780.         if (couldsee(mm.x, mm.y)
2781.             /* don't move grid bugs diagonally */
2782.             && (diagok || mm.x == mtmp->mx || mm.y == mtmp->my)) {
2783.             rloc_to(mtmp, mm.x, mm.y);
2784.             return;
2785.         }
2786.     } while (--tryct > 0);
2787. }
2788. 
2789. /* mnearto()
2790.  * Put monster near (or at) location if possible.
2791.  * Returns:
2792.  *  2 if another monster was moved out of this one's way;
2793.  *  1 if relocation was successful (without moving another one);
2794.  *  0 otherwise.
2795.  * Note: if already at the target spot, result is 1 rather than 0.
2796.  *
2797.  * Might be called recursively if 'move_other' is True; if so, that argument
2798.  * will be False on the nested call so there won't be any further recursion.
2799.  */
2800. int
2801. mnearto(mtmp, x, y, move_other)
2802. register struct monst *mtmp;
2803. xchar x, y;
2804. boolean move_other; /* make sure mtmp gets to x, y! so move m_at(x, y) */
2805. {
2806.     struct monst *othermon = (struct monst *) 0;
2807.     xchar newx, newy;
2808.     coord mm;
2809.     int res = 1;
2810. 
2811.     if (mtmp->mx == x && mtmp->my == y && m_at(x, y) == mtmp)
2812.         return res;
2813. 
2814.     if (move_other && (othermon = m_at(x, y)) != 0) {
2815.         if (othermon->wormno)
2816.             remove_worm(othermon);
2817.         else
2818.             remove_monster(x, y);
2819. 
2820.         othermon->mx = othermon->my = 0; /* 'othermon' is not on the map */
2821.         othermon->mstate |= MON_OFFMAP;
2822.     }
2823. 
2824.     newx = x;
2825.     newy = y;
2826.     if (!goodpos(newx, newy, mtmp, 0)) {
2827.         /* Actually we have real problems if enexto ever fails.
2828.          * Migrating_mons that need to be placed will cause
2829.          * no end of trouble.
2830.          */
2831.         if (!enexto(&mm, newx, newy, mtmp->data) || !isok(mm.x, mm.y)) {
2832.             if (othermon) {
2833.                 /* othermon already had its mx, my set to 0 above
2834.                  * and this would shortly cause a sanity check to fail
2835.                  * if we just return 0 here. The caller only possesses
2836.                  * awareness of mtmp, not othermon. */
2837.                 deal_with_overcrowding(othermon);
2838.             }
2839.             return 0;
2840.         }
2841.         newx = mm.x;
2842.         newy = mm.y;
2843.     }
2844.     rloc_to(mtmp, newx, newy);
2845. 
2846.     if (move_other && othermon) {
2847.         res = 2; /* moving another monster out of the way */
2848.         if (!mnearto(othermon, x, y, FALSE))  /* no 'move_other' this time */
2849.             deal_with_overcrowding(othermon);
2850.     }
2851. 
2852.     return res;
2853. }
2854. 
2855. /* monster responds to player action; not the same as a passive attack;
2856.    assumes reason for response has been tested, and response _must_ be made */
2857. void
2858. m_respond(mtmp)
2859. struct monst *mtmp;
2860. {
2861.     if (mtmp->data->msound == MS_SHRIEK) {
2862.         if (!Deaf) {
2863.             pline("%s shrieks.", Monnam(mtmp));
2864.             stop_occupation();
2865.         }
2866.         if (!rn2(10)) {
2867.             if (!rn2(13))
2868.                 (void) makemon(&mons[PM_PURPLE_WORM], 0, 0, NO_MM_FLAGS);
2869.             else
2870.                 (void) makemon((struct permonst *) 0, 0, 0, NO_MM_FLAGS);
2871.         }
2872.         aggravate();
2873.     }
2874.     if (mtmp->data == &mons[PM_MEDUSA]) {
2875.         register int i;
2876. 
2877.         for (i = 0; i < NATTK; i++)
2878.             if (mtmp->data->mattk[i].aatyp == AT_GAZE) {
2879.                 (void) gazemu(mtmp, &mtmp->data->mattk[i]);
2880.                 break;
2881.             }
2882.     }
2883. }
2884. 
2885. /* Called whenever the player attacks mtmp; also called in other situations
2886.    where mtmp gets annoyed at the player. Handles mtmp getting annoyed at the
2887.    attack and any ramifications that might have. Useful also in situations
2888.    where mtmp was already hostile; it checks for situations where the player
2889.    shouldn't be attacking and any ramifications /that/ might have. */
2890. void
2891. setmangry(mtmp, via_attack)
2892. struct monst *mtmp;
2893. boolean via_attack;
2894. {
2895.     if (via_attack && sengr_at("Elbereth", u.ux, u.uy, TRUE)
2896.         /* only hypocritical if monster is vulnerable to Elbereth (or
2897.            peaceful--not vulnerable but attacking it is hypocritical) */
2898.         && (onscary(u.ux, u.uy, mtmp) || mtmp->mpeaceful)) {
2899.         You_feel("like a hypocrite.");
2900.         /* AIS: Yes, I know alignment penalties and bonuses aren't balanced
2901.            at the moment. This is about correct relative to other "small"
2902.            penalties; it should be fairly large, as attacking while standing
2903.            on an Elbereth means that you're requesting peace and then
2904.            violating your own request. I know 5 isn't actually large, but
2905.            it's intentionally larger than the 1s and 2s that are normally
2906.            given for this sort of thing. */
2907.         /* reduce to 3 (average) when alignment is already very low */
2908.         adjalign((u.ualign.record > 5) ? -5 : -rnd(5));
2909. 
2910.         if (!Blind)
2911.             pline("The engraving beneath you fades.");
2912.         del_engr_at(u.ux, u.uy);
2913.     }
2914. 
2915.     /* AIS: Should this be in both places, or just in wakeup()? */
2916.     mtmp->mstrategy &= ~STRAT_WAITMASK;
2917.     if (!mtmp->mpeaceful)
2918.         return;
2919.     if (mtmp->mtame)
2920.         return;
2921.     mtmp->mpeaceful = 0;
2922.     if (mtmp->ispriest) {
2923.         if (p_coaligned(mtmp))
2924.             adjalign(-5); /* very bad */
2925.         else
2926.             adjalign(2);
2927.     } else
2928.         adjalign(-1); /* attacking peaceful monsters is bad */
2929.     if (couldsee(mtmp->mx, mtmp->my)) {
2930.         if (humanoid(mtmp->data) || mtmp->isshk || mtmp->isgd)
2931.             pline("%s gets angry!", Monnam(mtmp));
2932.         else if (flags.verbose && !Deaf)
2933.             growl(mtmp);
2934.     }
2935. 
2936.     /* attacking your own quest leader will anger his or her guardians */
2937.     if (!context.mon_moving /* should always be the case here */
2938.         && mtmp->data == &mons[quest_info(MS_LEADER)]) {
2939.         struct monst *mon;
2940.         struct permonst *q_guardian = &mons[quest_info(MS_GUARDIAN)];
2941.         int got_mad = 0;
2942. 
2943.         /* guardians will sense this attack even if they can't see it */
2944.         for (mon = fmon; mon; mon = mon->nmon) {
2945.             if (DEADMONSTER(mon))
2946.                 continue;
2947.             if (mon->data == q_guardian && mon->mpeaceful) {
2948.                 mon->mpeaceful = 0;
2949.                 if (canseemon(mon))
2950.                     ++got_mad;
2951.             }
2952.         }
2953.         if (got_mad && !Hallucination) {
2954.             const char *who = q_guardian->mname;
2955. 
2956.             if (got_mad > 1)
2957.                 who = makeplural(who);
2958.             pline_The("%s %s to be angry too...",
2959.                       who, vtense(who, "appear"));
2960.         }
2961.     }
2962. 
2963.     /* make other peaceful monsters react */
2964.     if (!context.mon_moving) {
2965.         static const char *const Exclam[] = {
2966.             "Gasp!", "Uh-oh.", "Oh my!", "What?", "Why?",
2967.         };
2968.         struct monst *mon;
2969.         int mndx = monsndx(mtmp->data);
2970. 
2971.         for (mon = fmon; mon; mon = mon->nmon) {
2972.             if (DEADMONSTER(mon))
2973.                 continue;
2974.             if (mon == mtmp) /* the mpeaceful test catches this since mtmp */
2975.                 continue;    /* is no longer peaceful, but be explicit...  */
2976. 
2977.             if (!mindless(mon->data) && mon->mpeaceful
2978.                 && couldsee(mon->mx, mon->my) && !mon->msleeping
2979.                 && mon->mcansee && m_canseeu(mon)) {
2980.                 boolean exclaimed = FALSE;
2981. 
2982.                 if (humanoid(mon->data) || mon->isshk || mon->ispriest) {
2983.                     if (is_watch(mon->data)) {
2984.                         verbalize("Halt!  You're under arrest!");
2985.                         (void) angry_guards(!!Deaf);
2986.                     } else {
2987.                         if (!rn2(5)) {
2988.                             verbalize("%s", Exclam[mon->m_id % SIZE(Exclam)]);
2989.                             exclaimed = TRUE;
2990.                         }
2991.                         /* shopkeepers and temple priests might gasp in
2992.                            surprise, but they won't become angry here */
2993.                         if (mon->isshk || mon->ispriest)
2994.                             continue;
2995. 
2996.                         if (mon->data->mlevel < rn2(10)) {
2997.                             monflee(mon, rn2(50) + 25, TRUE, !exclaimed);
2998.                             exclaimed = TRUE;
2999.                         }
3000.                         if (mon->mtame) {
3001.                             /* mustn't set mpeaceful to 0 as below;
3002.                                perhaps reduce tameness? */
3003.                         } else {
3004.                             mon->mpeaceful = 0;
3005.                             adjalign(-1);
3006.                             if (!exclaimed)
3007.                                 pline("%s gets angry!", Monnam(mon));
3008.                         }
3009.                     }
3010.                 } else if (mon->data->mlet == mtmp->data->mlet
3011.                            && big_little_match(mndx, monsndx(mon->data))
3012.                            && !rn2(3)) {
3013.                     if (!rn2(4)) {
3014.                         growl(mon);
3015.                         exclaimed = TRUE;
3016.                     }
3017.                     if (rn2(6))
3018.                         monflee(mon, rn2(25) + 15, TRUE, !exclaimed);
3019.                 }
3020.             }
3021.         }
3022.     }
3023. }
3024. 
3025. /* wake up a monster, possibly making it angry in the process */
3026. void
3027. wakeup(mtmp, via_attack)
3028. register struct monst *mtmp;
3029. boolean via_attack;
3030. {
3031.     mtmp->msleeping = 0;
3032.     if (M_AP_TYPE(mtmp)) {
3033.         seemimic(mtmp);
3034.     } else if (context.forcefight && !context.mon_moving
3035.                && mtmp->mundetected) {
3036.         mtmp->mundetected = 0;
3037.         newsym(mtmp->mx, mtmp->my);
3038.     }
3039.     finish_meating(mtmp);
3040.     if (via_attack)
3041.         setmangry(mtmp, TRUE);
3042. }
3043. 
3044. /* Wake up nearby monsters without angering them. */
3045. void
3046. wake_nearby()
3047. {
3048.     wake_nearto(u.ux, u.uy, u.ulevel * 20);
3049. }
3050. 
3051. /* Wake up monsters near some particular location. */
3052. void
3053. wake_nearto(x, y, distance)
3054. int x, y, distance;
3055. {
3056.     struct monst *mtmp;
3057. 
3058.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
3059.         if (DEADMONSTER(mtmp))
3060.             continue;
3061.         if (distance == 0 || dist2(mtmp->mx, mtmp->my, x, y) < distance) {
3062.             /* sleep for N turns uses mtmp->mfrozen, but so does paralysis
3063.                so we leave mfrozen monsters alone */
3064.             mtmp->msleeping = 0; /* wake indeterminate sleep */
3065.             if (!(mtmp->data->geno & G_UNIQ))
3066.                 mtmp->mstrategy &= ~STRAT_WAITMASK; /* wake 'meditation' */
3067.             if (context.mon_moving)
3068.                 continue;
3069.             if (mtmp->mtame) {
3070.                 if (!mtmp->isminion)
3071.                     EDOG(mtmp)->whistletime = moves;
3072.                 /* Clear mtrack. This is to fix up a pet who is
3073.                    stuck "fleeing" its master. */
3074.                 memset(mtmp->mtrack, 0, sizeof mtmp->mtrack);
3075.             }
3076.         }
3077.     }
3078. }
3079. 
3080. /* NOTE: we must check for mimicry before calling this routine */
3081. void
3082. seemimic(mtmp)
3083. register struct monst *mtmp;
3084. {
3085.     boolean is_blocker_appear = (is_lightblocker_mappear(mtmp));
3086. 
3087.     if (has_mcorpsenm(mtmp))
3088.         freemcorpsenm(mtmp);
3089. 
3090.     mtmp->m_ap_type = M_AP_NOTHING;
3091.     mtmp->mappearance = 0;
3092. 
3093.     /*
3094.      *  Discovered mimics don't block light.
3095.      */
3096.     if (is_blocker_appear
3097.         && !does_block(mtmp->mx, mtmp->my, &levl[mtmp->mx][mtmp->my]))
3098.         unblock_point(mtmp->mx, mtmp->my);
3099. 
3100.     newsym(mtmp->mx, mtmp->my);
3101. }
3102. 
3103. /* force all chameleons to become normal */
3104. void
3105. rescham()
3106. {
3107.     register struct monst *mtmp;
3108.     int mcham;
3109. 
3110.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
3111.         if (DEADMONSTER(mtmp))
3112.             continue;
3113.         mcham = (int) mtmp->cham;
3114.         if (mcham >= LOW_PM) {
3115.             (void) newcham(mtmp, &mons[mcham], FALSE, FALSE);
3116.             mtmp->cham = NON_PM;
3117.         }
3118.         if (is_were(mtmp->data) && mtmp->data->mlet != S_HUMAN)
3119.             new_were(mtmp);
3120.         if (M_AP_TYPE(mtmp) && cansee(mtmp->mx, mtmp->my)) {
3121.             seemimic(mtmp);
3122.             /* we pretend that the mimic doesn't
3123.                know that it has been unmasked */
3124.             mtmp->msleeping = 1;
3125.         }
3126.     }
3127. }
3128. 
3129. /* Let the chameleons change again -dgk */
3130. void
3131. restartcham()
3132. {
3133.     register struct monst *mtmp;
3134. 
3135.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
3136.         if (DEADMONSTER(mtmp))
3137.             continue;
3138.         if (!mtmp->mcan)
3139.             mtmp->cham = pm_to_cham(monsndx(mtmp->data));
3140.         if (mtmp->data->mlet == S_MIMIC && mtmp->msleeping
3141.             && cansee(mtmp->mx, mtmp->my)) {
3142.             set_mimic_sym(mtmp);
3143.             newsym(mtmp->mx, mtmp->my);
3144.         }
3145.     }
3146. }
3147. 
3148. /* called when restoring a monster from a saved level; protection
3149.    against shape-changing might be different now than it was at the
3150.    time the level was saved. */
3151. void
3152. restore_cham(mon)
3153. struct monst *mon;
3154. {
3155.     int mcham;
3156. 
3157.     if (Protection_from_shape_changers) {
3158.         mcham = (int) mon->cham;
3159.         if (mcham >= LOW_PM) {
3160.             mon->cham = NON_PM;
3161.             (void) newcham(mon, &mons[mcham], FALSE, FALSE);
3162.         } else if (is_were(mon->data) && !is_human(mon->data)) {
3163.             new_were(mon);
3164.         }
3165.     } else if (mon->cham == NON_PM) {
3166.         mon->cham = pm_to_cham(monsndx(mon->data));
3167.     }
3168. }
3169. 
3170. /* unwatched hiders may hide again; if so, returns True */
3171. STATIC_OVL boolean
3172. restrap(mtmp)
3173. register struct monst *mtmp;
3174. {
3175.     struct trap *t;
3176. 
3177.     if (mtmp->mcan || M_AP_TYPE(mtmp) || cansee(mtmp->mx, mtmp->my)
3178.         || rn2(3) || mtmp == u.ustuck
3179.         /* can't hide while trapped except in pits */
3180.         || (mtmp->mtrapped && (t = t_at(mtmp->mx, mtmp->my)) != 0
3181.             && !is_pit(t->ttyp))
3182.         || (sensemon(mtmp) && distu(mtmp->mx, mtmp->my) <= 2))
3183.         return FALSE;
3184. 
3185.     if (mtmp->data->mlet == S_MIMIC) {
3186.         set_mimic_sym(mtmp);
3187.         return TRUE;
3188.     } else if (levl[mtmp->mx][mtmp->my].typ == ROOM) {
3189.         mtmp->mundetected = 1;
3190.         return TRUE;
3191.     }
3192. 
3193.     return FALSE;
3194. }
3195. 
3196. /* monster/hero tries to hide under something at the current location */
3197. boolean
3198. hideunder(mtmp)
3199. struct monst *mtmp;
3200. {
3201.     struct trap *t;
3202.     boolean undetected = FALSE, is_u = (mtmp == &youmonst);
3203.     xchar x = is_u ? u.ux : mtmp->mx, y = is_u ? u.uy : mtmp->my;
3204. 
3205.     if (mtmp == u.ustuck) {
3206.         ; /* can't hide if holding you or held by you */
3207.     } else if (is_u ? (u.utrap && u.utraptype != TT_PIT)
3208.                     : (mtmp->mtrapped && (t = t_at(x, y)) != 0
3209.                        && !is_pit(t->ttyp))) {
3210.         ; /* can't hide while stuck in a non-pit trap */
3211.     } else if (mtmp->data->mlet == S_EEL) {
3212.         undetected = (is_pool(x, y) && !Is_waterlevel(&u.uz));
3213.     } else if (hides_under(mtmp->data) && OBJ_AT(x, y)) {
3214.         struct obj *otmp = level.objects[x][y];
3215. 
3216.         /* most monsters won't hide under cockatrice corpse */
3217.         if (otmp->nexthere || otmp->otyp != CORPSE
3218.             || (mtmp == &youmonst ? Stone_resistance : resists_ston(mtmp))
3219.             || !touch_petrifies(&mons[otmp->corpsenm]))
3220.             undetected = TRUE;
3221.     }
3222. 
3223.     if (is_u)
3224.         u.uundetected = undetected;
3225.     else
3226.         mtmp->mundetected = undetected;
3227.     return undetected;
3228. }
3229. 
3230. /* called when returning to a previously visited level */
3231. void
3232. hide_monst(mon)
3233. struct monst *mon;
3234. {
3235.     boolean hider_under = hides_under(mon->data) || mon->data->mlet == S_EEL;
3236. 
3237.     if ((is_hider(mon->data) || hider_under)
3238.         && !(mon->mundetected || M_AP_TYPE(mon))) {
3239.         xchar x = mon->mx, y = mon->my;
3240.         char save_viz = viz_array[y][x];
3241. 
3242.         /* override vision, forcing hero to be unable to see monster's spot */
3243.         viz_array[y][x] &= ~(IN_SIGHT | COULD_SEE);
3244.         if (is_hider(mon->data))
3245.             (void) restrap(mon);
3246.         /* try again if mimic missed its 1/3 chance to hide */
3247.         if (mon->data->mlet == S_MIMIC && !M_AP_TYPE(mon))
3248.             (void) restrap(mon);
3249.         if (hider_under)
3250.             (void) hideunder(mon);
3251.         viz_array[y][x] = save_viz;
3252.     }
3253. }
3254. 
3255. static short *animal_list = 0; /* list of PM values for animal monsters */
3256. static int animal_list_count;
3257. 
3258. void
3259. mon_animal_list(construct)
3260. boolean construct;
3261. {
3262.     if (construct) {
3263.         short animal_temp[SPECIAL_PM];
3264.         int i, n;
3265. 
3266.         /* if (animal_list) impossible("animal_list already exists"); */
3267. 
3268.         for (n = 0, i = LOW_PM; i < SPECIAL_PM; i++)
3269.             if (is_animal(&mons[i]))
3270.                 animal_temp[n++] = i;
3271.         /* if (n == 0) animal_temp[n++] = NON_PM; */
3272. 
3273.         animal_list = (short *) alloc(n * sizeof *animal_list);
3274.         (void) memcpy((genericptr_t) animal_list, (genericptr_t) animal_temp,
3275.                       n * sizeof *animal_list);
3276.         animal_list_count = n;
3277.     } else { /* release */
3278.         if (animal_list)
3279.             free((genericptr_t) animal_list), animal_list = 0;
3280.         animal_list_count = 0;
3281.     }
3282. }
3283. 
3284. STATIC_OVL int
3285. pick_animal()
3286. {
3287.     int res;
3288. 
3289.     if (!animal_list)
3290.         mon_animal_list(TRUE);
3291. 
3292.     res = animal_list[rn2(animal_list_count)];
3293.     /* rogue level should use monsters represented by uppercase letters
3294.        only, but since chameleons aren't generated there (not uppercase!)
3295.        we don't perform a lot of retries */
3296.     if (Is_rogue_level(&u.uz) && !isupper((uchar) mons[res].mlet))
3297.         res = animal_list[rn2(animal_list_count)];
3298.     return res;
3299. }
3300. 
3301. void
3302. decide_to_shapeshift(mon, shiftflags)
3303. struct monst *mon;
3304. int shiftflags;
3305. {
3306.     struct permonst *ptr = 0;
3307.     int mndx;
3308.     unsigned was_female = mon->female;
3309.     boolean msg = FALSE, dochng = FALSE;
3310. 
3311.     if ((shiftflags & SHIFT_MSG)
3312.         || ((shiftflags & SHIFT_SEENMSG) && sensemon(mon)))
3313.         msg = TRUE;
3314. 
3315.     if (!is_vampshifter(mon)) {
3316.         /* regular shapeshifter */
3317.         if (!rn2(6))
3318.             dochng = TRUE;
3319.     } else {
3320.         /* The vampire has to be in good health (mhp) to maintain
3321.          * its shifted form.
3322.          *
3323.          * If we're shifted and getting low on hp, maybe shift back, or
3324.          * if we're a fog cloud at full hp, maybe pick a different shape.
3325.          * If we're not already shifted and in good health, maybe shift.
3326.          */
3327.         if (mon->data->mlet != S_VAMPIRE) {
3328.             if ((mon->mhp <= (mon->mhpmax + 5) / 6) && rn2(4)
3329.                 && mon->cham >= LOW_PM) {
3330.                 ptr = &mons[mon->cham];
3331.                 dochng = TRUE;
3332.             } else if (mon->data == &mons[PM_FOG_CLOUD]
3333.                      && mon->mhp == mon->mhpmax && !rn2(4)
3334.                      && (!canseemon(mon)
3335.                          || distu(mon->mx, mon->my) > BOLT_LIM * BOLT_LIM)) {
3336.                 /* if a fog cloud, maybe change to wolf or vampire bat;
3337.                    those are more likely to take damage--at least when
3338.                    tame--and then switch back to vampire; they'll also
3339.                    switch to fog cloud if they encounter a closed door */
3340.                 mndx = pickvampshape(mon);
3341.                 if (mndx >= LOW_PM) {
3342.                     ptr = &mons[mndx];
3343.                     dochng = (ptr != mon->data);
3344.                 }
3345.             }
3346.         } else {
3347.             if (mon->mhp >= 9 * mon->mhpmax / 10 && !rn2(6)
3348.                 && (!canseemon(mon)
3349.                     || distu(mon->mx, mon->my) > BOLT_LIM * BOLT_LIM))
3350.                 dochng = TRUE; /* 'ptr' stays Null */
3351.         }
3352.     }
3353.     if (dochng) {
3354.         if (newcham(mon, ptr, FALSE, msg) && is_vampshifter(mon)) {
3355.             /* for vampshift, override the 10% chance for sex change */
3356.             ptr = mon->data;
3357.             if (!is_male(ptr) && !is_female(ptr) && !is_neuter(ptr))
3358.                 mon->female = was_female;
3359.         }
3360.     }
3361. }
3362. 
3363. STATIC_OVL int
3364. pickvampshape(mon)
3365. struct monst *mon;
3366. {
3367.     int mndx = mon->cham, wolfchance = 10;
3368.     /* avoid picking monsters with lowercase display symbols ('d' for wolf
3369.        and 'v' for fog cloud) on rogue level*/
3370.     boolean uppercase_only = Is_rogue_level(&u.uz);
3371. 
3372.     switch (mndx) {
3373.     case PM_VLAD_THE_IMPALER:
3374.         /* ensure Vlad can keep carrying the Candelabrum */
3375.         if (mon_has_special(mon))
3376.             break; /* leave mndx as is */
3377.         wolfchance = 3;
3378.     /*FALLTHRU*/
3379.     case PM_VAMPIRE_LORD: /* vampire lord or Vlad can become wolf */
3380.         if (!rn2(wolfchance) && !uppercase_only) {
3381.             mndx = PM_WOLF;
3382.             break;
3383.         }
3384.     /*FALLTHRU*/
3385.     case PM_VAMPIRE: /* any vampire can become fog or bat */
3386.         mndx = (!rn2(4) && !uppercase_only) ? PM_FOG_CLOUD : PM_VAMPIRE_BAT;
3387.         break;
3388.     }
3389.     return mndx;
3390. }
3391. 
3392. /* nonshapechangers who warrant special polymorph handling */
3393. STATIC_OVL boolean
3394. isspecmon(mon)
3395. struct monst *mon;
3396. {
3397.     return (mon->isshk || mon->ispriest || mon->isgd
3398.             || mon->m_id == quest_status.leader_m_id);
3399. }
3400. 
3401. /* restrict certain special monsters (shopkeepers, aligned priests,
3402.    vault guards) to forms that allow them to behave sensibly (catching
3403.    gold, speaking?) so that they don't need too much extra code */
3404. STATIC_OVL boolean
3405. validspecmon(mon, mndx)
3406. struct monst *mon;
3407. int mndx;
3408. {
3409.     if (mndx == NON_PM)
3410.         return TRUE; /* caller wants random */
3411. 
3412.     if (!accept_newcham_form(mon, mndx))
3413.         return FALSE; /* geno'd or !polyok */
3414. 
3415.     if (isspecmon(mon)) {
3416.         struct permonst *ptr = &mons[mndx];
3417. 
3418.         /* reject notake because object manipulation is expected
3419.            and nohead because speech capability is expected */
3420.         if (notake(ptr) || !has_head(ptr))
3421.             return FALSE;
3422.         /* [should we check ptr->msound here too?] */
3423.     }
3424.     return TRUE; /* potential new form is ok */
3425. }
3426. 
3427. /* prevent wizard mode user from specifying invalid vampshifter shape */
3428. boolean
3429. validvamp(mon, mndx_p, monclass)
3430. struct monst *mon;
3431. int *mndx_p, monclass;
3432. {
3433.     /* simplify caller's usage */
3434.     if (!is_vampshifter(mon))
3435.         return validspecmon(mon, *mndx_p);
3436. 
3437.     if (mon->cham == PM_VLAD_THE_IMPALER && mon_has_special(mon)) {
3438.         /* Vlad with Candelabrum; override choice, then accept it */
3439.         *mndx_p = PM_VLAD_THE_IMPALER;
3440.         return TRUE;
3441.     }
3442.     if (*mndx_p >= LOW_PM && is_shapeshifter(&mons[*mndx_p])) {
3443.         /* player picked some type of shapeshifter; use mon's self
3444.            (vampire or chameleon) */
3445.         *mndx_p = mon->cham;
3446.         return TRUE;
3447.     }
3448.     /* basic vampires can't become wolves; any can become fog or bat
3449.        (we don't enforce upper-case only for rogue level here) */
3450.     if (*mndx_p == PM_WOLF)
3451.         return (boolean) (mon->cham != PM_VAMPIRE);
3452.     if (*mndx_p == PM_FOG_CLOUD || *mndx_p == PM_VAMPIRE_BAT)
3453.         return TRUE;
3454. 
3455.     /* if we get here, specific type was no good; try by class */
3456.     switch (monclass) {
3457.     case S_VAMPIRE:
3458.         *mndx_p = mon->cham;
3459.         break;
3460.     case S_BAT:
3461.         *mndx_p = PM_VAMPIRE_BAT;
3462.         break;
3463.     case S_VORTEX:
3464.         *mndx_p = PM_FOG_CLOUD;
3465.         break;
3466.     case S_DOG:
3467.         if (mon->cham != PM_VAMPIRE) {
3468.             *mndx_p = PM_WOLF;
3469.             break;
3470.         }
3471.         /*FALLTHRU*/
3472.     default:
3473.         *mndx_p = NON_PM;
3474.         break;
3475.     }
3476.     return (boolean) (*mndx_p != NON_PM);
3477. }
3478. 
3479. int
3480. select_newcham_form(mon)
3481. struct monst *mon;
3482. {
3483.     int mndx = NON_PM, tryct;
3484. 
3485.     switch (mon->cham) {
3486.     case PM_SANDESTIN:
3487.         if (rn2(7))
3488.             mndx = pick_nasty();
3489.         break;
3490.     case PM_DOPPELGANGER:
3491.         if (!rn2(7)) {
3492.             mndx = pick_nasty();
3493.         } else if (rn2(3)) { /* role monsters */
3494.             mndx = rn1(PM_WIZARD - PM_ARCHEOLOGIST + 1, PM_ARCHEOLOGIST);
3495.         } else if (!rn2(3)) { /* quest guardians */
3496.             mndx = rn1(PM_APPRENTICE - PM_STUDENT + 1, PM_STUDENT);
3497.             /* avoid own role's guardian */
3498.             if (mndx == urole.guardnum)
3499.                 mndx = NON_PM;
3500.         } else { /* general humanoids */
3501.             tryct = 5;
3502.             do {
3503.                 mndx = rn1(SPECIAL_PM - LOW_PM, LOW_PM);
3504.                 if (humanoid(&mons[mndx]) && polyok(&mons[mndx]))
3505.                     break;
3506.             } while (--tryct > 0);
3507.             if (!tryct)
3508.                 mndx = NON_PM;
3509.         }
3510.         break;
3511.     case PM_CHAMELEON:
3512.         if (!rn2(3))
3513.             mndx = pick_animal();
3514.         break;
3515.     case PM_VLAD_THE_IMPALER:
3516.     case PM_VAMPIRE_LORD:
3517.     case PM_VAMPIRE:
3518.         mndx = pickvampshape(mon);
3519.         break;
3520.     case NON_PM: /* ordinary */
3521.       {
3522.         struct obj *m_armr = which_armor(mon, W_ARM);
3523. 
3524.         if (m_armr && Is_dragon_scales(m_armr))
3525.             mndx = (int) (Dragon_scales_to_pm(m_armr) - mons);
3526.         else if (m_armr && Is_dragon_mail(m_armr))
3527.             mndx = (int) (Dragon_mail_to_pm(m_armr) - mons);
3528.       }
3529.         break;
3530.     }
3531. 
3532.     /* for debugging: allow control of polymorphed monster */
3533.     if (wizard && iflags.mon_polycontrol) {
3534.         char pprompt[BUFSZ], parttwo[QBUFSZ], buf[BUFSZ];
3535.         int monclass, len;
3536. 
3537.         /* construct prompt in pieces */
3538.         Sprintf(pprompt, "Change %s", noit_mon_nam(mon));
3539.         Sprintf(parttwo, " @ %s into what?",
3540.                 coord_desc((int) mon->mx, (int) mon->my, buf,
3541.                            (iflags.getpos_coords != GPCOORDS_NONE)
3542.                               ? iflags.getpos_coords : GPCOORDS_MAP));
3543.         /* combine the two parts, not exceeding QBUFSZ-1 in overall length;
3544.            if combined length is too long it has to be due to monster's
3545.            name so we'll chop enough of that off to fit the second part */
3546.         if ((len = (int) strlen(pprompt) + (int) strlen(parttwo)) >= QBUFSZ)
3547.             /* strlen(parttwo) is less than QBUFSZ/2 so strlen(pprompt) is
3548.                more than QBUFSZ/2 and excess amount being truncated can't
3549.                exceed pprompt's length and back up to before &pprompt[0]) */
3550.             *(eos(pprompt) - (len - (QBUFSZ - 1))) = '\0';
3551.         Strcat(pprompt, parttwo);
3552. 
3553.         buf[0] = '\0'; /* clear buffer for EDIT_GETLIN */
3554. #define TRYLIMIT 5
3555.         tryct = TRYLIMIT;
3556.         do {
3557.             if (tryct == TRYLIMIT - 1) { /* first retry */
3558.                 /* change "into what?" to "into what kind of monster?" */
3559.                 if (strlen(pprompt) + sizeof " kind of monster" - 1 < QBUFSZ)
3560.                     Strcpy(eos(pprompt) - 1, " kind of monster?");
3561.             }
3562. #undef TRYLIMIT
3563.             monclass = 0;
3564.             getlin(pprompt, buf);
3565.             mungspaces(buf);
3566.             /* for ESC, take form selected above (might be NON_PM) */
3567.             if (*buf == '\033')
3568.                 break;
3569.             /* for "*", use NON_PM to pick an arbitrary shape below */
3570.             if (!strcmp(buf, "*") || !strcmpi(buf, "random")) {
3571.                 mndx = NON_PM;
3572.                 break;
3573.             }
3574.             mndx = name_to_mon(buf);
3575.             if (mndx == NON_PM) {
3576.                 /* didn't get a type, so check whether it's a class
3577.                    (single letter or text match with def_monsyms[]) */
3578.                 monclass = name_to_monclass(buf, &mndx);
3579.                 if (monclass && mndx == NON_PM)
3580.                     mndx = mkclass_poly(monclass);
3581.             }
3582.             if (mndx >= LOW_PM) {
3583.                 /* got a specific type of monster; use it if we can */
3584.                 if (validvamp(mon, &mndx, monclass))
3585.                     break;
3586.                 /* can't; revert to random in case we exhaust tryct */
3587.                 mndx = NON_PM;
3588.             }
3589. 
3590.             pline("It can't become that.");
3591.         } while (--tryct > 0);
3592. 
3593.         if (!tryct)
3594.             pline1(thats_enough_tries);
3595.         if (is_vampshifter(mon) && !validvamp(mon, &mndx, monclass))
3596.             mndx = pickvampshape(mon); /* don't resort to arbitrary */
3597.     }
3598. 
3599.     /* if no form was specified above, pick one at random now */
3600.     if (mndx == NON_PM) {
3601.         tryct = 50;
3602.         do {
3603.             mndx = rn1(SPECIAL_PM - LOW_PM, LOW_PM);
3604.         } while (--tryct > 0 && !validspecmon(mon, mndx)
3605.                  /* try harder to select uppercase monster on rogue level */
3606.                  && (tryct > 40 && Is_rogue_level(&u.uz)
3607.                      && !isupper((uchar) mons[mndx].mlet)));
3608.     }
3609.     return mndx;
3610. }
3611. 
3612. /* this used to be inline within newcham() but monpolycontrol needs it too */
3613. STATIC_OVL struct permonst *
3614. accept_newcham_form(mon, mndx)
3615. struct monst *mon;
3616. int mndx;
3617. {
3618.     struct permonst *mdat;
3619. 
3620.     if (mndx == NON_PM)
3621.         return 0;
3622.     mdat = &mons[mndx];
3623.     if ((mvitals[mndx].mvflags & G_GENOD) != 0)
3624.         return 0;
3625.     if (is_placeholder(mdat))
3626.         return 0;
3627.     /* select_newcham_form() might deliberately pick a player
3628.        character type (random selection never does) which
3629.        polyok() rejects, so we need a special case here */
3630.     if (is_mplayer(mdat))
3631.         return mdat;
3632.     /* shapeshifters are rejected by polyok() but allow a shapeshifter
3633.        to take on its 'natural' form */
3634.     if (is_shapeshifter(mdat)
3635.         && mon->cham >= LOW_PM && mdat == &mons[mon->cham])
3636.         return mdat;
3637.     /* polyok() rules out M2_PNAME, M2_WERE, and all humans except Kops */
3638.     return polyok(mdat) ? mdat : 0;
3639. }
3640. 
3641. void
3642. mgender_from_permonst(mtmp, mdat)
3643. struct monst *mtmp;
3644. struct permonst *mdat;
3645. {
3646.     if (is_male(mdat)) {
3647.         if (mtmp->female)
3648.             mtmp->female = FALSE;
3649.     } else if (is_female(mdat)) {
3650.         if (!mtmp->female)
3651.             mtmp->female = TRUE;
3652.     } else if (!is_neuter(mdat)) {
3653.         if (!rn2(10))
3654.             mtmp->female = !mtmp->female;
3655.     }
3656. }
3657. 
3658. /* make a chameleon take on another shape, or a polymorph target
3659.    (possibly self-inflicted) become a different monster;
3660.    returns 1 if it actually changes form */
3661. int
3662. newcham(mtmp, mdat, polyspot, msg)
3663. struct monst *mtmp;
3664. struct permonst *mdat;
3665. boolean polyspot; /* change is the result of wand or spell of polymorph */
3666. boolean msg;      /* "The oldmon turns into a newmon!" */
3667. {
3668.     int hpn, hpd;
3669.     int mndx, tryct;
3670.     struct permonst *olddata = mtmp->data;
3671.     char *p, oldname[BUFSZ], l_oldname[BUFSZ], newname[BUFSZ];
3672. 
3673.     /* Riders are immune to polymorph and green slime
3674.        (but apparent Rider might actually be a doppelganger) */
3675.     if (mtmp->cham == NON_PM) { /* not a shapechanger */
3676.         if (is_rider(olddata))
3677.             return 0;
3678.         /* make Nazgul and erinyes immune too, to reduce chance of
3679.            anomalous extinction feedback during final disclsoure */
3680.         if (mbirth_limit(monsndx(olddata)) < MAXMONNO)
3681.             return 0;
3682.         /* cancelled shapechangers become uncancelled prior
3683.            to being given a new shape */
3684.         if (mtmp->mcan && !Protection_from_shape_changers) {
3685.             mtmp->cham = pm_to_cham(monsndx(mtmp->data));
3686.             if (mtmp->cham != NON_PM)
3687.                 mtmp->mcan = 0;
3688.         }
3689.     }
3690. 
3691.     if (msg) {
3692.         /* like Monnam() but never mention saddle */
3693.         Strcpy(oldname, x_monnam(mtmp, ARTICLE_THE, (char *) 0,
3694.                                  SUPPRESS_SADDLE, FALSE));
3695.         oldname[0] = highc(oldname[0]);
3696.     }
3697.     /* we need this one whether msg is true or not */
3698.     Strcpy(l_oldname, x_monnam(mtmp, ARTICLE_THE, (char *) 0,
3699.                                has_mname(mtmp) ? SUPPRESS_SADDLE : 0, FALSE));
3700. 
3701.     /* mdat = 0 -> caller wants a random monster shape */
3702.     if (mdat == 0) {
3703.         /* select_newcham_form() loops when resorting to random but
3704.            it doesn't always pick that so we still retry here too */
3705.         tryct = 20;
3706.         do {
3707.             mndx = select_newcham_form(mtmp);
3708.             mdat = accept_newcham_form(mtmp, mndx);
3709.             /* for the first several tries we require upper-case on
3710.                the rogue level (after that, we take whatever we get) */
3711.             if (tryct > 15 && Is_rogue_level(&u.uz)
3712.                 && mdat && !isupper((uchar) mdat->mlet))
3713.                 mdat = 0;
3714.             if (mdat)
3715.                 break;
3716.         } while (--tryct > 0);
3717.         if (!tryct)
3718.             return 0;
3719.     } else if (mvitals[monsndx(mdat)].mvflags & G_GENOD)
3720.         return 0; /* passed in mdat is genocided */
3721. 
3722.     if (mdat == olddata)
3723.         return 0; /* still the same monster */
3724. 
3725.     mgender_from_permonst(mtmp, mdat);
3726.     /* Endgame mplayers start out as "Foo the Bar", but some of the
3727.      * titles are inappropriate when polymorphed, particularly into
3728.      * the opposite sex.  Player characters don't use ranks when
3729.      * polymorphed, so dropping rank for mplayers seems reasonable.
3730.      */
3731.     if (In_endgame(&u.uz) && is_mplayer(olddata)
3732.         && has_mname(mtmp) && (p = strstr(MNAME(mtmp), " the ")) != 0)
3733.         *p = '\0';
3734. 
3735.     if (mtmp->wormno) { /* throw tail away */
3736.         wormgone(mtmp);
3737.         place_monster(mtmp, mtmp->mx, mtmp->my);
3738.     }
3739.     if (M_AP_TYPE(mtmp) && mdat->mlet != S_MIMIC)
3740.         seemimic(mtmp); /* revert to normal monster */
3741. 
3742.     /* (this code used to try to adjust the monster's health based on
3743.        a normal one of its type but there are too many special cases
3744.        which need to handled in order to do that correctly, so just
3745.        give the new form the same proportion of HP as its old one had) */
3746.     hpn = mtmp->mhp;
3747.     hpd = mtmp->mhpmax;
3748.     /* set level and hit points */
3749.     newmonhp(mtmp, monsndx(mdat));
3750.     /* new hp: same fraction of max as before */
3751. #ifndef LINT
3752.     mtmp->mhp = (int) (((long) hpn * (long) mtmp->mhp) / (long) hpd);
3753. #endif
3754.     /* sanity check (potential overflow) */
3755.     if (mtmp->mhp < 0 || mtmp->mhp > mtmp->mhpmax)
3756.         mtmp->mhp = mtmp->mhpmax;
3757.     /* unlikely but not impossible; a 1HD creature with 1HP that changes
3758.        into a 0HD creature will require this statement */
3759.     if (!mtmp->mhp)
3760.         mtmp->mhp = 1;
3761. 
3762.     /* take on the new form... */
3763.     set_mon_data(mtmp, mdat);
3764. 
3765.     if (mtmp->mleashed && !leashable(mtmp))
3766.         m_unleash(mtmp, TRUE);
3767. 
3768.     if (emits_light(olddata) != emits_light(mtmp->data)) {
3769.         /* used to give light, now doesn't, or vice versa,
3770.            or light's range has changed */
3771.         if (emits_light(olddata))
3772.             del_light_source(LS_MONSTER, monst_to_any(mtmp));
3773.         if (emits_light(mtmp->data))
3774.             new_light_source(mtmp->mx, mtmp->my, emits_light(mtmp->data),
3775.                              LS_MONSTER, monst_to_any(mtmp));
3776.     }
3777.     if (!mtmp->perminvis || pm_invisible(olddata))
3778.         mtmp->perminvis = pm_invisible(mdat);
3779.     mtmp->minvis = mtmp->invis_blkd ? 0 : mtmp->perminvis;
3780.     if (mtmp->mundetected)
3781.         (void) hideunder(mtmp);
3782.     if (u.ustuck == mtmp) {
3783.         if (u.uswallow) {
3784.             if (!attacktype(mdat, AT_ENGL)) {
3785.                 /* Does mdat care? */
3786.                 if (!noncorporeal(mdat) && !amorphous(mdat)
3787.                     && !is_whirly(mdat) && (mdat != &mons[PM_YELLOW_LIGHT])) {
3788.                     char msgtrail[BUFSZ];
3789. 
3790.                     if (is_vampshifter(mtmp)) {
3791.                         Sprintf(msgtrail, " which was a shapeshifted %s",
3792.                                 noname_monnam(mtmp, ARTICLE_NONE));
3793.                     } else if (is_animal(mdat)) {
3794.                         Strcpy(msgtrail, "'s stomach");
3795.                     } else {
3796.                         msgtrail[0] = '\0';
3797.                     }
3798. 
3799.                     /* Do this even if msg is FALSE */
3800.                     You("%s %s%s!",
3801.                         (amorphous(olddata) || is_whirly(olddata))
3802.                             ? "emerge from" : "break out of",
3803.                         l_oldname, msgtrail);
3804.                     msg = FALSE; /* message has been given */
3805.                     mtmp->mhp = 1; /* almost dead */
3806.                 }
3807.                 expels(mtmp, olddata, FALSE);
3808.             } else {
3809.                 /* update swallow glyphs for new monster */
3810.                 swallowed(0);
3811.             }
3812.         } else if (!sticks(mdat) && !sticks(youmonst.data))
3813.             unstuck(mtmp);
3814.     }
3815. 
3816. #ifndef DCC30_BUG
3817.     if (mdat == &mons[PM_LONG_WORM] && (mtmp->wormno = get_wormno()) != 0) {
3818. #else
3819.     /* DICE 3.0 doesn't like assigning and comparing mtmp->wormno in the
3820.      * same expression.
3821.      */
3822.     if (mdat == &mons[PM_LONG_WORM]
3823.         && (mtmp->wormno = get_wormno(), mtmp->wormno != 0)) {
3824. #endif
3825.         /* we can now create worms with tails - 11/91 */
3826.         initworm(mtmp, rn2(5));
3827.         place_worm_tail_randomly(mtmp, mtmp->mx, mtmp->my);
3828.     }
3829. 
3830.     newsym(mtmp->mx, mtmp->my);
3831. 
3832.     if (msg) {
3833.         Strcpy(newname, noname_monnam(mtmp, ARTICLE_A));
3834.         /* oldname was capitalized above; newname will be lower case */
3835.         if (!strcmpi(newname, "it")) { /* can't see or sense it now */
3836.             if (!!strcmpi(oldname, "it")) /* could see or sense it before */
3837.                 pline("%s disappears!", oldname);
3838.             (void) usmellmon(mdat);
3839.         } else { /* can see or sense it now */
3840.             if (!strcmpi(oldname, "it")) /* couldn't see or sense it before */
3841.                 pline("%s appears!", upstart(newname));
3842.             else
3843.                 pline("%s turns into %s!", oldname, newname);
3844.         }
3845.     }
3846. 
3847.     /* when polymorph trap/wand/potion produces a vampire, turn in into
3848.        a full-fledged vampshifter unless shape-changing is blocked */
3849.     if (mtmp->cham == NON_PM && mdat->mlet == S_VAMPIRE
3850.         && !Protection_from_shape_changers)
3851.         mtmp->cham = pm_to_cham(monsndx(mdat));
3852. 
3853.     possibly_unwield(mtmp, polyspot); /* might lose use of weapon */
3854.     mon_break_armor(mtmp, polyspot);
3855.     if (!(mtmp->misc_worn_check & W_ARMG))
3856.         mselftouch(mtmp, "No longer petrify-resistant, ",
3857.                    !context.mon_moving);
3858.     m_dowear(mtmp, FALSE);
3859. 
3860.     /* This ought to re-test can_carry() on each item in the inventory
3861.      * rather than just checking ex-giants & boulders, but that'd be
3862.      * pretty expensive to perform.  If implemented, then perhaps
3863.      * minvent should be sorted in order to drop heaviest items first.
3864.      */
3865.     /* former giants can't continue carrying boulders */
3866.     if (mtmp->minvent && !throws_rocks(mdat)) {
3867.         register struct obj *otmp, *otmp2;
3868. 
3869.         for (otmp = mtmp->minvent; otmp; otmp = otmp2) {
3870.             otmp2 = otmp->nobj;
3871.             if (otmp->otyp == BOULDER) {
3872.                 /* this keeps otmp from being polymorphed in the
3873.                    same zap that the monster that held it is polymorphed */
3874.                 if (polyspot)
3875.                     bypass_obj(otmp);
3876.                 obj_extract_self(otmp);
3877.                 /* probably ought to give some "drop" message here */
3878.                 if (flooreffects(otmp, mtmp->mx, mtmp->my, ""))
3879.                     continue;
3880.                 place_object(otmp, mtmp->mx, mtmp->my);
3881.             }
3882.         }
3883.     }
3884. 
3885.     return 1;
3886. }
3887. 
3888. /* sometimes an egg will be special */
3889. #define BREEDER_EGG (!rn2(77))
3890. 
3891. /*
3892.  * Determine if the given monster number can be hatched from an egg.
3893.  * Return the monster number to use as the egg's corpsenm.  Return
3894.  * NON_PM if the given monster can't be hatched.
3895.  */
3896. int
3897. can_be_hatched(mnum)
3898. int mnum;
3899. {
3900.     /* ranger quest nemesis has the oviparous bit set, making it
3901.        be possible to wish for eggs of that unique monster; turn
3902.        such into ordinary eggs rather than forbidding them outright */
3903.     if (mnum == PM_SCORPIUS)
3904.         mnum = PM_SCORPION;
3905. 
3906.     mnum = little_to_big(mnum);
3907.     /*
3908.      * Queen bees lay killer bee eggs (usually), but killer bees don't
3909.      * grow into queen bees.  Ditto for [winged-]gargoyles.
3910.      */
3911.     if (mnum == PM_KILLER_BEE || mnum == PM_GARGOYLE
3912.         || (lays_eggs(&mons[mnum])
3913.             && (BREEDER_EGG
3914.                 || (mnum != PM_QUEEN_BEE && mnum != PM_WINGED_GARGOYLE))))
3915.         return mnum;
3916.     return NON_PM;
3917. }
3918. 
3919. /* type of egg laid by #sit; usually matches parent */
3920. int
3921. egg_type_from_parent(mnum, force_ordinary)
3922. int mnum; /* parent monster; caller must handle lays_eggs() check */
3923. boolean force_ordinary;
3924. {
3925.     if (force_ordinary || !BREEDER_EGG) {
3926.         if (mnum == PM_QUEEN_BEE)
3927.             mnum = PM_KILLER_BEE;
3928.         else if (mnum == PM_WINGED_GARGOYLE)
3929.             mnum = PM_GARGOYLE;
3930.     }
3931.     return mnum;
3932. }
3933. 
3934. /* decide whether an egg of the indicated monster type is viable;
3935.    also used to determine whether an egg or tin can be created... */
3936. boolean
3937. dead_species(m_idx, egg)
3938. int m_idx;
3939. boolean egg;
3940. {
3941.     int alt_idx;
3942. 
3943.     /* generic eggs are unhatchable and have corpsenm of NON_PM */
3944.     if (m_idx < LOW_PM)
3945.         return TRUE;
3946.     /*
3947.      * For monsters with both baby and adult forms, genociding either
3948.      * form kills all eggs of that monster.  Monsters with more than
3949.      * two forms (small->large->giant mimics) are more or less ignored;
3950.      * fortunately, none of them have eggs.  Species extinction due to
3951.      * overpopulation does not kill eggs.
3952.      */
3953.     alt_idx = egg ? big_to_little(m_idx) : m_idx;
3954.     return (boolean) ((mvitals[m_idx].mvflags & G_GENOD) != 0
3955.                       || (mvitals[alt_idx].mvflags & G_GENOD) != 0);
3956. }
3957. 
3958. /* kill off any eggs of genocided monsters */
3959. STATIC_OVL void
3960. kill_eggs(obj_list)
3961. struct obj *obj_list;
3962. {
3963.     struct obj *otmp;
3964. 
3965.     for (otmp = obj_list; otmp; otmp = otmp->nobj)
3966.         if (otmp->otyp == EGG) {
3967.             if (dead_species(otmp->corpsenm, TRUE)) {
3968.                 /*
3969.                  * It seems we could also just catch this when
3970.                  * it attempted to hatch, so we wouldn't have to
3971.                  * search all of the objlists.. or stop all
3972.                  * hatch timers based on a corpsenm.
3973.                  */
3974.                 kill_egg(otmp);
3975.             }
3976. #if 0 /* not used */
3977.         } else if (otmp->otyp == TIN) {
3978.             if (dead_species(otmp->corpsenm, FALSE))
3979.                 otmp->corpsenm = NON_PM; /* empty tin */
3980.         } else if (otmp->otyp == CORPSE) {
3981.             if (dead_species(otmp->corpsenm, FALSE))
3982.                 ; /* not yet implemented... */
3983. #endif
3984.         } else if (Has_contents(otmp)) {
3985.             kill_eggs(otmp->cobj);
3986.         }
3987. }
3988. 
3989. /* kill all members of genocided species */
3990. void
3991. kill_genocided_monsters()
3992. {
3993.     struct monst *mtmp, *mtmp2;
3994.     boolean kill_cham;
3995.     int mndx;
3996. 
3997.     /*
3998.      * Called during genocide, and again upon level change.  The latter
3999.      * catches up with any migrating monsters as they finally arrive at
4000.      * their intended destinations, so possessions get deposited there.
4001.      *
4002.      * Chameleon handling:
4003.      *  1) if chameleons have been genocided, destroy them
4004.      *     regardless of current form;
4005.      *  2) otherwise, force every chameleon which is imitating
4006.      *     any genocided species to take on a new form.
4007.      */
4008.     for (mtmp = fmon; mtmp; mtmp = mtmp2) {
4009.         mtmp2 = mtmp->nmon;
4010.         if (DEADMONSTER(mtmp))
4011.             continue;
4012.         mndx = monsndx(mtmp->data);
4013.         kill_cham = (mtmp->cham >= LOW_PM
4014.                      && (mvitals[mtmp->cham].mvflags & G_GENOD));
4015.         if ((mvitals[mndx].mvflags & G_GENOD) || kill_cham) {
4016.             if (mtmp->cham >= LOW_PM && !kill_cham)
4017.                 (void) newcham(mtmp, (struct permonst *) 0, FALSE, FALSE);
4018.             else
4019.                 mondead(mtmp);
4020.         }
4021.         if (mtmp->minvent)
4022.             kill_eggs(mtmp->minvent);
4023.     }
4024. 
4025.     kill_eggs(invent);
4026.     kill_eggs(fobj);
4027.     kill_eggs(migrating_objs);
4028.     kill_eggs(level.buriedobjlist);
4029. }
4030. 
4031. void
4032. golemeffects(mon, damtype, dam)
4033. register struct monst *mon;
4034. int damtype, dam;
4035. {
4036.     int heal = 0, slow = 0;
4037. 
4038.     if (mon->data == &mons[PM_FLESH_GOLEM]) {
4039.         if (damtype == AD_ELEC)
4040.             heal = (dam + 5) / 6;
4041.         else if (damtype == AD_FIRE || damtype == AD_COLD)
4042.             slow = 1;
4043.     } else if (mon->data == &mons[PM_IRON_GOLEM]) {
4044.         if (damtype == AD_ELEC)
4045.             slow = 1;
4046.         else if (damtype == AD_FIRE)
4047.             heal = dam;
4048.     } else {
4049.         return;
4050.     }
4051.     if (slow) {
4052.         if (mon->mspeed != MSLOW)
4053.             mon_adjust_speed(mon, -1, (struct obj *) 0);
4054.     }
4055.     if (heal) {
4056.         if (mon->mhp < mon->mhpmax) {
4057.             mon->mhp += heal;
4058.             if (mon->mhp > mon->mhpmax)
4059.                 mon->mhp = mon->mhpmax;
4060.             if (cansee(mon->mx, mon->my))
4061.                 pline("%s seems healthier.", Monnam(mon));
4062.         }
4063.     }
4064. }
4065. 
4066. boolean
4067. angry_guards(silent)
4068. boolean silent;
4069. {
4070.     struct monst *mtmp;
4071.     int ct = 0, nct = 0, sct = 0, slct = 0;
4072. 
4073.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
4074.         if (DEADMONSTER(mtmp))
4075.             continue;
4076.         if (is_watch(mtmp->data) && mtmp->mpeaceful) {
4077.             ct++;
4078.             if (cansee(mtmp->mx, mtmp->my) && mtmp->mcanmove) {
4079.                 if (distu(mtmp->mx, mtmp->my) == 2)
4080.                     nct++;
4081.                 else
4082.                     sct++;
4083.             }
4084.             if (mtmp->msleeping || mtmp->mfrozen) {
4085.                 slct++;
4086.                 mtmp->msleeping = mtmp->mfrozen = 0;
4087.             }
4088.             mtmp->mpeaceful = 0;
4089.         }
4090.     }
4091.     if (ct) {
4092.         if (!silent) { /* do we want pline msgs? */
4093.             if (slct)
4094.                 pline_The("guard%s wake%s up!", slct > 1 ? "s" : "",
4095.                           slct == 1 ? "s" : "");
4096.             if (nct || sct) {
4097.                 if (nct)
4098.                     pline_The("guard%s get%s angry!", nct == 1 ? "" : "s",
4099.                               nct == 1 ? "s" : "");
4100.                 else if (!Blind)
4101.                     You_see("%sangry guard%s approaching!",
4102.                             sct == 1 ? "an " : "", sct > 1 ? "s" : "");
4103.             } else
4104.                 You_hear("the shrill sound of a guard's whistle.");
4105.         }
4106.         return TRUE;
4107.     }
4108.     return FALSE;
4109. }
4110. 
4111. void
4112. pacify_guards()
4113. {
4114.     struct monst *mtmp;
4115. 
4116.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
4117.         if (DEADMONSTER(mtmp))
4118.             continue;
4119.         if (is_watch(mtmp->data))
4120.             mtmp->mpeaceful = 1;
4121.     }
4122. }
4123. 
4124. void
4125. mimic_hit_msg(mtmp, otyp)
4126. struct monst *mtmp;
4127. short otyp;
4128. {
4129.     short ap = mtmp->mappearance;
4130. 
4131.     switch (M_AP_TYPE(mtmp)) {
4132.     case M_AP_NOTHING:
4133.     case M_AP_FURNITURE:
4134.     case M_AP_MONSTER:
4135.         break;
4136.     case M_AP_OBJECT:
4137.         if (otyp == SPE_HEALING || otyp == SPE_EXTRA_HEALING) {
4138.             pline("%s seems a more vivid %s than before.",
4139.                   The(simple_typename(ap)),
4140.                   c_obj_colors[objects[ap].oc_color]);
4141.         }
4142.         break;
4143.     }
4144. }
4145. 
4146. boolean
4147. usmellmon(mdat)
4148. struct permonst *mdat;
4149. {
4150.     int mndx;
4151.     boolean nonspecific = FALSE;
4152.     boolean msg_given = FALSE;
4153. 
4154.     if (mdat) {
4155.         if (!olfaction(youmonst.data))
4156.             return FALSE;
4157.         mndx = monsndx(mdat);
4158.         switch (mndx) {
4159.         case PM_ROTHE:
4160.         case PM_MINOTAUR:
4161.             You("notice a bovine smell.");
4162.             msg_given = TRUE;
4163.             break;
4164.         case PM_CAVEMAN:
4165.         case PM_CAVEWOMAN:
4166.         case PM_BARBARIAN:
4167.         case PM_NEANDERTHAL:
4168.             You("smell body odor.");
4169.             msg_given = TRUE;
4170.             break;
4171.         /*
4172.         case PM_PESTILENCE:
4173.         case PM_FAMINE:
4174.         case PM_DEATH:
4175.             break;
4176.         */
4177.         case PM_HORNED_DEVIL:
4178.         case PM_BALROG:
4179.         case PM_ASMODEUS:
4180.         case PM_DISPATER:
4181.         case PM_YEENOGHU:
4182.         case PM_ORCUS:
4183.             break;
4184.         case PM_HUMAN_WEREJACKAL:
4185.         case PM_HUMAN_WERERAT:
4186.         case PM_HUMAN_WEREWOLF:
4187.         case PM_WEREJACKAL:
4188.         case PM_WERERAT:
4189.         case PM_WEREWOLF:
4190.         case PM_OWLBEAR:
4191.             You("detect an odor reminiscent of an animal's den.");
4192.             msg_given = TRUE;
4193.             break;
4194.         /*
4195.         case PM_PURPLE_WORM:
4196.             break;
4197.         */
4198.         case PM_STEAM_VORTEX:
4199.             You("smell steam.");
4200.             msg_given = TRUE;
4201.             break;
4202.         case PM_GREEN_SLIME:
4203.             pline("%s stinks.", Something);
4204.             msg_given = TRUE;
4205.             break;
4206.         case PM_VIOLET_FUNGUS:
4207.         case PM_SHRIEKER:
4208.             You("smell mushrooms.");
4209.             msg_given = TRUE;
4210.             break;
4211.         /* These are here to avoid triggering the
4212.            nonspecific treatment through the default case below*/
4213.         case PM_WHITE_UNICORN:
4214.         case PM_GRAY_UNICORN:
4215.         case PM_BLACK_UNICORN:
4216.         case PM_JELLYFISH:
4217.             break;
4218.         default:
4219.             nonspecific = TRUE;
4220.             break;
4221.         }
4222. 
4223.         if (nonspecific)
4224.             switch (mdat->mlet) {
4225.             case S_DOG:
4226.                 You("notice a dog smell.");
4227.                 msg_given = TRUE;
4228.                 break;
4229.             case S_DRAGON:
4230.                 You("smell a dragon!");
4231.                 msg_given = TRUE;
4232.                 break;
4233.             case S_FUNGUS:
4234.                 pline("%s smells moldy.", Something);
4235.                 msg_given = TRUE;
4236.                 break;
4237.             case S_UNICORN:
4238.                 You("detect a%s odor reminiscent of a stable.",
4239.                     (mndx == PM_PONY) ? "n" : " strong");
4240.                 msg_given = TRUE;
4241.                 break;
4242.             case S_ZOMBIE:
4243.                 You("smell rotting flesh.");
4244.                 msg_given = TRUE;
4245.                 break;
4246.             case S_EEL:
4247.                 You("smell fish.");
4248.                 msg_given = TRUE;
4249.                 break;
4250.             case S_ORC:
4251.                 if (maybe_polyd(is_orc(youmonst.data), Race_if(PM_ORC)))
4252.                     You("notice an attractive smell.");
4253.                 else
4254.                     pline("A foul stench makes you feel a little nauseated.");
4255.                 msg_given = TRUE;
4256.                 break;
4257.             default:
4258.                 break;
4259.             }
4260.     }
4261.     return msg_given ? TRUE : FALSE;
4262. }
4263. 
4264. /*mon.c*/