Source:NetHack 5.0.0/src/makemon.c

From NetHackWiki
Jump to navigation Jump to search

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

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

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

1. /* NetHack 5.0	makemon.c	$NHDT-Date: 1770949988 2026/02/12 18:33:08 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.271 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Robert Patrick Rankin, 2012. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. 
8. /* this assumes that a human quest leader or nemesis is an archetype
9.    of the corresponding role; that isn't so for some roles (tourist
10.    for instance) but is for the priests and monks we use it for... */
11. #define quest_mon_represents_role(mptr, role_pm) \
12.     (mptr->mlet == S_HUMAN && Role_if(role_pm)   \
13.      && (mptr->msound == MS_LEADER || mptr->msound == MS_NEMESIS))
14. 
15. staticfn boolean uncommon(int);
16. staticfn int align_shift(struct permonst *);
17. staticfn int temperature_shift(struct permonst *);
18. staticfn boolean mk_gen_ok(int, unsigned, unsigned);
19. staticfn int QSORTCALLBACK cmp_init_mongen_order(const void *, const void *);
20. staticfn void init_mongen_order(void);
21. staticfn boolean wrong_elem_type(struct permonst *);
22. staticfn void m_initgrp(struct monst *, coordxy, coordxy, int, mmflags_nht);
23. staticfn void m_initthrow(struct monst *, int, int);
24. staticfn void m_initweap(struct monst *);
25. staticfn void m_initinv(struct monst *);
26. staticfn boolean makemon_rnd_goodpos(struct monst *, mmflags_nht, coord *);
27. staticfn void init_mextra(struct mextra *);
28. 
29. #define m_initsgrp(mtmp, x, y, mmf) m_initgrp(mtmp, x, y, 3, mmf)
30. #define m_initlgrp(mtmp, x, y, mmf) m_initgrp(mtmp, x, y, 10, mmf)
31. 
32. boolean
33. is_home_elemental(struct permonst *ptr)
34. {
35.     if (ptr->mlet == S_ELEMENTAL) {
36.         switch (monsndx(ptr)) {
37.         case PM_AIR_ELEMENTAL:
38.             return Is_airlevel(&u.uz);
39.         case PM_FIRE_ELEMENTAL:
40.             return Is_firelevel(&u.uz);
41.         case PM_EARTH_ELEMENTAL:
42.             return Is_earthlevel(&u.uz);
43.         case PM_WATER_ELEMENTAL:
44.             return Is_waterlevel(&u.uz);
45.         default:
46.             break;
47.         }
48.     }
49.     return FALSE;
50. }
51. 
52. /*
53.  * Return true if the given monster cannot exist on this elemental level.
54.  */
55. staticfn boolean
56. wrong_elem_type(struct permonst *ptr)
57. {
58.     if (ptr->mlet == S_ELEMENTAL) {
59.         return (boolean) !is_home_elemental(ptr);
60.     } else if (Is_earthlevel(&u.uz)) {
61.         /* no restrictions? */
62.     } else if (Is_waterlevel(&u.uz)) {
63.         /* just monsters that can swim */
64.         if (!is_swimmer(ptr))
65.             return TRUE;
66.     } else if (Is_firelevel(&u.uz)) {
67.         if (!pm_resistance(ptr, MR_FIRE))
68.             return TRUE;
69.     } else if (Is_airlevel(&u.uz)) {
70.         if (!(is_flyer(ptr) && ptr->mlet != S_TRAPPER) && !is_floater(ptr)
71.             && !amorphous(ptr) && !noncorporeal(ptr) && !is_whirly(ptr))
72.             return TRUE;
73.     }
74.     return FALSE;
75. }
76. 
77. /* make a group just like mtmp */
78. staticfn void
79. m_initgrp(
80.     struct monst *mtmp,
81.     coordxy x, coordxy y, int n,
82.     mmflags_nht mmflags)
83. {
84.     coord mm;
85.     int cnt = rnd(n);
86.     struct monst *mon;
87. #if defined(__GNUC__) && (defined(HPUX) || defined(DGUX))
88.     /* There is an unresolved problem with several people finding that
89.      * the game hangs eating CPU; if interrupted and restored, the level
90.      * will be filled with monsters.  Of those reports giving system type,
91.      * there were two DG/UX and two HP-UX, all using gcc as the compiler.
92.      * hcroft@hpopb1.cern.ch, using gcc 2.6.3 on HP-UX, says that the
93.      * problem went away for him and another reporter-to-newsgroup
94.      * after adding this debugging code.  This has almost got to be a
95.      * compiler bug, but until somebody tracks it down and gets it fixed,
96.      * might as well go with the "but it went away when I tried to find
97.      * it" code.
98.      */
99.     int cnttmp, cntdiv;
100. 
101.     cnttmp = cnt;
102.     debugpline4("init group call <%d,%d>, n=%d, cnt=%d.", x, y, n, cnt);
103.     cntdiv = ((u.ulevel < 3) ? 4 : (u.ulevel < 5) ? 2 : 1);
104. #endif
105.     /* Tuning: cut down on swarming at low character levels [mrs] */
106.     cnt /= (u.ulevel < 3) ? 4 : (u.ulevel < 5) ? 2 : 1;
107. #if defined(__GNUC__) && (defined(HPUX) || defined(DGUX))
108.     if (cnt != (cnttmp / cntdiv)) {
109.         pline("cnt=%d using %d, cnttmp=%d, cntdiv=%d", cnt,
110.               (u.ulevel < 3) ? 4 : (u.ulevel < 5) ? 2 : 1, cnttmp, cntdiv);
111.     }
112. #endif
113.     if (!cnt)
114.         cnt++;
115. #if defined(__GNUC__) && (defined(HPUX) || defined(DGUX))
116.     if (cnt < 0)
117.         cnt = 1;
118.     if (cnt > 10)
119.         cnt = 10;
120. #endif
121. 
122.     mm.x = x;
123.     mm.y = y;
124.     while (cnt--) {
125.         if (peace_minded(mtmp->data))
126.             continue;
127.         /* Don't create groups of peaceful monsters since they'll get
128.          * in our way.  If the monster has a percentage chance so some
129.          * are peaceful and some are not, the result will just be a
130.          * smaller group.
131.          */
132.         if (enexto_gpflags(&mm, mm.x, mm.y, mtmp->data, mmflags)) {
133.             mon = makemon(mtmp->data, mm.x, mm.y, (mmflags | MM_NOGRP));
134.             if (mon) {
135.                 mon->mpeaceful = FALSE;
136.                 mon->mavenge = 0;
137.                 set_malign(mon);
138.                 /* Undo the second peace_minded() check in makemon(); if the
139.                  * monster turned out to be peaceful the first time we
140.                  * didn't create it at all; we don't want a second check.
141.                  */
142.             }
143.         }
144.     }
145. }
146. 
147. staticfn void
148. m_initthrow(struct monst *mtmp, int otyp, int oquan)
149. {
150.     struct obj *otmp;
151. 
152.     otmp = mksobj(otyp, TRUE, FALSE);
153.     otmp->quan = (long) rn1(oquan, 3);
154.     otmp->owt = weight(otmp);
155.     if (otyp == ORCISH_ARROW)
156.         otmp->opoisoned = TRUE;
157.     (void) mpickobj(mtmp, otmp);
158. }
159. 
160. staticfn void
161. m_initweap(struct monst *mtmp)
162. {
163.     struct permonst *ptr = mtmp->data;
164.     int mm = monsndx(ptr);
165.     struct obj *otmp;
166.     int bias, w1, w2;
167. 
168.     if (Is_rogue_level(&u.uz))
169.         return;
170.     /*
171.      *  First a few special cases:
172.      *          giants get a boulder to throw sometimes
173.      *          ettins get clubs
174.      *          kobolds get darts to throw
175.      *          centaurs get some sort of bow & arrows or bolts
176.      *          soldiers get all sorts of things
177.      *          kops get clubs & cream pies.
178.      */
179.     switch (ptr->mlet) {
180.     case S_GIANT:
181.         if (rn2(2))
182.             (void) mongets(mtmp, (mm != PM_ETTIN) ? BOULDER : CLUB);
183.         if ((mm != PM_ETTIN) && !rn2(5))
184.             (void) mongets(mtmp, rn2(2) ? TWO_HANDED_SWORD : BATTLE_AXE);
185.         break;
186.     case S_HUMAN:
187.         if (is_mercenary(ptr)) {
188.             w1 = w2 = 0;
189.             switch (mm) {
190.             case PM_WATCHMAN:
191.             case PM_SOLDIER:
192.                 if (!rn2(3)) {
193.                     /* lance and dwarvish mattock used to be in midst of
194.                        the polearms but use different skills from polearms
195.                        and aren't appropriates choices for human soldiers */
196.                     do {
197.                         w1 = rn1(BEC_DE_CORBIN - PARTISAN + 1, PARTISAN);
198.                     } while (objects[w1].oc_skill != P_POLEARMS);
199.                     w2 = rn2(2) ? DAGGER : KNIFE;
200.                 } else
201.                     w1 = rn2(2) ? SPEAR : SHORT_SWORD;
202.                 break;
203.             case PM_SERGEANT:
204.                 w1 = rn2(2) ? FLAIL : MACE;
205.                 break;
206.             case PM_LIEUTENANT:
207.                 w1 = rn2(2) ? BROADSWORD : LONG_SWORD;
208.                 break;
209.             case PM_CAPTAIN:
210.             case PM_WATCH_CAPTAIN:
211.                 w1 = rn2(2) ? LONG_SWORD : SILVER_SABER;
212.                 break;
213.             default:
214.                 if (!rn2(4))
215.                     w1 = DAGGER;
216.                 if (!rn2(7))
217.                     w2 = SPEAR;
218.                 break;
219.             }
220.             if (w1)
221.                 (void) mongets(mtmp, w1);
222.             if (!w2 && w1 != DAGGER && !rn2(4))
223.                 w2 = KNIFE;
224.             if (w2)
225.                 (void) mongets(mtmp, w2);
226.         } else if (is_elf(ptr)) {
227.             if (rn2(2))
228.                 (void) mongets(mtmp,
229.                                rn2(2) ? ELVEN_MITHRIL_COAT : ELVEN_CLOAK);
230.             if (rn2(2))
231.                 (void) mongets(mtmp, ELVEN_LEATHER_HELM);
232.             else if (!rn2(4))
233.                 (void) mongets(mtmp, ELVEN_BOOTS);
234.             if (rn2(2))
235.                 (void) mongets(mtmp, ELVEN_DAGGER);
236.             switch (rn2(3)) {
237.             case 0:
238.                 if (!rn2(4))
239.                     (void) mongets(mtmp, ELVEN_SHIELD);
240.                 if (rn2(3))
241.                     (void) mongets(mtmp, ELVEN_SHORT_SWORD);
242.                 (void) mongets(mtmp, ELVEN_BOW);
243.                 m_initthrow(mtmp, ELVEN_ARROW, 12);
244.                 break;
245.             case 1:
246.                 (void) mongets(mtmp, ELVEN_BROADSWORD);
247.                 if (rn2(2))
248.                     (void) mongets(mtmp, ELVEN_SHIELD);
249.                 break;
250.             case 2:
251.                 if (rn2(2)) {
252.                     (void) mongets(mtmp, ELVEN_SPEAR);
253.                     (void) mongets(mtmp, ELVEN_SHIELD);
254.                 }
255.                 break;
256.             }
257.             if (mm == PM_ELVEN_MONARCH) {
258.                 if (rn2(3) || (gi.in_mklev && Is_earthlevel(&u.uz)))
259.                     (void) mongets(mtmp, PICK_AXE);
260.                 if (!rn2(50))
261.                     (void) mongets(mtmp, CRYSTAL_BALL);
262.             }
263.         } else if (ptr->msound == MS_PRIEST
264.                    || quest_mon_represents_role(ptr, PM_CLERIC)) {
265.             otmp = mksobj(MACE, FALSE, FALSE);
266.             otmp->spe = rnd(3);
267.             if (!rn2(2))
268.                 curse(otmp);
269.             (void) mpickobj(mtmp, otmp);
270.         } else if (mm == PM_NINJA) { /* extra quest villains */
271.             (void) mongets(mtmp, rn2(4) ? SHURIKEN : DART);
272.             (void) mongets(mtmp, rn2(4) ? SHORT_SWORD : AXE);
273.         } else if (ptr->msound == MS_GUARDIAN) {
274.             /* quest "guardians" */
275.             switch (mm) {
276.             case PM_STUDENT:
277.             case PM_ATTENDANT:
278.             case PM_ABBOT:
279.             case PM_ACOLYTE:
280.             case PM_GUIDE:
281.             case PM_APPRENTICE:
282.                 if (rn2(2))
283.                     (void) mongets(mtmp, rn2(3) ? DAGGER : KNIFE);
284.                 if (rn2(5))
285.                     (void) mongets(mtmp, rn2(3) ? LEATHER_JACKET
286.                                                 : LEATHER_CLOAK);
287.                 if (rn2(3))
288.                     (void) mongets(mtmp, rn2(3) ? LOW_BOOTS : HIGH_BOOTS);
289.                 if (rn2(3))
290.                     (void) mongets(mtmp, POT_HEALING);
291.                 break;
292.             case PM_CHIEFTAIN:
293.             case PM_PAGE:
294.             case PM_ROSHI:
295.             case PM_WARRIOR:
296.                 (void) mongets(mtmp, rn2(3) ? LONG_SWORD : SHORT_SWORD);
297.                 (void) mongets(mtmp, rn2(3) ? CHAIN_MAIL : LEATHER_ARMOR);
298.                 if (rn2(2))
299.                     (void) mongets(mtmp, rn2(2) ? LOW_BOOTS : HIGH_BOOTS);
300.                 if (!rn2(3))
301.                     (void) mongets(mtmp, LEATHER_CLOAK);
302.                 if (!rn2(3)) {
303.                     (void) mongets(mtmp, BOW);
304.                     m_initthrow(mtmp, ARROW, 12);
305.                 }
306.                 break;
307.             case PM_HUNTER:
308.                 (void) mongets(mtmp, rn2(3) ? SHORT_SWORD : DAGGER);
309.                 if (rn2(2))
310.                     (void) mongets(mtmp, rn2(2) ? LEATHER_JACKET
311.                                                 : LEATHER_ARMOR);
312.                 (void) mongets(mtmp, BOW);
313.                 m_initthrow(mtmp, ARROW, 12);
314.                 break;
315.             case PM_THUG:
316.                 (void) mongets(mtmp, CLUB);
317.                 (void) mongets(mtmp, rn2(3) ? DAGGER : KNIFE);
318.                 if (rn2(2))
319.                     (void) mongets(mtmp, LEATHER_GLOVES);
320.                 (void) mongets(mtmp, rn2(2) ? LEATHER_JACKET : LEATHER_ARMOR);
321.                 break;
322.             case PM_NEANDERTHAL:
323.                 (void) mongets(mtmp, CLUB);
324.                 (void) mongets(mtmp, LEATHER_ARMOR);
325.                 break;
326.             }
327.         }
328.         break;
329. 
330.     case S_ANGEL:
331.         if (humanoid(ptr)) {
332.             /* create minion stuff; bypass mongets */
333.             int typ = rn2(3) ? LONG_SWORD : SILVER_MACE;
334.             const char *nam = (typ == LONG_SWORD) ? "Sunsword" : "Demonbane";
335. 
336.             otmp = mksobj(typ, FALSE, FALSE);
337.             /* maybe promote weapon to an artifact */
338.             if ((!rn2(20) || is_lord(ptr))
339.                  && sgn(mtmp->isminion ? EMIN(mtmp)->min_align
340.                                        : ptr->maligntyp) == A_LAWFUL)
341.                 otmp = oname(otmp, nam, ONAME_RANDOM); /* randomly created */
342.             /* enhance the weapon */
343.             bless(otmp);
344.             otmp->oerodeproof = TRUE;
345.             /* make long sword be +0 to +3, mace be +3 to +6 to compensate
346.                for being significantly weaker against large opponents */
347.             otmp->spe = rn2(4);
348.             if (typ == SILVER_MACE)
349.                 otmp->spe += 3;
350.             (void) mpickobj(mtmp, otmp);
351. 
352.             otmp = mksobj(!rn2(4) || is_lord(ptr) ? SHIELD_OF_REFLECTION
353.                                                   : LARGE_SHIELD,
354.                           FALSE, FALSE);
355.             /* uncurse(otmp); -- mksobj(,FALSE,) item is always uncursed */
356.             otmp->oerodeproof = TRUE;
357.             otmp->spe = 0;
358.             (void) mpickobj(mtmp, otmp);
359.         }
360.         break;
361. 
362.     case S_HUMANOID:
363.         if (mm == PM_HOBBIT) {
364.             switch (rn2(3)) {
365.             case 0:
366.                 (void) mongets(mtmp, DAGGER);
367.                 break;
368.             case 1:
369.                 (void) mongets(mtmp, ELVEN_DAGGER);
370.                 break;
371.             case 2:
372.                 (void) mongets(mtmp, SLING);
373.                 m_initthrow(mtmp, !rn2(4) ? FLINT : ROCK, 6);
374.                 break;
375.             }
376.             if (!rn2(10))
377.                 (void) mongets(mtmp, ELVEN_MITHRIL_COAT);
378.             if (!rn2(10))
379.                 (void) mongets(mtmp, DWARVISH_CLOAK);
380.         } else if (is_dwarf(ptr)) {
381.             if (rn2(7))
382.                 (void) mongets(mtmp, DWARVISH_CLOAK);
383.             if (rn2(7))
384.                 (void) mongets(mtmp, IRON_SHOES);
385.             if (!rn2(4)) {
386.                 (void) mongets(mtmp, DWARVISH_SHORT_SWORD);
387.                 /* note: you can't use a mattock with a shield */
388.                 if (rn2(2))
389.                     (void) mongets(mtmp, DWARVISH_MATTOCK);
390.                 else {
391.                     (void) mongets(mtmp, rn2(2) ? AXE : DWARVISH_SPEAR);
392.                     (void) mongets(mtmp, DWARVISH_ROUNDSHIELD);
393.                 }
394.                 (void) mongets(mtmp, DWARVISH_IRON_HELM);
395.                 if (!rn2(3))
396.                     (void) mongets(mtmp, DWARVISH_MITHRIL_COAT);
397.             } else {
398.                 (void) mongets(mtmp, !rn2(3) ? PICK_AXE : DAGGER);
399.             }
400.         }
401.         break;
402.     case S_KOP:
403.         /* create Keystone Kops with cream pies to
404.            throw. As suggested by KAA.     [MRS] */
405.         if (!rn2(4))
406.             m_initthrow(mtmp, CREAM_PIE, 2);
407.         if (!rn2(3))
408.             (void) mongets(mtmp, (rn2(2)) ? CLUB : RUBBER_HOSE);
409.         break;
410.     case S_ORC:
411.         if (rn2(2))
412.             (void) mongets(mtmp, ORCISH_HELM);
413.         switch ((mm != PM_ORC_CAPTAIN) ? mm
414.                 : rn2(2) ? PM_MORDOR_ORC : PM_URUK_HAI) {
415.         case PM_MORDOR_ORC:
416.             if (!rn2(3))
417.                 (void) mongets(mtmp, SCIMITAR);
418.             if (!rn2(3))
419.                 (void) mongets(mtmp, ORCISH_SHIELD);
420.             if (!rn2(3))
421.                 (void) mongets(mtmp, KNIFE);
422.             if (!rn2(3))
423.                 (void) mongets(mtmp, ORCISH_CHAIN_MAIL);
424.             break;
425.         case PM_URUK_HAI:
426.             if (!rn2(3))
427.                 (void) mongets(mtmp, ORCISH_CLOAK);
428.             if (!rn2(3))
429.                 (void) mongets(mtmp, ORCISH_SHORT_SWORD);
430.             if (!rn2(3))
431.                 (void) mongets(mtmp, IRON_SHOES);
432.             if (!rn2(3)) {
433.                 (void) mongets(mtmp, ORCISH_BOW);
434.                 m_initthrow(mtmp, ORCISH_ARROW, 12);
435.             }
436.             if (!rn2(3))
437.                 (void) mongets(mtmp, URUK_HAI_SHIELD);
438.             break;
439.         default:
440.             if (mm != PM_ORC_SHAMAN && rn2(2))
441.                 (void) mongets(mtmp, (mm == PM_GOBLIN || rn2(2) == 0)
442.                                          ? ORCISH_DAGGER
443.                                          : SCIMITAR);
444.         }
445.         break;
446.     case S_OGRE:
447.         if (!rn2(mm == PM_OGRE_TYRANT ? 3 : mm == PM_OGRE_LEADER ? 6 : 12))
448.             (void) mongets(mtmp, BATTLE_AXE);
449.         else
450.             (void) mongets(mtmp, CLUB);
451.         break;
452.     case S_TROLL:
453.         if (!rn2(2))
454.             switch (rn2(4)) {
455.             case 0:
456.                 (void) mongets(mtmp, RANSEUR);
457.                 break;
458.             case 1:
459.                 (void) mongets(mtmp, PARTISAN);
460.                 break;
461.             case 2:
462.                 (void) mongets(mtmp, GLAIVE);
463.                 break;
464.             case 3:
465.                 (void) mongets(mtmp, SPETUM);
466.                 break;
467.             }
468.         break;
469.     case S_KOBOLD:
470.         if (!rn2(4))
471.             m_initthrow(mtmp, DART, 12);
472.         break;
473. 
474.     case S_CENTAUR:
475.         if (rn2(2)) {
476.             if (ptr == &mons[PM_FOREST_CENTAUR]) {
477.                 (void) mongets(mtmp, BOW);
478.                 m_initthrow(mtmp, ARROW, 12);
479.             } else {
480.                 (void) mongets(mtmp, CROSSBOW);
481.                 m_initthrow(mtmp, CROSSBOW_BOLT, 12);
482.             }
483.         }
484.         break;
485.     case S_WRAITH:
486.         (void) mongets(mtmp, KNIFE);
487.         (void) mongets(mtmp, LONG_SWORD);
488.         break;
489.     case S_ZOMBIE:
490.         if (!rn2(4))
491.             (void) mongets(mtmp, LEATHER_ARMOR);
492.         if (!rn2(4))
493.             (void) mongets(mtmp, (rn2(3) ? KNIFE : SHORT_SWORD));
494.         break;
495.     case S_LIZARD:
496.         if (mm == PM_SALAMANDER)
497.             (void) mongets(mtmp,
498.                            (rn2(7) ? SPEAR : rn2(3) ? TRIDENT : STILETTO));
499.         break;
500.     case S_DEMON:
501.         switch (mm) {
502.         case PM_BALROG:
503.             (void) mongets(mtmp, BULLWHIP);
504.             (void) mongets(mtmp, BROADSWORD);
505.             break;
506.         case PM_ORCUS:
507.             (void) mongets(mtmp, WAN_DEATH); /* the Wand of Orcus */
508.             break;
509.         case PM_HORNED_DEVIL:
510.             (void) mongets(mtmp, rn2(4) ? TRIDENT : BULLWHIP);
511.             break;
512.         case PM_DISPATER:
513.             (void) mongets(mtmp, WAN_STRIKING);
514.             break;
515.         case PM_YEENOGHU:
516.             (void) mongets(mtmp, FLAIL);
517.             break;
518.         }
519.         /* prevent djinn and mail daemons from leaving objects when
520.          * they vanish
521.          */
522.         if (!is_demon(ptr))
523.             break;
524.         FALLTHROUGH;
525.         /*FALLTHRU*/
526.     default:
527.         /*
528.          * Now the general case, some chance of getting some type
529.          * of weapon for "normal" monsters.  Certain special types
530.          * of monsters will get a bonus chance or different selections.
531.          */
532.         bias = is_lord(ptr) + is_prince(ptr) * 2 + extra_nasty(ptr);
533.         switch (rnd(14 - (2 * bias))) {
534.         case 1:
535.             if (strongmonst(ptr))
536.                 (void) mongets(mtmp, BATTLE_AXE);
537.             else
538.                 m_initthrow(mtmp, DART, 12);
539.             break;
540.         case 2:
541.             if (strongmonst(ptr))
542.                 (void) mongets(mtmp, TWO_HANDED_SWORD);
543.             else {
544.                 (void) mongets(mtmp, CROSSBOW);
545.                 m_initthrow(mtmp, CROSSBOW_BOLT, 12);
546.             }
547.             break;
548.         case 3:
549.             (void) mongets(mtmp, BOW);
550.             m_initthrow(mtmp, ARROW, 12);
551.             break;
552.         case 4:
553.             if (strongmonst(ptr))
554.                 (void) mongets(mtmp, LONG_SWORD);
555.             else
556.                 m_initthrow(mtmp, DAGGER, 3);
557.             break;
558.         case 5:
559.             if (strongmonst(ptr))
560.                 (void) mongets(mtmp, LUCERN_HAMMER);
561.             else
562.                 (void) mongets(mtmp, AKLYS);
563.             break;
564.         default:
565.             break;
566.         }
567.         break;
568.     }
569. 
570.     if ((int) mtmp->m_lev > rn2(75))
571.         (void) mongets(mtmp, rnd_offensive_item(mtmp));
572. }
573. 
574. /* create a new stack of gold in monster's inventory */
575. void
576. mkmonmoney(struct monst *mtmp, long amount)
577. {
578.     /* mk_mplayer() passes rn2(1000) so the amount might be 0 */
579.     if (amount > 0L) {
580.         struct obj *gold = mksobj(GOLD_PIECE, FALSE, FALSE);
581. 
582.         gold->quan = amount;
583.         gold->owt = weight(gold);
584.         add_to_minv(mtmp, gold);
585.     }
586. }
587. 
588. staticfn void
589. m_initinv(struct monst *mtmp)
590. {
591.     int cnt;
592.     struct obj *otmp;
593.     struct permonst *ptr = mtmp->data;
594. 
595.     if (Is_rogue_level(&u.uz))
596.         return;
597.     /*
598.      *  Soldiers get armour & rations - armour approximates their ac.
599.      *  Nymphs may get mirror or potion of object detection.
600.      */
601.     switch (ptr->mlet) {
602.     case S_HUMAN:
603.         if (is_mercenary(ptr)) {
604.             int mac;
605. 
606.             switch (monsndx(ptr)) {
607.             case PM_GUARD:
608.                 mac = -1;
609.                 break;
610.             case PM_SOLDIER:
611.                 mac = 3;
612.                 break;
613.             case PM_SERGEANT:
614.                 mac = 0;
615.                 break;
616.             case PM_LIEUTENANT:
617.                 mac = -2;
618.                 break;
619.             case PM_CAPTAIN:
620.                 mac = -3;
621.                 break;
622.             case PM_WATCHMAN:
623.                 mac = 3;
624.                 break;
625.             case PM_WATCH_CAPTAIN:
626.                 mac = -2;
627.                 break;
628.             default:
629.                 impossible("odd mercenary %d?", monsndx(ptr));
630.                 mac = 0;
631.                 break;
632.             }
633. 
634. #define add_ac(otmp) \
635.     if (otmp) { mac += ARM_BONUS(otmp); } \
636.     otmp = (struct obj *) 0;
637. 
638.             /* round 1: give them body armor */
639.             if (mac < -1 && rn2(5))
640.                 otmp = mongets(mtmp, (rn2(5)) ? PLATE_MAIL
641.                                               : CRYSTAL_PLATE_MAIL);
642.             else if (mac < 3 && rn2(5))
643.                 otmp = mongets(mtmp, (rn2(3)) ? SPLINT_MAIL : BANDED_MAIL);
644.             else if (rn2(5))
645.                 otmp = mongets(mtmp, (rn2(3)) ? RING_MAIL
646.                                               : STUDDED_LEATHER_ARMOR);
647.             else
648.                 otmp = mongets(mtmp, LEATHER_ARMOR);
649.             add_ac(otmp);
650. 
651.             /* round 2: helmets */
652.             if (mac < 10 && rn2(3))
653.                 otmp = mongets(mtmp, HELMET);
654.             else if (mac < 10 && rn2(2))
655.                 otmp = mongets(mtmp, DENTED_POT);
656.             add_ac(otmp);
657. 
658.             /* round 3: shields */
659.             if (mac < 10 && rn2(3))
660.                 otmp = mongets(mtmp, SMALL_SHIELD);
661.             else if (mac < 10 && rn2(2))
662.                 otmp = mongets(mtmp, LARGE_SHIELD);
663.             add_ac(otmp);
664. 
665.             /* round 4: boots */
666.             if (mac < 10 && rn2(3))
667.                 otmp = mongets(mtmp, LOW_BOOTS);
668.             else if (mac < 10 && rn2(2))
669.                 otmp = mongets(mtmp, HIGH_BOOTS);
670.             add_ac(otmp);
671. 
672.             /* round 5: gloves + cloak */
673.             if (mac < 10 && rn2(3))
674.                 otmp = mongets(mtmp, LEATHER_GLOVES);
675.             else if (mac < 10 && rn2(2))
676.                 otmp = mongets(mtmp, LEATHER_CLOAK);
677.             add_ac(otmp); /* not technically needed */
678. 
679. #undef add_ac
680.             nhUse(mac); /* suppress 'dead increment' from static analyzer */
681. 
682.             if (ptr == &mons[PM_WATCH_CAPTAIN]) {
683.                 ; /* better weapon rather than extra gear here */
684.             } else if (ptr == &mons[PM_WATCHMAN]) {
685.                 if (rn2(3)) /* most watchmen carry a whistle */
686.                     (void) mongets(mtmp, TIN_WHISTLE);
687.             } else if (ptr == &mons[PM_GUARD]) {
688.                 /* if hero teleports out of a vault while being confronted
689.                    by the vault's guard, there is a shrill whistling sound,
690.                    so guard evidently carries a cursed whistle */
691.                 otmp = mksobj(TIN_WHISTLE, TRUE, FALSE);
692.                 curse(otmp);
693.                 (void) mpickobj(mtmp, otmp);
694.             } else { /* soldiers and their officers */
695.                 if (!rn2(3))
696.                     (void) mongets(mtmp, K_RATION);
697.                 if (!rn2(2))
698.                     (void) mongets(mtmp, C_RATION);
699.                 if (ptr != &mons[PM_SOLDIER] && !rn2(3))
700.                     (void) mongets(mtmp, BUGLE);
701.             }
702.         } else if (ptr == &mons[PM_SHOPKEEPER]) {
703.             (void) mongets(mtmp, SKELETON_KEY);
704.             switch (rn2(4)) {
705.             /* MAJOR fall through ... */
706.             case 0:
707.                 (void) mongets(mtmp, WAN_MAGIC_MISSILE);
708.                 FALLTHROUGH;
709.                 /*FALLTHRU*/
710.             case 1:
711.                 (void) mongets(mtmp, POT_EXTRA_HEALING);
712.                 FALLTHROUGH;
713.                 /*FALLTHRU*/
714.             case 2:
715.                 (void) mongets(mtmp, POT_HEALING);
716.                 FALLTHROUGH;
717.                 /*FALLTHRU*/
718.             case 3:
719.                 (void) mongets(mtmp, WAN_STRIKING);
720.             }
721.         } else if (ptr->msound == MS_PRIEST
722.                    || quest_mon_represents_role(ptr, PM_CLERIC)) {
723.             (void) mongets(mtmp, rn2(7) ? ROBE
724.                                         : rn2(3) ? CLOAK_OF_PROTECTION
725.                                                  : CLOAK_OF_MAGIC_RESISTANCE);
726.             (void) mongets(mtmp, SMALL_SHIELD);
727.             mkmonmoney(mtmp, (long) rn1(10, 20));
728.         } else if (quest_mon_represents_role(ptr, PM_MONK)) {
729.             (void) mongets(mtmp, rn2(11) ? ROBE : CLOAK_OF_MAGIC_RESISTANCE);
730.         }
731.         break;
732.     case S_NYMPH:
733.         if (!rn2(2))
734.             (void) mongets(mtmp, MIRROR);
735.         if (!rn2(2))
736.             (void) mongets(mtmp, POT_OBJECT_DETECTION);
737.         break;
738.     case S_GIANT:
739.         if (ptr == &mons[PM_MINOTAUR]) {
740.             if (!rn2(8) || (gi.in_mklev && Is_earthlevel(&u.uz)))
741.                 (void) mongets(mtmp, WAN_DIGGING);
742.         } else if (is_giant(ptr)) {
743.             for (cnt = rn2((int) (mtmp->m_lev / 2)); cnt; cnt--) {
744.                 otmp = mksobj(rnd_class(DILITHIUM_CRYSTAL, LUCKSTONE - 1),
745.                               FALSE, FALSE);
746.                 otmp->quan = (long) rn1(2, 3);
747.                 otmp->owt = weight(otmp);
748.                 (void) mpickobj(mtmp, otmp);
749.             }
750.         }
751.         break;
752.     case S_WRAITH:
753.         if (ptr == &mons[PM_NAZGUL]) {
754.             otmp = mksobj(RIN_INVISIBILITY, FALSE, FALSE);
755.             curse(otmp);
756.             (void) mpickobj(mtmp, otmp);
757.         }
758.         break;
759.     case S_LICH:
760.         if (ptr == &mons[PM_MASTER_LICH] && !rn2(13))
761.             (void) mongets(mtmp, (rn2(7) ? ATHAME : WAN_NOTHING));
762.         else if (ptr == &mons[PM_ARCH_LICH] && !rn2(3)) {
763.             otmp = mksobj(rn2(3) ? ATHAME : QUARTERSTAFF, TRUE,
764.                           rn2(13) ? FALSE : TRUE);
765.             if (otmp->spe < 2)
766.                 otmp->spe = rnd(3);
767.             if (!rn2(4))
768.                 otmp->oerodeproof = 1;
769.             (void) mpickobj(mtmp, otmp);
770.         }
771.         break;
772.     case S_MUMMY:
773.         if (rn2(7))
774.             (void) mongets(mtmp, MUMMY_WRAPPING);
775.         break;
776.     case S_QUANTMECH:
777.         if (!rn2(20) && ptr == &mons[PM_QUANTUM_MECHANIC]) {
778.             struct obj *catcorpse;
779. 
780.             otmp = mksobj(LARGE_BOX, FALSE, FALSE);
781.             /* we used to just set the flag, which resulted in weight()
782.                treating the box as being heavier by the weight of a cat;
783.                now we include a cat corpse that won't rot; when opening or
784.                disclosing the box's contents, the corpse might be revived,
785.                otherwise it's given a rot timer; weight is now ordinary */
786.             if ((catcorpse = mksobj(CORPSE, TRUE, FALSE)) != 0) {
787.                 otmp->spe = 1; /* flag for special SchroedingersBox */
788.                 set_corpsenm(catcorpse, PM_HOUSECAT);
789.                 (void) stop_timer(ROT_CORPSE, obj_to_any(catcorpse));
790.                 add_to_container(otmp, catcorpse);
791.                 otmp->owt = weight(otmp);
792.             }
793.             (void) mpickobj(mtmp, otmp);
794.         }
795.         break;
796.     case S_LEPRECHAUN:
797.         mkmonmoney(mtmp, (long) d(level_difficulty(), 30));
798.         break;
799.     case S_DEMON:
800.         /* moved here from m_initweap() because these don't
801.            have AT_WEAP so m_initweap() is not called for them */
802.         if (ptr == &mons[PM_ICE_DEVIL] && !rn2(4)) {
803.             (void) mongets(mtmp, SPEAR);
804.         } else if (ptr == &mons[PM_ASMODEUS]) {
805.             (void) mongets(mtmp, WAN_COLD);
806.             (void) mongets(mtmp, WAN_FIRE);
807.         }
808.         break;
809.     case S_GNOME:
810.         if (!rn2((In_mines(&u.uz) && gi.in_mklev) ? 20 : 60)) {
811.             otmp = mksobj(rn2(4) ? TALLOW_CANDLE : WAX_CANDLE, TRUE, FALSE);
812.             otmp->quan = 1;
813.             otmp->owt = weight(otmp);
814.             if (!mpickobj(mtmp, otmp) && !levl[mtmp->mx][mtmp->my].lit)
815.                 begin_burn(otmp, FALSE);
816.         }
817.         break;
818.     default:
819.         break;
820.     }
821. 
822.     /* ordinary soldiers rarely have access to magic (or gold :-) */
823.     if (ptr == &mons[PM_SOLDIER] && rn2(13))
824.         return;
825. 
826.     if ((int) mtmp->m_lev > rn2(50))
827.         (void) mongets(mtmp, rnd_defensive_item(mtmp));
828.     if ((int) mtmp->m_lev > rn2(100))
829.         (void) mongets(mtmp, rnd_misc_item(mtmp));
830.     if (likes_gold(ptr) && !findgold(mtmp->minvent) && !rn2(5))
831.         mkmonmoney(mtmp,
832.                    (long) d(level_difficulty(), mtmp->minvent ? 5 : 10));
833. }
834. 
835. /* Note: for long worms, always call cutworm (cutworm calls clone_mon) */
836. struct monst *
837. clone_mon(
838.     struct monst *mon,
839.     coordxy x, coordxy y) /* clone's preferred location or 0 (near mon) */
840. {
841.     coord mm;
842.     struct monst *m2;
843. 
844.     /* may be too weak or have been extinguished for population control */
845.     if (mon->mhp <= 1
846.         || (svm.mvitals[monsndx(mon->data)].mvflags & G_EXTINCT) != 0)
847.         return (struct monst *) 0;
848. 
849.     if (x == 0) {
850.         mm.x = mon->mx;
851.         mm.y = mon->my;
852.     } else {
853.         mm.x = x;
854.         mm.y = y;
855.     }
856.     if (!isok(mm.x, mm.y)) { /* paranoia */
857.         impossible("clone_mon trying to create a monster at <%d,%d>?",
858.                    mm.x, mm.y);
859.         return (struct monst *) 0;
860.     }
861.     if (MON_AT(mm.x, mm.y)) { /* (always True for the x==0 case) */
862.         if (!enexto(&mm, mm.x, mm.y, mon->data) || MON_AT(mm.x, mm.y))
863.             return (struct monst *) 0;
864.     }
865. 
866.     m2 = newmonst();
867.     *m2 = *mon; /* copy condition of old monster */
868.     m2->mextra = (struct mextra *) 0;
869.     m2->nmon = fmon;
870.     fmon = m2;
871.     m2->m_id = next_ident();
872.     m2->mx = mm.x;
873.     m2->my = mm.y;
874. 
875.     m2->mundetected = 0;
876.     m2->mtrapped = 0;
877.     m2->mcloned = 1;
878.     m2->minvent = (struct obj *) 0; /* objects don't clone */
879.     m2->mleashed = 0;
880.     /* Max HP the same, but current HP halved for both.  The caller
881.      * might want to override this by halving the max HP also.
882.      * When current HP is odd, the original keeps the extra point.
883.      * We know original has more than 1 HP, so both end up with at least 1.
884.      */
885.     m2->mhpmax = mon->mhpmax;
886.     m2->mhp = mon->mhp / 2;
887.     mon->mhp -= m2->mhp;
888. 
889.     /* clone doesn't have mextra so mustn't retain special monster flags */
890.     m2->isshk = 0;
891.     m2->isgd = 0;
892.     m2->ispriest = 0;
893.     /* ms->isminion handled below */
894. 
895.     /* clone shouldn't be reluctant to move on spots 'parent' just moved on */
896.     mon_track_clear(m2);
897. 
898.     place_monster(m2, m2->mx, m2->my);
899.     if (emits_light(m2->data))
900.         new_light_source(m2->mx, m2->my, emits_light(m2->data), LS_MONSTER,
901.                          monst_to_any(m2));
902.     /* if 'parent' is named, give the clone the same name */
903.     if (has_mgivenname(mon)) {
904.         m2 = christen_monst(m2, MGIVENNAME(mon));
905.     } else if (mon->isshk) {
906.         m2 = christen_monst(m2, shkname(mon));
907.     }
908. 
909.     /* not all clones caused by player are tame or peaceful */
910.     if (!svc.context.mon_moving && mon->mpeaceful) {
911.         if (mon->mtame)
912.             m2->mtame = rn2(max(2 + u.uluck, 2)) ? mon->mtame : 0;
913.         else if (mon->mpeaceful)
914.             m2->mpeaceful = rn2(max(2 + u.uluck, 2)) ? 1 : 0;
915.     }
916.     /* if guardian angel could be cloned (maybe after polymorph?),
917.        m2 could be both isminion and mtame; isminion takes precedence */
918.     if (m2->isminion) {
919.         int atyp;
920. 
921.         newemin(m2);
922.         assert(has_emin(m2) && has_emin(mon));
923.         *EMIN(m2) = *EMIN(mon);
924.         /* renegade when same alignment as hero but not peaceful or
925.            when peaceful while being different alignment from hero */
926.         atyp = EMIN(m2)->min_align;
927.         EMIN(m2)->renegade = (atyp != u.ualign.type) ^ !m2->mpeaceful;
928.     } else if (m2->mtame) {
929.         /* Because m2 is a copy of mon it is tame but not init'ed.
930.            However, tamedog() will not re-tame a tame dog, so m2
931.            must be made non-tame to get initialized properly. */
932.         m2->mtame = 0;
933.         if (tamedog(m2, (struct obj *) 0, FALSE)) {
934.             assert(has_edog(m2) && has_edog(mon));
935.             *EDOG(m2) = *EDOG(mon);
936.         }
937.         /* [TODO? some (most? all?) edog fields probably should be
938.            reinitialized rather that retain the 'parent's values] */
939.     }
940.     set_malign(m2);
941.     newsym(m2->mx, m2->my); /* display the new monster */
942. 
943.     return m2;
944. }
945. 
946. /*
947.  * Propagate a species
948.  *
949.  * Once a certain number of monsters are created, don't create any more
950.  * at random (i.e. make them extinct).  The previous (3.2) behavior was
951.  * to do this when a certain number had _died_, which didn't make
952.  * much sense.
953.  *
954.  * Returns FALSE propagation unsuccessful
955.  *         TRUE  propagation successful
956.  */
957. boolean
958. propagate(int mndx, boolean tally, boolean ghostly)
959. {
960.     boolean gone, result;
961.     int lim = mbirth_limit(mndx);
962. 
963.     gone = (svm.mvitals[mndx].mvflags & G_GONE) != 0; /* geno'd|extinct */
964.     result = ((int) svm.mvitals[mndx].born < lim && !gone) ? TRUE : FALSE;
965. 
966.     /* if it's unique, don't ever make it again */
967.     if ((mons[mndx].geno & G_UNIQ) != 0 && mndx != PM_HIGH_CLERIC)
968.         svm.mvitals[mndx].mvflags |= G_EXTINCT;
969. 
970.     if (svm.mvitals[mndx].born < 255 && tally && (!ghostly || result))
971.         svm.mvitals[mndx].born++;
972.     if ((int) svm.mvitals[mndx].born >= lim
973.         && !(mons[mndx].geno & G_NOGEN)
974.         && !(svm.mvitals[mndx].mvflags & G_EXTINCT)) {
975.         if (wizard) {
976.             debugpline1("Automatically extinguished %s.",
977.                         makeplural(mons[mndx].pmnames[NEUTRAL]));
978.         }
979.         svm.mvitals[mndx].mvflags |= G_EXTINCT;
980.     }
981.     return result;
982. }
983. 
984. /* amount of HP to lose from level drain (or gain from Stormbringer) */
985. int
986. monhp_per_lvl(struct monst *mon)
987. {
988.     struct permonst *ptr = mon->data;
989.     int hp = rnd(8); /* default is d8 */
990. 
991.     /* like newmonhp, but home elementals are ignored, riders use normal d8 */
992.     if (is_golem(ptr)) {
993.         /* draining usually won't be applicable for these critters */
994.         hp = golemhp(monsndx(ptr)) / (int) ptr->mlevel;
995.     } else if (ptr->mlevel > 49) {
996.         /* arbitrary; such monsters won't be involved in draining anyway */
997.         hp = 4 + rnd(4); /* 5..8 */
998.     } else if (ptr->mlet == S_DRAGON && monsndx(ptr) >= PM_GRAY_DRAGON) {
999.         /* adult dragons; newmonhp() uses In_endgame(&u.uz) ? 8 : 4 + rnd(4)
1000.          */
1001.         hp = 4 + rn2(5); /* 4..8 */
1002.     } else if (!mon->m_lev) {
1003.         /* level 0 monsters use 1d4 instead of Nd8 */
1004.         hp = rnd(4);
1005.     }
1006.     return hp;
1007. }
1008. 
1009. /* set up a new monster's initial level and hit points;
1010.    used by newcham() as well as by makemon() */
1011. void
1012. newmonhp(struct monst *mon, int mndx)
1013. {
1014.     struct permonst *ptr = &mons[mndx];
1015.     int basehp = 0;
1016. 
1017.     mon->m_lev = adj_lev(ptr);
1018.     if (is_golem(ptr)) {
1019.         /* golems have a fixed amount of HP, varying by golem type */
1020.         mon->mhpmax = mon->mhp = golemhp(mndx);
1021.     } else if (is_rider(ptr)) {
1022.         /* we want low HP, but a high mlevel so they can attack well */
1023.         basehp = 10; /* minimum is 1 per false (weaker) level */
1024.         mon->mhpmax = mon->mhp = d(basehp, 8);
1025.     } else if (ptr->mlevel > 49) {
1026.         /* "special" fixed hp monster
1027.          * the hit points are encoded in the mlevel in a somewhat strange
1028.          * way to fit in the 50..127 positive range of a signed character
1029.          * above the 1..49 that indicate "normal" monster levels */
1030.         mon->mhpmax = mon->mhp = 2 * (ptr->mlevel - 6);
1031.         mon->m_lev = mon->mhp / 4; /* approximation */
1032.     } else if (ptr->mlet == S_DRAGON && mndx >= PM_GRAY_DRAGON) {
1033.         /* adult dragons; N*(4+rnd(4)) before endgame, N*8 once there */
1034.         basehp = (int) mon->m_lev; /* not really applicable; isolates cast */
1035.         mon->mhpmax = mon->mhp = In_endgame(&u.uz) ? (8 * basehp)
1036.                                  : (4 * basehp + d(basehp, 4));
1037.     } else if (!mon->m_lev) {
1038.         basehp = 1; /* minimum is 1, increased to 2 below */
1039.         mon->mhpmax = mon->mhp = rnd(4);
1040.     } else {
1041.         basehp = (int) mon->m_lev; /* minimum possible is one per level */
1042.         mon->mhpmax = mon->mhp = d(basehp, 8);
1043.         if (is_home_elemental(ptr))
1044.             mon->mhpmax = (mon->mhp *= 3); /* leave 'basehp' as-is */
1045.     }
1046. 
1047.     /* if d(X,8) rolled a 1 all X times, give a boost;
1048.        most beneficial for level 0 and level 1 monsters, making mhpmax
1049.        and starting mhp always be at least 2 */
1050.     if (mon->mhpmax == basehp) {
1051.         mon->mhpmax += 1;
1052.         mon->mhp = mon->mhpmax;
1053.     }
1054. }
1055. 
1056. static const struct mextra zeromextra = DUMMY;
1057. 
1058. staticfn void
1059. init_mextra(struct mextra *mex)
1060. {
1061.     *mex = zeromextra;
1062.     mex->mcorpsenm = NON_PM;
1063. }
1064. 
1065. struct mextra *
1066. newmextra(void)
1067. {
1068.     struct mextra *mextra;
1069. 
1070.     mextra = (struct mextra *) alloc(sizeof (struct mextra));
1071.     init_mextra(mextra);
1072.     return mextra;
1073. }
1074. 
1075. staticfn boolean
1076. makemon_rnd_goodpos(
1077.     struct monst *mon,
1078.     mmflags_nht gpflags,
1079.     coord *cc) /* output */
1080. {
1081.     int tryct = 0;
1082.     coordxy nx, ny;
1083.     boolean good;
1084. 
1085.     gpflags |= GP_AVOID_MONPOS;
1086.     do {
1087.         nx = rn1(COLNO - 3, 2);
1088.         ny = rn2(ROWNO);
1089.         good = (!gi.in_mklev && cansee(nx,ny)) ? FALSE
1090.                                               : goodpos(nx, ny, mon, gpflags);
1091.     } while ((++tryct < 50) && !good);
1092. 
1093.     if (!good) {
1094.         /* else go through all map positions, twice, first round
1095.            ignoring positions in sight, and pick first good one.
1096.            skip first round if we're in special level loader or blind */
1097.         coordxy xofs = nx;
1098.         coordxy yofs = ny;
1099.         coordxy dx,dy;
1100.         int bl = (gi.in_mklev || Blind) ? 1 : 0;
1101. 
1102.         for ( ; bl < 2; bl++) {
1103.             if (!bl)
1104.                 gpflags &= ~GP_CHECKSCARY; /* perhaps should be a 3rd pass */
1105.             for (dx = 0; dx < COLNO; dx++)
1106.                 for (dy = 0; dy < ROWNO; dy++) {
1107.                     nx = ((dx + xofs) % (COLNO - 1)) + 1;
1108.                     ny = ((dy + yofs) % (ROWNO - 1)) + 1;
1109.                     if (bl == 0 && cansee(nx,ny))
1110.                         continue;
1111.                     if (goodpos(nx, ny, mon, gpflags))
1112.                         goto gotgood;
1113.                 }
1114.             if (bl == 0 && (!mon || mon->data->mmove)) {
1115.                 stairway *stway = gs.stairs;
1116.                 /* all map positions are visible (or not good),
1117.                    try to pick something logical */
1118.                 while (stway) {
1119.                     if (stway->tolev.dnum == u.uz.dnum && !rn2(2)) {
1120.                         nx = stway->sx;
1121.                         ny = stway->sy;
1122.                         break;
1123.                     }
1124.                     stway = stway->next;
1125.                 }
1126.                 if (goodpos(nx, ny, mon, gpflags))
1127.                     goto gotgood;
1128.             }
1129.         }
1130.     } else {
1131.  gotgood:
1132.         cc->x = nx;
1133.         cc->y = ny;
1134.         return TRUE;
1135.     }
1136.     return FALSE;
1137. }
1138. 
1139. /*
1140.  * called with [x,y] = coordinates;
1141.  *      [0,0] means anyplace
1142.  *      [u.ux,u.uy] means: near player (if !gi.in_mklev)
1143.  *
1144.  *      In case we make a monster group, only return the one at [x,y].
1145.  */
1146. struct monst *
1147. makemon(
1148.     struct permonst *ptr,
1149.     coordxy x, coordxy y,
1150.     mmflags_nht mmflags)
1151. {
1152.     struct monst *mtmp;
1153.     struct monst fakemon;
1154.     coord cc;
1155.     int mndx, mcham, ct, mitem;
1156.     boolean femaleok, maleok,
1157.             anymon = !ptr,
1158.             byyou = u_at(x, y),
1159.             allow_minvent = ((mmflags & NO_MINVENT) == 0),
1160.             countbirth = ((mmflags & MM_NOCOUNTBIRTH) == 0),
1161.             allowtail = ((mmflags & MM_NOTAIL) == 0);
1162.     mmflags_nht gpflags = (((mmflags & MM_IGNOREWATER) ? MM_IGNOREWATER : 0)
1163.                            | GP_CHECKSCARY | GP_AVOID_MONPOS);
1164. 
1165.     fakemon = cg.zeromonst;
1166.     cc.x = cc.y = 0;
1167. 
1168.     if (iflags.debug_mongen || (!svl.level.flags.rndmongen && !ptr))
1169.         return (struct monst *) 0;
1170. 
1171.     /* if caller wants random location, do it here */
1172.     if (x == 0 && y == 0) {
1173.         fakemon.data = ptr; /* set up for goodpos */
1174.         if (!makemon_rnd_goodpos(ptr ? &fakemon : (struct monst *) 0,
1175.                                  gpflags, &cc))
1176.             return (struct monst *) 0;
1177.         x = cc.x;
1178.         y = cc.y;
1179.     } else if (byyou && !gi.in_mklev) {
1180.         if (!enexto_core(&cc, u.ux, u.uy, ptr, gpflags)
1181.             && !enexto_core(&cc, u.ux, u.uy, ptr, gpflags & ~GP_CHECKSCARY))
1182.             return (struct monst *) 0;
1183.         x = cc.x;
1184.         y = cc.y;
1185.     }
1186. 
1187.     /* sanity check */
1188.     if (!isok(x, y)) {
1189.         impossible("makemon trying to create a monster at <%d,%d>?", x, y);
1190.         return (struct monst *) 0;
1191.     }
1192. 
1193.     /* Does monster already exist at the position? */
1194.     if (MON_AT(x, y)) {
1195.         if (!(mmflags & MM_ADJACENTOK)
1196.             || !enexto_core(&cc, x, y, ptr, gpflags))
1197.             return (struct monst *) 0;
1198.         x = cc.x;
1199.         y = cc.y;
1200.     }
1201. 
1202.     if (ptr) {
1203.         mndx = monsndx(ptr);
1204.         /* if you are to make a specific monster and it has
1205.            already been genocided, return */
1206.         if (svm.mvitals[mndx].mvflags & G_GENOD)
1207.             return (struct monst *) 0;
1208.         if (wizard && (svm.mvitals[mndx].mvflags & G_EXTINCT)) {
1209.             debugpline1("Explicitly creating extinct monster %s.",
1210.                         mons[mndx].pmnames[NEUTRAL]);
1211.         }
1212.     } else {
1213.         /* make a random (common) monster that can survive here.
1214.          * (the special levels ask for random monsters at specific
1215.          * positions, causing mass drowning on the medusa level,
1216.          * for instance.)
1217.          */
1218.         int tryct = 0; /* maybe there are no good choices */
1219. 
1220.         do {
1221.             if (!(ptr = rndmonst())) {
1222.                 debugpline0("Warning: no monster.");
1223.                 return (struct monst *) 0; /* no more monsters! */
1224.             }
1225.             fakemon.data = ptr; /* set up for goodpos */
1226.         } while (++tryct <= 50
1227.                  /* in Sokoban, don't accept a giant on first try;
1228.                     after that, boulder carriers are fair game */
1229.                  && ((tryct == 1 && throws_rocks(ptr) && In_sokoban(&u.uz))
1230.                      || !goodpos(x, y, &fakemon, gpflags)));
1231.         mndx = monsndx(ptr);
1232.     }
1233.     (void) propagate(mndx, countbirth, FALSE);
1234.     mtmp = newmonst();
1235.     *mtmp = cg.zeromonst; /* clear all entries in structure */
1236. 
1237.     if (mmflags & MM_EGD)
1238.         newegd(mtmp);
1239.     if (mmflags & MM_EPRI)
1240.         newepri(mtmp);
1241.     if (mmflags & MM_ESHK)
1242.         neweshk(mtmp);
1243.     if (mmflags & MM_EMIN)
1244.         newemin(mtmp);
1245.     if (mmflags & MM_EDOG)
1246.         newedog(mtmp);
1247.     if (mmflags & MM_ASLEEP)
1248.         mtmp->msleeping = 1;
1249.     mtmp->nmon = fmon;
1250.     fmon = mtmp;
1251.     mtmp->m_id = next_ident();
1252.     set_mon_data(mtmp, ptr); /* mtmp->data = ptr; */
1253.     if (ptr->msound == MS_LEADER && quest_info(MS_LEADER) == mndx)
1254.         svq.quest_status.leader_m_id = mtmp->m_id;
1255.     mtmp->mnum = mndx;
1256. 
1257.     /* set up level and hit points */
1258.     newmonhp(mtmp, mndx);
1259. 
1260.     femaleok = (!is_male(ptr) && !is_neuter(ptr));
1261.     maleok = (!is_female(ptr) && !is_neuter(ptr));
1262.     if (is_female(ptr) || ((mmflags & MM_FEMALE) != 0 && femaleok))
1263.         mtmp->female = 1;
1264.     else if (is_male(ptr) || ((mmflags & MM_MALE) != 0 && maleok))
1265.         mtmp->female = 0;
1266. 
1267.     /* leader and nemesis gender is usually hardcoded in mons[],
1268.        but for ones which can be random, it has already been chosen
1269.        (in role_init(), for possible use by the quest pager code) */
1270.     else if (ptr->msound == MS_LEADER && quest_info(MS_LEADER) == mndx)
1271.         mtmp->female = svq.quest_status.ldrgend;
1272.     else if (ptr->msound == MS_NEMESIS && quest_info(MS_NEMESIS) == mndx)
1273.         mtmp->female = svq.quest_status.nemgend;
1274. 
1275.     /* female used to be set randomly here even for neuters on the
1276.        grounds that it was ignored, but after corpses were changed to
1277.        retain gender it matters because it affects stacking of corpses */
1278.     else
1279.         mtmp->female = femaleok ? rn2(2) : 0;
1280. 
1281.     if (In_sokoban(&u.uz) && !mindless(ptr)) { /* know about traps here */
1282.         mon_learns_traps(mtmp, PIT);
1283.         mon_learns_traps(mtmp, HOLE);
1284.     }
1285.     if (Is_stronghold(&u.uz) && !mindless(ptr)) /* know about trap doors */
1286.         mon_learns_traps(mtmp, TRAPDOOR);
1287.     /* quest leader and nemesis both know about all trap types */
1288.     if (ptr->msound == MS_LEADER || ptr->msound == MS_NEMESIS)
1289.         mon_learns_traps(mtmp, ALL_TRAPS);
1290.     /* locations where monsters are already experienced with wands */
1291.     if (Is_stronghold(&u.uz) || Is_knox(&u.uz) || In_endgame(&u.uz) ||
1292.         In_hell(&u.uz) || In_V_tower(&u.uz) || In_quest(&u.uz))
1293.         mtmp->mwandexp = TRUE;
1294. 
1295.     place_monster(mtmp, x, y);
1296.     mtmp->mcansee = mtmp->mcanmove = TRUE;
1297.     mtmp->mgenmklev = gi.in_mklev;
1298.     mtmp->seen_resistance = M_SEEN_NOTHING;
1299.     mtmp->mpeaceful = (mmflags & MM_ANGRY) ? FALSE : peace_minded(ptr);
1300.     if ((mmflags & MM_MINVIS) != 0) /* for ^G */
1301.         mon_set_minvis(mtmp, FALSE); /* call after place_monster() */
1302. 
1303.     switch (ptr->mlet) {
1304.     case S_MIMIC:
1305.         set_mimic_sym(mtmp);
1306.         break;
1307.     case S_SPIDER:
1308.     case S_SNAKE:
1309.         if (gi.in_mklev) {
1310.             if (x && y)
1311.                 (void) mkobj_at(RANDOM_CLASS, x, y, TRUE);
1312.             (void) hideunder(mtmp);
1313.         }
1314.         break;
1315.     case S_LIGHT:
1316.     case S_ELEMENTAL:
1317.         if (mndx == PM_STALKER || mndx == PM_BLACK_LIGHT) {
1318.             mtmp->perminvis = TRUE;
1319.             mtmp->minvis = TRUE;
1320.         }
1321.         break;
1322.     case S_EEL:
1323.         if (gi.in_mklev) {
1324.             (void) hideunder(mtmp);
1325.         }
1326.         break;
1327.     case S_LEPRECHAUN:
1328.         mtmp->msleeping = 1;
1329.         break;
1330.     case S_JABBERWOCK:
1331.     case S_NYMPH:
1332.         if (rn2(5) && !u.uhave.amulet)
1333.             mtmp->msleeping = 1;
1334.         break;
1335.     case S_ORC:
1336.         if (Race_if(PM_ELF))
1337.             mtmp->mpeaceful = FALSE;
1338.         break;
1339.     case S_UNICORN:
1340.         if (is_unicorn(ptr) && sgn(u.ualign.type) == sgn(ptr->maligntyp))
1341.             mtmp->mpeaceful = TRUE;
1342.         break;
1343.     case S_BAT:
1344.         if (Inhell && is_bat(ptr))
1345.             mon_adjust_speed(mtmp, 2, (struct obj *) 0);
1346.         break;
1347.     }
1348.     if ((ct = emits_light(mtmp->data)) > 0)
1349.         new_light_source(mtmp->mx, mtmp->my, ct, LS_MONSTER,
1350.                          monst_to_any(mtmp));
1351.     mitem = STRANGE_OBJECT; /* extra inventory item for this monster */
1352. 
1353.     if (mndx == PM_VLAD_THE_IMPALER)
1354.         mitem = CANDELABRUM_OF_INVOCATION;
1355.     mtmp->cham = NON_PM; /* default is "not a shapechanger" */
1356.     if (!Protection_from_shape_changers
1357.         && (mcham = pm_to_cham(mndx)) != NON_PM) {
1358.         /* this is a shapechanger after all */
1359.         mtmp->cham = mcham;
1360.         /* Vlad stays in his normal shape so he can carry the Candelabrum */
1361.         if (mndx != PM_VLAD_THE_IMPALER
1362.             /* Note:  shapechanger's initial form used to be chosen here
1363.                with rndmonst(), yielding a monster which was appropriate
1364.                to the level's difficulty but ignoring the changer's usual
1365.                type selection, so was inappropriate for vampshifters.
1366.                Let newcham() pick the shape. */
1367.             && newcham(mtmp, (struct permonst *) 0, NO_NC_FLAGS))
1368.             allow_minvent = FALSE;
1369.     } else if (mndx == PM_WIZARD_OF_YENDOR) {
1370.         mtmp->iswiz = TRUE;
1371.         svc.context.no_of_wizards++;
1372.         if (svc.context.no_of_wizards == 1 && Is_earthlevel(&u.uz))
1373.             mitem = SPE_DIG;
1374.     } else if (mndx == PM_GHOST && !(mmflags & MM_NONAME)) {
1375.         mtmp = christen_monst(mtmp, rndghostname());
1376.     } else if (mndx == PM_CROESUS) {
1377.         mitem = TWO_HANDED_SWORD;
1378.     } else if (ptr->msound == MS_NEMESIS) {
1379.         mitem = BELL_OF_OPENING;
1380.     } else if (mndx == PM_PESTILENCE) {
1381.         mitem = POT_SICKNESS;
1382.     }
1383.     if (mitem != STRANGE_OBJECT && allow_minvent)
1384.         (void) mongets(mtmp, mitem);
1385. 
1386.     if (gi.in_mklev) {
1387.         if ((is_ndemon(ptr) || mndx == PM_WUMPUS
1388.              || mndx == PM_LONG_WORM || mndx == PM_GIANT_EEL)
1389.             && !u.uhave.amulet && rn2(5))
1390.             mtmp->msleeping = TRUE;
1391.     } else {
1392.         if (byyou) {
1393.             newsym(mtmp->mx, mtmp->my);
1394.             set_apparxy(mtmp);
1395.         }
1396.     }
1397.     if (is_dprince(ptr) && ptr->msound == MS_BRIBE) {
1398.         mtmp->mpeaceful = mtmp->minvis = mtmp->perminvis = 1;
1399.         mtmp->mavenge = 0;
1400.         if (u_wield_art(ART_EXCALIBUR) || u_wield_art(ART_DEMONBANE))
1401.             mtmp->mpeaceful = mtmp->mtame = FALSE;
1402.     }
1403.     if (mndx == PM_RAVEN && uwep && uwep->otyp == BEC_DE_CORBIN)
1404.         mtmp->mpeaceful = TRUE;
1405.     if (mndx == PM_LONG_WORM && (mtmp->wormno = get_wormno()) != 0) {
1406.         initworm(mtmp, allowtail ? rn2(5) : 0);
1407.         if (count_wsegs(mtmp))
1408.             place_worm_tail_randomly(mtmp, x, y);
1409.     }
1410.     /* it's possible to create an ordinary monster of some special
1411.        types; make sure their extended data is initialized to
1412.        something sensible if caller hasn't specified MM_EPRI|MM_EMIN
1413.        (when they're specified, caller intends to handle this itself) */
1414.     if ((mndx == PM_ALIGNED_CLERIC || mndx == PM_HIGH_CLERIC)
1415.             ? !(mmflags & (MM_EPRI | MM_EMIN))
1416.             : (mndx == PM_ANGEL && !(mmflags & MM_EMIN) && !rn2(3))) {
1417.         struct emin *eminp;
1418. 
1419.         newemin(mtmp);
1420.         eminp = EMIN(mtmp);
1421. 
1422.         mtmp->isminion = 1;            /* make priest be a roamer */
1423.         eminp->min_align = rn2(3) - 1; /* no A_NONE */
1424.         eminp->renegade = (boolean) ((mmflags & MM_ANGRY) ? 1 : !rn2(3));
1425.         mtmp->mpeaceful = (eminp->min_align == u.ualign.type)
1426.                               ? !eminp->renegade
1427.                               : eminp->renegade;
1428.     }
1429.     set_malign(mtmp); /* having finished peaceful changes */
1430.     if (anymon && !(mmflags & MM_NOGRP)) {
1431.         if ((ptr->geno & G_SGROUP) && rn2(2)) {
1432.             m_initsgrp(mtmp, mtmp->mx, mtmp->my, mmflags);
1433.         } else if (ptr->geno & G_LGROUP) {
1434.             if (rn2(3))
1435.                 m_initlgrp(mtmp, mtmp->mx, mtmp->my, mmflags);
1436.             else
1437.                 m_initsgrp(mtmp, mtmp->mx, mtmp->my, mmflags);
1438.         }
1439.     }
1440. 
1441.     if (allow_minvent) {
1442.         if (is_armed(ptr))
1443.             m_initweap(mtmp); /* equip with weapons / armor */
1444.         m_initinv(mtmp); /* add on a few special items incl. more armor */
1445.         m_dowear(mtmp, TRUE);
1446. 
1447.         if (!rn2(100) && is_domestic(ptr)
1448.             && can_saddle(mtmp) && !which_armor(mtmp, W_SADDLE)) {
1449.             /* NULL obj arg means put_saddle_on_mon()
1450.              * will create the saddle itself */
1451.             put_saddle_on_mon((struct obj *) 0, mtmp);
1452.         }
1453. 
1454.     } else {
1455.         /* no initial inventory is allowed */
1456.         if (mtmp->minvent)
1457.             discard_minvent(mtmp, TRUE);
1458.         mtmp->minvent = (struct obj *) 0; /* caller expects this */
1459.     }
1460.     if (ptr->mflags3 && !(mmflags & MM_NOWAIT)) {
1461.         if (ptr->mflags3 & M3_WAITFORU)
1462.             mtmp->mstrategy |= STRAT_WAITFORU;
1463.         if (ptr->mflags3 & M3_CLOSE)
1464.             mtmp->mstrategy |= STRAT_CLOSE;
1465.         if (ptr->mflags3 & (M3_WAITMASK | M3_COVETOUS))
1466.             mtmp->mstrategy |= STRAT_APPEARMSG;
1467.     }
1468. 
1469.     if (allow_minvent && gm.migrating_objs)
1470.         deliver_obj_to_mon(mtmp, 1, DF_NONE); /* in case of waiting items */
1471. 
1472.     if (!gi.in_mklev) {
1473.         newsym(mtmp->mx, mtmp->my); /* make sure the mon shows up */
1474.         if (!(mmflags & MM_NOMSG)) {
1475.             char mbuf[BUFSZ], *what = 0;
1476.             /* MM_NOEXCLAM is used for #wizgenesis (^G) */
1477.             boolean exclaim = !(mmflags & MM_NOEXCLAM);
1478. 
1479.             if ((canseemon(mtmp) && (M_AP_TYPE(mtmp) == M_AP_NOTHING
1480.                                      || M_AP_TYPE(mtmp) == M_AP_MONSTER))
1481.                 || sensemon(mtmp)) {
1482.                 what = Amonnam(mtmp);
1483.                 if (M_AP_TYPE(mtmp) == M_AP_MONSTER)
1484.                     exclaim = TRUE;
1485.             } else if (canseemon(mtmp)) {
1486.                 /* mimic masquerading as furniture or object and not sensed */
1487.                 mhidden_description(mtmp, MHID_ARTICLE | MHID_ALTMON, mbuf);
1488.                 what = upstart(mbuf);
1489.             }
1490.             if (what) {
1491.                 set_msg_xy(mtmp->mx, mtmp->my);
1492.                 Norep("%s%s %s%s%c", what,
1493.                       exclaim ? " suddenly" : "",
1494.                       /* 'what' might be "gold pieces" so need plural verb */
1495.                       vtense(what, "appear"),
1496.                       next2u(x, y) ? " next to you"
1497.                       : (distu(x, y) <= (BOLT_LIM * BOLT_LIM)) ? " close by"
1498.                         : "",
1499.                       exclaim ? '!' : '.');
1500.             }
1501.         }
1502.         /* if discernable and a threat, stop fiddling while Rome burns */
1503.         if (go.occupation)
1504.             (void) dochugw(mtmp, FALSE);
1505. 
1506.         /* TODO: unify with teleport appears msg */
1507.     }
1508. 
1509.     return mtmp;
1510. }
1511. 
1512. /* caller rejects makemon()'s result; always returns Null */
1513. struct monst *
1514. unmakemon(
1515.     struct monst *mon,
1516.     mmflags_nht mmflags)
1517. {
1518.     boolean countbirth = ((mmflags & MM_NOCOUNTBIRTH) == 0);
1519.     int mndx = monsndx(mon->data);
1520. 
1521.     /* if count has reached the limit of 255, we don't know whether
1522.        that just happened when creating this monster or the threshold
1523.        had already been reached and further increments were suppressed;
1524.        assume the latter */
1525.     if (countbirth && svm.mvitals[mndx].born > 0
1526.         && svm.mvitals[mndx].born < 255)
1527.         svm.mvitals[mndx].born -= 1;
1528.     if ((mon->data->geno & G_UNIQ) != 0)
1529.         svm.mvitals[mndx].mvflags &= ~G_EXTINCT;
1530. 
1531.     mon->mhp = 0; /* let discard_minvent() know that mon isn't being kept */
1532.     /* uncreate any artifact that the monster was provided with; unlike
1533.        mongone(), this doesn't protect special items like the Amulet
1534.        by dropping them so caller should handle them when applicable */
1535.     discard_minvent(mon, TRUE);
1536. 
1537.     mongone(mon);
1538.     return (struct monst *) 0;
1539. }
1540. 
1541. int
1542. mbirth_limit(int mndx)
1543. {
1544.     /* There is an implicit limit of 4 for "high priest of <deity>",
1545.      * but aligned priests can grow into high priests, thus they aren't
1546.      * really limited to 4, so leave the default amount in place for them.
1547.      */
1548. 
1549.     /* assert(MAXMONNO < 255); */
1550.     return (mndx == PM_NAZGUL ? 9 : mndx == PM_ERINYS ? 3 : MAXMONNO);
1551. }
1552. 
1553. /* used for wand/scroll/spell of create monster */
1554. /* returns TRUE iff you know monsters have been created */
1555. boolean
1556. create_critters(
1557.     int cnt,
1558.     struct permonst *mptr, /* usually null; used for confused reading */
1559.     boolean neverask)
1560. {
1561.     coord c;
1562.     coordxy x, y;
1563.     struct monst *mon;
1564.     boolean known = FALSE;
1565.     boolean ask = (wizard && !neverask);
1566. 
1567.     while (cnt--) {
1568.         if (ask) {
1569.             if (create_particular()) {
1570.                 known = TRUE;
1571.                 continue;
1572.             } else
1573.                 ask = FALSE; /* ESC will shut off prompting */
1574.         }
1575.         x = u.ux, y = u.uy;
1576.         /* if in water, try to encourage an aquatic monster
1577.            by finding and then specifying another wet location */
1578.         if (!mptr && u.uinwater && enexto(&c, x, y, &mons[PM_GIANT_EEL]))
1579.             x = c.x, y = c.y;
1580. 
1581.         if ((mon = makemon(mptr, x, y, NO_MM_FLAGS)) == 0)
1582.             continue; /* try again [should probably stop instead] */
1583. 
1584.         if ((canseemon(mon) && (M_AP_TYPE(mon) == M_AP_NOTHING
1585.                                 || M_AP_TYPE(mon) == M_AP_MONSTER))
1586.             || sensemon(mon))
1587.             known = TRUE;
1588.     }
1589.     return known;
1590. }
1591. 
1592. staticfn boolean
1593. uncommon(int mndx)
1594. {
1595.     if (mons[mndx].geno & (G_NOGEN | G_UNIQ))
1596.         return TRUE;
1597.     if (svm.mvitals[mndx].mvflags & G_GONE)
1598.         return TRUE;
1599.     if (Inhell)
1600.         return (boolean) (mons[mndx].maligntyp > A_NEUTRAL);
1601.     else
1602.         return (boolean) ((mons[mndx].geno & G_HELL) != 0);
1603. }
1604. 
1605. /*
1606.  *      shift the probability of a monster's generation by
1607.  *      comparing the dungeon alignment and monster alignment.
1608.  *      return an integer in the range of 0-5.
1609.  */
1610. staticfn int
1611. align_shift(struct permonst *ptr)
1612. {
1613.     static NEARDATA long oldmoves = 0L; /* != 1, starting value of moves */
1614.     static NEARDATA s_level *lev;
1615.     int alshift;
1616. 
1617.     if (oldmoves != svm.moves) {
1618.         lev = Is_special(&u.uz);
1619.         oldmoves = svm.moves;
1620.     }
1621.     switch ((lev) ? lev->flags.align : svd.dungeons[u.uz.dnum].flags.align) {
1622.     default: /* just in case */
1623.     case AM_NONE:
1624.         alshift = 0;
1625.         break;
1626.     case AM_LAWFUL:
1627.         alshift = (ptr->maligntyp + 20) / (2 * ALIGNWEIGHT);
1628.         break;
1629.     case AM_NEUTRAL:
1630.         alshift = (20 - abs(ptr->maligntyp)) / ALIGNWEIGHT;
1631.         break;
1632.     case AM_CHAOTIC:
1633.         alshift = (-(ptr->maligntyp - 20)) / (2 * ALIGNWEIGHT);
1634.         break;
1635.     }
1636.     return alshift;
1637. }
1638. 
1639. /* return larger value if monster prefers the level temperature */
1640. staticfn int
1641. temperature_shift(struct permonst *ptr)
1642. {
1643.     if (svl.level.flags.temperature
1644.         && pm_resistance(ptr, (svl.level.flags.temperature > 0)
1645.                          ? MR_FIRE : MR_COLD))
1646.         return 3;
1647.     return 0;
1648. }
1649. 
1650. /* select a random monster type */
1651. struct permonst *
1652. rndmonst(void)
1653. {
1654.     return rndmonst_adj(0, 0);
1655. }
1656. 
1657. /* select a random monster type, with adjusted difficulty */
1658. struct permonst *
1659. rndmonst_adj(int minadj, int maxadj)
1660. {
1661.     struct permonst *ptr;
1662.     int mndx;
1663.     int weight, totalweight, selected_mndx, zlevel, minmlev, maxmlev;
1664.     boolean elemlevel, upper;
1665. 
1666.     if (u.uz.dnum == quest_dnum && rn2(7) && (ptr = qt_montype()) != 0)
1667.         return ptr;
1668. 
1669.     zlevel = level_difficulty();
1670.     minmlev = monmin_difficulty(zlevel) + minadj;
1671.     maxmlev = monmax_difficulty(zlevel) + maxadj;
1672.     upper = Is_rogue_level(&u.uz); /* prefer uppercase only on rogue level */
1673.     elemlevel = In_endgame(&u.uz) && !Is_astralevel(&u.uz); /* elmntl plane */
1674. 
1675.     /* amount processed so far */
1676.     totalweight = 0;
1677.     selected_mndx = NON_PM;
1678. 
1679.     for (mndx = LOW_PM; mndx < SPECIAL_PM; ++mndx) {
1680.         ptr = &mons[mndx];
1681. 
1682.         if (montooweak(mndx, minmlev) || montoostrong(mndx, maxmlev))
1683.             continue;
1684.         if (upper && !isupper(monsym(ptr)))
1685.             continue;
1686.         if (elemlevel && wrong_elem_type(ptr))
1687.             continue;
1688.         if (uncommon(mndx))
1689.             continue;
1690.         if (Inhell && (ptr->geno & G_NOHELL))
1691.             continue;
1692. 
1693.         /*
1694.          * Weighted reservoir sampling:  select ptr with a
1695.          * (ptr weight)/(total of all weights so far including ptr's)
1696.          * probability.  For example, if the previous total is 10, and
1697.          * this is now looking at acid blobs with a frequency of 2, it
1698.          * has a 2/12 chance of abandoning ptr's previous value in favor
1699.          * of acid blobs, and 10/12 chance of keeping whatever it was.
1700.          *
1701.          * This does not bias results towards either the earlier or the
1702.          * later monsters:  the smaller pool and better odds from being
1703.          * earlier are exactly canceled out by having more monsters to
1704.          * potentially steal its spot.
1705.          */
1706.         weight = (int) (ptr->geno & G_FREQ) + align_shift(ptr);
1707.         weight += temperature_shift(ptr);
1708.         if (weight < 0 || weight > 127) {
1709.             impossible("bad weight in rndmonst for mndx %d", mndx);
1710.             weight = 0;
1711.         }
1712.         /* was unconditional, but if weight==0, rn2() < 0 will always fail;
1713.            also need to avoid rn2(0) if totalweight is still 0 so far */
1714.         if (weight > 0) {
1715.             totalweight += weight; /* totalweight now guaranteed to be > 0 */
1716.             if (rn2(totalweight) < weight)
1717.                 selected_mndx = mndx;
1718.         }
1719.     }
1720.     /*
1721.      * Possible modification:  if totalweight is "too low" or nothing
1722.      * viable was picked, expand minmlev..maxmlev range and try again.
1723.      */
1724.     if (selected_mndx == NON_PM || uncommon(selected_mndx)) {
1725.         /* maybe no common monsters left, or all are too weak or too strong */
1726.         if (selected_mndx != NON_PM)
1727.             debugpline1("rndmonst returning Null [uncommon 'mndx'=#%d]",
1728.                         selected_mndx);
1729.         return (struct permonst *) 0;
1730.     }
1731.     return &mons[selected_mndx];
1732. }
1733. 
1734. /* decide whether it's ok to generate a candidate monster by mkclass() */
1735. staticfn boolean
1736. mk_gen_ok(int mndx, unsigned mvflagsmask, unsigned genomask)
1737. {
1738.     struct permonst *ptr = &mons[mndx];
1739. 
1740.     if (svm.mvitals[mndx].mvflags & mvflagsmask)
1741.         return FALSE;
1742.     if (ptr->geno & genomask)
1743.         return FALSE;
1744.     if (is_placeholder(ptr))
1745.         return FALSE;
1746. #ifdef MAIL_STRUCTURES
1747.     /* special levels might ask for random demon type; reject this one */
1748.     if (ptr == &mons[PM_MAIL_DAEMON])
1749.         return FALSE;
1750. #endif
1751.     return TRUE;
1752. }
1753. 
1754. /* monsters in order by mlet & difficulty for mkclass() */
1755. static int mongen_order[NUMMONS];
1756. static xint8 mclass_maxf[MAXMCLASSES];
1757. static boolean mongen_order_init = FALSE;
1758. 
1759. staticfn int QSORTCALLBACK
1760. cmp_init_mongen_order(const void *p1, const void *p2)
1761. {
1762.     int i1 = *((int *) p1), i2 = *((int *) p2);
1763.  #if 0
1764.     /* This will cause these to be moved last in the mlet sort order */
1765.     int offset1 = ((mons[i1].geno & (G_NOGEN | G_UNIQ)) != 0) ? 99 : 0,
1766.         offset2 = ((mons[i2].geno & (G_NOGEN | G_UNIQ)) != 0) ? 99 : 0;
1767. #else
1768.     int offset1 = 0, offset2 = 0;
1769. #endif
1770. 
1771.     /* incorporate the mlet into the sort values for comparison */
1772.     int difficulty1 =
1773.         ((mons[i1].difficulty + offset1) | ((int) mons[i1].mlet << 8)),
1774.         difficulty2 =
1775.         ((mons[i2].difficulty + offset2) | ((int) mons[i2].mlet << 8));
1776.     return difficulty1 - difficulty2;
1777. }
1778. 
1779. #if (NH_DEVEL_STATUS != NH_STATUS_RELEASED)
1780. staticfn void check_mongen_order(void);
1781. /* check that monsters are in correct difficulty order for mkclass() */
1782. staticfn void
1783. check_mongen_order(void)
1784. {
1785.     int i, diff = 0;
1786.     char mlet = '\0';
1787.     for (i = LOW_PM; i < SPECIAL_PM; i++) {
1788.         if (i != mongen_order[i]) {
1789.             debugpline2("changed:%s=>%s", mons[i].pmnames[NEUTRAL], mons[mongen_order[i]].pmnames[NEUTRAL]);
1790.         }
1791. 
1792.         if (mlet == mons[mongen_order[i]].mlet) {
1793.             if (mons[mongen_order[i]].difficulty < diff)
1794.                 debugpline1("%s", mons[mongen_order[i]].pmnames[NEUTRAL]);
1795.             diff = mons[mongen_order[i]].difficulty;
1796.         }
1797.         if (!mlet || mlet != mons[mongen_order[i]].mlet) {
1798.             mlet = mons[mongen_order[i]].mlet;
1799.             diff = 0;
1800.         }
1801.     }
1802. }
1803. #endif
1804. 
1805. /* initialize monster order for mkclass */
1806. staticfn void
1807. init_mongen_order(void)
1808. {
1809.     int i, mlet;
1810. 
1811.     if (mongen_order_init)
1812.         return;
1813. 
1814.     mongen_order_init = TRUE;
1815.     for (i = LOW_PM; i < NUMMONS; i++) {
1816.         mongen_order[i] = i;
1817.         mlet = mons[i].mlet;
1818.         if ((xint8) (mons[i].geno & G_FREQ) > mclass_maxf[mlet])
1819.             mclass_maxf[mlet] = (xint8) (mons[i].geno & G_FREQ);
1820.     }
1821. #if (NH_DEVEL_STATUS != NH_STATUS_RELEASED)
1822.     check_mongen_order();
1823. #endif
1824.     qsort((genericptr_t) mongen_order, SPECIAL_PM, sizeof(int), cmp_init_mongen_order);
1825. #if (NH_DEVEL_STATUS != NH_STATUS_RELEASED)
1826.     check_mongen_order();
1827. #endif
1828. }
1829. 
1830. #define MONSi(i) (mongen_order[i])
1831. 
1832. extern struct enum_dump monsdump[];  /* allmain.c */
1833. 
1834. void
1835. dump_mongen(void)
1836. {
1837.     char mlet, prev_mlet = 0;
1838.     int i, nmwidth = 27, special;
1839.     char nmbuf[80];
1840. 
1841.     monst_globals_init();
1842.     init_mongen_order();
1843.     raw_printf("int mongen_order[] = {");
1844.     for (i = LOW_PM; i < SPECIAL_PM; ++i) {
1845.         special = (mons[MONSi(i)].geno & (G_NOGEN | G_UNIQ));
1846.         mlet = def_monsyms[(int) mons[MONSi(i)].mlet].sym;
1847.         if (prev_mlet && prev_mlet != mlet)
1848.             raw_print("");
1849.         Snprintf(nmbuf, sizeof nmbuf, "PM_%s%s",
1850.                  monsdump[MONSi(i)].nm,
1851.                  (i == SPECIAL_PM - 1) ? "" : ",");
1852.         raw_printf("    %*s /* %c seq=%3d, idx=%3d, sym='%c', diff=%2d, freq=%2d[%d] %s */",
1853.                    -nmwidth, nmbuf, (i == MONSi(i)) ? ' ' : '.', i, MONSi(i),
1854.                    mlet, (int) mons[MONSi(i)].difficulty,
1855.                    (int) (mons[MONSi(i)].geno & G_FREQ),
1856.                    (int) mclass_maxf[(int) mons[MONSi(i)].mlet],
1857.                    (special == (G_NOGEN | G_UNIQ)) ? "(G_NOGEN | G_UNIQ)"
1858.                    : (special == G_NOGEN)          ? "(G_NOGEN)"
1859.                    : (special == G_UNIQ)           ? "(G_UNIQ)"
1860.                                                    : "");
1861.         prev_mlet = mlet;
1862.     }
1863.     raw_print("};");
1864.     raw_print("");
1865.     freedynamicdata();
1866. }
1867. 
1868. /* Make one of the multiple types of a given monster class.
1869.    The second parameter specifies a special casing bit mask
1870.    to allow the normal genesis masks to be deactivated.
1871.    Returns Null if no monsters in that class can be made. */
1872. struct permonst *
1873. mkclass(char class, int spc)
1874. {
1875.     return mkclass_aligned(class, spc, A_NONE);
1876. }
1877. 
1878. /* mkclass() with alignment restrictions; used by ndemon() */
1879. struct permonst *
1880. mkclass_aligned(char class, int spc, /* special mons[].geno handling */
1881.                 aligntyp atyp)
1882. {
1883.     int first, last, num = 0;
1884.     int k, nums[SPECIAL_PM + 1]; /* +1: insurance for final return value */
1885.     int maxmlev, gehennom = Inhell != 0;
1886.     unsigned mv_mask, gn_mask;
1887.     boolean zero_freq_for_entire_class;
1888. 
1889.     (void) memset((genericptr_t) nums, 0, sizeof nums);
1890.     maxmlev = level_difficulty() >> 1;
1891.     if (class < 1 || class >= MAXMCLASSES) {
1892.         impossible("mkclass called with bad class!");
1893.         return (struct permonst *) 0;
1894.     }
1895. 
1896.     init_mongen_order();
1897.     /* the following must come after init_mongen_order() */
1898.     zero_freq_for_entire_class = (mclass_maxf[(int) class] == 0);
1899. 
1900.     /*  Assumption #1:  monsters of a given class are contiguous in the
1901.      *                  mons[] array.  Player monsters and quest denizens
1902.      *                  are an exception; mkclass() won't pick them.
1903.      *                  SPECIAL_PM is long worm tail and separates the
1904.      *                  regular monsters from the exceptions.
1905.      */
1906.     for (first = LOW_PM; first < SPECIAL_PM; first++)
1907.         if (mons[MONSi(first)].mlet == class)
1908.             break;
1909.     if (first == SPECIAL_PM) {
1910.         impossible("mkclass found no class %d monsters", class);
1911.         return (struct permonst *) 0;
1912.     }
1913. 
1914.     mv_mask = G_GONE; /* G_GENOD | G_EXTINCT */
1915.     if ((spc & G_IGNORE) != 0) {
1916.         mv_mask = 0; /* mv_mask &= ~G_GONE; */
1917.         /* G_IGNORE is not a mons[].geno mask so get rid of it now */
1918.         spc &= ~G_IGNORE;
1919.     }
1920. 
1921.     /*  Assumption #2:  monsters of a given class are presented in ascending
1922.      *                  order of strength.
1923.      */
1924.     for (last = first; last < SPECIAL_PM && mons[MONSi(last)].mlet == class;
1925.          last++) {
1926.         if (atyp != A_NONE && sgn(mons[MONSi(last)].maligntyp) != sgn(atyp))
1927.             continue;
1928.         /* traditionally mkclass() ignored hell-only and never-in-hell;
1929.            now we usually honor those but not all the time, mostly so that
1930.            the majority of major demons aren't constrained to Gehennom;
1931.            arch- and master liches are always so constrained (for creation;
1932.            lesser liches might grow up into them elsewhere) */
1933.         gn_mask = (G_NOGEN | G_UNIQ);
1934.         if (rn2(9) || class == S_LICH)
1935.             gn_mask |= (gehennom ? G_NOHELL : G_HELL);
1936.         gn_mask &= ~spc;
1937. 
1938.         if (mk_gen_ok(MONSi(last), mv_mask, gn_mask)) {
1939.             /* consider it; don't reject a toostrong() monster if we
1940.                don't have anything yet (num==0) or if it is the same
1941.                (or lower) difficulty as preceding candidate (non-zero
1942.                'num' implies last > first so mons[last-1] is safe);
1943.                sometimes accept it even if high difficulty */
1944.             if (num && montoostrong(MONSi(last), maxmlev)
1945.                 && mons[MONSi(last)].difficulty > mons[MONSi(last - 1)].difficulty
1946.                 && rn2(2))
1947.                 break;
1948.             if ((k = (mons[MONSi(last)].geno & G_FREQ)) > 0
1949.                 || (k = (zero_freq_for_entire_class ? 1 : 0)) > 0) {
1950.                 /* skew towards lower value monsters at lower exp. levels
1951.                    (this used to be done in the next loop, but that didn't
1952.                    work well when multiple species had the same level and
1953.                    were followed by one that was past the bias threshold;
1954.                    cited example was succubus and incubus, where the bias
1955.                    against picking the next demon resulted in incubus
1956.                    being picked nearly twice as often as succubus);
1957.                    we need the '+1' in case the entire set is too high
1958.                    level (really low svl.level hero) */
1959.                 nums[MONSi(last)] = k + 1 - (adj_lev(&mons[MONSi(last)]) > (u.ulevel * 2));
1960.                 num += nums[MONSi(last)];
1961.             }
1962.         }
1963.     }
1964.     if (!num)
1965.         return (struct permonst *) 0;
1966. 
1967.     /* the hard work has already been done; 'num' should hit 0 before
1968.        first reaches last (which is actually one past our last candidate) */
1969.     for (num = rnd(num); first < last; first++)
1970.         if ((num -= nums[MONSi(first)]) <= 0)
1971.             break;
1972. 
1973.     return nums[MONSi(first)] ? &mons[MONSi(first)] : (struct permonst *) 0;
1974. }
1975. #undef MONSi
1976. 
1977. 
1978. /* like mkclass(), but excludes difficulty considerations; used when
1979.    player with polycontrol picks a class instead of a specific type;
1980.    genocided types are avoided but extinct ones are acceptable; we don't
1981.    check polyok() here--caller accepts some choices !polyok() would reject */
1982. int
1983. mkclass_poly(int class)
1984. {
1985.     int first, last, num = 0;
1986.     unsigned gmask;
1987. 
1988.     for (first = LOW_PM; first < SPECIAL_PM; first++)
1989.         if (mons[first].mlet == class)
1990.             break;
1991.     if (first == SPECIAL_PM)
1992.         return NON_PM;
1993. 
1994.     gmask = (G_NOGEN | G_UNIQ);
1995.     /* mkclass() does this on a per monster type basis, but doing that here
1996.        would make the two loops inconsistent with each other for non L */
1997.     if (rn2(9) || class == S_LICH)
1998.         gmask |= (Inhell ? G_NOHELL : G_HELL);
1999. 
2000.     for (last = first; last < SPECIAL_PM && mons[last].mlet == class; last++)
2001.         if (mk_gen_ok(last, G_GENOD, gmask))
2002.             num += mons[last].geno & G_FREQ;
2003.     if (!num)
2004.         return NON_PM;
2005. 
2006.     for (num = rnd(num); num > 0; first++)
2007.         if (mk_gen_ok(first, G_GENOD, gmask))
2008.             num -= mons[first].geno & G_FREQ;
2009.     first--; /* correct an off-by-one error */
2010. 
2011.     return first;
2012. }
2013. 
2014. /* adjust strength of monsters based on u.uz and u.ulevel */
2015. int
2016. adj_lev(struct permonst *ptr)
2017. {
2018.     int tmp, tmp2;
2019. 
2020.     if (ptr == &mons[PM_WIZARD_OF_YENDOR]) {
2021.         /* does not depend on other strengths, but does get stronger
2022.          * every time he is killed
2023.          */
2024.         tmp = ptr->mlevel + svm.mvitals[PM_WIZARD_OF_YENDOR].died;
2025.         if (tmp > 49)
2026.             tmp = 49;
2027.         return tmp;
2028.     }
2029. 
2030.     if ((tmp = ptr->mlevel) > 49)
2031.         return 50; /* "special" demons/devils */
2032.     tmp2 = (level_difficulty() - tmp);
2033.     if (tmp2 < 0)
2034.         tmp--; /* if mlevel > u.uz decrement tmp */
2035.     else
2036.         tmp += (tmp2 / 5); /* else increment 1 per five diff */
2037. 
2038.     tmp2 = (u.ulevel - ptr->mlevel); /* adjust vs. the player */
2039.     if (tmp2 > 0)
2040.         tmp += (tmp2 / 4); /* level as well */
2041. 
2042.     tmp2 = (3 * ((int) ptr->mlevel)) / 2; /* crude upper limit */
2043.     if (tmp2 > 49)
2044.         tmp2 = 49;                                      /* hard upper limit */
2045.     return ((tmp > tmp2) ? tmp2 : (tmp > 0 ? tmp : 0)); /* 0 lower limit */
2046. }
2047. 
2048. /* monster earned experience and will gain some hit points; it might also
2049.    grow into a bigger monster (baby to adult, soldier to officer, etc) */
2050. struct permonst *
2051. grow_up(struct monst *mtmp, struct monst *victim)
2052. {
2053.     int oldtype, newtype, max_increase, cur_increase, lev_limit, hp_threshold;
2054.     unsigned fem;
2055.     struct permonst *ptr = mtmp->data;
2056. 
2057.     /* monster died after killing enemy but before calling this function */
2058.     /* currently possible if killing a gas spore */
2059.     if (DEADMONSTER(mtmp))
2060.         return (struct permonst *) 0;
2061. 
2062.     /* note:  none of the monsters with special hit point calculations
2063.        have both little and big forms (killer bee can't grow into queen
2064.        bee by just killing things, so isn't in the little_to_big list) */
2065.     oldtype = monsndx(ptr);
2066.     newtype = (oldtype == PM_KILLER_BEE && !victim) ? PM_QUEEN_BEE
2067.                                                     : little_to_big(oldtype);
2068. #if 0
2069.     /* gender-neutral PM_CLERIC now */
2070.     if (newtype == PM_PRIEST && mtmp->female)
2071.         newtype = PM_PRIESTESS;
2072. #endif
2073. 
2074.     /* growth limits differ depending on method of advancement */
2075.     if (victim) {                       /* killed a monster */
2076.         /*
2077.          * The HP threshold is the maximum number of hit points for the
2078.          * current level; once exceeded, a level will be gained.
2079.          * Possible bug: if somehow the hit points are already higher
2080.          * than that, monster will gain a level without any increase in HP.
2081.          */
2082.         hp_threshold = mtmp->m_lev * 8; /* normal limit */
2083.         if (!mtmp->m_lev)
2084.             hp_threshold = 4;
2085.         else if (is_golem(ptr)) /* strange creatures */
2086.             hp_threshold = ((mtmp->mhpmax / 10) + 1) * 10 - 1;
2087.         else if (is_home_elemental(ptr))
2088.             hp_threshold *= 3;
2089.         lev_limit = 3 * (int) ptr->mlevel / 2; /* same as adj_lev() */
2090.         /* If they can grow up, be sure the level is high enough for that */
2091.         if (oldtype != newtype && mons[newtype].mlevel > lev_limit)
2092.             lev_limit = (int) mons[newtype].mlevel;
2093.         /* number of hit points to gain; unlike for the player, we put
2094.            the limit at the bottom of the next level rather than the top */
2095.         max_increase = rnd((int) victim->m_lev + 1);
2096.         if (mtmp->mhpmax + max_increase > hp_threshold + 1)
2097.             max_increase = max((hp_threshold + 1) - mtmp->mhpmax, 0);
2098.         cur_increase = (max_increase > 1) ? rn2(max_increase) : 0;
2099.     } else {
2100.         /* a gain level potion or wraith corpse; always go up a level
2101.            unless already at maximum (49 is hard upper limit except
2102.            for demon lords, who start at 50 and can't go any higher) */
2103.         max_increase = cur_increase = rnd(8);
2104.         hp_threshold = 0; /* smaller than `mhpmax + max_increase' */
2105.         lev_limit = 50;   /* recalc below */
2106.     }
2107. 
2108.     mtmp->mhpmax += max_increase;
2109.     mtmp->mhp += cur_increase;
2110.     if (mtmp->mhpmax <= hp_threshold)
2111.         return ptr; /* doesn't gain a level */
2112. 
2113.     if (is_mplayer(ptr))
2114.         lev_limit = 30; /* same as player */
2115.     else if (lev_limit < 5)
2116.         lev_limit = 5; /* arbitrary */
2117.     else if (lev_limit > 49)
2118.         lev_limit = (ptr->mlevel > 49 ? 50 : 49);
2119. 
2120.     if ((int) ++mtmp->m_lev >= mons[newtype].mlevel && newtype != oldtype) {
2121.         ptr = &mons[newtype];
2122.         /* new form might force gender change */
2123.         fem = is_male(ptr) ? 0 : is_female(ptr) ? 1 : mtmp->female;
2124. 
2125.         if (svm.mvitals[newtype].mvflags & G_GENOD) { /* allow G_EXTINCT */
2126.             if (canspotmon(mtmp))
2127.                 pline("As %s grows up into %s, %s %s!", mon_nam(mtmp),
2128.                       an(pmname(ptr, Mgender(mtmp))), mhe(mtmp),
2129.                       nonliving(ptr) ? "expires" : "dies");
2130.             set_mon_data(mtmp, ptr); /* keep svm.mvitals[] accurate */
2131.             mondied(mtmp);
2132.             return (struct permonst *) 0;
2133.         } else if (canspotmon(mtmp)) {
2134.             char buf[BUFSZ];
2135. 
2136.             /* 3.6.1:
2137.              * Temporary (?) hack to fix growing into opposite gender.
2138.              */
2139.             Sprintf(buf, "%s%s",
2140.                     /* deal with female gnome becoming a gnome lord */
2141.                     (mtmp->female && !fem) ? "male "
2142.                         /* or a male gnome becoming a gnome lady
2143.                            (can't happen with 3.6.0 mons[], but perhaps
2144.                            slightly less sexist if prepared for it...) */
2145.                       : (fem && !mtmp->female) ? "female " : "",
2146.                     pmname(ptr, fem));
2147.             pline_mon(mtmp, "%s %s %s.", YMonnam(mtmp),
2148.                       (fem != mtmp->female) ? "changes into"
2149.                                             : humanoid(ptr) ? "becomes"
2150.                                                             : "grows up into",
2151.                       an(buf));
2152.         }
2153.         set_mon_data(mtmp, ptr);
2154.         if (mtmp->cham == oldtype && is_shapeshifter(ptr))
2155.             mtmp->cham = newtype; /* vampire growing into vampire lord */
2156.         newsym(mtmp->mx, mtmp->my);    /* color may change */
2157.         lev_limit = (int) mtmp->m_lev; /* never undo increment */
2158. 
2159.         mtmp->female = fem; /* gender might be changing */
2160.         /* if 'mtmp' is leashed, persistent inventory window needs updating */
2161.         if (mtmp->mleashed)
2162.             update_inventory(); /* x - leash (attached to a <mon>) */
2163.     }
2164. 
2165.     /* sanity checks */
2166.     if ((int) mtmp->m_lev > lev_limit) {
2167.         mtmp->m_lev--; /* undo increment */
2168.         /* HP might have been allowed to grow when it shouldn't */
2169.         if (mtmp->mhpmax == hp_threshold + 1)
2170.             mtmp->mhpmax--;
2171.     }
2172.     if (mtmp->mhpmax > 50 * 8)
2173.         mtmp->mhpmax = 50 * 8; /* absolute limit */
2174.     if (mtmp->mhp > mtmp->mhpmax)
2175.         mtmp->mhp = mtmp->mhpmax;
2176. 
2177.     return ptr;
2178. }
2179. 
2180. struct obj *
2181. mongets(struct monst *mtmp, int otyp)
2182. {
2183.     struct obj *otmp;
2184. 
2185.     if (!otyp)
2186.         return (struct obj *) 0;
2187.     otmp = mksobj(otyp, TRUE, FALSE);
2188.     if (otmp) {
2189.         if (mtmp->data->mlet == S_DEMON) {
2190.             /* demons never get blessed objects */
2191.             if (otmp->blessed)
2192.                 curse(otmp);
2193.         } else if (is_lminion(mtmp)) {
2194.             /* lawful minions don't get cursed, bad, or rusting objects */
2195.             otmp->cursed = FALSE;
2196.             if (otmp->spe < 0)
2197.                 otmp->spe = 0;
2198.             otmp->oerodeproof = 1;
2199.             otmp->oeroded = otmp->oeroded2 = 0;
2200.         } else if (is_mplayer(mtmp->data) && is_sword(otmp)) {
2201.             otmp->spe = (3 + rn2(4));
2202.         }
2203. 
2204.         if (otmp->otyp == CANDELABRUM_OF_INVOCATION) {
2205.             otmp->spe = 0;
2206.             otmp->age = 0L;
2207.             otmp->lamplit = FALSE;
2208.             otmp->blessed = otmp->cursed = FALSE;
2209.         } else if (otmp->otyp == BELL_OF_OPENING) {
2210.             otmp->blessed = otmp->cursed = FALSE;
2211.         } else if (otmp->otyp == SPE_BOOK_OF_THE_DEAD) {
2212.             otmp->blessed = FALSE;
2213.             otmp->cursed = TRUE;
2214.         }
2215. 
2216.         /* leaders don't tolerate inferior quality battle gear */
2217.         if (is_prince(mtmp->data)) {
2218.             if (otmp->oclass == WEAPON_CLASS && otmp->spe < 1)
2219.                 otmp->spe = 1;
2220.             else if (otmp->oclass == ARMOR_CLASS && otmp->spe < 0)
2221.                 otmp->spe = 0;
2222.         }
2223. 
2224.         if (mpickobj(mtmp, otmp)) {
2225.             /* otmp was freed via merging with something else */
2226.             otmp = (struct obj *) 0;
2227.         }
2228.     }
2229.     return otmp;
2230. }
2231. 
2232. int
2233. golemhp(int type)
2234. {
2235.     switch (type) {
2236.     case PM_STRAW_GOLEM:
2237.         return 20;
2238.     case PM_PAPER_GOLEM:
2239.         return 20;
2240.     case PM_ROPE_GOLEM:
2241.         return 30;
2242.     case PM_LEATHER_GOLEM:
2243.         return 40;
2244.     case PM_GOLD_GOLEM:
2245.         return 60;
2246.     case PM_WOOD_GOLEM:
2247.         return 50;
2248.     case PM_FLESH_GOLEM:
2249.         return 40;
2250.     case PM_CLAY_GOLEM:
2251.         return 70;
2252.     case PM_STONE_GOLEM:
2253.         return 100;
2254.     case PM_GLASS_GOLEM:
2255.         return 80;
2256.     case PM_IRON_GOLEM:
2257.         return 120;
2258.     default:
2259.         return 0;
2260.     }
2261. }
2262. 
2263. /*
2264.  *      Alignment vs. yours determines monster's attitude to you.
2265.  *      (Some "animal" types are co-aligned, but also hungry.)
2266.  */
2267. boolean
2268. peace_minded(struct permonst *ptr)
2269. {
2270.     aligntyp mal = ptr->maligntyp, ual = u.ualign.type;
2271. 
2272.     if (always_peaceful(ptr))
2273.         return TRUE;
2274.     if (always_hostile(ptr))
2275.         return FALSE;
2276.     if (ptr->msound == MS_LEADER || ptr->msound == MS_GUARDIAN)
2277.         return TRUE;
2278.     if (ptr->msound == MS_NEMESIS)
2279.         return FALSE;
2280.     if (ptr == &mons[PM_ERINYS])
2281.         return !u.ualign.abuse;
2282. 
2283.     if (race_peaceful(ptr))
2284.         return TRUE;
2285.     if (race_hostile(ptr))
2286.         return FALSE;
2287. 
2288.     /* the monster is hostile if its alignment is different from the
2289.      * player's */
2290.     if (sgn(mal) != sgn(ual))
2291.         return FALSE;
2292. 
2293.     /* Negative monster hostile to player with Amulet. */
2294.     if (mal < A_NEUTRAL && u.uhave.amulet)
2295.         return FALSE;
2296. 
2297.     /* minions are hostile to players that have strayed at all */
2298.     if (is_minion(ptr))
2299.         return (boolean) (u.ualign.record >= 0);
2300. 
2301.     /* Last case:  a chance of a co-aligned monster being
2302.      * hostile.  This chance is greater if the player has strayed
2303.      * (u.ualign.record negative) or the monster is not strongly aligned.
2304.      */
2305.     return (boolean) (!!rn2(16 + (u.ualign.record < -15 ? -15
2306.                                                         : u.ualign.record))
2307.                       && !!rn2(2 + abs(mal)));
2308. }
2309. 
2310. /* Set malign to have the proper effect on player alignment if monster is
2311.  * killed.  Negative numbers mean it's bad to kill this monster; positive
2312.  * numbers mean it's good.  Since there are more hostile monsters than
2313.  * peaceful monsters, the penalty for killing a peaceful monster should be
2314.  * greater than the bonus for killing a hostile monster to maintain balance.
2315.  * Rules:
2316.  *   it's bad to kill peaceful monsters, potentially worse to kill always-
2317.  *      peaceful monsters;
2318.  *   it's never bad to kill a hostile monster, although it may not be good.
2319.  */
2320. void
2321. set_malign(struct monst *mtmp)
2322. {
2323.     schar mal = mtmp->data->maligntyp;
2324.     boolean coaligned;
2325. 
2326.     if (mtmp->ispriest || mtmp->isminion) {
2327.         /* some monsters have individual alignments; check them */
2328.         if (mtmp->ispriest && EPRI(mtmp))
2329.             mal = EPRI(mtmp)->shralign;
2330.         else if (mtmp->isminion && EMIN(mtmp))
2331.             mal = EMIN(mtmp)->min_align;
2332.         /* unless alignment is none, set mal to -5,0,5 */
2333.         /* (see align.h for valid aligntyp values)     */
2334.         if (mal != A_NONE)
2335.             mal *= 5;
2336.     }
2337. 
2338.     coaligned = (sgn(mal) == sgn(u.ualign.type));
2339.     if (mtmp->data->msound == MS_LEADER) {
2340.         mtmp->malign = -20;
2341.     } else if (mal == A_NONE) {
2342.         if (mtmp->mpeaceful)
2343.             mtmp->malign = 0;
2344.         else
2345.             mtmp->malign = 20; /* really hostile */
2346.     } else if (always_peaceful(mtmp->data)) {
2347.         int absmal = abs(mal);
2348.         if (mtmp->mpeaceful)
2349.             mtmp->malign = -3 * max(5, absmal);
2350.         else
2351.             mtmp->malign = 3 * max(5, absmal); /* renegade */
2352.     } else if (always_hostile(mtmp->data)) {
2353.         int absmal = abs(mal);
2354.         if (coaligned)
2355.             mtmp->malign = 0;
2356.         else
2357.             mtmp->malign = max(5, absmal);
2358.     } else if (coaligned) {
2359.         int absmal = abs(mal);
2360.         if (mtmp->mpeaceful)
2361.             mtmp->malign = -3 * max(3, absmal);
2362.         else /* renegade */
2363.             mtmp->malign = max(3, absmal);
2364.     } else /* not coaligned and therefore hostile */
2365.         mtmp->malign = abs(mal);
2366. }
2367. 
2368. /* allocate a new mcorpsenm field for a monster; only need mextra itself */
2369. void
2370. newmcorpsenm(struct monst *mtmp)
2371. {
2372.     if (!mtmp->mextra)
2373.         mtmp->mextra = newmextra();
2374.     MCORPSENM(mtmp) = NON_PM; /* not initialized yet */
2375. }
2376. 
2377. /* release monster's mcorpsenm field; basically a no-op */
2378. void
2379. freemcorpsenm(struct monst *mtmp)
2380. {
2381.     if (has_mcorpsenm(mtmp))
2382.         MCORPSENM(mtmp) = NON_PM;
2383. }
2384. 
2385. static const NEARDATA char syms[] = {
2386.     MAXOCLASSES,  MAXOCLASSES,     RING_CLASS,   WAND_CLASS,   WEAPON_CLASS,
2387.     FOOD_CLASS,   COIN_CLASS,      SCROLL_CLASS, POTION_CLASS, ARMOR_CLASS,
2388.     AMULET_CLASS, TOOL_CLASS,      ROCK_CLASS,   GEM_CLASS,    SPBOOK_CLASS,
2389.     S_MIMIC_DEF,  S_MIMIC_DEF,
2390. };
2391. 
2392. void
2393. set_mimic_sym(struct monst *mtmp)
2394. {
2395.     int typ, roomno, rt;
2396.     unsigned appear, ap_type;
2397.     int s_sym;
2398.     struct obj *otmp;
2399.     int mx, my;
2400. 
2401.     if (!mtmp || Protection_from_shape_changers)
2402.         return;
2403.     mx = mtmp->mx;
2404.     my = mtmp->my;
2405.     typ = levl[mx][my].typ;
2406.     /* only valid for INSIDE of room */
2407.     roomno = levl[mx][my].roomno - ROOMOFFSET;
2408.     if (roomno >= 0)
2409.         rt = svr.rooms[roomno].rtype;
2410. #ifdef SPECIALIZATION
2411.     else if (IS_ROOM(typ))
2412.         rt = OROOM, roomno = 0;
2413. #endif
2414.     else
2415.         rt = 0; /* roomno < 0 case for GCC_WARN */
2416. 
2417.     if (OBJ_AT(mx, my)) {
2418.         ap_type = M_AP_OBJECT;
2419.         appear = svl.level.objects[mx][my]->otyp;
2420.     } else if (IS_DOOR(typ) || IS_WALL(typ) || typ == SDOOR || typ == SCORR) {
2421.         ap_type = M_AP_FURNITURE;
2422.         /*
2423.          *  If there is a wall to the left that connects to this
2424.          *  location, then the mimic mimics a horizontal closed door.
2425.          *  This does not allow doors to be in corners of rooms.
2426.          *  Since rogue has no closed doors, mimic a wall there
2427.          *  (yes, mimics can end up on this level by various means).
2428.          */
2429.         if (mx != 0 && (levl[mx - 1][my].typ == HWALL
2430.                         || levl[mx - 1][my].typ == TLCORNER
2431.                         || levl[mx - 1][my].typ == TRWALL
2432.                         || levl[mx - 1][my].typ == BLCORNER
2433.                         || levl[mx - 1][my].typ == TDWALL
2434.                         || levl[mx - 1][my].typ == CROSSWALL
2435.                         || levl[mx - 1][my].typ == TUWALL))
2436.             appear = Is_rogue_level(&u.uz) ? S_hwall : S_hcdoor;
2437.         else
2438.             appear = Is_rogue_level(&u.uz) ? S_vwall : S_vcdoor;
2439.     } else if (svl.level.flags.is_maze_lev
2440.                && !(In_mines(&u.uz) && in_town(u.ux, u.uy))
2441.                && !In_sokoban(&u.uz) && rn2(2)) {
2442.         ap_type = M_AP_OBJECT;
2443.         appear = STATUE;
2444.     } else if (roomno < 0 && !t_at(mx, my)) {
2445.         ap_type = M_AP_OBJECT;
2446.         appear = BOULDER;
2447.     } else if (rt == ZOO || rt == VAULT) {
2448.         ap_type = M_AP_OBJECT;
2449.         appear = GOLD_PIECE;
2450.     } else if (rt == DELPHI) {
2451.         if (rn2(2)) {
2452.             ap_type = M_AP_OBJECT;
2453.             appear = STATUE;
2454.         } else {
2455.             ap_type = M_AP_FURNITURE;
2456.             appear = S_fountain;
2457.         }
2458.     } else if (rt == TEMPLE) {
2459.         ap_type = M_AP_FURNITURE;
2460.         appear = S_altar;
2461. 
2462.     /*
2463.      * We won't bother with beehives, morgues, barracks, throne rooms
2464.      * since they shouldn't contain too many mimics anyway...
2465.      */
2466. 
2467.     } else if (rt >= SHOPBASE) {
2468.         if (rn2(10) >= depth(&u.uz)) {
2469.             s_sym = S_MIMIC_DEF; /* -> STRANGE_OBJECT */
2470.             goto assign_sym;
2471.         }
2472.         s_sym = get_shop_item(rt - SHOPBASE);
2473.         if (s_sym < 0) {
2474.             ap_type = M_AP_OBJECT;
2475.             appear = -s_sym;
2476.         } else if (rt == FODDERSHOP && s_sym > MAXOCLASSES) {
2477.             /* health food store usually generates pseudo-class
2478.                VEGETARIAN_CLASS which is MAXOCLASSES+1; we don't bother
2479.                trying to select among all possible vegetarian food items */
2480.             ap_type = M_AP_OBJECT;
2481.             appear = rn2(2) ? LUMP_OF_ROYAL_JELLY : SLIME_MOLD;
2482.         } else {
2483.             if (s_sym == RANDOM_CLASS || s_sym >= MAXOCLASSES)
2484.                 s_sym = syms[rn2(SIZE(syms) - 2) + 2];
2485.             goto assign_sym;
2486.         }
2487.     } else {
2488.         s_sym = ROLL_FROM(syms);
2489.  assign_sym:
2490.         if (s_sym == MAXOCLASSES) {
2491.             static const int furnsyms[] = {
2492.                 S_upstair, S_upstair, S_dnstair, S_dnstair,
2493.                 S_altar, S_grave, S_throne, S_sink
2494.             };
2495. 
2496.             ap_type = M_AP_FURNITURE;
2497.             appear = ROLL_FROM(furnsyms);
2498.         } else {
2499.             ap_type = M_AP_OBJECT;
2500.             if (s_sym == S_MIMIC_DEF) {
2501.                 appear = STRANGE_OBJECT;
2502.             } else if (s_sym == COIN_CLASS) {
2503.                 appear = GOLD_PIECE;
2504.             } else {
2505.                 otmp = mkobj((char) s_sym, FALSE);
2506.                 appear = otmp->otyp;
2507.                 /* make sure container contents are free'ed */
2508.                 obfree(otmp, (struct obj *) 0);
2509.             }
2510.         }
2511.     }
2512.     mtmp->m_ap_type = ap_type;
2513.     mtmp->mappearance = appear;
2514.     /* when appearing as an object based on a monster type, pick a shape */
2515.     if (ap_type == M_AP_OBJECT
2516.         && (appear == STATUE || appear == FIGURINE
2517.             || appear == CORPSE || appear == EGG || appear == TIN)) {
2518.         int mndx = rndmonnum(),
2519.             nocorpse_ndx = (svm.mvitals[mndx].mvflags & G_NOCORPSE) != 0;
2520. 
2521.         if (appear == CORPSE && nocorpse_ndx)
2522.             mndx = rn1(PM_WIZARD - PM_ARCHEOLOGIST + 1, PM_ARCHEOLOGIST);
2523.         else if ((appear == EGG && !can_be_hatched(mndx))
2524.                  || (appear == TIN && nocorpse_ndx))
2525.             mndx = NON_PM; /* revert to generic egg or empty tin */
2526. 
2527.         newmcorpsenm(mtmp);
2528.         MCORPSENM(mtmp) = mndx;
2529.     } else if (ap_type == M_AP_OBJECT && appear == SLIME_MOLD) {
2530.         newmcorpsenm(mtmp);
2531.         MCORPSENM(mtmp) = svc.context.current_fruit;
2532.         /* if no objects of this fruit type have been created yet,
2533.            context.current_fruit is available for re-use when the player
2534.            assigns a new fruit name; override that--having a mimic as the
2535.            current_fruit is equivalent to creating an instance of that
2536.            fruit (no-op if a fruit of this type has actually been made) */
2537.         flags.made_fruit = TRUE;
2538.     } else if (ap_type == M_AP_FURNITURE && appear == S_altar) {
2539.         int algn = rn2(3) - 1; /* -1 (A_Cha) or 0 (A_Neu) or +1 (A_Law) */
2540. 
2541.         newmcorpsenm(mtmp);
2542.         MCORPSENM(mtmp) = (Inhell && rn2(3)) ? AM_NONE : Align2amask(algn);
2543.     } else if (has_mcorpsenm(mtmp)) {
2544.         /* don't retain stale value from a previously mimicked shape */
2545.         MCORPSENM(mtmp) = NON_PM;
2546.     }
2547. 
2548.     if (does_block(mx, my, &levl[mx][my]))
2549.         block_point(mx, my);
2550. }
2551. 
2552. /* release monster from bag of tricks; return number of monsters created */
2553. int
2554. bagotricks(
2555.     struct obj *bag,
2556.     boolean tipping, /* caller emptying entirely; affects shop handling */
2557.     int *seencount)  /* secondary output */
2558. {
2559.     int moncount = 0;
2560. 
2561.     if (!bag || bag->otyp != BAG_OF_TRICKS) {
2562.         impossible("bad bag o' tricks");
2563.     } else if (bag->spe < 1) {
2564.         /* if tipping known empty bag, give normal empty container message */
2565.         pline1((tipping && bag->cknown) ? "It's empty." : nothing_happens);
2566.         /* now known to be empty if sufficiently discovered */
2567.         if (bag->dknown && objects[bag->otyp].oc_name_known) {
2568.             bag->cknown = 1;
2569.             update_inventory(); /* for perm_invent */
2570.         }
2571.     } else {
2572.         struct monst *mtmp;
2573.         int creatcnt = 1, seecount = 0;
2574. 
2575.         consume_obj_charge(bag, !tipping);
2576. 
2577.         if (!rn2(23))
2578.             creatcnt += rnd(7);
2579.         do {
2580.             mtmp = makemon((struct permonst *) 0, u.ux, u.uy, NO_MM_FLAGS);
2581.             if (mtmp) {
2582.                 ++moncount;
2583.                 if ((canseemon(mtmp) && (M_AP_TYPE(mtmp) == M_AP_NOTHING
2584.                                          || M_AP_TYPE(mtmp) == M_AP_MONSTER))
2585.                     || sensemon(mtmp))
2586.                     ++seecount;
2587.             }
2588.         } while (--creatcnt > 0);
2589.         if (seecount) {
2590.             if (seencount)
2591.                 *seencount += seecount;
2592.             if (bag->dknown) {
2593.                 makeknown(BAG_OF_TRICKS);
2594.                 update_inventory(); /* for perm_invent */
2595.             }
2596.         } else if (!tipping) {
2597.             pline1(!moncount ? nothing_happens : nothing_seems_to_happen);
2598.         }
2599.     }
2600.     return moncount;
2601. }
2602. 
2603. /* create some or all remaining erinyes around the player */
2604. void
2605. summon_furies(int limit) /* number to create, or 0 to create until extinct */
2606. {
2607.     int i = 0;
2608.     while (mk_gen_ok(PM_ERINYS, G_GONE, 0U) && (i < limit || !limit)) {
2609.         makemon(&mons[PM_ERINYS], u.ux, u.uy, MM_ADJACENTOK | MM_NOWAIT);
2610.         i++;
2611.     }
2612. }
2613. 
2614. /*makemon.c*/