OSDN Git Service

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