OSDN Git Service

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