Source:NetHack 5.0.0/src/zap.c

From NetHackWiki
Jump to navigation Jump to search

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

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

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

1. /* NetHack 5.0	zap.c	$NHDT-Date: 1770949988 2026/02/12 18:33:08 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.584 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Robert Patrick Rankin, 2013. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. 
8. /* Disintegration rays have special treatment; corpses are never left.
9.  * But the routine which calculates the damage is separate from the routine
10.  * which kills the monster.  The damage routine returns this cookie to
11.  * indicate that the monster should be disintegrated.
12.  */
13. #define MAGIC_COOKIE 1000
14. 
15. staticfn int zaptype(int);
16. staticfn void probe_objchain(struct obj *) NO_NNARGS;
17. staticfn boolean zombie_can_dig(coordxy x, coordxy y);
18. staticfn void polyuse(struct obj *, int, int) NO_NNARGS;
19. staticfn void create_polymon(struct obj *, int) NO_NNARGS;
20. staticfn int stone_to_flesh_obj(struct obj *) NONNULLARG1;
21. staticfn boolean zap_updown(struct obj *) NONNULLARG1;
22. staticfn void zhitu(int, int, const char *, coordxy, coordxy) NO_NNARGS;
23. staticfn void revive_egg(struct obj *) NONNULLARG1;
24. staticfn boolean zap_steed(struct obj *) NONNULLARG1;
25. staticfn void skiprange(int, int *, int *) NONNULLPTRS;
26. staticfn void maybe_explode_trap(struct trap *, struct obj *,
27.                                boolean *) NONNULLARG3;
28. staticfn void zap_map(coordxy, coordxy, struct obj *) NONNULLARG3;
29. staticfn void bounce_dir(coordxy, coordxy, int *, int *, int) NO_NNARGS;
30. staticfn int zap_hit(int, int);
31. staticfn void disintegrate_mon(struct monst *, int, const char *) NONNULLARG1;
32. staticfn int adtyp_to_prop(int);
33. staticfn void backfire(struct obj *) NONNULLARG1;
34. staticfn int zap_ok(struct obj *) NO_NNARGS;
35. /* all callers of boxlock_invent() pass a NONNULL obj, and boxlock
36.  * boxlock_invent() calls boxlock() which has nonnull arg. */
37. staticfn void boxlock_invent(struct obj *) NONNULLARG1;
38. staticfn int spell_hit_bonus(int);
39. staticfn int maybe_destroy_item(struct monst *, struct obj *, int) NONNULLPTRS;
40. staticfn boolean destroyable(struct obj *, int);
41. 
42. staticfn void wishcmdassist(int);
43. staticfn void wish_history_menu(char *);
44. 
45. #define ZT_MAGIC_MISSILE (AD_MAGM - 1)
46. #define ZT_FIRE (AD_FIRE - 1)
47. #define ZT_COLD (AD_COLD - 1)
48. #define ZT_SLEEP (AD_SLEE - 1)
49. #define ZT_DEATH (AD_DISN - 1) /* or disintegration */
50. #define ZT_LIGHTNING (AD_ELEC - 1)
51. #define ZT_POISON_GAS (AD_DRST - 1)
52. #define ZT_ACID (AD_ACID - 1)
53. /* 8 and 9 are currently unassigned */
54. 
55. #define ZT_WAND(x) (x)
56. #define ZT_SPELL(x) (10 + (x))
57. #define ZT_BREATH(x) (20 + (x))
58. 
59. #define is_hero_spell(type) ((type) >= 10 && (type) < 20)
60. 
61. #define M_IN_WATER(ptr) ((ptr)->mlet == S_EEL || cant_drown(ptr))
62. 
63. static const char are_blinded_by_the_flash[] = "are blinded by the flash!";
64. 
65. /*
66.  * A positive index means zapped/cast/breathed by hero.
67.  * A negative index means zapped/cast/breathed by a monster, with value
68.  * index fixup beyond abs() needed for wand zaps.  Wand zaps for monster
69.  * use -39..-30 rather than -9..-0 because -0 is ambiguous (same as 0).
70.  */
71. static const char *const flash_types[] = {
72.     "magic missile", /* Wands must be 0-9 */
73.     "bolt of fire", "bolt of cold", "sleep ray", "death ray",
74.     "bolt of lightning", "", "", "", "",
75. 
76.     "magic missile", /* Spell equivalents must be 10-19 */
77.     "fireball", "cone of cold", "sleep ray", "finger of death",
78.     "bolt of lightning", /* there is no spell, used for retribution */
79.     "", "", "", "",
80. 
81.     "blast of missiles", /* Dragon breath equivalents 20-29*/
82.     "blast of fire", "blast of frost", "blast of sleep gas",
83.     "blast of disintegration", "blast of lightning",
84.     "blast of poison gas", "blast of acid", "", ""
85. };
86. 
87. /* convert monster zap/spell/breath value to hero zap/spell/breath value */
88. staticfn int
89. zaptype(int type)
90. {
91.     if (type <= -30 && -39 <= type) /* monster wand zap */
92.         type += 30; /* first convert -39..-30 to -9..0 so that abs()
93.                      * will yield 0..9 (hero wand zap) for it */
94.     type = abs(type);
95.     return type;
96. }
97. 
98. /*
99.  * Recognizing unseen wands by zapping:  in 3.4.3 and earlier, zapping
100.  * most wand types while blind would add that type to the discoveries
101.  * list even if it had never been seen (ie, picked up while blinded
102.  * and shown in inventory as simply "a wand").  This behavior has been
103.  * changed; now such wands won't be discovered.  But if the type is
104.  * already discovered, then the individual wand whose effect was just
105.  * observed will be flagged as if seen.  [You already know wands of
106.  * striking; you zap "a wand" and observe striking effect (presumably
107.  * by sound or touch); it'll become shown in inventory as "a wand of
108.  * striking".]
109.  *
110.  * Unfortunately, the new behavior isn't really correct either.  There
111.  * should be an `eknown' bit for "effect known" added for wands (and
112.  * for potions since quaffing one of a stack is similar) so that the
113.  * particular wand which has been zapped would have its type become
114.  * known (it would change from "a wand" to "a wand of striking", for
115.  * example) without the type becoming discovered or other unknown wands
116.  * of that type showing additional information.  When blindness ends,
117.  * all objects in inventory with the eknown bit set would be discovered
118.  * and other items of the same type would become known as such.
119.  */
120. 
121. /* wand discovery gets special handling when hero is blinded */
122. void
123. learnwand(struct obj *obj)
124. {
125.     /* For a wand (or wand-like tool) zapped by the player, if the
126.        effect was observable (determined by caller; usually seen, but
127.        possibly heard or felt if the hero is blinded) then discover the
128.        object type provided that the object itself is known (as more
129.        than just "a wand").  If object type is already discovered and
130.        we observed the effect, mark the individual wand as having been
131.        seen.  Suppress spells (which use fake spellbook object for `obj')
132.        so that casting a spell won't re-discover its forgotten book. */
133.     if (obj->oclass != SPBOOK_CLASS) {
134.         /* if type already discovered, treat this item has having been seen
135.            even if hero is currently blinded (skips redundant makeknown) */
136.         if (objects[obj->otyp].oc_name_known) {
137.             observe_object(obj); /* will usually be dknown already */
138. 
139.         /* otherwise discover it if item itself has been or can be seen */
140.         } else {
141.             /* in case it was picked up while blind and then zapped without
142.                examining inventory after regaining sight (bypassing xname) */
143.             if (!Blind)
144.                 observe_object(obj);
145.             /* make the discovery iff we know what we're manipulating */
146.             if (obj->dknown)
147.                 makeknown(obj->otyp);
148.         }
149.         update_inventory();
150.     }
151. }
152. 
153. /*
154.  * Routines for IMMEDIATE wands and spells.
155.  * Also RAY or NODIR for wands that are being broken rather than zapped.
156.  */
157. 
158. /* bhitm: monster mtmp was hit by the effect of wand or spell otmp */
159. int
160. bhitm(struct monst *mtmp, struct obj *otmp)
161. {
162.     int ret = 0;
163.     boolean wake = TRUE; /* Most 'zaps' should wake monster */
164.     boolean reveal_invis = FALSE, learn_it = FALSE;
165.     boolean dbldam = Role_if(PM_KNIGHT) && u.uhave.questart;
166.     boolean skilled_spell, helpful_gesture = FALSE;
167.     int dmg, otyp = otmp->otyp; /* otmp is not NULL */
168.     const char *zap_type_text = "spell";
169.     struct obj *obj;
170.     boolean disguised_mimic = (mtmp->data->mlet == S_MIMIC
171.                                && M_AP_TYPE(mtmp) != M_AP_NOTHING);
172.     /* box_or_door(): mimic appearances that have locks */
173. #define box_or_door(monst) \
174.     ((M_AP_TYPE(monst) == M_AP_OBJECT                                   \
175.       && ((monst)->mappearance == CHEST                                 \
176.           || (monst)->mappearance == LARGE_BOX))                        \
177.      || (M_AP_TYPE(monst) == M_AP_FURNITURE                             \
178.          /* is_cmap_door() tests S_symbol values, and            */     \
179.          /* mon->mappearance for furniture contains one of those */     \
180.          && is_cmap_door((monst)->mappearance)))
181. 
182.     if (engulfing_u(mtmp))
183.         reveal_invis = FALSE;
184. 
185.     gn.notonhead = (mtmp->mx != gb.bhitpos.x || mtmp->my != gb.bhitpos.y);
186.     skilled_spell = (otmp->oclass == SPBOOK_CLASS && otmp->blessed);
187. 
188.     switch (otyp) {
189.     case WAN_STRIKING:
190.         zap_type_text = "wand";
191.         FALLTHROUGH;
192.     /*FALLTHRU*/
193.     case SPE_FORCE_BOLT:
194.         reveal_invis = TRUE;
195.         learn_it = cansee(gb.bhitpos.x, gb.bhitpos.y);
196.         if (resists_magm(mtmp)) { /* match effect on player */
197.             if (disguised_mimic && !disguised_as_mon(mtmp))
198.                 seemimic(mtmp);
199.             shieldeff(mtmp->mx, mtmp->my);
200.             pline("Boing!");
201.             /* 5.0: used to 'break' to avoid setting learn_it here */
202.         } else if (u.uswallow || rnd(20) < 10 + find_mac(mtmp)) {
203.             if (disguised_mimic)
204.                 seemimic(mtmp);
205.             dmg = d(2, 12);
206.             if (dbldam)
207.                 dmg *= 2;
208.             if (otyp == SPE_FORCE_BOLT)
209.                 dmg = spell_damage_bonus(dmg);
210.             hit(zap_type_text, mtmp, exclam(dmg));
211.             (void) resist(mtmp, otmp->oclass, dmg, TELL);
212.         } else {
213.             if (!disguised_mimic)
214.                 miss(zap_type_text, mtmp);
215.             learn_it = FALSE;
216.         }
217.         break;
218.     case WAN_SLOW_MONSTER:
219.     case SPE_SLOW_MONSTER:
220.         if (!resist(mtmp, otmp->oclass, 0, NOTELL)) {
221.             if (disguised_mimic)
222.                 seemimic(mtmp);
223.             mon_adjust_speed(mtmp, -1, otmp);
224.             check_gear_next_turn(mtmp); /* might want speed boots */
225. 
226.             if (engulfing_u(mtmp) && is_whirly(mtmp->data)) {
227.                 You("disrupt %s!", mon_nam(mtmp));
228.                 pline("A huge hole opens up...");
229.                 expels(mtmp, mtmp->data, TRUE);
230.             }
231.         }
232.         break;
233.     case WAN_SPEED_MONSTER:
234.         if (!resist(mtmp, otmp->oclass, 0, NOTELL)) {
235.             if (disguised_mimic)
236.                 seemimic(mtmp);
237.             mon_adjust_speed(mtmp, 1, otmp);
238.             check_gear_next_turn(mtmp); /* might want speed boots */
239.         }
240.         /* wake but don't anger a peaceful target */
241.         helpful_gesture = TRUE;
242.         break;
243.     case WAN_UNDEAD_TURNING:
244.     case SPE_TURN_UNDEAD:
245.         wake = FALSE;
246.         if (unturn_dead(mtmp))
247.             wake = TRUE;
248.         if (is_undead(mtmp->data) || is_vampshifter(mtmp)) {
249.             reveal_invis = TRUE;
250.             wake = TRUE;
251.             dmg = rnd(8);
252.             if (dbldam)
253.                 dmg *= 2;
254.             if (otyp == SPE_TURN_UNDEAD)
255.                 dmg = spell_damage_bonus(dmg);
256.             svc.context.bypasses = TRUE; /* for make_corpse() */
257.             if (!resist(mtmp, otmp->oclass, dmg, NOTELL)) {
258.                 if (!DEADMONSTER(mtmp))
259.                     monflee(mtmp, 0, FALSE, TRUE);
260.             }
261.         }
262.         break;
263.     case WAN_POLYMORPH:
264.     case SPE_POLYMORPH:
265.     case POT_POLYMORPH:
266.         if (mtmp->data == &mons[PM_LONG_WORM] && has_mcorpsenm(mtmp)) {
267.             /* if a long worm has mcorpsenm set, it was polymorphed by
268.                the current zap and shouldn't be affected if hit again */
269.             ;
270.         } else if (resists_magm(mtmp)) {
271.             /* magic resistance protects from polymorph traps, so make
272.                it guard against involuntary polymorph attacks too... */
273.             shieldeff_mon(mtmp);
274.         } else if (!resist(mtmp, otmp->oclass, 0, NOTELL)) {
275.             boolean polyspot = (otyp != POT_POLYMORPH),
276.                     give_msg = (!Hallucination
277.                                 && (canseemon(mtmp)
278.                                     || engulfing_u(mtmp)));
279. 
280.             /* dropped inventory (due to death by system shock,
281.                or loss of wielded weapon and/or worn armor due to
282.                limitations of new shape) won't be hit by this zap */
283.             if (polyspot)
284.                 for (obj = mtmp->minvent; obj; obj = obj->nobj)
285.                     bypass_obj(obj);
286. 
287.             /* natural shapechangers aren't affected by system shock
288.                (unless protection from shapechangers is interfering
289.                with their metabolism...) */
290.             if (mtmp->cham == NON_PM && !rn2(25)) {
291.                 if (canseemon(mtmp)) {
292.                     pline("%s shudders!", Monnam(mtmp));
293.                     learn_it = TRUE;
294.                 }
295.                 /* svc.context.bypasses = TRUE; ## for make_corpse() */
296.                 /* no corpse after system shock */
297.                 xkilled(mtmp, XKILL_GIVEMSG | XKILL_NOCORPSE);
298.             } else {
299.                 unsigned ncflags = NO_NC_FLAGS;
300. 
301.                 if (polyspot)
302.                     ncflags |= NC_VIA_WAND_OR_SPELL;
303.                 if (give_msg)
304.                     ncflags |= NC_SHOW_MSG;
305.                 if (newcham(mtmp, (struct permonst *) 0, ncflags) != 0
306.                            /* if shapechange failed because there aren't
307.                               enough eligible candidates (most likely for
308.                               vampshifter), try reverting to original form */
309.                            || (ismnum(mtmp->cham)
310.                                && newcham(mtmp, &mons[mtmp->cham],
311.                                           ncflags) != 0)) {
312.                     if (give_msg && (canspotmon(mtmp)
313.                                      || engulfing_u(mtmp)))
314.                         learn_it = TRUE;
315.                 }
316.             }
317. 
318.             /* do this even if polymorphed failed (otherwise using
319.                flags.mon_polycontrol prompting to force mtmp to remain
320.                'long worm' would prompt again if zap hit another segment) */
321.             if (!DEADMONSTER(mtmp) && mtmp->data == &mons[PM_LONG_WORM]) {
322.                 if (!has_mcorpsenm(mtmp))
323.                     newmcorpsenm(mtmp);
324.                 /* flag to indicate that mtmp became a long worm
325.                    on current zap, so further hits (on mtmp's new
326.                    tail) don't do further transforms */
327.                 MCORPSENM(mtmp) = PM_LONG_WORM;
328.                 /* flag to indicate that cleanup is needed; object
329.                    bypass cleanup also clears mon->mextra->mcorpsenm
330.                    for all long worms on the level */
331.                 svc.context.bypasses = TRUE;
332.             }
333.         }
334.         break;
335.     case WAN_CANCELLATION:
336.     case SPE_CANCELLATION:
337.         if (disguised_mimic)
338.             seemimic(mtmp);
339.         (void) cancel_monst(mtmp, otmp, TRUE, TRUE, FALSE);
340.         break;
341.     case WAN_TELEPORTATION:
342.     case SPE_TELEPORT_AWAY:
343.         if (disguised_mimic)
344.             seemimic(mtmp);
345.         reveal_invis = !u_teleport_mon(mtmp, TRUE);
346.         learn_it = canspotmon(mtmp);
347.         break;
348.     case WAN_MAKE_INVISIBLE: {
349.         int oldinvis = mtmp->minvis;
350.         boolean couldsee = canseemon(mtmp);
351.         char nambuf[BUFSZ];
352. 
353.         if (disguised_mimic)
354.             seemimic(mtmp);
355.         /* format monster's name before altering its visibility */
356.         Strcpy(nambuf, Monnam(mtmp));
357.         mon_set_minvis(mtmp, FALSE);
358.         if (!oldinvis && knowninvisible(mtmp)) {
359.             pline("%s turns transparent!", nambuf);
360.             reveal_invis = TRUE;
361.             learn_it = TRUE;
362.         } else if (couldsee && !canseemon(mtmp)) {
363.             /* keep the immediate effects of make invisible and teleportation
364.                ambiguous by using the same message that's used if we
365.                teleported mtmp (and it ended up somewhere you can't see) */
366.             pline("%s vanishes!", nambuf);
367.         }
368.         break;
369.     }
370.     case WAN_LOCKING:
371.     case SPE_WIZARD_LOCK:
372.         if (disguised_mimic && box_or_door(mtmp))
373.             that_is_a_mimic(mtmp, MIM_REVEAL); /*seemimic()*/
374.         wake = closeholdingtrap(mtmp, &learn_it);
375.         break;
376.     case WAN_PROBING:
377.         wake = FALSE;
378.         reveal_invis = TRUE;
379.         probe_monster(mtmp);
380.         learn_it = TRUE;
381.         break;
382.     case WAN_OPENING:
383.     case SPE_KNOCK:
384.         if (disguised_mimic && box_or_door(mtmp))
385.             that_is_a_mimic(mtmp, MIM_REVEAL); /*seemimic()*/
386.         wake = FALSE; /* don't want immediate counterattack */
387.         if (mtmp == u.ustuck) {
388.             /* zapping either holder/holdee or self [zapyourself()] will
389.                release hero from holder's grasp or holdee from hero's grasp */
390.             release_hold();
391.             learn_it = TRUE;
392. 
393.         /* zap which hits steed will only release saddle if it
394.            doesn't hit a holding or falling trap; playability
395.            here overrides the more logical target ordering */
396.         } else if (openholdingtrap(mtmp, &learn_it)) {
397.             break;
398.         } else if (openfallingtrap(mtmp, TRUE, &learn_it)) {
399.             /* mtmp might now be on the migrating monsters list */
400.             break;
401.         } else if (otyp == SPE_KNOCK) {
402.             wake = TRUE;
403.             ret = 1;
404.             if (mtmp->data->msize < MZ_HUMAN && !m_is_steadfast(mtmp)) {
405.                 if (canseemon(mtmp))
406.                     pline("%s is knocked back!",
407.                           Monnam(mtmp));
408.                 mhurtle(mtmp, mtmp->mx - u.ux, mtmp->my - u.uy, rnd(2));
409.             } else {
410.                 if (canseemon(mtmp))
411.                     pline("%s doesn't budge.", Monnam(mtmp));
412.             }
413.             if (!DEADMONSTER(mtmp)) {
414.                 wakeup(mtmp, !mindless(mtmp->data));
415.                 abuse_dog(mtmp);
416.             }
417.         } else if ((obj = which_armor(mtmp, W_SADDLE)) != 0) {
418.             char buf[BUFSZ];
419. 
420.             Sprintf(buf, "%s %s", s_suffix(Monnam(mtmp)),
421.                     distant_name(obj, xname));
422.             if (cansee(mtmp->mx, mtmp->my)) {
423.                 if (!canspotmon(mtmp))
424.                     Strcpy(buf, An(distant_name(obj, xname)));
425.                 pline("%s falls to the %s.", buf,
426.                       surface(mtmp->mx, mtmp->my));
427.             } else if (canspotmon(mtmp)) {
428.                 pline("%s falls off.", buf);
429.             }
430.             mdrop_obj(mtmp, obj, FALSE);
431.         }
432.         break;
433.     case SPE_HEALING:
434.     case SPE_EXTRA_HEALING: {
435.         int healamt = d(6, otyp == SPE_EXTRA_HEALING ? 8 : 4);
436. 
437.         reveal_invis = TRUE;
438.         if (mtmp->data != &mons[PM_PESTILENCE]) {
439.             int delta = mtmp->mhpmax - mtmp->mhp;
440. 
441.             wake = FALSE; /* wakeup() makes the target angry */
442.             healmon(mtmp, healamt, 0);
443.             /* plain healing must be blessed to cure blindness; extra
444.                healing only needs to not be cursed, so spell always cures
445.                [potions quaffed by monsters behave slightly differently;
446.                we use the rules for the hero here...] */
447.             if (skilled_spell || otyp == SPE_EXTRA_HEALING)
448.                 mcureblindness(mtmp, canseemon(mtmp));
449.             if (canseemon(mtmp)) {
450.                 if (disguised_mimic) {
451.                     if (is_obj_mappear(mtmp, STRANGE_OBJECT)) {
452.                         /* it can do better now */
453.                         set_mimic_sym(mtmp);
454.                         newsym(mtmp->mx, mtmp->my);
455.                     } else
456.                         mimic_hit_msg(mtmp, otyp);
457.                 } else
458.                     pline("%s looks%s better.", Monnam(mtmp),
459.                           otyp == SPE_EXTRA_HEALING ? " much" : "");
460.             }
461.             if (mtmp->mtame && Role_if(PM_HEALER) && (delta > 0)) {
462.                 more_experienced(min(delta, healamt), 0);
463.                 newexplevel();
464.             }
465.             if (mtmp->mtame || mtmp->mpeaceful) {
466.                 adjalign(Role_if(PM_HEALER) ? 1 : sgn(u.ualign.type));
467.             }
468.         } else { /* Pestilence */
469.             /* Pestilence will always resist; damage is half of (healamt/2) */
470.             (void) resist(mtmp, otmp->oclass, healamt / 2, TELL);
471.         }
472.         break;
473.     }
474.     case WAN_LIGHT: /* (broken wand) */
475.         if (flash_hits_mon(mtmp, otmp)) {
476.             learn_it = TRUE;
477.             reveal_invis = TRUE;
478.         }
479.         break;
480.     case WAN_SLEEP: /* (broken wand) */
481.         /* [wakeup() doesn't rouse victims of temporary sleep,
482.            so it's okay to leave `wake' set to TRUE here;
483.            revealing concealed mimic is handled by sleep_monst()] */
484.         reveal_invis = TRUE;
485.         if (sleep_monst(mtmp, d(1 + otmp->spe, 12), WAND_CLASS))
486.             slept_monst(mtmp);
487.         if (!Blind)
488.             learn_it = TRUE;
489.         break;
490.     case SPE_STONE_TO_FLESH:
491.         if (mtmp->data->mlet == S_GOLEM) {
492.             const char *mesg;
493.             char *name = Monnam(mtmp); /* before possible polymorph */
494. 
495.             /* turn stone golem into flesh golem */
496.             if (monsndx(mtmp->data) == PM_STONE_GOLEM
497.                 && newcham(mtmp, &mons[PM_FLESH_GOLEM], NO_NC_FLAGS))
498.                 mesg = "turns to flesh!";
499.             else if (monsndx(mtmp->data) == PM_FLESH_GOLEM)
500.                 mesg = "seems fleshier...";
501.             else
502.                 mesg = "looks rather fleshy for a moment.";
503. 
504.             if (canseemon(mtmp))
505.                 pline("%s %s", name, mesg);
506.         } else if (mtmp->data->mlet == S_MIMIC
507.                    && ((M_AP_TYPE(mtmp) == M_AP_FURNITURE
508.                         && stone_furniture_type(mtmp->mappearance))
509.                        || (M_AP_TYPE(mtmp) == M_AP_OBJECT
510.                            && stone_object_type(mtmp->mappearance)))) {
511.             /* note: if that_is_a_mimic() doesn't get called to reveal the
512.                mimic, wakeup() below will call seemimic() */
513.             if (cansee(mtmp->mx, mtmp->my)) {
514.                 set_msg_xy(mtmp->mx, mtmp->my);
515.                 that_is_a_mimic(mtmp, MIM_REVEAL | MIM_OMIT_WAIT);
516.             }
517.         } else {
518.             wake = FALSE;
519.         }
520.         break;
521.     case SPE_DRAIN_LIFE:
522.         if (disguised_mimic)
523.             seemimic(mtmp);
524.         dmg = monhp_per_lvl(mtmp);
525.         if (dbldam)
526.             dmg *= 2;
527.         if (otyp == SPE_DRAIN_LIFE)
528.             dmg = spell_damage_bonus(dmg);
529.         if (resists_drli(mtmp)) {
530.             shieldeff_mon(mtmp);
531.         } else if (!resist(mtmp, otmp->oclass, dmg, NOTELL)
532.                    && !DEADMONSTER(mtmp)) {
533.             mtmp->mhp -= dmg;
534.             mtmp->mhpmax -= dmg;
535.             /* die if already level 0, regardless of hit points */
536.             if (DEADMONSTER(mtmp) || mtmp->mhpmax <= 0 || mtmp->m_lev < 1) {
537.                 killed(mtmp);
538.             } else {
539.                 mtmp->m_lev--;
540.                 if (canseemon(mtmp))
541.                     pline("%s suddenly seems weaker!", Monnam(mtmp));
542.             }
543.         }
544.         break;
545.     case WAN_NOTHING:
546.         wake = FALSE;
547.         break;
548.     default:
549.         impossible("What an interesting effect (%d)", otyp);
550.         break;
551.     }
552.     if (wake && !DEADMONSTER(mtmp)) {
553.         /* seemimic() is done by wakeup() and might unblock vision */
554.         wakeup(mtmp, helpful_gesture ? FALSE : TRUE);
555.         m_respond(mtmp);
556.         if (mtmp->isshk && !*u.ushops)
557.             hot_pursuit(mtmp);
558.     }
559.     /* note: gb.bhitpos won't be set if swallowed, but that's okay since
560.      * reveal_invis will be false.  We can't use mtmp->mx, my since it
561.      * might be an invisible worm hit on the tail.
562.      */
563.     if (reveal_invis && !DEADMONSTER(mtmp)) {
564.         if (cansee(gb.bhitpos.x, gb.bhitpos.y) && !canspotmon(mtmp))
565.             map_invisible(gb.bhitpos.x, gb.bhitpos.y);
566.     }
567.     /* if effect was observable then discover the wand type provided
568.        that the wand itself has been seen */
569.     if (learn_it)
570.         learnwand(otmp);
571.     return ret;
572. #undef box_or_door
573. }
574. 
575. /* hero is held by a monster or engulfed or holding a monster and has zapped
576.    opening/unlocking magic at holder/engulfer/holdee or at self */
577. void
578. release_hold(void)
579. {
580.     struct monst *mtmp = u.ustuck;
581. 
582.     if (!mtmp) {
583.         impossible("release_hold when not held?");
584.     } else if (u.uswallow) { /* possible for sticky hero to be swallowed */
585.         if (digests(mtmp->data)) {
586.             if (!Blind)
587.                 pline("%s opens its mouth!", Monnam(mtmp));
588.             else
589.                 You_feel("a sudden rush of air!");
590.         }
591.         /* gives "you get regurgitated" or "you get expelled from <mon>" */
592.         expels(mtmp, mtmp->data, TRUE);
593.     } else if (sticks(gy.youmonst.data)) {
594.         /* order matters if 'holding' status condition is enabled;
595.            set_ustuck() will set flag for botl update, You() pline will
596.            trigger a status update with "UHold" removed */
597.         set_ustuck((struct monst *) 0);
598.         You("release %s.", mon_nam(mtmp));
599.     } else { /* held but not swallowed */
600.         char relbuf[BUFSZ];
601. 
602.         unstuck(u.ustuck);
603.         if (!nohands(mtmp->data))
604.             Sprintf(relbuf, "from %s grasp", s_suffix(mon_nam(mtmp)));
605.         else
606.             Sprintf(relbuf, "by %s", mon_nam(mtmp));
607.         You("are released %s.", relbuf);
608.     }
609. }
610. 
611. staticfn void
612. probe_objchain(struct obj *otmp)
613. {
614.     for (; otmp; otmp = otmp->nobj) {
615.         observe_object(otmp); /* treat as "seen" */
616.         if (Is_container(otmp) || otmp->otyp == STATUE) {
617.             otmp->lknown = 1;
618.             if (!SchroedingersBox(otmp))
619.                 otmp->cknown = 1;
620.         } else if (otmp->otyp == TIN)
621.             otmp->known = 1;
622.     }
623. }
624. 
625. void
626. probe_monster(struct monst *mtmp)
627. {
628.     mstatusline(mtmp);
629.     if (gn.notonhead)
630.         return; /* don't show minvent for long worm tail */
631. 
632.     if (mtmp->minvent) {
633.         probe_objchain(mtmp->minvent);
634.         (void) display_minventory(mtmp, MINV_ALL | MINV_NOLET | PICK_NONE,
635.                                   (char *) 0);
636.     } else {
637.         pline("%s is not carrying anything%s.", noit_Monnam(mtmp),
638.               engulfing_u(mtmp) ? " besides you" : "");
639.     }
640. }
641. 
642. /*
643.  * Return the object's physical location.  This only makes sense for
644.  * objects that are currently on the level (i.e. migrating objects
645.  * are nowhere).  By default, only things that can be seen (in hero's
646.  * inventory, monster's inventory, or on the ground) are reported.
647.  * By adding BURIED_TOO and/or CONTAINED_TOO flags, you can also get
648.  * the location of buried and contained objects.  Note that if an
649.  * object is carried by a monster, its reported position may change
650.  * from turn to turn.  This function returns FALSE if the position
651.  * is not available or subject to the constraints above.
652.  */
653. boolean
654. get_obj_location(
655.     struct obj *obj,
656.     coordxy *xp, coordxy *yp,
657.     int locflags)
658. {
659.     switch (obj->where) {
660.     case OBJ_INVENT:
661.         *xp = u.ux;
662.         *yp = u.uy;
663.         return TRUE;
664.     case OBJ_FLOOR:
665.         *xp = obj->ox;
666.         *yp = obj->oy;
667.         return TRUE;
668.     case OBJ_MINVENT:
669.         if (obj->ocarry->mx) {
670.             *xp = obj->ocarry->mx;
671.             *yp = obj->ocarry->my;
672.             return TRUE;
673.         }
674.         break; /* !mx => migrating monster */
675.     case OBJ_BURIED:
676.         if (locflags & BURIED_TOO) {
677.             *xp = obj->ox;
678.             *yp = obj->oy;
679.             return TRUE;
680.         }
681.         break;
682.     case OBJ_CONTAINED:
683.         if (locflags & CONTAINED_TOO)
684.             return get_obj_location(obj->ocontainer, xp, yp, locflags);
685.         break;
686.     }
687.     *xp = *yp = 0;
688.     return FALSE;
689. }
690. 
691. boolean
692. get_mon_location(
693.     struct monst *mon,
694.     coordxy *xp, coordxy *yp,
695.     int locflags) /* non-zero means get location even if monster is buried */
696. {
697.     if (mon == &gy.youmonst || (u.usteed && mon == u.usteed)) {
698.         *xp = u.ux;
699.         *yp = u.uy;
700.         return TRUE;
701.     } else if (mon->mx > 0 && (!mon->mburied || locflags)) {
702.         *xp = mon->mx;
703.         *yp = mon->my;
704.         return TRUE;
705.     } else { /* migrating or buried */
706.         *xp = *yp = 0;
707.         return FALSE;
708.     }
709. }
710. 
711. /* used by revive() and animate_statue() */
712. struct monst *
713. montraits(
714.     struct obj *obj,
715.     coord *cc,
716.     boolean adjacentok) /* False: at obj's spot only,
717.                          * True: nearby is allowed */
718. {
719.     struct monst *mtmp = (struct monst *) 0,
720.                  *mtmp2 = has_omonst(obj) ? get_mtraits(obj, TRUE) : 0;
721. 
722.     if (mtmp2) {
723.         /* save_mtraits() validated mtmp2->mnum */
724.         mtmp2->data = &mons[mtmp2->mnum];
725. 
726.         if (mtmp2->mhpmax > 0 || is_rider(mtmp2->data)) {
727.             mtmp = makemon(mtmp2->data, cc->x, cc->y,
728.                            (NO_MINVENT | MM_NOWAIT | MM_NOCOUNTBIRTH
729.                             /* in case mtmp2 is a long worm; saved traits for
730.                                long worm don't include tail segments so don't
731.                                give mtmp any; it will be given a new 'wormno'
732.                                though (unless those are exhausted) so be able
733.                                to grow new tail segments */
734.                             | MM_NOTAIL | MM_NOMSG
735.                             | (adjacentok ? MM_ADJACENTOK : 0)));
736.         }
737.         if (!mtmp) {
738.             /* mtmp2 is a copy of obj's object->oextra->omonst extension
739.                and is not on the map or on any monst lists */
740.             dealloc_monst(mtmp2);
741.             return (struct monst *) 0;
742.         }
743. 
744.         /* heal the monster; lower than normal level might come from
745.            adj_lev() but we assume it has come from 'mtmp' being level
746.            drained before finally killed; give a chance to restore
747.            some levels so that trolls and Riders can't be drained to
748.            level 0 and then trivially killed repeatedly */
749.         if ((int) mtmp->m_lev < mtmp->data->mlevel) {
750.             int ltmp = rnd(mtmp->data->mlevel + 1);
751. 
752.             if (ltmp > (int) mtmp->m_lev) {
753.                 while ((int) mtmp->m_lev < ltmp) {
754.                     mtmp->m_lev++;
755.                     mtmp->mhpmax += monhp_per_lvl(mtmp);
756.                 }
757.                 mtmp2->m_lev = mtmp->m_lev;
758.             }
759.         }
760.         if (mtmp->mhpmax > mtmp2->mhpmax) /* &&is_rider(mtmp2->data)*/
761.             mtmp2->mhpmax = mtmp->mhpmax;
762.         mtmp2->mhp = mtmp2->mhpmax;
763.         /* Get these ones from mtmp */
764.         mtmp2->minvent = mtmp->minvent; /*redundant*/
765.         /* monster ID is available if the monster died in the current
766.            game, but will be zero if the corpse was in a bones level
767.            (we cleared it when loading bones) */
768.         if (mtmp->m_id) {
769.             mtmp2->m_id = mtmp->m_id;
770.             /* might be bringing quest leader back to life */
771.             if (svq.quest_status.leader_is_dead
772.                 /* leader_is_dead implies leader_m_id is valid */
773.                 && mtmp2->m_id == svq.quest_status.leader_m_id)
774.                 svq.quest_status.leader_is_dead = FALSE;
775.         }
776.         mtmp2->mx = mtmp->mx;
777.         mtmp2->my = mtmp->my;
778.         mtmp2->mux = mtmp->mux;
779.         mtmp2->muy = mtmp->muy;
780.         mtmp2->mw = mtmp->mw;
781.         mtmp2->wormno = mtmp->wormno;
782.         mtmp2->misc_worn_check = mtmp->misc_worn_check;
783.         mtmp2->weapon_check = mtmp->weapon_check;
784.         mtmp2->mtrapseen = mtmp->mtrapseen;
785.         mtmp2->mflee = mtmp->mflee;
786.         mtmp2->mburied = mtmp->mburied;
787.         mtmp2->mundetected = mtmp->mundetected;
788.         mtmp2->mfleetim = mtmp->mfleetim;
789.         mtmp2->mlstmv = mtmp->mlstmv;
790.         mtmp2->m_ap_type = mtmp->m_ap_type;
791.         /* set these ones explicitly */
792.         mtmp2->mrevived = 1;
793.         mtmp2->mavenge = 0;
794.         mtmp2->meating = 0;
795.         mtmp2->mleashed = 0;
796.         mtmp2->mtrapped = 0;
797.         mtmp2->msleeping = 0;
798.         mtmp2->mfrozen = 0;
799.         mtmp2->mcanmove = 1;
800.         /* most cancelled monsters return to normal,
801.            but some need to stay cancelled */
802.         if (!dmgtype(mtmp2->data, AD_SEDU)
803.             && (!SYSOPT_SEDUCE || !dmgtype(mtmp2->data, AD_SSEX)))
804.             mtmp2->mcan = 0;
805.         mtmp2->mcansee = 1; /* set like in makemon */
806.         mtmp2->mblinded = 0;
807.         mtmp2->mstun = 0;
808.         mtmp2->mconf = 0;
809.         /* when traits are for a shopkeeper, dummy monster 'mtmp' won't
810.            have necessary eshk data for replmon() -> replshk() */
811.         if (mtmp2->isshk) {
812.             neweshk(mtmp);
813.             *ESHK(mtmp) = *ESHK(mtmp2);
814.             if (ESHK(mtmp2)->bill_p != 0
815.                 && ESHK(mtmp2)->bill_p != (struct bill_x *) -1000)
816.                 ESHK(mtmp)->bill_p = &(ESHK(mtmp)->bill[0]);
817.             mtmp->isshk = 1;
818.         }
819.         replmon(mtmp, mtmp2);
820.         newsym(mtmp2->mx, mtmp2->my); /* Might now be invisible */
821. 
822.         /* in case Protection_from_shape_changers is different
823.            now than it was when the traits were stored */
824.         restore_cham(mtmp2);
825.     }
826.     return mtmp2;
827. }
828. 
829. /*
830.  * get_container_location() returns the following information
831.  * about the outermost container:
832.  * loc argument gets set to:
833.  *      OBJ_INVENT      if in hero's inventory; return 0.
834.  *      OBJ_FLOOR       if on the floor; return 0.
835.  *      OBJ_BURIED      if buried; return 0.
836.  *      OBJ_MINVENT     if in monster's inventory; return monster.
837.  * container_nesting is updated with the nesting depth of the containers
838.  * if applicable.
839.  */
840. struct monst *
841. get_container_location(
842.     struct obj *obj,
843.     int *loc,
844.     int *container_nesting)
845. {
846.     if (container_nesting)
847.         *container_nesting = 0;
848.     while (obj && obj->where == OBJ_CONTAINED) {
849.         if (container_nesting)
850.             *container_nesting += 1;
851.         obj = obj->ocontainer;
852.     }
853.     if (obj) {
854.         *loc = obj->where; /* outermost container's location */
855.         if (obj->where == OBJ_MINVENT)
856.             return obj->ocarry;
857.     }
858.     return (struct monst *) 0;
859. }
860. 
861. /* can zombie dig the location at x,y */
862. staticfn boolean
863. zombie_can_dig(coordxy x, coordxy y)
864. {
865.     if (isok(x, y)) {
866.         schar typ = levl[x][y].typ;
867.         struct trap *ttmp;
868. 
869.         if ((ttmp = t_at(x, y)) != 0)
870.             return FALSE;
871.         if (typ == ROOM || typ == CORR || typ == GRAVE)
872.             return TRUE;
873.     }
874.     return FALSE;
875. }
876. 
877. /*
878.  * Attempt to revive the given corpse, return the revived monster if
879.  * successful.  Note: this does NOT use up the corpse if it fails.
880.  * If corpse->quan is more than 1, only one corpse will be affected
881.  * and only one monster will be resurrected.
882.  */
883. struct monst *
884. revive(struct obj *corpse, boolean by_hero)
885. {
886.     struct monst *mtmp = 0;
887.     struct permonst *mptr;
888.     struct obj *container;
889.     coord xy;
890.     coordxy x, y;
891.     boolean one_of;
892.     mmflags_nht mmflags = NO_MINVENT | MM_NOWAIT | MM_NOMSG;
893.     int montype, cgend, container_nesting = 0;
894.     boolean is_zomb;
895. 
896.     if (corpse->otyp != CORPSE) {
897.         impossible("Attempting to revive %s?", xname(corpse));
898.         return (struct monst *) 0;
899.     }
900.     montype = corpse->corpsenm;
901.     /* treat buried auto-reviver (troll, Rider?) like a zombie
902.        so that it can dig itself out of the ground if it revives */
903.     is_zomb = mons[montype].mlet == S_ZOMBIE
904.               || (corpse->where == OBJ_BURIED && is_reviver(&mons[montype]));
905. 
906.     /* if this corpse is being eaten, stop doing that; this should be done
907.        after makemon() succeeds and skipped if it fails, but waiting until
908.        we know the result for that would be too late */
909.     cant_finish_meal(corpse);
910. 
911.     x = y = 0;
912.     if (corpse->where != OBJ_CONTAINED) {
913.         int locflags = is_zomb ? BURIED_TOO : 0;
914. 
915.         /* only for invent, minvent, or floor, or if zombie, buried */
916.         container = 0;
917.         (void) get_obj_location(corpse, &x, &y, locflags);
918.     } else {
919.         /* deal with corpses in [possibly nested] containers */
920.         struct monst *carrier;
921.         int holder = OBJ_FREE;
922. 
923.         container = corpse->ocontainer;
924.         carrier =
925.             get_container_location(container, &holder, &container_nesting);
926.         switch (holder) {
927.         case OBJ_MINVENT:
928.             x = carrier->mx, y = carrier->my;
929.             break;
930.         case OBJ_INVENT:
931.             x = u.ux, y = u.uy;
932.             break;
933.         case OBJ_FLOOR:
934.             (void) get_obj_location(corpse, &x, &y, CONTAINED_TOO);
935.             break;
936.         default:
937.             break; /* x,y are 0 */
938.         }
939.     }
940.     if (x) /* update corpse's location now that we're sure where it is */
941.         corpse->ox = x, corpse->oy = y;
942. 
943.     if (!x
944.         /* Rules for revival from containers:
945.          *  - the container cannot be locked
946.          *  - the container cannot be heavily nested (>2 is arbitrary)
947.          *  - the container cannot be a statue or bag of holding
948.          *    (except in very rare cases for the latter)
949.          */
950.         || (container && (container->olocked || container_nesting > 2
951.                           || container->otyp == STATUE
952.                           || (container->otyp == BAG_OF_HOLDING && rn2(40))))
953.         /* if buried zombie cannot dig itself out, do not revive */
954.         || (is_zomb && corpse->where == OBJ_BURIED && !zombie_can_dig(x, y)))
955.         return (struct monst *) 0;
956. 
957.     /* prepare for the monster */
958.     mptr = &mons[montype];
959.     /* [should probably handle recorporealization first; if corpse and
960.        ghost are at same location, revived creature shouldn't be bumped
961.        to an adjacent spot by ghost which joins with it] */
962.     if (MON_AT(x, y)) {
963.         if (enexto(&xy, x, y, mptr))
964.             x = xy.x, y = xy.y;
965.     }
966. 
967.     if (corpse->norevive
968.         || (mons[montype].mlet == S_EEL && !IS_POOL(levl[x][y].typ))) {
969.         if (cansee(x, y))
970.             pline("%s twitches feebly.",
971.                 upstart(corpse_xname(corpse, (const char *) 0, CXN_PFX_THE)));
972.         return (struct monst *) 0;
973.     }
974. 
975.     /* applicable when montraits/corpse->oextra->omonst aren't used */
976.     cgend = (corpse->spe & CORPSTAT_GENDER);
977.     if (cgend == CORPSTAT_MALE)
978.         mmflags |= MM_MALE;
979.     else if (cgend == CORPSTAT_FEMALE)
980.         mmflags |= MM_FEMALE;
981. 
982.     if (cant_revive(&montype, TRUE, corpse)) {
983.         /* make a zombie or doppelganger instead */
984.         /* note: montype has changed; mptr keeps old value for newcham() */
985.         mtmp = makemon(&mons[montype], x, y, mmflags);
986.         if (mtmp) {
987.             /* skip ghost handling */
988.             if (has_omid(corpse))
989.                 free_omid(corpse);
990.             if (has_omonst(corpse))
991.                 free_omonst(corpse);
992.             if (mtmp->cham == PM_DOPPELGANGER) {
993.                 /* change shape to match the corpse */
994.                 (void) newcham(mtmp, mptr, NO_NC_FLAGS);
995.             } else if (mtmp->data->mlet == S_ZOMBIE) {
996.                 mtmp->mhp = mtmp->mhpmax = 100;
997.                 mon_adjust_speed(mtmp, 2, (struct obj *) 0); /* MFAST */
998.             }
999.         }
1000.     } else if (has_omonst(corpse)) {
1001.         /* use saved traits */
1002.         xy.x = x, xy.y = y;
1003.         mtmp = montraits(corpse, &xy, FALSE);
1004.         if (mtmp && mtmp->mtame && !mtmp->isminion)
1005.             wary_dog(mtmp, TRUE);
1006.     } else {
1007.         /* make a new monster */
1008.         mtmp = makemon(mptr, x, y, mmflags | MM_NOCOUNTBIRTH);
1009.     }
1010.     if (!mtmp)
1011.         return (struct monst *) 0;
1012. 
1013.     /* hiders shouldn't already be re-hidden when they revive */
1014.     if (mtmp->mundetected) {
1015.         mtmp->mundetected = 0;
1016.         newsym(mtmp->mx, mtmp->my);
1017.     }
1018.     if (M_AP_TYPE(mtmp))
1019.         seemimic(mtmp);
1020. 
1021.     one_of = (corpse->quan > 1L);
1022.     if (one_of)
1023.         corpse = splitobj(corpse, 1L);
1024. 
1025.     /* if this is caused by the hero there might be a shop charge */
1026.     if (by_hero) {
1027.         struct monst *shkp = 0;
1028. 
1029.         x = corpse->ox, y = corpse->oy;
1030.         if (costly_spot(x, y)
1031.             && (carried(corpse) ? corpse->unpaid : !corpse->no_charge))
1032.             shkp = shop_keeper(*in_rooms(x, y, SHOPBASE));
1033. 
1034.         if (cansee(x, y)) {
1035.             char buf[BUFSZ];
1036. 
1037.             Strcpy(buf, one_of ? "one of " : "");
1038.             /* shk_your: "the " or "your " or "<mon>'s " or "<Shk>'s ".
1039.                If the result is "Shk's " then it will be ambiguous:
1040.                is Shk the mon carrying it, or does Shk's shop own it?
1041.                Let's not worry about that... */
1042.             (void) shk_your(eos(buf), corpse);
1043.             if (one_of)
1044.                 corpse->quan++; /* force plural */
1045.             Strcat(buf, corpse_xname(corpse, (const char *) 0, CXN_NO_PFX));
1046.             if (one_of) /* could be simplified to corpse->quan = 1L; */
1047.                 corpse->quan--;
1048.             pline("%s glows iridescently.", upstart(buf));
1049.             iflags.last_msg = PLNMSG_OBJ_GLOWS; /* usually for BUC change */
1050.         } else if (shkp) {
1051.             /* need some prior description of the corpse since
1052.                stolen_value() will refer to the object as "it" */
1053.             pline("A corpse is resuscitated.");
1054.         }
1055.         /* don't charge for shopkeeper's own corpse if we just revived him */
1056.         if (shkp && mtmp != shkp)
1057.             (void) stolen_value(corpse, x, y, (boolean) shkp->mpeaceful,
1058.                                 FALSE);
1059. 
1060.         /* [we don't give any comparable message about the corpse for
1061.            the !by_hero case because caller might have already done so] */
1062.     }
1063. 
1064.     /* handle recorporealization of an active ghost */
1065.     if (has_omid(corpse)) {
1066.         unsigned m_id;
1067.         struct monst *ghost;
1068.         struct obj *otmp;
1069. 
1070.         m_id = OMID(corpse);
1071.         ghost = find_mid(m_id, FM_FMON);
1072.         if (ghost && ghost->data == &mons[PM_GHOST]) {
1073.             if (canseemon(ghost))
1074.                 pline("%s is suddenly drawn into its former body!",
1075.                       Monnam(ghost));
1076.             /* transfer the ghost's inventory along with it */
1077.             while ((otmp = ghost->minvent) != 0) {
1078.                 obj_extract_self(otmp);
1079.                 add_to_minv(mtmp, otmp);
1080.             }
1081.             /* tame the revived monster if its ghost was tame */
1082.             if (ghost->mtame && !mtmp->mtame) {
1083.                 if (tamedog(mtmp, (struct obj *) 0, FALSE)) {
1084.                     /* ghost's edog data is ignored */
1085.                     mtmp->mtame = ghost->mtame;
1086.                 }
1087.             }
1088.             /* was ghost, now alive, it's all very confusing */
1089.             mtmp->mconf = 1;
1090.             /* separate ghost monster no longer exists */
1091.             mongone(ghost);
1092.         }
1093.         free_omid(corpse);
1094.     }
1095. 
1096.     /* monster retains its name */
1097.     if (has_oname(corpse) && !unique_corpstat(mtmp->data))
1098.         mtmp = christen_monst(mtmp, ONAME(corpse));
1099.     /* partially eaten corpse yields wounded monster */
1100.     if (corpse->oeaten)
1101.         mtmp->mhp = eaten_stat(mtmp->mhp, corpse);
1102.     /* track that this monster was revived at least once */
1103.     mtmp->mrevived = 1;
1104. 
1105.     /* finally, get rid of the corpse--it's gone now */
1106.     switch (corpse->where) {
1107.     case OBJ_INVENT:
1108.         useup(corpse);
1109.         break;
1110.     case OBJ_FLOOR:
1111.         /* not useupf(), which charges;
1112.            delobj() won't use up a Rider's corpse, delobj_core(,TRUE) will */
1113.         delobj_core(corpse, TRUE); /* for floor, also calls newsym() */
1114.         break;
1115.     case OBJ_MINVENT:
1116.         m_useup(corpse->ocarry, corpse);
1117.         break;
1118.     case OBJ_CONTAINED:
1119.         /* obj_extract_self() will update corpse->ocontainer->owt */
1120.         obj_extract_self(corpse);
1121.         obfree(corpse, (struct obj *) 0);
1122.         break;
1123.     case OBJ_BURIED:
1124.         if (is_zomb) {
1125.             obj_extract_self(corpse);
1126.             obfree(corpse, (struct obj *) 0);
1127.             break;
1128.         }
1129.         FALLTHROUGH;
1130.         /*FALLTHRU*/
1131.     case OBJ_FREE:
1132.     case OBJ_MIGRATING:
1133.     case OBJ_ONBILL:
1134.     case OBJ_LUAFREE:
1135.     default:
1136.         panic("revive default case %d", (int) corpse->where);
1137.     }
1138. 
1139.     return mtmp;
1140. }
1141. 
1142. staticfn void
1143. revive_egg(struct obj *obj) /* nonnull */
1144. {
1145.     /*
1146.      * Note: generic eggs with corpsenm set to NON_PM will never hatch.
1147.      */
1148.     if (obj->otyp != EGG)
1149.         return;
1150.     if (obj->corpsenm != NON_PM && !dead_species(obj->corpsenm, TRUE))
1151.         attach_egg_hatch_timeout(obj, 0L);
1152. }
1153. 
1154. /* try to revive all corpses and eggs carried by `mon' */
1155. int
1156. unturn_dead(struct monst *mon)
1157. {
1158.     struct obj *otmp, *otmp2;
1159.     struct monst *mtmp2;
1160.     char owner[BUFSZ], corpse[BUFSZ];
1161.     unsigned save_norevive;
1162.     boolean youseeit, different_type, is_u = (mon == &gy.youmonst);
1163.     int corpsenm, res = 0;
1164. 
1165.     youseeit = is_u ? TRUE : canseemon(mon);
1166.     otmp2 = is_u ? gi.invent : mon->minvent;
1167.     owner[0] = corpse[0] = '\0'; /* lint suppression */
1168. 
1169.     while ((otmp = otmp2) != 0) {
1170.         otmp2 = otmp->nobj;
1171.         if (otmp->otyp == EGG)
1172.             revive_egg(otmp);
1173.         if (otmp->otyp != CORPSE)
1174.             continue;
1175.         /* save the name; the object is liable to go away */
1176.         if (youseeit) {
1177.             Strcpy(corpse, corpse_xname(otmp, (const char *) 0, CXN_NORMAL));
1178.             /* shk_your/Shk_Your produces a value with a trailing space */
1179.             if (otmp->quan > 1L) {
1180.                 Strcpy(owner, "One of ");
1181.                 (void) shk_your(eos(owner), otmp);
1182.             } else
1183.                 (void) Shk_Your(owner, otmp);
1184.         }
1185.         /* for a stack, only one is revived; if is_u, revive() calls
1186.            useup() which calls update_inventory() but not encumber_msg() */
1187.         corpsenm = otmp->corpsenm;
1188.         /* norevive applies to revive timer, not to explicit unturn_dead() */
1189.         save_norevive = otmp->norevive;
1190.         otmp->norevive = 0;
1191. 
1192.         if ((mtmp2 = revive(otmp, !svc.context.mon_moving)) != 0) {
1193.             ++res;
1194.             /* might get revived as a zombie rather than corpse's monster */
1195.             different_type = (mtmp2->data != &mons[corpsenm]);
1196.             if (iflags.last_msg == PLNMSG_OBJ_GLOWS) {
1197.                 /* when hero zaps undead turning at self (or breaks
1198.                    non-empty wand), revive() reports "[one of] your <mon>
1199.                    corpse[s] glows iridescently"; override saved corpse
1200.                    and owner names to say "It comes alive" [note: we did
1201.                    earlier setup because corpse gets used up but need to
1202.                    do the override here after revive() sets 'last_msg'] */
1203.                 Strcpy(corpse, "It");
1204.                 owner[0] = '\0';
1205.             }
1206.             if (youseeit)
1207.                 pline("%s%s suddenly %s%s%s!", owner, corpse,
1208.                       nonliving(mtmp2->data) ? "reanimates" : "comes alive",
1209.                       different_type ? " as " : "",
1210.                       different_type ? an(mon_pmname(mtmp2)) : "");
1211.             else if (canseemon(mtmp2))
1212.                 pline("%s suddenly appears!", Amonnam(mtmp2));
1213.         } else {
1214.             /* revival failed; corpse 'otmp' is intact */
1215.             otmp->norevive = save_norevive ? 1 : 0;
1216.         }
1217.     }
1218.     if (is_u && res)
1219.         encumber_msg();
1220. 
1221.     return res;
1222. }
1223. 
1224. void
1225. unturn_you(void)
1226. {
1227.     (void) unturn_dead(&gy.youmonst); /* hit carried corpses and eggs */
1228. 
1229.     if (is_undead(gy.youmonst.data)) {
1230.         You_feel("frightened and %sstunned.", Stunned ? "even more " : "");
1231.         make_stunned((HStun & TIMEOUT) + (long) rnd(30), FALSE);
1232.     } else {
1233.         You("shudder in dread.");
1234.     }
1235. }
1236. 
1237. /* cancel obj, possibly carried by you or a monster */
1238. void
1239. cancel_item(struct obj *obj)
1240. {
1241.     int otyp = obj->otyp;
1242. 
1243.     if (carried(obj)) {
1244.         /* handle items being worn by hero */
1245.         switch (otyp) {
1246.         case RIN_GAIN_STRENGTH:
1247.             if ((obj->owornmask & W_RING) != 0L) {
1248.                 ABON(A_STR) -= obj->spe;
1249.                 disp.botl = TRUE;
1250.             }
1251.             break;
1252.         case RIN_GAIN_CONSTITUTION:
1253.             if ((obj->owornmask & W_RING) != 0L) {
1254.                 ABON(A_CON) -= obj->spe;
1255.                 disp.botl = TRUE;
1256.             }
1257.             break;
1258.         case RIN_ADORNMENT:
1259.             if ((obj->owornmask & W_RING) != 0L) {
1260.                 ABON(A_CHA) -= obj->spe;
1261.                 disp.botl = TRUE;
1262.             }
1263.             break;
1264.         case RIN_INCREASE_ACCURACY:
1265.             if ((obj->owornmask & W_RING) != 0L)
1266.                 u.uhitinc -= obj->spe;
1267.             break;
1268.         case RIN_INCREASE_DAMAGE:
1269.             if ((obj->owornmask & W_RING) != 0L)
1270.                 u.udaminc -= obj->spe;
1271.             break;
1272.         case RIN_PROTECTION:
1273.             if ((obj->owornmask & W_RING) != 0L)
1274.                 disp.botl = TRUE;
1275.             break;
1276.         case GAUNTLETS_OF_DEXTERITY:
1277.             if ((obj->owornmask & W_ARMG) != 0L) {
1278.                 ABON(A_DEX) -= obj->spe;
1279.                 disp.botl = TRUE;
1280.             }
1281.             break;
1282.         case HELM_OF_BRILLIANCE:
1283.             if ((obj->owornmask & W_ARMH) != 0L) {
1284.                 ABON(A_INT) -= obj->spe;
1285.                 ABON(A_WIS) -= obj->spe;
1286.                 disp.botl = TRUE;
1287.             }
1288.             break;
1289.         default:
1290.             if ((obj->owornmask & W_ARMOR) != 0L) /* AC */
1291.                 disp.botl = TRUE;
1292.             break;
1293.         }
1294.     }
1295.     /* cancelled item might not be in hero's possession but
1296.        cancellation is presumed to be instigated by hero */
1297.     if (objects[otyp].oc_magic
1298.         || (obj->spe && (obj->oclass == ARMOR_CLASS
1299.                          || obj->oclass == WEAPON_CLASS || is_weptool(obj)))
1300.         || otyp == POT_ACID
1301.         || otyp == POT_SICKNESS
1302.         || (otyp == POT_WATER && (obj->blessed || obj->cursed))
1303.         /* not magic; cancels to blank spellbook */
1304.         || otyp == SPE_NOVEL) {
1305.         int cancelled_spe = (obj->oclass == WAND_CLASS
1306.                              || otyp == CRYSTAL_BALL) ? -1 : 0;
1307. 
1308.         if (obj->spe != cancelled_spe
1309.             && otyp != WAN_CANCELLATION /* can't cancel cancellation */
1310.             && otyp != MAGIC_LAMP /* cancelling doesn't remove djinni */
1311.             && otyp != CANDELABRUM_OF_INVOCATION) {
1312.             costly_alteration(obj, COST_CANCEL);
1313.             obj->spe = cancelled_spe;
1314.         }
1315.         switch (obj->oclass) {
1316.         case SCROLL_CLASS:
1317.             costly_alteration(obj, COST_CANCEL);
1318.             obj->otyp = SCR_BLANK_PAPER;
1319.             obj->spe = 0;
1320.             break;
1321.         case SPBOOK_CLASS:
1322.             if (otyp != SPE_CANCELLATION && otyp != SPE_BOOK_OF_THE_DEAD) {
1323.                 costly_alteration(obj, COST_CANCEL);
1324.                 obj->otyp = SPE_BLANK_PAPER;
1325.                 /* cancelling a novel is more involved than a spellbook */
1326.                 if (otyp == SPE_NOVEL) /* old type */
1327.                     blank_novel(obj);
1328.             }
1329.             break;
1330.         case POTION_CLASS:
1331.             costly_alteration(obj, (otyp != POT_WATER) ? COST_CANCEL
1332.                                    : obj->cursed ? COST_UNCURS : COST_UNBLSS);
1333.             if (otyp == POT_SICKNESS || otyp == POT_SEE_INVISIBLE) {
1334.                 /* sickness is "biologically contaminated" fruit juice;
1335.                    cancel it and it just becomes fruit juice...
1336.                    whereas see invisible tastes like "enchanted" fruit
1337.                    juice, it similarly cancels */
1338.                 obj->otyp = POT_FRUIT_JUICE;
1339.             } else {
1340.                 obj->otyp = POT_WATER;
1341.                 obj->odiluted = 0; /* same as any other water */
1342.             }
1343.             break;
1344.         }
1345.     }
1346.     /* cancelling a troll's corpse prevents it from reviving (on its own;
1347.        does not affect undead turning induced revival) */
1348.     if (obj->otyp == CORPSE && obj->timed
1349.         && !is_rider(&mons[obj->corpsenm])) {
1350.         anything a = *obj_to_any(obj);
1351.         long timout = peek_timer(REVIVE_MON, &a);
1352. 
1353.         if (timout) {
1354.             (void) stop_timer(REVIVE_MON, &a);
1355.             (void) start_timer(timout, TIMER_OBJECT, ROT_CORPSE, &a);
1356.         }
1357.     }
1358. 
1359.     unbless(obj);
1360.     uncurse(obj);
1361.     return;
1362. }
1363. 
1364. /* soaking or cancelling a novel converts it into a blank spellbook but
1365.    needs more than just changing its otyp (caller is responsible for that) */
1366. void
1367. blank_novel(struct obj *obj)
1368. {
1369.     assert(obj->otyp == SPE_BLANK_PAPER);
1370.     /* novelidx overloads corpsenm, not used for spellbooks */
1371.     obj->novelidx = 0;
1372.     free_oname(obj); /* get rid of [former] novel's title */
1373.     /* a blank spellbook weighs more than a novel; update obj's weight and
1374.        recursively the weight of any container holding it */
1375.     container_weight(obj);
1376. }
1377. 
1378. /* Remove a positive enchantment or charge from obj,
1379.  * possibly carried by you or a monster
1380.  */
1381. boolean
1382. drain_item(struct obj *obj, boolean by_you)
1383. {
1384.     boolean u_ring;
1385. 
1386.     /* Is this a charged/enchanted object? */
1387.     if (!obj
1388.         || (!objects[obj->otyp].oc_charged && obj->oclass != WEAPON_CLASS
1389.             && obj->oclass != ARMOR_CLASS && !is_weptool(obj))
1390.         || obj->spe <= 0)
1391.         return FALSE;
1392.     if (defends(AD_DRLI, obj) || defends_when_carried(AD_DRLI, obj)
1393.         || obj_resists(obj, 10, 90))
1394.         return FALSE;
1395. 
1396.     /* Charge for the cost of the object */
1397.     if (by_you)
1398.         costly_alteration(obj, COST_DRAIN);
1399. 
1400.     /* Drain the object and any implied effects */
1401.     obj->spe--;
1402.     u_ring = (obj == uleft) || (obj == uright);
1403.     switch (obj->otyp) {
1404.     case RIN_GAIN_STRENGTH:
1405.         if ((obj->owornmask & W_RING) && u_ring) {
1406.             ABON(A_STR)--;
1407.             disp.botl = TRUE;
1408.         }
1409.         break;
1410.     case RIN_GAIN_CONSTITUTION:
1411.         if ((obj->owornmask & W_RING) && u_ring) {
1412.             ABON(A_CON)--;
1413.             disp.botl = TRUE;
1414.         }
1415.         break;
1416.     case RIN_ADORNMENT:
1417.         if ((obj->owornmask & W_RING) && u_ring) {
1418.             ABON(A_CHA)--;
1419.             disp.botl = TRUE;
1420.         }
1421.         break;
1422.     case RIN_INCREASE_ACCURACY:
1423.         if ((obj->owornmask & W_RING) && u_ring)
1424.             u.uhitinc--;
1425.         break;
1426.     case RIN_INCREASE_DAMAGE:
1427.         if ((obj->owornmask & W_RING) && u_ring)
1428.             u.udaminc--;
1429.         break;
1430.     case RIN_PROTECTION:
1431.         if (u_ring)
1432.             disp.botl = TRUE; /* bot() will recalc u.uac */
1433.         break;
1434.     case HELM_OF_BRILLIANCE:
1435.         if ((obj->owornmask & W_ARMH) && (obj == uarmh)) {
1436.             ABON(A_INT)--;
1437.             ABON(A_WIS)--;
1438.             disp.botl = TRUE;
1439.         }
1440.         break;
1441.     case GAUNTLETS_OF_DEXTERITY:
1442.         if ((obj->owornmask & W_ARMG) && (obj == uarmg)) {
1443.             ABON(A_DEX)--;
1444.             disp.botl = TRUE;
1445.         }
1446.         break;
1447.     default:
1448.         break;
1449.     }
1450.     if (disp.botl)
1451.         bot();
1452.     if (carried(obj))
1453.         update_inventory();
1454.     return TRUE;
1455. }
1456. 
1457. boolean
1458. obj_resists(struct obj *obj,
1459.             int ochance, /* percent chance for ordinary objects */
1460.             int achance) /* percent chance for artifacts */
1461. {
1462.     if (obj->otyp == AMULET_OF_YENDOR
1463.         || obj->otyp == SPE_BOOK_OF_THE_DEAD
1464.         || obj->otyp == CANDELABRUM_OF_INVOCATION
1465.         || obj->otyp == BELL_OF_OPENING
1466.         || (obj->otyp == CORPSE && is_rider(&mons[obj->corpsenm]))) {
1467.         return TRUE;
1468.     } else {
1469.         int chance = rn2(100);
1470. 
1471.         return (boolean) (chance < (obj->oartifact ? achance : ochance));
1472.     }
1473. }
1474. 
1475. boolean
1476. obj_shudders(struct obj *obj)
1477. {
1478.     int zap_odds;
1479. 
1480.     if (svc.context.bypasses && obj->bypass)
1481.         return FALSE;
1482. 
1483.     if (obj->oclass == WAND_CLASS)
1484.         zap_odds = 3; /* half-life = 2 zaps */
1485.     else if (obj->cursed)
1486.         zap_odds = 3; /* half-life = 2 zaps */
1487.     else if (obj->blessed)
1488.         zap_odds = 12; /* half-life = 8 zaps */
1489.     else
1490.         zap_odds = 8; /* half-life = 6 zaps */
1491. 
1492.     /* adjust for "large" quantities of identical things */
1493.     if (obj->quan > 4L)
1494.         zap_odds /= 2;
1495. 
1496.     return (boolean) !rn2(zap_odds);
1497. }
1498. 
1499. /* Use up at least minwt number of things made of material mat.
1500.  * There's also a chance that other stuff will be used up.  Finally,
1501.  * there's a random factor here to keep from always using the stuff
1502.  * at the top of the pile.
1503.  */
1504. staticfn void
1505. polyuse(struct obj *objhdr, int mat, int minwt)
1506. {
1507.     struct obj *otmp, *otmp2;
1508. 
1509.     for (otmp = objhdr; minwt > 0 && otmp; otmp = otmp2) {
1510.         otmp2 = otmp->nexthere;
1511.         if (svc.context.bypasses && otmp->bypass)
1512.             continue;
1513.         if (otmp == uball || otmp == uchain)
1514.             continue;
1515.         if (obj_resists(otmp, 0, 0))
1516.             continue; /* preserve unique objects */
1517. #ifdef MAIL_STRUCTURES
1518.         if (otmp->otyp == SCR_MAIL)
1519.             continue;
1520. #endif
1521. 
1522.         if (((int) objects[otmp->otyp].oc_material == mat)
1523.             == (rn2(minwt + 1) != 0)) {
1524.             /* appropriately add damage to bill */
1525.             if (costly_spot(otmp->ox, otmp->oy)) {
1526.                 if (*u.ushops)
1527.                     addtobill(otmp, FALSE, FALSE, FALSE);
1528.                 else
1529.                     (void) stolen_value(otmp, otmp->ox, otmp->oy, FALSE,
1530.                                         FALSE);
1531.             }
1532.             if (otmp->quan < LARGEST_INT)
1533.                 minwt -= (int) otmp->quan;
1534.             else
1535.                 minwt = 0;
1536.             delobj(otmp);
1537.         }
1538.     }
1539. }
1540. 
1541. /*
1542.  * Polymorph some of the stuff in this pile into a monster, preferably
1543.  * a golem of the kind okind.
1544.  */
1545. staticfn void
1546. create_polymon(struct obj *obj, int okind)
1547. {
1548.     struct permonst *mdat = (struct permonst *) 0;
1549.     struct monst *mtmp;
1550.     const char *material;
1551.     int pm_index;
1552. 
1553.     if (svc.context.bypasses) {
1554.         /* this is approximate because the "no golems" !obj->nexthere
1555.            check below doesn't understand bypassed objects; but it
1556.            should suffice since bypassed objects always end up as a
1557.            consecutive group at the top of their pile */
1558.         while (obj && obj->bypass)
1559.             obj = obj->nexthere;
1560.     }
1561. 
1562.     /* no golems if you zap only one object -- not enough stuff */
1563.     if (!obj || (!obj->nexthere && obj->quan == 1L))
1564.         return;
1565. 
1566.     /* some of these choices are arbitrary */
1567.     switch (okind) {
1568.     case IRON:
1569.     case METAL:
1570.     case MITHRIL:
1571.         pm_index = PM_IRON_GOLEM;
1572.         material = "metal ";
1573.         break;
1574.     case COPPER:
1575.     case SILVER:
1576.     case PLATINUM:
1577.     case GEMSTONE:
1578.     case MINERAL:
1579.         pm_index = rn2(2) ? PM_STONE_GOLEM : PM_CLAY_GOLEM;
1580.         material = "lithic ";
1581.         break;
1582.     case 0:
1583.     case FLESH:
1584.         /* there is no flesh type, but all food is type 0, so we use it */
1585.         pm_index = PM_FLESH_GOLEM;
1586.         material = "organic ";
1587.         break;
1588.     case WOOD:
1589.         pm_index = PM_WOOD_GOLEM;
1590.         material = "wood ";
1591.         break;
1592.     case LEATHER:
1593.         pm_index = PM_LEATHER_GOLEM;
1594.         material = "leather ";
1595.         break;
1596.     case CLOTH:
1597.         pm_index = PM_ROPE_GOLEM;
1598.         material = "cloth ";
1599.         break;
1600.     case BONE:
1601.         pm_index = PM_SKELETON; /* nearest thing to "bone golem" */
1602.         material = "bony ";
1603.         break;
1604.     case GOLD:
1605.         pm_index = PM_GOLD_GOLEM;
1606.         material = "gold ";
1607.         break;
1608.     case GLASS:
1609.         pm_index = PM_GLASS_GOLEM;
1610.         material = "glassy ";
1611.         break;
1612.     case PAPER:
1613.         pm_index = PM_PAPER_GOLEM;
1614.         material = "paper ";
1615.         break;
1616.     default:
1617.         /* if all else fails... */
1618.         pm_index = PM_STRAW_GOLEM;
1619.         material = "";
1620.         break;
1621.     }
1622. 
1623.     if (!(svm.mvitals[pm_index].mvflags & G_GENOD))
1624.         mdat = &mons[pm_index];
1625. 
1626.     mtmp = makemon(mdat, obj->ox, obj->oy, MM_NOMSG);
1627.     polyuse(obj, okind, (int) mons[pm_index].cwt);
1628. 
1629.     if (mtmp && cansee(mtmp->mx, mtmp->my)) {
1630.         pline("Some %sobjects meld, and %s arises from the pile!", material,
1631.               a_monnam(mtmp));
1632.     }
1633. }
1634. 
1635. /* Assumes obj is on the floor. */
1636. void
1637. do_osshock(struct obj *obj)
1638. {
1639.     long i;
1640. 
1641. #ifdef MAIL_STRUCTURES
1642.     if (obj->otyp == SCR_MAIL)
1643.         return;
1644. #endif
1645.     go.obj_zapped = TRUE;
1646. 
1647.     if (gp.poly_zapped < 0) {
1648.         /* some may metamorphose */
1649.         for (i = obj->quan; i; i--)
1650.             if (!rn2(Luck + 45)) {
1651.                 gp.poly_zapped = objects[obj->otyp].oc_material;
1652.                 break;
1653.             }
1654.     }
1655. 
1656.     /* if quan > 1 then some will survive intact */
1657.     if (obj->quan > 1L) {
1658.         if (obj->quan > LARGEST_INT)
1659.             obj = splitobj(obj, (long) rnd(30000));
1660.         else
1661.             obj = splitobj(obj, (long) rnd((int) obj->quan - 1));
1662.     }
1663. 
1664.     /* appropriately add damage to bill */
1665.     if (costly_spot(obj->ox, obj->oy)) {
1666.         if (*u.ushops)
1667.             addtobill(obj, FALSE, FALSE, FALSE);
1668.         else
1669.             (void) stolen_value(obj, obj->ox, obj->oy, FALSE, FALSE);
1670.     }
1671. 
1672.     /* zap the object */
1673.     delobj(obj);
1674. }
1675. 
1676. /* Returns TRUE if obj resists polymorphing */
1677. boolean
1678. obj_unpolyable(struct obj *obj)
1679. {
1680.     return (unpolyable(obj)
1681.             || obj == uball || obj == uskin
1682.             || obj_resists(obj, 5, 95));
1683. }
1684. 
1685. /* classes of items whose current charge count carries over across polymorph
1686.  */
1687. staticfn const char charged_objs[] = { WAND_CLASS, WEAPON_CLASS, ARMOR_CLASS,
1688.                                      '\0' };
1689. 
1690. /*
1691.  * Polymorph the object to the given object ID.  If the ID is STRANGE_OBJECT
1692.  * then pick random object from the source's class (this is the standard
1693.  * "polymorph" case).  If ID is set to a specific object, inhibit fusing
1694.  * n objects into 1.  This could have been added as a flag, but currently
1695.  * it is tied to not being the standard polymorph case. The new polymorphed
1696.  * object replaces obj in its link chains.  Return value is a pointer to
1697.  * the new object.
1698.  *
1699.  * This should be safe to call for an object anywhere.
1700.  */
1701. struct obj *
1702. poly_obj(struct obj *obj, int id)
1703. {
1704.     struct obj *otmp;
1705.     coordxy ox = 0, oy = 0;
1706.     long old_wornmask, new_wornmask = 0L;
1707.     boolean can_merge = (id == STRANGE_OBJECT);
1708.     int obj_location = obj->where;
1709. 
1710.     if (obj->otyp == BOULDER)
1711.         sokoban_guilt();
1712.     if (id == STRANGE_OBJECT) { /* preserve symbol */
1713.         int try_limit = 3;
1714.         unsigned magic_obj = objects[obj->otyp].oc_magic;
1715. 
1716.         if (obj->otyp == UNICORN_HORN && obj->degraded_horn)
1717.             magic_obj = 0;
1718.         /* Try up to 3 times to make the magic-or-not status of
1719.            the new item the same as the old item. */
1720.         otmp = (struct obj *) 0;
1721.         do {
1722.             if (otmp)
1723.                 delobj(otmp);
1724.             otmp = mkobj(obj->oclass, FALSE);
1725.         } while (--try_limit > 0
1726.                  && objects[otmp->otyp].oc_magic != magic_obj);
1727.     } else {
1728.         /* literally replace obj with this new thing */
1729.         otmp = mksobj(id, FALSE, FALSE);
1730. /* Actually more things use corpsenm but they polymorph differently */
1731. #define USES_CORPSENM(typ) \
1732.     ((typ) == CORPSE || (typ) == STATUE || (typ) == FIGURINE)
1733. 
1734.         if (USES_CORPSENM(obj->otyp) && USES_CORPSENM(id))
1735.             set_corpsenm(otmp, obj->corpsenm);
1736. #undef USES_CORPSENM
1737.     }
1738. 
1739.     /* preserve quantity */
1740.     otmp->quan = obj->quan;
1741.     /* preserve the shopkeeper's (lack of) interest */
1742.     otmp->no_charge = obj->no_charge;
1743.     /* preserve inventory letter if in inventory */
1744.     if (obj_location == OBJ_INVENT)
1745.         otmp->invlet = obj->invlet;
1746. #ifdef MAIL_STRUCTURES
1747.     /* You can't send yourself 100 mail messages and then
1748.      * polymorph them into useful scrolls
1749.      */
1750.     if (obj->otyp == SCR_MAIL) {
1751.         otmp->otyp = SCR_MAIL;
1752.         otmp->spe = 1;
1753.     }
1754. #endif
1755. 
1756.     /* avoid abusing eggs laid by you */
1757.     if (obj->otyp == EGG && obj->spe) {
1758.         int mnum, tryct = 100;
1759. 
1760.         /* first, turn into a generic egg */
1761.         if (otmp->otyp == EGG)
1762.             kill_egg(otmp);
1763.         else {
1764.             otmp->otyp = EGG;
1765.             otmp->owt = weight(otmp);
1766.         }
1767.         otmp->corpsenm = NON_PM;
1768.         otmp->spe = 0;
1769. 
1770.         /* now change it into something laid by the hero */
1771.         while (tryct--) {
1772.             mnum = can_be_hatched(random_monster(rn2));
1773.             if (mnum != NON_PM && !dead_species(mnum, TRUE)) {
1774.                 otmp->spe = 1;            /* laid by hero */
1775.                 set_corpsenm(otmp, mnum); /* also sets hatch timer */
1776.                 break;
1777.             }
1778.         }
1779.     }
1780. 
1781.     /* keep special fields (including charges on wands) */
1782.     if (strchr(charged_objs, otmp->oclass))
1783.         otmp->spe = obj->spe;
1784.     otmp->recharged = obj->recharged;
1785. 
1786.     otmp->cursed = obj->cursed;
1787.     otmp->blessed = obj->blessed;
1788. 
1789.     if (erosion_matters(otmp)) {
1790.         if (is_flammable(otmp) || is_rustprone(otmp) || is_crackable(otmp))
1791.             otmp->oeroded = obj->oeroded;
1792.         if (is_corrodeable(otmp) || is_rottable(otmp))
1793.             otmp->oeroded2 = obj->oeroded2;
1794.         if (is_damageable(otmp))
1795.             otmp->oerodeproof = obj->oerodeproof;
1796.     }
1797. 
1798.     /* Keep chest/box traps and poisoned ammo if we may */
1799.     if (obj->otrapped && Is_box(otmp))
1800.         otmp->otrapped = 1;
1801.     if (obj->opoisoned && is_poisonable(otmp))
1802.         otmp->opoisoned = 1;
1803. 
1804.     if (id == STRANGE_OBJECT && obj->otyp == CORPSE) {
1805.         /* turn crocodile corpses into shoes */
1806.         if (obj->corpsenm == PM_CROCODILE) {
1807.             otmp->otyp = LOW_BOOTS;
1808.             otmp->oclass = ARMOR_CLASS;
1809.             otmp->spe = 0;
1810.             otmp->oeroded = 0;
1811.             otmp->oerodeproof = TRUE;
1812.             otmp->quan = 1L;
1813.             otmp->cursed = FALSE;
1814.         }
1815.     }
1816.     if (obj->otyp == LEASH && obj->leashmon != 0) {
1817.         if (otmp->otyp == LEASH) {
1818.             otmp->leashmon = obj->leashmon;
1819.             /* clear m_id before delobj(), to avoid o_unleash() by obfree() */
1820.             obj->leashmon = 0;
1821.         } else {
1822.             /* obfree() would do this if we didn't do it here */
1823.             o_unleash(obj);
1824.         }
1825.     }
1826. 
1827.     /* no box contents --KAA */
1828.     if (Has_contents(otmp))
1829.         delete_contents(otmp);
1830. 
1831.     /* 'n' merged objects may be fused into 1 object */
1832.     if (otmp->quan > 1L && (!objects[otmp->otyp].oc_merge
1833.                             || (can_merge && otmp->quan > (long) rn2(1000))))
1834.         otmp->quan = 1L;
1835. 
1836.     switch (otmp->oclass) {
1837.     case TOOL_CLASS:
1838.         if (otmp->otyp == MAGIC_LAMP) {
1839.             otmp->otyp = OIL_LAMP;
1840.             otmp->age = 1500L; /* "best" oil lamp possible */
1841.         } else if (otmp->otyp == MAGIC_MARKER) {
1842.             otmp->recharged = 1; /* degraded quality */
1843.         }
1844.         /* don't care about the recharge count of other tools */
1845.         break;
1846. 
1847.     case WAND_CLASS:
1848.         while (otmp->otyp == WAN_WISHING || otmp->otyp == WAN_POLYMORPH)
1849.             otmp->otyp = rnd_class(WAN_LIGHT, WAN_LIGHTNING);
1850.         /* altering the object tends to degrade its quality
1851.            (analogous to spellbook `read count' handling) */
1852.         if ((int) otmp->recharged < rn2(7)) /* recharge_limit */
1853.             otmp->recharged++;
1854.         break;
1855. 
1856.     case POTION_CLASS:
1857.         while (otmp->otyp == POT_POLYMORPH)
1858.             otmp->otyp = rnd_class(POT_GAIN_ABILITY, POT_WATER);
1859.         /* potions of oil use obj->age field differently from other potions */
1860.         if (otmp->otyp == POT_OIL || obj->otyp == POT_OIL)
1861.             fixup_oil(otmp, obj);
1862.         break;
1863. 
1864.     case SPBOOK_CLASS:
1865.         while (otmp->otyp == SPE_POLYMORPH)
1866.             otmp->otyp = rnd_class(svb.bases[SPBOOK_CLASS], SPE_BLANK_PAPER);
1867.         /* reduce spellbook abuse; non-blank books degrade;
1868.            5.0: novels don't use spestudied so shouldn't degrade to blank
1869.            (but don't force spestudied to zero for them since a non-zero
1870.            value could get passed along to a future polymorph) */
1871.         if (otmp->otyp != SPE_BLANK_PAPER && otmp->otyp != SPE_NOVEL) {
1872.             otmp->spestudied = obj->spestudied + 1;
1873.             if (otmp->spestudied > MAX_SPELL_STUDY) {
1874.                 otmp->otyp = SPE_BLANK_PAPER;
1875.                 /* writing a new book over it will yield an unstudied
1876.                    one; re-polymorphing this one as-is may or may not
1877.                    get something non-blank */
1878.                 otmp->spestudied = rn2(otmp->spestudied);
1879.             }
1880.         }
1881.         break;
1882. 
1883.     case GEM_CLASS:
1884.         if (otmp->quan > (long) rnd(4)
1885.             && objects[obj->otyp].oc_material == MINERAL
1886.             && objects[otmp->otyp].oc_material != MINERAL) {
1887.             otmp->otyp = ROCK; /* transmutation backfired */
1888.             otmp->quan /= 2L;  /* some material has been lost */
1889.         }
1890.         break;
1891.     }
1892. 
1893.     /* update the weight */
1894.     otmp->owt = weight(otmp);
1895. 
1896.     /*
1897.      * ** we are now done adjusting the object (except possibly wearing it) **
1898.      */
1899. 
1900.     (void) get_obj_location(obj, &ox, &oy, BURIED_TOO | CONTAINED_TOO);
1901.     old_wornmask = obj->owornmask & ~(W_ART | W_ARTI);
1902.     /* swap otmp for obj */
1903.     replace_object(obj, otmp);
1904.     if (obj_location == OBJ_INVENT) {
1905.         /*
1906.          * We may need to do extra adjustments for the hero if we're
1907.          * messing with the hero's inventory.  The following calls are
1908.          * equivalent to calling freeinv() on obj and addinv_nomerge()
1909.          * on otmp, while doing an in-place swap of the actual objects.
1910.          */
1911.         freeinv_core(obj);
1912.         addinv_core1(otmp);
1913.         addinv_core2(otmp);
1914.         /*
1915.          * Handle polymorph of worn item.  Stone-to-flesh cast on self can
1916.          * affect multiple objects at once, but their new forms won't
1917.          * produce any side-effects.  A single worn item dipped into potion
1918.          * of polymorph can produce side-effects but those won't yield out
1919.          * of sequence messages because current polymorph is finished.
1920.          */
1921.         if (old_wornmask) {
1922.             boolean was_twohanded = bimanual(obj), was_twoweap = u.twoweap;
1923. 
1924.             /* wearslot() expects us to deal with wielded/alt-wep/quivered
1925.                items in case they're not weapons; for other slots it might
1926.                return multiple bits (ring left|right); narrow that down to
1927.                the bit(s) currently in use */
1928.             new_wornmask = ((old_wornmask & W_WEAPONS) != 0L) ? old_wornmask
1929.                            : (wearslot(otmp) & old_wornmask);
1930.             remove_worn_item(obj, TRUE);
1931.             /* if the new form can be worn in the same slot, make it so */
1932.             if ((new_wornmask & W_WEP) != 0L) {
1933.                 if (was_twohanded || !bimanual(otmp) || !uarms)
1934.                     setuwep(otmp);
1935.                 if (was_twoweap && uwep && !bimanual(uwep))
1936.                     set_twoweap(TRUE); /* u.twoweap = TRUE */
1937.             } else if ((new_wornmask & W_SWAPWEP) != 0L) {
1938.                 if (was_twohanded || !bimanual(otmp))
1939.                     setuswapwep(otmp);
1940.                 if (was_twoweap && uswapwep)
1941.                     set_twoweap(TRUE); /* u.twoweap = TRUE */
1942.             } else if ((new_wornmask & W_QUIVER) != 0L) {
1943.                 setuqwep(otmp);
1944.             } else if (new_wornmask) {
1945.                 setworn(otmp, new_wornmask);
1946.                 /* set_wear() might result in otmp being destroyed if
1947.                    worn amulet has been turned into an amulet of change */
1948.                 set_wear(otmp);
1949.                 otmp = wearmask_to_obj(new_wornmask); /* might be Null */
1950.             }
1951.         } /* old_wornmask */
1952.     } else if (obj_location == OBJ_FLOOR) {
1953.         if (obj->otyp == BOULDER && otmp->otyp != BOULDER) {
1954.             if (!does_block(ox, oy, &levl[ox][oy]))
1955.                 unblock_point(ox, oy);
1956.         } else if (obj->otyp != BOULDER && otmp->otyp == BOULDER) {
1957.             /* leaving boulder in liquid would trigger sanity_check warning */
1958.             if (is_pool_or_lava(ox, oy))
1959.                 fracture_rock(otmp);
1960.             if (does_block(ox, oy, &levl[ox][oy]))
1961.                 block_point(ox, oy);
1962.         }
1963.     }
1964. 
1965.     /* note: if otmp is gone, billing for it was handled by useup() */
1966.     if (((otmp && !carried(otmp)) || obj->unpaid) && costly_spot(ox, oy)) {
1967.         struct monst *shkp = shop_keeper(*in_rooms(ox, oy, SHOPBASE));
1968. 
1969.         if ((!obj->no_charge
1970.              || (Has_contents(obj)
1971.                  && (contained_cost(obj, shkp, 0L, FALSE, FALSE) != 0L)))
1972.             && inhishop(shkp)) {
1973.             if (shkp->mpeaceful) {
1974.                 if (*u.ushops
1975.                     && (*in_rooms(u.ux, u.uy, 0)
1976.                         == *in_rooms(shkp->mx, shkp->my, 0))
1977.                     && !costly_spot(u.ux, u.uy)) {
1978.                     make_angry_shk(shkp, ox, oy);
1979.                 } else {
1980.                     pline("%s gets angry!", Shknam(shkp));
1981.                     hot_pursuit(shkp);
1982.                 }
1983.             } else
1984.                 Norep("%s is furious!", Shknam(shkp));
1985.         }
1986.     }
1987.     delobj(obj);
1988.     return otmp;
1989. }
1990. 
1991. /* stone-to-flesh spell hits and maybe transforms or animates obj */
1992. staticfn int
1993. stone_to_flesh_obj(struct obj *obj) /* nonnull */
1994. {
1995.     struct permonst *ptr;
1996.     struct monst *mon, *shkp;
1997.     struct obj *item;
1998.     coordxy oox, ooy;
1999.     boolean smell = FALSE, golem_xform = FALSE;
2000.     int res = 1; /* affected object by default */
2001. 
2002.     if (objects[obj->otyp].oc_material != MINERAL
2003.         && objects[obj->otyp].oc_material != GEMSTONE)
2004.         return 0;
2005.     /* Heart of Ahriman usually resists; ordinary items rarely do */
2006.     if (obj_resists(obj, 2, 98))
2007.         return 0;
2008. 
2009.     (void) get_obj_location(obj, &oox, &ooy, 0);
2010.     /* add more if stone objects are added... */
2011.     switch (objects[obj->otyp].oc_class) {
2012.     case ROCK_CLASS: /* boulders and statues */
2013.     case TOOL_CLASS: /* figurines */
2014.         if (obj->otyp == BOULDER) {
2015.             obj = poly_obj(obj, ENORMOUS_MEATBALL);
2016.             smell = TRUE;
2017.         } else if (obj->otyp == STATUE || obj->otyp == FIGURINE) {
2018.             ptr = &mons[obj->corpsenm];
2019.             if (is_golem(ptr)) {
2020.                 golem_xform = (ptr != &mons[PM_FLESH_GOLEM]);
2021.             } else if (vegetarian(ptr)) {
2022.                 /* Don't animate monsters that aren't flesh */
2023.                 obj = poly_obj(obj, MEATBALL);
2024.                 smell = TRUE;
2025.                 break;
2026.             }
2027.             if (obj->otyp == STATUE) {
2028.                 /* animate_statue() forces all golems to become flesh golems */
2029.                 mon = animate_statue(obj, oox, ooy, ANIMATE_SPELL, (int *) 0);
2030.             } else { /* (obj->otyp == FIGURINE) */
2031.                 if (golem_xform)
2032.                     ptr = &mons[PM_FLESH_GOLEM];
2033.                 mon = makemon(ptr, oox, ooy, NO_MINVENT|MM_NOMSG);
2034.                 if (mon) {
2035.                     if (costly_spot(oox, ooy)
2036.                         && (carried(obj) ? obj->unpaid : !obj->no_charge)) {
2037.                         shkp = shop_keeper(*in_rooms(oox, ooy, SHOPBASE));
2038.                         stolen_value(obj, oox, ooy,
2039.                                      (shkp && shkp->mpeaceful), FALSE);
2040.                     }
2041.                     if (obj->timed)
2042.                         obj_stop_timers(obj);
2043.                     if (carried(obj))
2044.                         useup(obj);
2045.                     else
2046.                         delobj(obj);
2047.                     if (cansee(mon->mx, mon->my))
2048.                         pline_The("figurine %sanimates!",
2049.                                   golem_xform ? "turns to flesh and " : "");
2050.                 }
2051.             }
2052.             if (mon) {
2053.                 ptr = mon->data;
2054.                 /* this golem handling is redundant... */
2055.                 if (is_golem(ptr) && ptr != &mons[PM_FLESH_GOLEM])
2056.                     (void) newcham(mon, &mons[PM_FLESH_GOLEM],
2057.                                    NC_VIA_WAND_OR_SPELL);
2058.             } else if ((ptr->geno & (G_NOCORPSE | G_UNIQ)) != 0) {
2059.                 /* didn't revive but can't leave corpse either */
2060.                 res = 0;
2061.             } else {
2062.                 /* unlikely to get here since genociding monsters also
2063.                    sets the G_NOCORPSE flag; drop statue's contents */
2064.                 while ((item = obj->cobj) != 0) {
2065.                     bypass_obj(item); /* make stone-to-flesh miss it */
2066.                     obj_extract_self(item);
2067.                     place_object(item, oox, ooy);
2068.                 }
2069.                 obj = poly_obj(obj, CORPSE);
2070.             }
2071.         } else { /* miscellaneous tool or unexpected rock... */
2072.             res = 0;
2073.         }
2074.         break;
2075.     /* maybe add weird things to become? */
2076.     case RING_CLASS: /* some of the rings are stone */
2077.         obj = poly_obj(obj, MEAT_RING);
2078.         smell = TRUE;
2079.         break;
2080.     case WAND_CLASS: /* marble wand */
2081.         obj = poly_obj(obj, MEAT_STICK);
2082.         smell = TRUE;
2083.         break;
2084.     case GEM_CLASS: /* stones & gems */
2085.         obj = poly_obj(obj, MEATBALL);
2086.         smell = TRUE;
2087.         break;
2088.     case WEAPON_CLASS: /* crysknife */
2089.         FALLTHROUGH;
2090.         /*FALLTHRU*/
2091.     default:
2092.         res = 0;
2093.         break;
2094.     }
2095.     nhUse(obj); /* avoid 'assigned value not used' for poly_obj() calls */
2096. 
2097.     if (smell) {
2098.         /* non-meat eaters smell meat, meat eaters smell its flavor;
2099.            monks are considered non-meat eaters regardless of behavior;
2100.            other roles are non-meat eaters if they haven't broken
2101.            vegetarian conduct yet (or if poly'd into non-carnivorous/
2102.            non-omnivorous form, regardless of whether it's herbivorous,
2103.            non-eating, or something stranger) */
2104.         if (Role_if(PM_MONK) || !u.uconduct.unvegetarian
2105.             || !carnivorous(gy.youmonst.data))
2106.             Norep("You smell the odor of meat.");
2107.         else
2108.             Norep("You smell a delicious smell.");
2109.     }
2110.     newsym(oox, ooy);
2111.     return res;
2112. }
2113. 
2114. /*
2115.  * Object obj was hit by the effect of the wand/spell otmp.  Return
2116.  * non-zero if the wand/spell had any effect.
2117.  */
2118. int
2119. bhito(struct obj *obj, struct obj *otmp)
2120. {
2121.     int res = 1; /* affected object by default */
2122.     boolean learn_it = FALSE, maybelearnit;
2123. 
2124.     /* fundamental: a wand effect hitting itself doesn't do anything;
2125.        otherwise we need to guard against accessing otmp after something
2126.        strange has happened to it (along the lines of polymorph or
2127.        stone-to-flesh [which aren't good examples since polymorph wands
2128.        aren't affected by polymorph zaps and stone-to-flesh isn't
2129.        available in wand form, but the concept still applies...]) */
2130.     if (obj == otmp)
2131.         return 0;
2132. 
2133.     if (obj->bypass) {
2134.         /* The bypass bit is currently only used as follows:
2135.          *
2136.          * POLYMORPH - When a monster being polymorphed drops something
2137.          *             from its inventory as a result of the change.
2138.          *             If the items fall to the floor, they are not
2139.          *             subject to direct subsequent polymorphing
2140.          *             themselves on that same zap.  This makes it
2141.          *             consistent with items that remain in the monster's
2142.          *             inventory.  They are not polymorphed either.
2143.          * UNDEAD_TURNING - When an undead creature gets killed via
2144.          *             undead turning, prevent its corpse from being
2145.          *             immediately revived by the same effect.
2146.          * STONE_TO_FLESH - If a statue can't be revived, its
2147.          *             contents get dropped before turning it into
2148.          *             meat; prevent those contents from being hit.
2149.          * retouch_equipment() - bypass flag is used to track which
2150.          *             items have been handled (bhito isn't involved).
2151.          * menu_drop(), askchain() - inventory traversal where multiple
2152.          *             Drop can alter the invent chain while traversal
2153.          *             is in progress (bhito isn't involved).
2154.          * destroy_items() - inventory traversal where item destruction can
2155.          *             trigger drop or destruction of other item(s) and alter
2156.          *             the invent or mon->minvent chain, possibly recursively.
2157.          *
2158.          * The bypass bit on all objects is reset each turn, whenever
2159.          * svc.context.bypasses is set.
2160.          *
2161.          * We check the obj->bypass bit above AND svc.context.bypasses
2162.          * as a safeguard against any stray occurrence left in an obj
2163.          * struct someplace, although that should never happen.
2164.          */
2165.         if (svc.context.bypasses) {
2166.             return 0;
2167.         } else {
2168.             debugpline1("%s for a moment.", Tobjnam(obj, "pulsate"));
2169.             obj->bypass = 0;
2170.         }
2171.     }
2172. 
2173.     /*
2174.      * Some parts of this function expect the object to be on the floor
2175.      * obj->{ox,oy} to be valid.  The exception to this (so far) is
2176.      * for the STONE_TO_FLESH spell.
2177.      */
2178.     if (!(obj->where == OBJ_FLOOR || otmp->otyp == SPE_STONE_TO_FLESH))
2179.         impossible("bhito: obj is not floor or Stone To Flesh spell");
2180. 
2181.     if (obj == uball) {
2182.         res = 0;
2183.     } else if (obj == uchain) {
2184.         if (otmp->otyp == WAN_OPENING || otmp->otyp == SPE_KNOCK) {
2185.             learn_it = TRUE;
2186.             unpunish();
2187.         } else
2188.             res = 0;
2189.     } else
2190.         switch (otmp->otyp) {
2191.         case WAN_POLYMORPH:
2192.         case SPE_POLYMORPH:
2193.             if (obj_unpolyable(obj)) {
2194.                 res = 0;
2195.                 break;
2196.             }
2197.             /* KMH, conduct */
2198.             if (!u.uconduct.polypiles++)
2199.                 livelog_printf(LL_CONDUCT, "polymorphed %s first object",
2200.                                uhis());
2201. 
2202.             /* any saved lock context will be dangerously obsolete */
2203.             if (Is_box(obj))
2204.                 (void) boxlock(obj, otmp);
2205. 
2206.             if (obj_shudders(obj)) {
2207.                 boolean cover = ((obj == svl.level.objects[u.ux][u.uy])
2208.                                  && u.uundetected
2209.                                  && hides_under(gy.youmonst.data));
2210. 
2211.                 if (cansee(obj->ox, obj->oy))
2212.                     learn_it = TRUE;
2213.                 do_osshock(obj);
2214.                 /* eek - your cover might have been blown */
2215.                 if (cover)
2216.                     (void) hideunder(&gy.youmonst);
2217.                 break;
2218.             }
2219.             obj = poly_obj(obj, STRANGE_OBJECT);
2220.             newsym(obj->ox, obj->oy);
2221.             break;
2222.         case WAN_PROBING:
2223.             res = !obj->dknown;
2224.             /* target object has now been "seen (up close)" */
2225.             observe_object(obj);
2226.             if (Is_container(obj) || obj->otyp == STATUE) {
2227.                 obj->cknown = obj->lknown = 1;
2228.                 if (Is_box(obj) && !obj->tknown) {
2229.                     /* obj->tknown applies to boxes and chests, not bags or
2230.                        statues; plural handling here and the "empty" case
2231.                        below are superfluous because containers don't stack */
2232.                     if (obj->otrapped)
2233.                         pline("%s trapped!", Tobjnam(obj, "are"));
2234.                     obj->tknown = 1;
2235.                 }
2236. 
2237.                 if (!obj->cobj) {
2238.                     pline("%s empty.", Tobjnam(obj, "are"));
2239.                 } else if (SchroedingersBox(obj)) {
2240.                     /* we don't want to force alive vs dead
2241.                        determination for Schroedinger's Cat here,
2242.                        so just make probing be inconclusive for it */
2243.                     You("aren't sure whether %s has %s or its corpse inside.",
2244.                         the(xname(obj)),
2245.                         /* unfortunately, we can't tell whether rndmonnam()
2246.                            picks a form which can't leave a corpse */
2247.                         an(Hallucination ? rndmonnam((char *) 0) : "cat"));
2248.                     obj->cknown = 0;
2249.                 } else {
2250.                     struct obj *o;
2251. 
2252.                     /* view contents (not recursively) */
2253.                     for (o = obj->cobj; o; o = o->nobj)
2254.                         observe_object(o); /* "seen", even if blind */
2255.                     (void) display_cinventory(obj);
2256.                 }
2257.                 res = 1;
2258.             } else if (obj->otyp == TIN) {
2259.                 /* don't learn wand if tin is already known */
2260.                 if (!obj->known || !obj->cknown)
2261.                     res = 1;
2262.                 obj->known = 1;
2263.                 set_cknown_lknown(obj); /* if TIN obj->cknown = 1 */
2264.             } else if (obj->otyp == EGG) {
2265.                 /* if egg is unhatchable, probing it won't learn wand
2266.                    because even when flagged as known, it's just "an egg" */
2267.                 if (!obj->known && obj->corpsenm != NON_PM)
2268.                     res = 1;
2269.                 obj->known = 1;
2270.                 /* [should this call learn_egg_type()?] */
2271.             }
2272.             if (res)
2273.                 learn_it = TRUE;
2274.             break;
2275.         case WAN_STRIKING:
2276.         case SPE_FORCE_BOLT:
2277.             /* learn the type if you see or hear something break
2278.                (the sound could be implicit) */
2279.             maybelearnit = cansee(obj->ox, obj->oy) || !Deaf;
2280.             if (obj->otyp == BOULDER) {
2281.                 Soundeffect(se_crumbling_sound, 75);
2282.                 if (cansee(obj->ox, obj->oy))
2283.                     pline_The("boulder falls apart.");
2284.                 else
2285.                     You_hear("a crumbling sound.");
2286.                 fracture_rock(obj);
2287.             } else if (obj->otyp == STATUE) {
2288.                 if (break_statue(obj)) {
2289.                     if (cansee(obj->ox, obj->oy)) {
2290.                         if (Hallucination)
2291.                             pline_The("%s shatters.", rndmonnam(NULL));
2292.                         else
2293.                             pline_The("statue shatters.");
2294.                     } else
2295.                         You_hear("a crumbling sound.");
2296.                 }
2297.             } else {
2298.                 int oox = obj->ox, ooy = obj->oy;
2299. 
2300.                 if (svc.context.mon_moving ? !breaks(obj, oox, ooy)
2301.                                           : !hero_breaks(obj, oox, ooy, 0))
2302.                     maybelearnit = FALSE; /* nothing broke */
2303.                 else
2304.                     /* obj broke; force redisplay in case it was the only--
2305.                        or last--item under non-breaking pile-top; top item
2306.                        here might now be a lone object rather than a pile */
2307.                     newsym_force(oox, ooy);
2308.                 res = 0;
2309.             }
2310.             if (maybelearnit)
2311.                 learn_it = TRUE;
2312.             break;
2313.         case WAN_CANCELLATION:
2314.         case SPE_CANCELLATION:
2315.             cancel_item(obj);
2316.             newsym(obj->ox, obj->oy); /* might change color */
2317.             break;
2318.         case SPE_DRAIN_LIFE:
2319.             (void) drain_item(obj, TRUE);
2320.             break;
2321.         case WAN_TELEPORTATION:
2322.         case SPE_TELEPORT_AWAY:
2323.             {
2324.                 coordxy ox = obj->ox, oy = obj->oy;
2325. 
2326.                 (void) rloco(obj);
2327.                 maybe_unhide_at(ox, oy);
2328.             }
2329.             break;
2330.         case WAN_MAKE_INVISIBLE:
2331.             break;
2332.         case WAN_UNDEAD_TURNING:
2333.         case SPE_TURN_UNDEAD:
2334.             if (obj->otyp == EGG) {
2335.                 revive_egg(obj);
2336.             } else if (obj->otyp == CORPSE) {
2337.                 struct monst *mtmp;
2338.                 coordxy ox, oy;
2339.                 unsigned save_norevive;
2340.                 boolean by_u = !svc.context.mon_moving;
2341.                 int corpsenm = corpse_revive_type(obj);
2342.                 char *corpsname = cxname_singular(obj);
2343. 
2344.                 /* get corpse's location before revive() uses it up */
2345.                 if (!get_obj_location(obj, &ox, &oy, 0))
2346.                     ox = obj->ox, oy = obj->oy; /* won't happen */
2347. 
2348.                 /* explicit revival magic overrides timer-based no-revive */
2349.                 save_norevive = obj->norevive;
2350.                 obj->norevive = 0;
2351. 
2352.                 mtmp = revive(obj, TRUE);
2353.                 if (!mtmp) {
2354.                     obj->norevive = save_norevive;
2355.                     res = 0; /* no monster implies corpse was left intact */
2356.                 } else {
2357.                     if (cansee(ox, oy)) {
2358.                         if (canspotmon(mtmp)) {
2359.                             pline("%s is resurrected!",
2360.                                   upstart(noname_monnam(mtmp, ARTICLE_THE)));
2361.                             learn_it = by_u ? TRUE : gz.zap_oseen;
2362.                         } else {
2363.                             /* saw corpse but don't see monster: maybe
2364.                                mtmp is invisible, or has been placed at
2365.                                a different spot than <ox,oy> */
2366.                             if (!type_is_pname(&mons[corpsenm]))
2367.                                 corpsname = The(corpsname);
2368.                             pline("%s disappears.", corpsname);
2369.                         }
2370.                     } else {
2371.                         /* couldn't see corpse's location */
2372.                         if (Role_if(PM_HEALER) && !Deaf
2373.                             && !nonliving(&mons[corpsenm])) {
2374.                             if (!type_is_pname(&mons[corpsenm]))
2375.                                 corpsname = an(corpsname);
2376.                             if (!Hallucination)
2377.                                 You_hear("%s reviving.", corpsname);
2378.                             else
2379.                                 You_hear("a defibrillator.");
2380.                             learn_it = by_u ? TRUE : gz.zap_oseen;
2381.                         }
2382.                         if (canspotmon(mtmp))
2383.                             /* didn't see corpse but do see monster: it
2384.                                has been placed somewhere other than <ox,oy>
2385.                                or blind hero spots it with ESP */
2386.                             pline("%s appears.", Monnam(mtmp));
2387.                     }
2388.                     if (learn_it)
2389.                         exercise(A_WIS, TRUE);
2390.                 }
2391.             }
2392.             break;
2393.         case WAN_OPENING:
2394.         case SPE_KNOCK:
2395.         case WAN_LOCKING:
2396.         case SPE_WIZARD_LOCK:
2397.             if (Is_box(obj))
2398.                 res = boxlock(obj, otmp);
2399.             else
2400.                 res = 0;
2401.             if (res)
2402.                 learn_it = TRUE;
2403.             break;
2404.         case WAN_SLOW_MONSTER: /* no effect on objects */
2405.         case SPE_SLOW_MONSTER:
2406.         case WAN_SPEED_MONSTER:
2407.         case WAN_NOTHING:
2408.         case SPE_HEALING:
2409.         case SPE_EXTRA_HEALING:
2410.             res = 0;
2411.             break;
2412.         case SPE_STONE_TO_FLESH:
2413.             res = stone_to_flesh_obj(obj);
2414.             break;
2415.         default:
2416.             impossible("What an interesting effect (%d)", otmp->otyp);
2417.             break;
2418.         }
2419.     /* if effect was observable then discover the wand type provided
2420.        that the wand itself has been seen */
2421.     if (learn_it)
2422.         learnwand(otmp);
2423.     return res;
2424. }
2425. 
2426. /* returns nonzero if something was hit */
2427. int
2428. bhitpile(
2429.     struct obj *obj,            /* wand or fake spellbook for type of zap */
2430.     int (*fhito)(OBJ_P, OBJ_P), /* callback for each object being hit */
2431.     coordxy tx, coordxy ty,     /* target location */
2432.     schar zz)                   /* direction for up/down zaps */
2433. {
2434.     struct obj *otmp, *next_obj;
2435.     boolean hidingunder, first;
2436.     int prevotyp, hitanything = 0;
2437. 
2438.     if (!svl.level.objects[tx][ty])
2439.         return 0;
2440. 
2441.     /* if hiding underneath an object and zapping up or down, the top item
2442.        is either the only thing hit (up) or is skipped (down) */
2443.     hidingunder = (zz != 0 && u.uundetected && hides_under(gy.youmonst.data));
2444.     first = TRUE;
2445. 
2446.     if (obj->otyp == SPE_FORCE_BOLT || obj->otyp == WAN_STRIKING) {
2447.         struct trap *t = t_at(tx, ty);
2448.         struct obj *topofpile = svl.level.objects[tx][ty];
2449. 
2450.         /* We can't settle for the default calling sequence of
2451.            bhito(otmp) -> break_statue(otmp) -> activate_statue_trap(ox,oy)
2452.            because that last call might end up operating on our `next_obj'
2453.            (below), rather than on the current object, if it happens to
2454.            encounter a statue which mustn't become animated. */
2455.         if (t && t->ttyp == STATUE_TRAP
2456.             && activate_statue_trap(t, tx, ty, TRUE))
2457.             learnwand(obj);
2458.         /* assume zapping up or down while hiding under the top item can
2459.            still activate the trap even if it's below (when zapping up)
2460.            or above (when zapping down) */
2461.         if (svl.level.objects[tx][ty] != topofpile)
2462.             first = FALSE; /* top item was statue which activated */
2463.     }
2464. 
2465.     gp.poly_zapped = -1;
2466.     for (otmp = svl.level.objects[tx][ty]; otmp; otmp = next_obj) {
2467.         next_obj = otmp->nexthere;
2468.         if (hidingunder) {
2469.             if (first) {
2470.                 first = FALSE; /* reset for next item */
2471.                 if (zz > 0) /* down when hiding-under skips first item */
2472.                     continue;
2473.             } else {
2474.                 /* !first */
2475.                 if (zz < 0) /* up when hiding-under skips rest of pile */
2476.                     continue;
2477.             }
2478.         }
2479.         if (otmp->where != OBJ_FLOOR || otmp->ox != tx || otmp->oy != ty)
2480.             continue;
2481.         hitanything += (*fhito)(otmp, obj);
2482.     }
2483. 
2484.     if (gp.poly_zapped >= 0)
2485.         create_polymon(svl.level.objects[tx][ty], gp.poly_zapped);
2486. 
2487.     /* when boulders are present they're expected to be on top; with
2488.        multiple boulders it's possible for some to have been changed into
2489.        non-boulders (polymorph, stone-to-flesh) while ones beneath resist,
2490.        so re-stack pile if there are any non-boulders above boulders */
2491.     prevotyp = BOULDER;
2492.     for (otmp = svl.level.objects[tx][ty]; otmp; otmp = otmp->nexthere) {
2493.         if (otmp->otyp == BOULDER && prevotyp != BOULDER) {
2494.             recreate_pile_at(tx, ty);
2495.             break;
2496.         }
2497.         prevotyp = otmp->otyp;
2498.     }
2499. 
2500.     if (hidingunder) /* pile might have been destroyed or dispersed */
2501.         maybe_unhide_at(tx, ty);
2502. 
2503.     fill_pit(tx, ty);
2504. 
2505.     return hitanything;
2506. }
2507. 
2508. /*
2509.  * zappable - returns 1 if zap is available, 0 otherwise.
2510.  *            it removes a charge from the wand if zappable.
2511.  * added by GAN 11/03/86
2512.  */
2513. int
2514. zappable(struct obj *wand)
2515. {
2516.     if (wand->spe < 0 || (wand->spe == 0 && rn2(WAND_WREST_CHANCE)))
2517.         return 0;
2518.     if (wand->spe == 0)
2519.         You("wrest one last charge from the worn-out wand.");
2520.     wand->spe--;
2521.     return 1;
2522. }
2523. 
2524. void
2525. do_enlightenment_effect(void)
2526. {
2527.     You_feel("self-knowledgeable...");
2528.     display_nhwindow(WIN_MESSAGE, FALSE);
2529.     enlightenment(MAGICENLIGHTENMENT, ENL_GAMEINPROGRESS);
2530.     pline_The("feeling subsides.");
2531.     exercise(A_WIS, TRUE);
2532. }
2533. 
2534. /*
2535.  * zapnodir - zaps a NODIR wand/spell.
2536.  * Won't get here if wand has no charges (unless wresting 1 last charge).
2537.  */
2538. void
2539. zapnodir(struct obj *obj)
2540. {
2541.     boolean known = FALSE;
2542. 
2543.     switch (obj->otyp) {
2544.     case WAN_LIGHT:
2545.     case SPE_LIGHT:
2546.         /* FIXME? wand of light becoming discovered should be contingent upon
2547.            seeing at least one previously unlit spot become lit */
2548.         known = (obj->dknown && !Blind);
2549.         litroom(TRUE, obj);
2550.         (void) lightdamage(obj, TRUE, 5);
2551.         break;
2552.     case WAN_SECRET_DOOR_DETECTION:
2553.     case SPE_DETECT_UNSEEN:
2554.         /* findit() gives sufficient feedback to discover the wand even when
2555.            blinded or when it fails to find anything */
2556.         known = !!obj->dknown;
2557.         (void) findit();
2558.         break;
2559.     case WAN_STASIS: {
2560.         long tmp_until = svm.moves + (long) rn1(21, 10);
2561. 
2562.         /* no immediately obvious effect, and no message so that it isn't
2563.            distinguishable from other NODIR wands that produce no message;
2564.            for multiple zaps, keep the longest duration rather than latest */
2565.         if (tmp_until > svl.level.flags.stasis_until)
2566.             svl.level.flags.stasis_until = tmp_until;
2567.         break;
2568.     }
2569.     case WAN_CREATE_MONSTER:
2570.         /* create_critters() returns True iff hero sees a new monster appear */
2571.         if (create_critters(rn2(23) ? 1 : rn1(7, 2),
2572.                             (struct permonst *) 0, FALSE))
2573.             known = !!obj->dknown;
2574.         break;
2575.     case WAN_WISHING:
2576.         if (Luck + rn2(5) < 0) {
2577.             pline("Unfortunately, nothing happens.");
2578.             known = FALSE;
2579.         } else {
2580.             known = !!obj->dknown;
2581.             /* wand of wishing asks player what to wish for so always becomes
2582.                discovered (unless it hasn't been seen) */
2583.             makewish();
2584.         }
2585.         break;
2586.     case WAN_ENLIGHTENMENT:
2587.         known = !!obj->dknown;
2588.         /* do_enlightenmnt_effect() always describes enlightenment */
2589.         do_enlightenment_effect();
2590.         break;
2591.     default:
2592.         break;
2593.     }
2594. 
2595.     if (known) {
2596.         if (!objects[obj->otyp].oc_name_known)
2597.             more_experienced(0, 10);
2598.         /* effect was observable; discover the wand type provided
2599.            that the wand itself has been seen */
2600.         learnwand(obj);
2601.     }
2602. }
2603. 
2604. staticfn void
2605. backfire(struct obj *otmp)
2606. {
2607.     int dmg;
2608. 
2609.     otmp->in_use = TRUE; /* in case losehp() is fatal */
2610.     pline("%s suddenly explodes!", The(xname(otmp)));
2611.     dmg = d(otmp->spe + 2, 6);
2612.     losehp(Maybe_Half_Phys(dmg), "exploding wand", KILLED_BY_AN);
2613.     useupall(otmp);
2614. }
2615. 
2616. /* getobj callback for object to zap */
2617. staticfn int
2618. zap_ok(struct obj *obj)
2619. {
2620.     if (obj && obj->oclass == WAND_CLASS)
2621.         return GETOBJ_SUGGEST;
2622.     return GETOBJ_EXCLUDE;
2623. }
2624. 
2625. /* #zap command, 'z' (or 'y' if numbed_pad==-1) */
2626. int
2627. dozap(void)
2628. {
2629.     struct obj *obj;
2630.     int damage, need_dir;
2631. 
2632.     if (nohands(gy.youmonst.data)) {
2633.         You("aren't able to zap anything in your current form.");
2634.         return ECMD_OK;
2635.     }
2636.     if (check_capacity((char *) 0))
2637.         return ECMD_OK;
2638.     obj = getobj("zap", zap_ok, GETOBJ_NOFLAGS);
2639.     if (!obj)
2640.         return ECMD_CANCEL;
2641. 
2642.     check_unpaid(obj);
2643. 
2644.     need_dir = objects[obj->otyp].oc_dir != NODIR;
2645.     if (!zappable(obj)) {
2646.         pline1(nothing_happens);
2647.     } else if (obj->cursed && !rn2(WAND_BACKFIRE_CHANCE)) {
2648.         backfire(obj); /* the wand blows up in your face! */
2649.         exercise(A_STR, FALSE);
2650.         /* 'obj' is gone; skip update_inventory() because
2651.            backfire() -> useupall() -> freeinv() did it */
2652.         return ECMD_TIME;
2653.     } else if (need_dir && !getdir((char *) 0)) {
2654.         if (!Blind)
2655.             pline("%s glows and fades.", The(xname(obj)));
2656.         /* make him pay for knowing !NODIR */
2657.     } else if (need_dir && !u.dx && !u.dy && !u.dz) {
2658.         if ((damage = zapyourself(obj, TRUE)) != 0) {
2659.             char buf[BUFSZ];
2660. 
2661.             Sprintf(buf, "zapped %sself with %s",
2662.                     uhim(), killer_xname(obj));
2663.             losehp(Maybe_Half_Phys(damage), buf, NO_KILLER_PREFIX);
2664.         }
2665.     } else {
2666.         /*      Are we having fun yet?
2667.          * weffects -> buzz(obj->otyp) -> zhitm (temple priest) ->
2668.          * attack -> hitum -> known_hitum -> ghod_hitsu ->
2669.          * buzz(AD_ELEC) -> destroy_items(AD_ELEC) ->
2670.          * useup -> obfree -> dealloc_obj -> free(obj)
2671.          */
2672.         gc.current_wand = obj;
2673.         weffects(obj);
2674.         obj = gc.current_wand;
2675.         gc.current_wand = 0;
2676.     }
2677.     if (obj && obj->spe < 0) {
2678.         pline("%s to dust.", Tobjnam(obj, "turn"));
2679.         useupall(obj); /* calls freeinv() -> update_inventory() */
2680.     } else
2681.         update_inventory(); /* maybe used a charge */
2682.     return ECMD_TIME;
2683. }
2684. 
2685. /* Lock or unlock all boxes in inventory */
2686. staticfn void
2687. boxlock_invent(struct obj *obj)
2688. {
2689.     struct obj *otmp, *nextobj;
2690.     boolean boxing = FALSE;
2691. 
2692.     /* (un)lock carried boxes */
2693.     for (otmp = gi.invent; otmp; otmp = nextobj) {
2694.         nextobj = otmp->nobj;
2695.         if (Is_box(otmp)) {
2696.             (void) boxlock(otmp, obj);
2697.             boxing = TRUE;
2698.         }
2699.     }
2700.     if (boxing)
2701.         update_inventory(); /* in case any box->lknown has changed */
2702. }
2703. 
2704. int
2705. zapyourself(struct obj *obj, boolean ordinary)
2706. {
2707.     boolean learn_it = FALSE;
2708.     int damage = 0;
2709.     int orig_dmg = 0; /* for passing to destroy_items() */
2710. 
2711.     switch (obj->otyp) {
2712.     case WAN_STRIKING:
2713.     case SPE_FORCE_BOLT:
2714.         learn_it = TRUE;
2715.         if (Antimagic) {
2716.             shieldeff(u.ux, u.uy);
2717.             pline("Boing!");
2718.             monstseesu(M_SEEN_MAGR);
2719.         } else {
2720.             if (ordinary) {
2721.                 You("bash yourself!");
2722.                 damage = d(2, 12);
2723.             } else
2724.                 damage = d(1 + obj->spe, 6);
2725.             exercise(A_STR, FALSE);
2726.             monstunseesu(M_SEEN_MAGR);
2727.         }
2728.         break;
2729. 
2730.     case WAN_LIGHTNING:
2731.         learn_it = TRUE;
2732.         orig_dmg = d(12, 6);
2733.         if (!Shock_resistance) {
2734.             You("shock yourself!");
2735.             damage = orig_dmg;
2736.             exercise(A_CON, FALSE);
2737.             monstunseesu(M_SEEN_ELEC);
2738.         } else {
2739.             shieldeff(u.ux, u.uy);
2740.             You("zap yourself, but seem unharmed.");
2741.             monstseesu(M_SEEN_ELEC);
2742.             ugolemeffects(AD_ELEC, orig_dmg);
2743.         }
2744.         (void) destroy_items(&gy.youmonst, AD_ELEC, orig_dmg);
2745.         (void) flashburn((long) rnd(100), TRUE);
2746.         break;
2747. 
2748.     case SPE_FIREBALL:
2749.         You("explode a fireball on top of yourself!");
2750.         explode(u.ux, u.uy, 11, d(6, 6), WAND_CLASS, EXPL_FIERY);
2751.         break;
2752.     case WAN_FIRE:
2753.     case FIRE_HORN:
2754.         learn_it = TRUE;
2755.         orig_dmg = d(12, 6);
2756.         if (Fire_resistance) {
2757.             shieldeff(u.ux, u.uy);
2758.             You_feel("rather warm.");
2759.             monstseesu(M_SEEN_FIRE);
2760.             ugolemeffects(AD_FIRE, orig_dmg);
2761.         } else {
2762.             pline("You've set yourself afire!");
2763.             damage = orig_dmg;
2764.             monstunseesu(M_SEEN_FIRE);
2765.         }
2766.         burn_away_slime();
2767.         (void) burnarmor(&gy.youmonst);
2768.         (void) destroy_items(&gy.youmonst, AD_FIRE, orig_dmg);
2769.         ignite_items(gi.invent);
2770.         break;
2771. 
2772.     case WAN_COLD:
2773.     case SPE_CONE_OF_COLD:
2774.     case FROST_HORN:
2775.         learn_it = TRUE;
2776.         orig_dmg = d(12, 6);
2777.         if (Cold_resistance) {
2778.             shieldeff(u.ux, u.uy);
2779.             You_feel("a little chill.");
2780.             monstseesu(M_SEEN_COLD);
2781.             ugolemeffects(AD_COLD, orig_dmg);
2782.         } else {
2783.             You("imitate a popsicle!");
2784.             damage = orig_dmg;
2785.             monstunseesu(M_SEEN_COLD);
2786.         }
2787.         (void) destroy_items(&gy.youmonst, AD_COLD, orig_dmg);
2788.         break;
2789. 
2790.     case WAN_MAGIC_MISSILE:
2791.     case SPE_MAGIC_MISSILE:
2792.         learn_it = TRUE;
2793.         if (Antimagic) {
2794.             shieldeff(u.ux, u.uy);
2795.             pline_The("missiles bounce!");
2796.             monstseesu(M_SEEN_MAGR);
2797.         } else {
2798.             damage = d(4, 6);
2799.             pline("Idiot!  You've shot yourself!");
2800.             monstunseesu(M_SEEN_MAGR);
2801.         }
2802.         break;
2803. 
2804.     case WAN_POLYMORPH:
2805.     case SPE_POLYMORPH:
2806.         if (!Unchanging) {
2807.             learn_it = TRUE;
2808.             polyself(POLY_NOFLAGS);
2809.         }
2810.         break;
2811. 
2812.     case WAN_CANCELLATION:
2813.     case SPE_CANCELLATION:
2814.         (void) cancel_monst(&gy.youmonst, obj, TRUE, TRUE, TRUE);
2815.         break;
2816. 
2817.     case SPE_DRAIN_LIFE:
2818.         if (!Drain_resistance) {
2819.             learn_it = TRUE; /* (no effect for spells...) */
2820.             losexp("life drainage");
2821.         }
2822.         damage = 0; /* No additional damage */
2823.         break;
2824. 
2825.     case WAN_MAKE_INVISIBLE: {
2826.         /* have to test before changing HInvis but must change
2827.          * HInvis before doing newsym().
2828.          */
2829.         int msg = !Invis && !Blind && !BInvis;
2830. 
2831.         if (BInvis && uarmc->otyp == MUMMY_WRAPPING) {
2832.             /* A mummy wrapping absorbs it and protects you */
2833.             You_feel("rather itchy under %s.", yname(uarmc));
2834.             break;
2835.         }
2836.         incr_itimeout(&HInvis, rn1(15, 31));
2837.         if (msg) {
2838.             learn_it = TRUE;
2839.             newsym(u.ux, u.uy);
2840.             self_invis_message();
2841.         }
2842.         break;
2843.     }
2844. 
2845.     case WAN_SPEED_MONSTER:
2846.         /* no longer gives intrinsic, but gives very fast speed instead */
2847.         speed_up(rn1(25, 50));
2848.         learn_it = TRUE;
2849.         break;
2850. 
2851.     case WAN_SLEEP:
2852.     case SPE_SLEEP:
2853.         learn_it = TRUE;
2854.         if (Sleep_resistance) {
2855.             shieldeff(u.ux, u.uy);
2856.             You("don't feel sleepy!");
2857.             monstseesu(M_SEEN_SLEEP);
2858.         } else {
2859.             if (ordinary)
2860.                 pline_The("sleep ray hits you!");
2861.             else
2862.                 You("fall asleep!");
2863.             monstunseesu(M_SEEN_SLEEP);
2864.             fall_asleep(-rnd(50), TRUE);
2865.         }
2866.         break;
2867. 
2868.     case WAN_SLOW_MONSTER:
2869.     case SPE_SLOW_MONSTER:
2870.         if (HFast & (TIMEOUT | INTRINSIC)) {
2871.             learn_it = TRUE;
2872.             u_slow_down();
2873.         }
2874.         break;
2875. 
2876.     case WAN_TELEPORTATION:
2877.     case SPE_TELEPORT_AWAY:
2878.         tele();
2879.         /* same criteria as when mounted (zap_steed) */
2880.         if ((Teleport_control && !Stunned) || !couldsee(u.ux0, u.uy0)
2881.             || distu(u.ux0, u.uy0) >= 16)
2882.             learn_it = TRUE;
2883.         break;
2884. 
2885.     case WAN_DEATH:
2886.     case SPE_FINGER_OF_DEATH:
2887.         if (nonliving(gy.youmonst.data) || is_demon(gy.youmonst.data)) {
2888.             pline((obj->otyp == WAN_DEATH)
2889.                       ? "The wand shoots an apparently harmless beam at you."
2890.                       : "You seem no deader than before.");
2891.             break;
2892.         }
2893.         learn_it = TRUE;
2894.         Sprintf(svk.killer.name, "shot %sself with a death ray", uhim());
2895.         svk.killer.format = NO_KILLER_PREFIX;
2896.         /* probably don't need these to be urgent; player just gave input
2897.            without subsequent opportunity to dismiss --More-- with ESC */
2898.         urgent_pline("You irradiate yourself with pure energy!");
2899.         urgent_pline("You die.");
2900.         /* They might survive with an amulet of life saving */
2901.         done(DIED);
2902.         break;
2903.     case WAN_UNDEAD_TURNING:
2904.     case SPE_TURN_UNDEAD:
2905.         learn_it = TRUE;
2906.         unturn_you();
2907.         break;
2908.     case SPE_HEALING:
2909.     case SPE_EXTRA_HEALING:
2910.         learn_it = TRUE; /* (no effect for spells...) */
2911.         healup(d(6, obj->otyp == SPE_EXTRA_HEALING ? 8 : 4), 0, FALSE,
2912.                (obj->blessed || obj->otyp == SPE_EXTRA_HEALING));
2913.         You_feel("%sbetter.", obj->otyp == SPE_EXTRA_HEALING ? "much " : "");
2914.         break;
2915.     case WAN_LIGHT: /* (broken wand) */
2916.         /* assert( !ordinary ); */
2917.         damage = d(obj->spe, 25);
2918.         FALLTHROUGH;
2919.         /*FALLTHRU*/
2920.     case EXPENSIVE_CAMERA:
2921.         if (!damage)
2922.             damage = 5;
2923.         damage = lightdamage(obj, ordinary, damage);
2924.         damage += rnd(25);
2925.         if (flashburn((long) damage, FALSE))
2926.             learn_it = TRUE;
2927.         damage = 0; /* reset */
2928.         break;
2929.     case WAN_OPENING:
2930.     case SPE_KNOCK:
2931.         if (u.ustuck) {
2932.             /* zapping either self or holder/holdee [bhitm()] will release
2933.                holder's grasp from the hero or hero's grasp from holdee */
2934.             release_hold();
2935.             learn_it = TRUE;
2936.         }
2937.         if (Punished) {
2938.             learn_it = TRUE;
2939.             unpunish();
2940.         }
2941.         /* invent is hit iff hero doesn't escape from a trap */
2942.         if (!u.utrap || !openholdingtrap(&gy.youmonst, &learn_it)) {
2943.             boxlock_invent(obj);
2944.             /* trigger previously escaped trapdoor */
2945.             (void) openfallingtrap(&gy.youmonst, TRUE, &learn_it);
2946.         }
2947.         break;
2948.     case WAN_LOCKING:
2949.     case SPE_WIZARD_LOCK:
2950.         /* similar logic to opening; invent is hit iff no trap triggered */
2951.         if (u.utrap || !closeholdingtrap(&gy.youmonst, &learn_it)) {
2952.             boxlock_invent(obj);
2953.         }
2954.         break;
2955.     case WAN_DIGGING:
2956.     case SPE_DIG:
2957.     case SPE_DETECT_UNSEEN:
2958.     case WAN_NOTHING:
2959.         break;
2960.     case WAN_PROBING:
2961.         probe_objchain(gi.invent);
2962.         update_inventory();
2963.         learn_it = TRUE;
2964.         ustatusline();
2965.         break;
2966.     case SPE_STONE_TO_FLESH: {
2967.         struct obj *otmp, *onxt;
2968.         boolean didmerge;
2969. 
2970.         if (u.umonnum == PM_STONE_GOLEM) {
2971.             learn_it = TRUE;
2972.             (void) polymon(PM_FLESH_GOLEM);
2973.         }
2974.         if (Stoned) {
2975.             learn_it = TRUE;
2976.             fix_petrification(); /* saved! */
2977.         }
2978.         /* but at a cost.. */
2979.         for (otmp = gi.invent; otmp; otmp = onxt) {
2980.             onxt = otmp->nobj;
2981.             if (bhito(otmp, obj))
2982.                 learn_it = TRUE;
2983.         }
2984.         /*
2985.          * It is possible that we can now merge some inventory.
2986.          * Do a highly paranoid merge.  Restart from the beginning until
2987.          * no merges.  Don't merge worn items (in case of stone-to-flesh
2988.          * of rocks wielded in differing weapon/alt-wep/quiver slot).
2989.          */
2990.         do {
2991.             didmerge = FALSE;
2992.             for (otmp = gi.invent; !didmerge && otmp; otmp = otmp->nobj) {
2993.                 if (otmp->owornmask)
2994.                     continue;
2995.                 for (onxt = otmp->nobj; onxt; onxt = onxt->nobj)
2996.                     if (merged(&otmp, &onxt)) {
2997.                         didmerge = TRUE;
2998.                         break;
2999.                     }
3000.             }
3001.         } while (didmerge);
3002.         break;
3003.     }
3004.     default:
3005.         impossible("zapyourself: object %d used?", obj->otyp);
3006.         break;
3007.     }
3008.     /* if effect was observable then discover the wand type provided
3009.        that the wand itself has been seen */
3010.     if (learn_it)
3011.         learnwand(obj);
3012.     return damage;
3013. }
3014. 
3015. /* called when poly'd hero uses breath attack against self */
3016. void
3017. ubreatheu(struct attack *mattk)
3018. {
3019.     int dtyp = 20 + mattk->adtyp - 1;      /* breath by hero */
3020. 
3021.     zhitu(dtyp, mattk->damn, flash_str(dtyp, TRUE), u.ux, u.uy);
3022. }
3023. 
3024. /* light damages hero in gremlin form */
3025. int
3026. lightdamage(
3027.     struct obj *obj,  /* item making light (fake book if spell) */
3028.     boolean ordinary, /* wand/camera zap vs wand destruction */
3029.     int amt)          /* pseudo-damage used to determine blindness duration */
3030. {
3031.     char buf[BUFSZ];
3032.     const char *how;
3033.     int dmg = amt;
3034. 
3035.     if (dmg && gy.youmonst.data == &mons[PM_GREMLIN]) {
3036.         /* reduce high values (from destruction of wand with many charges) */
3037.         dmg = rnd(dmg);
3038.         if (dmg > 10)
3039.             dmg = 10 + rnd(dmg - 10);
3040.         if (dmg > 20)
3041.             dmg = 20;
3042.         pline("Ow, that light hurts%c", (dmg > 2 || u.mh <= 5) ? '!' : '.');
3043.         /* [composing killer/reason is superfluous here; if fatal, cause
3044.            of death will always be "killed while stuck in creature form"] */
3045.         if (obj->oclass == SCROLL_CLASS || obj->oclass == SPBOOK_CLASS)
3046.             ordinary = FALSE; /* say blasted rather than zapped */
3047.         how = (obj->oclass == SPBOOK_CLASS) ? "spell of light"
3048.               : (!obj->oartifact) ? ansimpleoname(obj)
3049.                 : bare_artifactname(obj);
3050.         Sprintf(buf, "%s %sself with %s", ordinary ? "zapped" : "blasted",
3051.                 uhim(), how);
3052.         /* might rehumanize(); could be fatal, but only for Unchanging */
3053.         losehp(Maybe_Half_Phys(dmg), buf, NO_KILLER_PREFIX);
3054.     }
3055.     return dmg;
3056. }
3057. 
3058. /* light[ning] causes blindness */
3059. boolean
3060. flashburn(long duration, boolean via_lightning)
3061. {
3062.     if (!resists_blnd(&gy.youmonst)) {
3063.         You(are_blinded_by_the_flash);
3064.         make_blinded(duration, FALSE);
3065.         if (!Blind)
3066.             Your1(vision_clears);
3067.         return TRUE;
3068.     }
3069.     /* if blinding is resisted due to magical equipment (Sunsword), give
3070.        a sparkle animation (even if also resisted due to being blind)
3071.        _unless_ this is lightning-induced; we don't want a double sparkle
3072.        if hero is both lightning resistant and blindness resistant, or
3073.        worse, have a single sparkle where the player confuses blindness
3074.        resistance for lightning resistance */
3075.     if (!via_lightning && resists_blnd_by_arti(&gy.youmonst)) {
3076.         shieldeff(u.ux, u.uy);
3077.         return TRUE;
3078.     }
3079.     return FALSE;
3080. }
3081. 
3082. /* you've zapped a wand downwards while riding
3083.  * Return TRUE if the steed was hit by the wand.
3084.  * Return FALSE if the steed was not hit by the wand.
3085.  */
3086. staticfn boolean
3087. zap_steed(struct obj *obj) /* wand or spell */
3088. {
3089.     int steedhit = FALSE;
3090. 
3091.     gb.bhitpos.x = u.usteed->mx, gb.bhitpos.y = u.usteed->my;
3092.     gn.notonhead = FALSE;
3093.     switch (obj->otyp) {
3094.     /*
3095.      * Wands that are allowed to hit the steed
3096.      * Carefully test the results of any that are
3097.      * moved here from the bottom section.
3098.      */
3099.     case WAN_PROBING:
3100.         probe_monster(u.usteed);
3101.         learnwand(obj);
3102.         steedhit = TRUE;
3103.         break;
3104.     case WAN_TELEPORTATION:
3105.     case SPE_TELEPORT_AWAY:
3106.         /* you go together */
3107.         tele();
3108.         /* same criteria as when unmounted (zapyourself) */
3109.         if ((Teleport_control && !Stunned) || !couldsee(u.ux0, u.uy0)
3110.             || distu(u.ux0, u.uy0) >= 16)
3111.             learnwand(obj);
3112.         steedhit = TRUE;
3113.         break;
3114. 
3115.     /* Default processing via bhitm() for these */
3116.     case SPE_CURE_SICKNESS:
3117.     case WAN_MAKE_INVISIBLE:
3118.     case WAN_CANCELLATION:
3119.     case SPE_CANCELLATION:
3120.     case WAN_POLYMORPH:
3121.     case SPE_POLYMORPH:
3122.     case WAN_STRIKING:
3123.     case SPE_FORCE_BOLT:
3124.     case WAN_SLOW_MONSTER:
3125.     case SPE_SLOW_MONSTER:
3126.     case WAN_SPEED_MONSTER:
3127.     case SPE_HEALING:
3128.     case SPE_EXTRA_HEALING:
3129.     case SPE_DRAIN_LIFE:
3130.     case WAN_OPENING:
3131.     case SPE_KNOCK:
3132.         (void) bhitm(u.usteed, obj);
3133.         steedhit = TRUE;
3134.         break;
3135. 
3136.     default:
3137.         steedhit = FALSE;
3138.         break;
3139.     }
3140.     return steedhit;
3141. }
3142. 
3143. /*
3144.  * cancel a monster (possibly the hero).  inventory is cancelled only
3145.  * if the monster is zapping itself directly, since otherwise the
3146.  * effect is too strong.  currently non-hero monsters do not zap
3147.  * themselves with cancellation.
3148.  */
3149. boolean
3150. cancel_monst(struct monst *mdef, struct obj *obj, boolean youattack,
3151.              boolean allow_cancel_kill, boolean self_cancel)
3152. {
3153.     static const char
3154.         writing_vanishes[] = "Some writing vanishes from %s head!",
3155.         your[] = "your"; /* should be extern */
3156.     boolean youdefend = (mdef == &gy.youmonst);
3157. 
3158.     if (youdefend ? (!youattack && Antimagic)
3159.                   : resist(mdef, obj->oclass, 0, NOTELL))
3160.         return FALSE; /* resisted cancellation */
3161. 
3162.     if (self_cancel) { /* 1st cancel inventory */
3163.         struct obj *otmp;
3164. 
3165.         for (otmp = (youdefend ? gi.invent : mdef->minvent); otmp;
3166.              otmp = otmp->nobj)
3167.             cancel_item(otmp);
3168. 
3169.         if (youdefend) {
3170.             disp.botl = TRUE; /* potential AC change */
3171.             find_ac();
3172.             /* update_inventory(); -- handled by caller */
3173.         }
3174.     }
3175. 
3176.     /* now handle special cases */
3177.     if (youdefend) {
3178.         if (Upolyd) { /* includes lycanthrope in creature form */
3179.             /*
3180.              * Return to normal form unless Unchanging.
3181.              * Hero in clay golem form dies if Unchanging.
3182.              * Does not cure lycanthropy or stop timed random polymorph.
3183.              */
3184.             if (u.umonnum == PM_CLAY_GOLEM) {
3185.                 if (!Blind)
3186.                     pline(writing_vanishes, your);
3187.                 else /* note: "dark" rather than "heavy" is intentional... */
3188.                     You_feel("%s headed.", Hallucination ? "dark" : "light");
3189.                 u.mh = 0; /* fatal; death handled by rehumanize() */
3190.             }
3191.             if (Unchanging && u.mh > 0)
3192.                 Your("amulet grows hot for a moment, then cools.");
3193.             else
3194.                 rehumanize();
3195.         }
3196.     } else {
3197.         mdef->mcan = 1;
3198.         /* force shapeshifter into its base form or mimic to unhide */
3199.         normal_shape(mdef);
3200. 
3201.         if (mdef->data == &mons[PM_CLAY_GOLEM]) {
3202.             if (canseemon(mdef))
3203.                 pline(writing_vanishes, s_suffix(mon_nam(mdef)));
3204.             /* !allow_cancel_kill is for Magicbane, where clay golem
3205.                will be killed somewhere back up the call/return chain... */
3206.             if (allow_cancel_kill) {
3207.                 if (youattack)
3208.                     killed(mdef);
3209.                 else
3210.                     monkilled(mdef, "", AD_SPEL);
3211.             }
3212.         }
3213.     }
3214.     return TRUE;
3215. }
3216. 
3217. /* you've zapped an immediate type wand up or down */
3218. staticfn boolean
3219. zap_updown(struct obj *obj) /* wand or spell, nonnull */
3220. {
3221.     boolean striking = FALSE, disclose = FALSE, map_zapped = FALSE;
3222.     coordxy x, y, xx, yy;
3223.     int ptmp;
3224.     struct obj *otmp;
3225.     struct engr *e;
3226.     struct trap *ttmp;
3227.     stairway *stway = gs.stairs;
3228. 
3229.     /* some wands have special effects other than normal bhitpile */
3230.     /* drawbridge might change <u.ux,u.uy> */
3231.     x = xx = u.ux;     /* <x,y> is zap location */
3232.     y = yy = u.uy;     /* <xx,yy> is drawbridge (portcullis) position */
3233.     ttmp = t_at(x, y); /* trap if there is one */
3234. 
3235.     switch (obj->otyp) {
3236.     case WAN_PROBING:
3237.         ptmp = 0;
3238.         if (u.dz < 0) {
3239.             You("probe towards the %s.", ceiling(x, y));
3240.         } else { /* down */
3241.             const char *surf;
3242.             schar ltyp, rememberedltyp = update_mapseen_for(x, y);
3243. 
3244.             ptmp += bhitpile(obj, bhito, x, y, u.dz);
3245.             /* sequencing: zap_map() calls force_decor() for ice or furniture;
3246.                we need to call it before probing for buried objects */
3247.             ltyp = SURFACE_AT(x, y);
3248.             zap_map(x, y, obj);
3249.             /*map_zapped = TRUE; // not needed due to early return*/
3250.             if (ltyp == ICE || IS_FURNITURE(ltyp)) {
3251.                 surf = "it";
3252.                 if (svl.lastseentyp[x][y] != rememberedltyp)
3253.                     ptmp += 1;
3254.             } else {
3255.                 surf = the(surface(x, y));
3256.             }
3257.             You("probe beneath %s.", surf);
3258.             ptmp += display_binventory(x, y, TRUE);
3259.         }
3260.         if (!ptmp)
3261.             Your("probe reveals nothing.");
3262.         return TRUE; /* we've done our own bhitpile */
3263.     case WAN_OPENING:
3264.     case SPE_KNOCK:
3265.         while (stway) {
3266.             if (!stway->isladder && !stway->up
3267.                 && stway->tolev.dnum == u.uz.dnum)
3268.                 break;
3269.             stway = stway->next;
3270.         }
3271.         /* up or down, but at closed portcullis only */
3272.         if (is_db_wall(x, y) && find_drawbridge(&xx, &yy)) {
3273.             open_drawbridge(xx, yy);
3274.             disclose = TRUE;
3275.         } else if (u.dz > 0 && stway && stway->sx == x && stway->sy == y
3276.                    /* can't use the stairs down to quest level 2 until
3277.                       leader "unlocks" them; give feedback if you try */
3278.                    && on_level(&u.uz, &qstart_level) && !ok_to_quest()) {
3279.             pline_The("stairs seem to ripple momentarily.");
3280.             disclose = TRUE;
3281.         }
3282.         /* down will release you from bear trap or web */
3283.         if (u.dz > 0 && u.utrap) {
3284.             (void) openholdingtrap(&gy.youmonst, &disclose);
3285.             /* down will trigger trapdoor, hole, or [spiked-] pit */
3286.         } else if (u.dz > 0 && !u.utrap) {
3287.             (void) openfallingtrap(&gy.youmonst, FALSE, &disclose);
3288.         }
3289.         break;
3290.     case WAN_STRIKING:
3291.     case SPE_FORCE_BOLT:
3292.         striking = TRUE;
3293.         FALLTHROUGH;
3294.         /*FALLTHRU*/
3295.     case WAN_LOCKING:
3296.     case SPE_WIZARD_LOCK:
3297.         /* down at open bridge or up or down at open portcullis */
3298.         if (((levl[x][y].typ == DRAWBRIDGE_DOWN)
3299.                  ? (u.dz > 0)
3300.                  : (is_drawbridge_wall(x, y) >= 0 && !is_db_wall(x, y)))
3301.             && find_drawbridge(&xx, &yy)) {
3302.             if (!striking)
3303.                 close_drawbridge(xx, yy);
3304.             else
3305.                 destroy_drawbridge(xx, yy);
3306.             disclose = TRUE;
3307.         } else if (striking && u.dz < 0 && rn2(3) && !Is_airlevel(&u.uz)
3308.                    && !Is_waterlevel(&u.uz) && !Underwater
3309.                    && !Is_qstart(&u.uz)) {
3310.             int dmg;
3311.             /* similar to zap_dig() */
3312.             pline("A rock is dislodged from the %s and falls on your %s.",
3313.                   ceiling(x, y), body_part(HEAD));
3314.             dmg = rnd(hard_helmet(uarmh) ? 2 : 6);
3315.             losehp(Maybe_Half_Phys(dmg), "falling rock", KILLED_BY_AN);
3316.             if ((otmp = mksobj_at(ROCK, x, y, FALSE, FALSE)) != 0) {
3317.                 (void) xname(otmp); /* set dknown, maybe bknown */
3318.                 stackobj(otmp);
3319.             }
3320.             newsym(x, y);
3321.         } else if (u.dz > 0 && ttmp) {
3322.             if (!striking && closeholdingtrap(&gy.youmonst, &disclose)) {
3323.                 ; /* now stuck in web or bear trap */
3324.             } else if (striking && ttmp->ttyp == TRAPDOOR) {
3325.                 /* striking transforms trapdoor into hole */
3326.                 if (Blind && !ttmp->tseen) {
3327.                     pline("%s beneath you shatters.", Something);
3328.                 } else if (!ttmp->tseen) { /* => !Blind */
3329.                     pline("There's a trapdoor beneath you; it shatters.");
3330.                 } else {
3331.                     pline("The trapdoor beneath you shatters.");
3332.                     disclose = TRUE;
3333.                 }
3334.                 ttmp->ttyp = HOLE;
3335.                 ttmp->tseen = 1;
3336.                 newsym(x, y);
3337.                 /* might fall down hole */
3338.                 dotrap(ttmp, NO_TRAP_FLAGS);
3339.             } else if (!striking && ttmp->ttyp == HOLE) {
3340.                 /* locking transforms hole into trapdoor */
3341.                 ttmp->ttyp = TRAPDOOR;
3342.                 if (Blind || !ttmp->tseen) {
3343.                     pline("Some %s swirls beneath you.",
3344.                           is_ice(x, y) ? "frost" : "dust");
3345.                 } else {
3346.                     ttmp->tseen = 1;
3347.                     newsym(x, y);
3348.                     pline("A trapdoor appears beneath you.");
3349.                     disclose = TRUE;
3350.                 }
3351.                 /* hadn't fallen down hole; won't fall now */
3352.             }
3353.         }
3354.         break;
3355.     case SPE_STONE_TO_FLESH:
3356.         if (Is_airlevel(&u.uz) || Is_waterlevel(&u.uz) || Underwater
3357.             || (Is_qstart(&u.uz) && u.dz < 0)) {
3358.             pline1(nothing_happens);
3359.         } else if (u.dz < 0) { /* we should do more... */
3360.             pline("Blood drips on your %s.", body_part(FACE));
3361.         } else if (u.dz > 0 && !OBJ_AT(u.ux, u.uy)) {
3362.             /*
3363.             Print this message only if there wasn't an engraving
3364.             affected here.  If water or ice, act like waterlevel case.
3365.             */
3366.             e = engr_at(u.ux, u.uy);
3367.             if (!(e && e->engr_type == ENGRAVE)) {
3368.                 if (is_pool(u.ux, u.uy) || is_ice(u.ux, u.uy))
3369.                     pline1(nothing_happens);
3370.                 else
3371.                     pline("Blood %ss %s your %s.",
3372.                           is_lava(u.ux, u.uy) ? "boil" : "pool",
3373.                           Levitation ? "beneath" : "at",
3374.                           makeplural(body_part(FOOT)));
3375.             }
3376.         }
3377.         break;
3378.     default:
3379.         break;
3380.     }
3381. 
3382.     if (u.dz > 0) {
3383.         /* zapping downward */
3384.         (void) bhitpile(obj, bhito, x, y, u.dz);
3385. 
3386.         /* note: engraving handling that used to be here has been moved
3387.            to zap_map() */
3388.         if (!map_zapped)
3389.             zap_map(x, y, obj);
3390. 
3391.     } else if (u.dz < 0) {
3392.         /* zapping upward */
3393. 
3394.         /* game flavor: if you're hiding under "something"
3395.          * a zap upward should hit that "something".
3396.          */
3397.         if (u.uundetected && hides_under(gy.youmonst.data)) {
3398.             int hitit = 0;
3399.             otmp = svl.level.objects[u.ux][u.uy];
3400. 
3401.             if (otmp)
3402.                 hitit = bhito(otmp, obj);
3403.             if (hitit) {
3404.                 (void) hideunder(&gy.youmonst);
3405.                 disclose = TRUE;
3406.             }
3407.         }
3408.     }
3409. 
3410.     return disclose;
3411. }
3412. 
3413. /* used by do_break_wand() was well as by weffects() */
3414. void
3415. zapsetup(void)
3416. {
3417.     go.obj_zapped = FALSE;
3418. }
3419. 
3420. void
3421. zapwrapup(void)
3422. {
3423.     /* if do_osshock() set obj_zapped while polying, give a message now */
3424.     if (go.obj_zapped)
3425.         You_feel("shuddering vibrations.");
3426.     go.obj_zapped = FALSE;
3427. }
3428. 
3429. /* called for various wand and spell effects - M. Stephenson */
3430. void
3431. weffects(struct obj *obj)
3432. {
3433.     int otyp = obj->otyp;
3434.     boolean disclose = FALSE, was_unkn = !objects[otyp].oc_name_known;
3435. 
3436.     exercise(A_WIS, TRUE);
3437.     if (u.usteed && (objects[otyp].oc_dir != NODIR) && !u.dx && !u.dy
3438.         && (u.dz > 0) && zap_steed(obj)) {
3439.         disclose = TRUE;
3440.     } else if (objects[otyp].oc_dir == IMMEDIATE) {
3441.         zapsetup(); /* reset obj_zapped */
3442.         if (u.uswallow) {
3443.             (void) bhitm(u.ustuck, obj);
3444.             /* [how about `bhitpile(u.ustuck->minvent)' effect?] */
3445.         } else if (u.dz) {
3446.             disclose = zap_updown(obj);
3447.         } else {
3448.             (void) bhit(u.dx, u.dy, rn1(8, 6), ZAPPED_WAND, bhitm, bhito,
3449.                         &obj);
3450.         }
3451.         zapwrapup(); /* give feedback for obj_zapped */
3452. 
3453.     } else if (objects[otyp].oc_dir == NODIR) {
3454.         zapnodir(obj);
3455. 
3456.     } else {
3457.         /* neither immediate nor directionless */
3458. 
3459.         if (otyp == WAN_DIGGING || otyp == SPE_DIG)
3460.             zap_dig();
3461.         else if (otyp >= SPE_MAGIC_MISSILE && otyp <= SPE_FINGER_OF_DEATH)
3462.             ubuzz(BZ_U_SPELL(BZ_OFS_SPE(otyp)), u.ulevel / 2 + 1);
3463.         else if (otyp >= WAN_MAGIC_MISSILE && otyp <= WAN_LIGHTNING)
3464.             ubuzz(BZ_U_WAND(BZ_OFS_WAN(otyp)),
3465.                   (otyp == WAN_MAGIC_MISSILE) ? 2 : 6);
3466.         else
3467.             impossible("weffects: unexpected spell or wand");
3468.         disclose = TRUE;
3469.     }
3470.     if (disclose) {
3471.         learnwand(obj);
3472.         if (was_unkn)
3473.             more_experienced(0, 10);
3474.     }
3475.     return;
3476. }
3477. 
3478. /* augment damage for a spell based on the hero's intelligence (and level) */
3479. int
3480. spell_damage_bonus(
3481.     int dmg) /* base amount to be adjusted by bonus or penalty */
3482. {
3483.     int intell = ACURR(A_INT);
3484. 
3485.     /* Punish low intelligence before low level else low intelligence
3486.        gets punished only when high level */
3487.     if (intell <= 9) {
3488.         /* -3 penalty, but never reduce combined amount below 1
3489.            (if dmg is 0 for some reason, we're careful to leave it there) */
3490.         if (dmg > 1)
3491.             dmg = (dmg <= 3) ? 1 : dmg - 3;
3492.     } else if (intell <= 13 || u.ulevel < 5)
3493.         ; /* no bonus or penalty; dmg remains same */
3494.     else if (intell <= 18)
3495.         dmg += 1;
3496.     else if (intell <= 24 || u.ulevel < 14)
3497.         dmg += 2;
3498.     else
3499.         dmg += 3; /* Int 25 */
3500. 
3501.     return dmg;
3502. }
3503. 
3504. /*
3505.  * Generate the to-hit bonus for a spell.  Based on the hero's skill in
3506.  * spell class and dexterity.
3507.  */
3508. staticfn int
3509. spell_hit_bonus(int skill)
3510. {
3511.     int hit_bon = 0;
3512.     int dex = ACURR(A_DEX);
3513. 
3514.     switch (P_SKILL(spell_skilltype(skill))) {
3515.     case P_ISRESTRICTED:
3516.     case P_UNSKILLED:
3517.         hit_bon = -4;
3518.         break;
3519.     case P_BASIC:
3520.         hit_bon = 0;
3521.         break;
3522.     case P_SKILLED:
3523.         hit_bon = 2;
3524.         break;
3525.     case P_EXPERT:
3526.         hit_bon = 3;
3527.         break;
3528.     }
3529. 
3530.     if (dex < 4)
3531.         hit_bon -= 3;
3532.     else if (dex < 6)
3533.         hit_bon -= 2;
3534.     else if (dex < 8)
3535.         hit_bon -= 1;
3536.     else if (dex < 14)
3537.         /* Will change when print stuff below removed */
3538.         hit_bon -= 0;
3539.     else
3540.         /* Even increment for dexterous heroes (see weapon.c abon) */
3541.         hit_bon += dex - 14;
3542. 
3543.     return hit_bon;
3544. }
3545. 
3546. const char *
3547. exclam(int force)
3548. {
3549.     /* force == 0 occurs e.g. with sleep ray */
3550.     /* note that large force is usual with wands so that !! would
3551.             require information about hand/weapon/wand */
3552.     return (const char *) ((force < 0) ? "?" : (force <= 4) ? "." : "!");
3553. }
3554. 
3555. void
3556. hit(
3557.     const char *str,    /* zap text or missile name */
3558.     struct monst *mtmp, /* target; for missile, might be hero */
3559.     const char *force)  /* usually either "." or "!" via exclam() */
3560. {
3561.     boolean verbosely = (mtmp == &gy.youmonst
3562.                          || (flags.verbose
3563.                              && (cansee(gb.bhitpos.x, gb.bhitpos.y)
3564.                                  || canspotmon(mtmp) || engulfing_u(mtmp))));
3565. 
3566.     pline("%s %s %s%s", The(str), vtense(str, "hit"),
3567.           verbosely ? mon_nam(mtmp) : "it", force);
3568. }
3569. 
3570. void
3571. miss(const char *str, struct monst *mtmp)
3572. {
3573.     pline("%s %s %s.", The(str), vtense(str, "miss"),
3574.           ((cansee(gb.bhitpos.x, gb.bhitpos.y) || canspotmon(mtmp))
3575.            && flags.verbose) ? mon_nam(mtmp) : "it");
3576. }
3577. 
3578. staticfn void
3579. skiprange(int range, int *skipstart, int *skipend)
3580. {
3581.     int tr = (range / 4);
3582.     int tmp = range - ((tr > 0) ? rnd(tr) : 0);
3583. 
3584.     *skipstart = tmp;
3585.     *skipend = tmp - ((tmp / 4) * rnd(3));
3586.     if (*skipend >= tmp)
3587.         *skipend = tmp - 1;
3588. }
3589. 
3590. /* Maybe explode a trap hit by object otmp's effect;
3591.    cancellation beam hitting a magical trap causes an explosion.
3592.    Might delete the trap; won't destroy otmp. */
3593. staticfn void
3594. maybe_explode_trap(
3595.     struct trap *ttmp,
3596.     struct obj *otmp,
3597.     boolean *learn_it)
3598. {
3599.     if (!ttmp || !otmp)
3600.         return;
3601.     if (otmp->otyp == WAN_CANCELLATION || otmp->otyp == SPE_CANCELLATION) {
3602.         coordxy x = ttmp->tx, y = ttmp->ty;
3603. 
3604.         if (undestroyable_trap(ttmp->ttyp)) {
3605.             shieldeff(x, y);
3606.             if (cansee(x, y)) {
3607.                 ttmp->tseen = 1;
3608.                 newsym(x, y);
3609.                 *learn_it = TRUE;
3610.             }
3611.         } else if (is_magical_trap(ttmp->ttyp)) {
3612.             int seeit = cansee(x, y);
3613. 
3614.             /* note: this explosion mustn't destroy otmp */
3615.             explode(x, y, -WAN_CANCELLATION,
3616.                     20 + d(3, 6), TRAP_EXPLODE, EXPL_MAGICAL);
3617.             deltrap(ttmp);
3618.             newsym(x, y);
3619.             if (seeit)
3620.                 *learn_it = TRUE;
3621.         }
3622.     }
3623. }
3624. 
3625. /* zap_map() occurs before hitting monsters or objects and handles wands or
3626.    spells that don't dish out 'elemental' damage */
3627. staticfn void
3628. zap_map(
3629.     coordxy x, coordxy y,
3630.     struct obj *obj) /* zapped wand, or book for cast spell */
3631. {
3632.     struct trap *ttmp = t_at(x, y);
3633.     coordxy dbx = x, dby = y; /* might be changed by drawbridge handling */
3634.     boolean learn_it = FALSE;
3635. 
3636.     /*
3637.      * We handle drawbridge for lateral zaps; zap_updown() handles up/down.
3638.      * Engravings only get hit by down zaps and we handle that here.
3639.      */
3640. 
3641.     /* cancellation */
3642.     maybe_explode_trap(ttmp, obj, &learn_it);
3643.     ttmp = t_at(x, y); /* refresh in case trap was altered or is gone */
3644. 
3645.     if (u.dz > 0) { /* zapping down */
3646.         char ebuf[BUFSZ], pristinebuf[BUFSZ], *etxt;
3647.         struct engr *e = engr_at(x, y);
3648. 
3649.         /* subset of engraving effects; none sets `disclose' */
3650.         if (e && e->engr_type != HEADSTONE) {
3651.             switch (obj->otyp) {
3652.             case WAN_POLYMORPH:
3653.             case SPE_POLYMORPH:
3654.                 del_engr(e);
3655.                 etxt = random_engraving(ebuf, pristinebuf);
3656.                 make_engr_at(x, y, etxt, pristinebuf, svm.moves, 0);
3657.                 break;
3658.             case WAN_CANCELLATION:
3659.             case SPE_CANCELLATION:
3660.             case WAN_MAKE_INVISIBLE:
3661.                 del_engr(e);
3662.                 break;
3663.             case WAN_TELEPORTATION:
3664.             case SPE_TELEPORT_AWAY:
3665.                 rloc_engr(e);
3666.                 break;
3667.             case SPE_STONE_TO_FLESH:
3668.                 if (e->engr_type == ENGRAVE) {
3669.                     /* only affects things in stone */
3670.                     pline_The(Hallucination
3671.                                   ? "floor runs like butter!"
3672.                                   : "edges on the floor get smoother.");
3673.                     wipe_engr_at(x, y, d(2, 4), TRUE);
3674.                 }
3675.                 break;
3676.             case WAN_STRIKING:
3677.             case SPE_FORCE_BOLT:
3678.                 wipe_engr_at(x, y, d(2, 4), TRUE);
3679.                 break;
3680.             default:
3681.                 break;
3682.             }
3683.         }
3684. 
3685.     } else if (!u.dz) {
3686.         int ltyp = levl[x][y].typ;
3687. 
3688.         if (find_drawbridge(&dbx, &dby)) {
3689.             switch (obj->otyp) {
3690.             case WAN_OPENING:
3691.             case SPE_KNOCK:
3692.                 /* dbwall: 'closed door' of raised drawbridge */
3693.                 if (is_db_wall(x, y)) {
3694.                     if (cansee(dbx, dby) || cansee(x, y))
3695.                         learn_it = TRUE;
3696.                     open_drawbridge(dbx, dby);
3697.                 }
3698.                 break;
3699.             case WAN_LOCKING:
3700.             case SPE_WIZARD_LOCK:
3701.                 /* drawbridge_down: span of lowered drawbridge */
3702.                 if ((cansee(dbx, dby) || cansee(x, y))
3703.                     && levl[dbx][dby].typ == DRAWBRIDGE_DOWN)
3704.                     learn_it = TRUE;
3705.                 close_drawbridge(dbx, dby);
3706.                 break;
3707.             case WAN_STRIKING:
3708.             case SPE_FORCE_BOLT:
3709.                 /* !drawbridge_up: not spot in front of raised bridge,
3710.                    so either span of lowered bridge or portcullis */
3711.                 if (ltyp != DRAWBRIDGE_UP) {
3712.                     learn_it = TRUE;
3713.                     destroy_drawbridge(dbx, dby);
3714.                 }
3715.                 break;
3716.             }
3717.         } /* find_drawbridge */
3718.     } /* !u.uz */
3719. 
3720.     if (obj->otyp == WAN_PROBING) {
3721.         /*
3722.          * Probing, either up/down or lateral.
3723.          */
3724.         schar ltyp;
3725.         int oldtyp, oldglyph;
3726. 
3727.         /* map terrain; might reveal a special room which is already within
3728.            view that hasn't been entered yet */
3729.         oldtyp = svl.lastseentyp[x][y];
3730.         oldglyph = glyph_at(x, y);
3731.         show_map_spot(x, y, FALSE);
3732.         if (oldtyp != svl.lastseentyp[x][y] || oldglyph != glyph_at(x, y)) {
3733.             /* TODO: ought to give some message */
3734.             learn_it = TRUE;
3735.         }
3736.         ltyp = SURFACE_AT(x, y);
3737.         /* secret door gets revealed, converted into regular door */
3738.         if (ltyp == SDOOR) {
3739.             cvt_sdoor_to_door(&levl[x][y]); /* .typ = DOOR */
3740.             recalc_block_point(x, y);
3741.             newsym(x, y);
3742.             if (cansee(x, y)) {
3743.                 pline("Probing reveals a secret door.");
3744.                 learn_it = TRUE;
3745.             } else if (Is_rogue_level(&u.uz)) { /* from zap_over_floor() */
3746.                 draft_message(FALSE); /* "You feel a draft." (open doorway) */
3747.             }
3748. 
3749.         /* secret corridor likewise, although only ones within view will
3750.            still be secret; for the !cansee(x,y) case, show_map_spot()
3751.            above has already converted the spot to regular corridor */
3752.         } else if (ltyp == SCORR) {
3753.             levl[x][y].typ = CORR;
3754.             unblock_point(x, y);
3755.             newsym(x, y);
3756.             pline("Probing exposes a secret corridor.");
3757.             learn_it = TRUE;
3758. 
3759.         /* if on or over ice, describe it ("solid ice", "thin ice", &c);
3760.            likewise for furniture in case hero is levitating while blind */
3761.         } else if (ltyp == ICE || IS_FURNITURE(ltyp)) {
3762.             if (u.dz > 0) { /* down, which also means x,y == u.ux,u.uy */
3763.                 force_decor(TRUE);
3764.                 learn_it = TRUE;
3765.             }
3766.         }
3767.         /*
3768.          * Probing reveals undiscovered traps.
3769.          *
3770.          * FIXME?  This finds floor traps even when zapping up and
3771.          * ceiling traps even when zapping down.
3772.          */
3773.         if (ttmp) {
3774.             const char *ttmpname;
3775.             unsigned t_already_seen = ttmp->tseen;
3776.             boolean use_the, hallu = Hallucination != 0;
3777. 
3778.             /* should probably be changed to use sense_trap(detect.c)
3779.                so that trap can temporarily be forced to be shown and
3780.                map browsing can take place before it reverts to being
3781.                covered by monster or object(s) */
3782.             ttmp->tseen = 1;
3783.             newsym(x, y);
3784. 
3785.             if (!t_already_seen || hallu) {
3786.                 ttmpname = trapname(ttmp->ttyp, FALSE);
3787.                 use_the = !hallu ? (ttmp->ttyp == VIBRATING_SQUARE
3788.                                     && Invocation_lev(&u.uz))
3789.                                  : !rn2(4);
3790.                 You("find %s%c",
3791.                     use_the ? the(ttmpname) : an(ttmpname),
3792.                     use_the ? '!' : '.');
3793.                 learn_it = !hallu;
3794.             }
3795.         } /* t_at() */
3796.     } /* probing */
3797. 
3798.     if (learn_it)
3799.         learnwand(obj);
3800.     return;
3801. }
3802. 
3803. /*
3804.  *  Called for the following distance effects:
3805.  *      when a weapon is thrown (weapon == THROWN_WEAPON)
3806.  *      when an object is kicked (KICKED_WEAPON)
3807.  *      when an IMMEDIATE wand is zapped (ZAPPED_WAND)
3808.  *      when a light beam is flashed (FLASHED_LIGHT)
3809.  *      when a mirror is applied (INVIS_BEAM)
3810.  *  A thrown/kicked object falls down at end of its range or when a monster
3811.  *  is hit.  The variable 'gb.bhitpos' is set to the final position of the
3812.  *  weapon thrown/zapped.  The ray of a wand may affect (by calling a provided
3813.  *  function) several objects and monsters on its path.  The return value
3814.  *  is the monster hit (weapon != ZAPPED_WAND), or a null monster pointer.
3815.  *
3816.  *  Thrown and kicked objects (THROWN_WEAPON or KICKED_WEAPON) may be
3817.  *  destroyed and *pobj set to NULL to indicate this.
3818.  *
3819.  *  Check !u.uswallow before calling bhit().
3820.  *  This function reveals the absence of a remembered invisible monster in
3821.  *  necessary cases (throwing or kicking weapons).  The presence of a real
3822.  *  one is revealed for a weapon, but if not a weapon is left up to fhitm().
3823.  *
3824.  *  If fhitm returns non-zero value, stops the beam and returns the monster
3825.  */
3826. struct monst *
3827. bhit(
3828.     int ddx, int ddy, int range,  /* direction and range */
3829.     enum bhit_call_types weapon,  /* defined in hack.h */
3830.     int (*fhitm)(MONST_P, OBJ_P), /* fns called when mon/obj hit */
3831.     int (*fhito)(OBJ_P, OBJ_P),
3832.     struct obj **pobj)            /* object tossed/used, set to NULL
3833.                                    * if object is destroyed */
3834. {
3835.     struct monst *mtmp, *result = (struct monst *) 0;
3836.     struct obj *obj = *pobj;
3837.     struct trap *ttmp;
3838.     uchar typ;
3839.     boolean shopdoor = FALSE, point_blank = TRUE;
3840.     boolean in_skip = FALSE, allow_skip = FALSE;
3841.     boolean tethered_weapon = FALSE;
3842.     int skiprange_start = 0, skiprange_end = 0, skipcount = 0;
3843.     struct obj *was_returning = (iflags.returning_missile == obj) ? obj
3844.                                 : (struct obj *) 0;
3845. 
3846.     if (weapon == KICKED_WEAPON) {
3847.         /* object starts one square in front of player */
3848.         gb.bhitpos.x = u.ux + ddx;
3849.         gb.bhitpos.y = u.uy + ddy;
3850.         range--;
3851.     } else {
3852.         gb.bhitpos.x = u.ux;
3853.         gb.bhitpos.y = u.uy;
3854.     }
3855. 
3856.     if (weapon == THROWN_WEAPON && obj && obj->otyp == ROCK) {
3857.         skiprange(range, &skiprange_start, &skiprange_end);
3858.         allow_skip = !rn2(3);
3859.     }
3860. 
3861.     if (weapon == FLASHED_LIGHT) {
3862.         tmp_at(DISP_BEAM, cmap_to_glyph(S_flashbeam));
3863.     } else if (weapon == THROWN_TETHERED_WEAPON && obj) {
3864.         tethered_weapon = TRUE;
3865.         weapon = THROWN_WEAPON; /* simplify 'if's that follow below */
3866.         tmp_at(DISP_TETHER, obj_to_glyph(obj, rn2_on_display_rng));
3867.     } else if (weapon != ZAPPED_WAND && weapon != INVIS_BEAM)
3868.         tmp_at(DISP_FLASH, obj_to_glyph(obj, rn2_on_display_rng));
3869. 
3870.     while (range-- > 0) {
3871.         coordxy x, y;
3872.         int xyglyph;
3873. 
3874.         gb.bhitpos.x += ddx;
3875.         gb.bhitpos.y += ddy;
3876.         x = gb.bhitpos.x;
3877.         y = gb.bhitpos.y;
3878. 
3879.         if (!isok(x, y)) {
3880.             gb.bhitpos.x -= ddx;
3881.             gb.bhitpos.y -= ddy;
3882.             break;
3883.         }
3884. 
3885.         if (is_pick(obj) && inside_shop(x, y)
3886.             && (mtmp = shkcatch(obj, x, y)) != 0) {
3887.             tmp_at(DISP_END, 0);
3888.             result = mtmp;
3889.             goto bhit_done;
3890.         }
3891. 
3892.         typ = levl[x][y].typ;
3893. 
3894.         /* WATER aka "wall of water" stops items */
3895.         if (IS_WATERWALL(typ) || typ == LAVAWALL) {
3896.             if (weapon == THROWN_WEAPON || weapon == KICKED_WEAPON)
3897.                 break;
3898.         }
3899. 
3900.         /* iron bars will block anything big enough and break some things */
3901.         if (weapon == THROWN_WEAPON || weapon == KICKED_WEAPON) {
3902.             if (obj->lamplit && !Blind)
3903.                 show_transient_light(obj, x, y);
3904.             if (typ == IRONBARS
3905.                 && hits_bars(pobj, x - ddx, y - ddy, x, y,
3906.                              point_blank ? 0 : !rn2(5), 1)) {
3907.                 /* caveat: obj might now be null... */
3908.                 obj = *pobj;  /* not currently needed due to 'break'; keep */
3909.                 nhUse(obj);   /* in case usage gets added after the loop   */
3910.                 gb.bhitpos.x -= ddx;
3911.                 gb.bhitpos.y -= ddy;
3912.                 break;
3913.             }
3914.         } else if (weapon == FLASHED_LIGHT) {
3915.             if (!Blind)
3916.                 show_transient_light((struct obj *) 0, x, y);
3917.         }
3918. 
3919.         if (weapon == ZAPPED_WAND) {
3920.             /* cancellation/opening/locking/striking/probing */
3921.             zap_map(x, y, obj);
3922.             /* terrain might have changed (exposed secret door|corridor) */
3923.             typ = levl[x][y].typ;
3924.         }
3925. 
3926.         mtmp = m_at(x, y);
3927.         ttmp = t_at(x, y);
3928.         if (!mtmp && ttmp && (ttmp->ttyp == WEB)
3929.             && (weapon == THROWN_WEAPON || weapon == KICKED_WEAPON)
3930.             && !rn2(3)) {
3931.             if (cansee(x, y)) {
3932.                 pline("%s gets stuck in a web!", Yname2(obj));
3933.                 ttmp->tseen = TRUE;
3934.                 newsym(x, y);
3935.             }
3936.             if (was_returning)
3937.                 iflags.returning_missile = (genericptr_t) 0;
3938.             break;
3939.         }
3940. 
3941.         /*
3942.          * skipping rocks
3943.          *
3944.          * skiprange_start is only set if this is a thrown rock
3945.          */
3946.         if (skiprange_start && (range == skiprange_start) && allow_skip) {
3947.             if (is_pool(x, y) && !mtmp) {
3948.                 in_skip = TRUE;
3949.                 if (!Blind)
3950.                     pline("%s %s%s.", Yname2(obj), otense(obj, "skip"),
3951.                           skipcount ? " again" : "");
3952.                 else
3953.                     You_hear("%s skip.", yname(obj));
3954.                 skipcount++;
3955.             } else if (skiprange_start > skiprange_end + 1) {
3956.                 --skiprange_start;
3957.             }
3958.         }
3959.         if (in_skip) {
3960.             if (range <= skiprange_end) {
3961.                 in_skip = FALSE;
3962.                 if (range > 3) /* another bounce? */
3963.                     skiprange(range, &skiprange_start, &skiprange_end);
3964.             } else if (mtmp && M_IN_WATER(mtmp->data)) {
3965.                 if (!Blind && canspotmon(mtmp))
3966.                     pline("%s %s over %s.", Yname2(obj), otense(obj, "pass"),
3967.                           mon_nam(mtmp));
3968.                 mtmp = (struct monst *) 0;
3969.             }
3970.         }
3971. 
3972.         /* if mtmp is a shade and missile passes harmlessly through it,
3973.            give message and skip it in order to keep going;
3974.            if attack is light and mtmp is a mimic pretending to be an
3975.            object, behave as if there is no monster here (if pretending
3976.            to be furniture, it will be revealed by flash_hits_mon());
3977.            thrown objects don't hit mimics pretending to be objects (both
3978.            because the hero is likely aiming to throw over what seems to
3979.            be an object rather than at it, and for balance because
3980.            otherwise mimics are too easy to identify by throwing gold at
3981.            them); exception: if the hero knows there is a monster there,
3982.            they will be aiming at the monster */
3983.         xyglyph = glyph_at(x, y);
3984.         if (mtmp && (((weapon == THROWN_WEAPON || weapon == KICKED_WEAPON)
3985.                       && (shade_miss(&gy.youmonst, mtmp, obj, TRUE, TRUE)
3986.                           || (M_AP_TYPE(mtmp) == M_AP_OBJECT
3987.                               && !glyph_is_monster(xyglyph)
3988.                               && !glyph_is_warning(xyglyph)
3989.                               && !glyph_is_invisible(xyglyph))))
3990.                      || (weapon == FLASHED_LIGHT
3991.                          && M_AP_TYPE(mtmp) == M_AP_OBJECT)))
3992.             mtmp = (struct monst *) 0;
3993. 
3994.         if (mtmp) {
3995.             gn.notonhead = (x != mtmp->mx || y != mtmp->my);
3996.             if (weapon == FLASHED_LIGHT) {
3997.                 /* FLASHED_LIGHT hitting invisible monster should pass
3998.                    through instead of stop so we call flash_hits_mon()
3999.                    directly rather than returning mtmp back to caller.
4000.                    That allows the flash to keep on going.  Note that we
4001.                    use mtmp->minvis, not canspotmon(), because it makes no
4002.                    difference whether hero can see the monster or not. */
4003.                 if (mtmp->minvis) {
4004.                     obj->ox = u.ux, obj->oy = u.uy;
4005.                     (void) flash_hits_mon(mtmp, obj);
4006.                 } else {
4007.                     tmp_at(DISP_END, 0);
4008.                     result = mtmp; /* caller will call flash_hits_mon() */
4009.                     goto bhit_done;
4010.                 }
4011.             } else if (weapon == INVIS_BEAM) {
4012.                 /* Like FLASHED_LIGHT, INVIS_BEAM should continue
4013.                    through invisible targets; unlike it, we aren't
4014.                    prepared for multiple hits so just get first one
4015.                    that's either visible or could see its invisible
4016.                    self.  [No tmp_at() cleanup is needed here.] */
4017.                 if (!mtmp->minvis || perceives(mtmp->data)) {
4018.                     result = mtmp;
4019.                     goto bhit_done;
4020.                 }
4021.             } else if (weapon != ZAPPED_WAND) {
4022.                 /* THROWN_WEAPON, KICKED_WEAPON */
4023.                 if (!tethered_weapon)
4024.                     tmp_at(DISP_END, 0);
4025. 
4026.                 if (cansee(x, y) && !canspotmon(mtmp))
4027.                     map_invisible(x, y);
4028.                 result = mtmp;
4029.                 goto bhit_done;
4030.             } else {
4031.                 /* ZAPPED_WAND */
4032.                 if ((*fhitm)(mtmp, obj)) {
4033.                     result = mtmp;
4034.                     goto bhit_done;
4035.                 }
4036.                 range -= 3;
4037.             }
4038.         } else {
4039.             if (weapon == ZAPPED_WAND && obj->otyp == WAN_PROBING
4040.                 && glyph_is_invisible(levl[x][y].glyph)) {
4041.                 unmap_object(x, y);
4042.                 newsym(x, y);
4043.             }
4044.         }
4045.         if (fhito) {
4046.             if (bhitpile(obj, fhito, x, y, 0))
4047.                 range--;
4048.         } else {
4049.             if (weapon == KICKED_WEAPON
4050.                 && ((obj->oclass == COIN_CLASS && OBJ_AT(x, y))
4051.                     || ship_object(obj, x, y, costly_spot(x, y)))) {
4052.                 tmp_at(DISP_END, 0);
4053.                 goto bhit_done; /* result == (struct monst *) 0 */
4054.             }
4055.         }
4056.         if (weapon == ZAPPED_WAND && (IS_DOOR(typ) || typ == SDOOR)) {
4057.             switch (obj->otyp) {
4058.             case WAN_OPENING:
4059.             case WAN_LOCKING:
4060.             case WAN_STRIKING:
4061.             case SPE_KNOCK:
4062.             case SPE_WIZARD_LOCK:
4063.             case SPE_FORCE_BOLT:
4064.                 if (doorlock(obj, x, y)) {
4065.                     if (cansee(x, y) || (obj->otyp == WAN_STRIKING && !Deaf))
4066.                         learnwand(obj);
4067.                     if (levl[x][y].doormask == D_BROKEN
4068.                         && *in_rooms(x, y, SHOPBASE)) {
4069.                         shopdoor = TRUE;
4070.                         add_damage(x, y, SHOP_DOOR_COST);
4071.                     }
4072.                 }
4073.                 break;
4074.             }
4075.         }
4076.         if (!ZAP_POS(typ) || closed_door(x, y)) {
4077.             gb.bhitpos.x -= ddx;
4078.             gb.bhitpos.y -= ddy;
4079.             break;
4080.         }
4081.         if (weapon != ZAPPED_WAND && weapon != INVIS_BEAM) {
4082.             /* 'I' present but no monster: erase; do this before tmp_at() */
4083.             if (glyph_is_invisible(levl[x][y].glyph) && cansee(x, y)) {
4084.                 unmap_object(x, y);
4085.                 newsym(x, y);
4086.             }
4087.             tmp_at(x, y);
4088.             nh_delay_output();
4089.             /* kicked objects fall in pools */
4090.             if ((weapon == KICKED_WEAPON) && is_pool_or_lava(x, y))
4091.                 break;
4092.             if (IS_SINK(typ) && weapon != FLASHED_LIGHT)
4093.                 break; /* physical objects fall onto sink */
4094.         }
4095.         /* limit range of ball so hero won't make an invalid move */
4096.         if (weapon == THROWN_WEAPON && range > 0
4097.             && obj->otyp == HEAVY_IRON_BALL) {
4098.             struct obj *bobj;
4099.             struct trap *t;
4100. 
4101.             if ((bobj = sobj_at(BOULDER, x, y)) != 0) {
4102.                 if (cansee(x, y))
4103.                     pline("%s hits %s.", The(distant_name(obj, xname)),
4104.                           an(xname(bobj)));
4105.                 range = 0;
4106.             } else if (obj == uball) {
4107.                 if (!test_move(x - ddx, y - ddy, ddx, ddy, TEST_MOVE)) {
4108.                     /* nb: it didn't hit anything directly */
4109.                     if (cansee(x, y))
4110.                         pline("%s jerks to an abrupt halt.",
4111.                               The(distant_name(obj, xname))); /* lame */
4112.                     range = 0;
4113.                 } else if (Sokoban && (t = t_at(x, y)) != 0
4114.                            && (is_pit(t->ttyp) || is_hole(t->ttyp))) {
4115.                     /* hero falls into the trap, so ball stops */
4116.                     range = 0;
4117.                 }
4118.             }
4119.         }
4120. 
4121.         /* thrown/kicked missile has moved away from its starting spot */
4122.         point_blank = FALSE; /* affects passing through iron bars */
4123.     }
4124. 
4125.     if ((weapon != ZAPPED_WAND && weapon != INVIS_BEAM && !tethered_weapon)
4126.         || (was_returning && was_returning != iflags.returning_missile))
4127.         tmp_at(DISP_END, 0);
4128. 
4129.     if (shopdoor)
4130.         pay_for_damage("destroy", FALSE);
4131. 
4132.  bhit_done:
4133.     /* note: for FLASHED_LIGHT, _caller_ must call transient_light_cleanup()
4134.        after possibly calling flash_hits_mon() */
4135.     if (weapon == THROWN_WEAPON || weapon == KICKED_WEAPON)
4136.         transient_light_cleanup();
4137. 
4138.     return result;
4139. }
4140. 
4141. /* process thrown boomerang, which travels a curving path...
4142.  * A multi-shot volley ought to have all missiles in flight at once,
4143.  * but we're called separately for each one.  We terminate the volley
4144.  * early on a failed catch since continuing to throw after being hit
4145.  * is too obviously silly.
4146.  */
4147. struct monst *
4148. boomhit(struct obj *obj, int dx, int dy)
4149. {
4150.     int i, ct;
4151.     int boom; /* showsym[] index  */
4152.     struct monst *mtmp;
4153.     boolean counterclockwise = URIGHTY; /* ULEFTY => clockwise */
4154.     int nhits = max(1, obj->spe + 1);
4155. 
4156.     /* counterclockwise traversal patterns, from @ to 1 then on through to 9
4157.      *  ..........................54.................................
4158.      *  ..................43.....6..3....765.........................
4159.      *  ..........32.....5..2...7...2...8...4....87..................
4160.      *  .........4..1....6..1...8..1....9...3...9..6.....98..........
4161.      *  ..21@....5...@...7..@....9@......@12....@...5...@..7.....@9..
4162.      *  .3...9....6..9....89.....................1..4...1..6....1..8.
4163.      *  .4...8.....78.............................23....2..5...2...7.
4164.      *  ..567............................................34....3..6..
4165.      *  ........................................................45...
4166.      * (invert rows for corresponding clockwise patterns)
4167.      */
4168. 
4169.     gb.bhitpos.x = u.ux;
4170.     gb.bhitpos.y = u.uy;
4171.     boom = counterclockwise ? S_boomleft : S_boomright;
4172.     i = xytodir(dx, dy);
4173.     tmp_at(DISP_FLASH, cmap_to_glyph(boom));
4174.     for (ct = 0; ct < 10; ct++) {
4175.         i = DIR_CLAMP(i);
4176.         boom = (S_boomleft + S_boomright - boom); /* toggle */
4177.         tmp_at(DISP_CHANGE, cmap_to_glyph(boom)); /* change glyph */
4178.         dx = xdir[i];
4179.         dy = ydir[i];
4180.         gb.bhitpos.x += dx;
4181.         gb.bhitpos.y += dy;
4182.         if (!isok(gb.bhitpos.x, gb.bhitpos.y)) {
4183.             gb.bhitpos.x -= dx;
4184.             gb.bhitpos.y -= dy;
4185.             break;
4186.         }
4187.         if ((mtmp = m_at(gb.bhitpos.x, gb.bhitpos.y)) != 0) {
4188.             m_respond(mtmp);
4189.             if (nhits-- < 0) {
4190.                 tmp_at(DISP_END, 0);
4191.                 return mtmp;
4192.             } else if (throwit_mon_hit(obj, mtmp) || !gt.thrownobj) {
4193.                 break;
4194.             }
4195.         }
4196.         if (!ZAP_POS(levl[gb.bhitpos.x][gb.bhitpos.y].typ)
4197.             || closed_door(gb.bhitpos.x, gb.bhitpos.y)) {
4198.             gb.bhitpos.x -= dx;
4199.             gb.bhitpos.y -= dy;
4200.             break;
4201.         }
4202.         if (u_at(gb.bhitpos.x, gb.bhitpos.y)) { /* ct == 9 */
4203.             if (Fumbling || rn2(20) >= ACURR(A_DEX)) {
4204.                 int dam = dmgval(obj, &gy.youmonst);
4205. 
4206.                 /* we hit ourselves */
4207.                 (void) thitu(10 + obj->spe, Maybe_Half_Phys(dam), &obj,
4208.                              "boomerang");
4209.                 endmultishot(TRUE);
4210.                 break;
4211.             } else { /* we catch it */
4212.                 tmp_at(DISP_END, 0);
4213.                 You("skillfully catch the boomerang.");
4214.                 return &gy.youmonst;
4215.             }
4216.         }
4217.         tmp_at(gb.bhitpos.x, gb.bhitpos.y);
4218.         nh_delay_output();
4219.         if (IS_SINK(levl[gb.bhitpos.x][gb.bhitpos.y].typ)) {
4220.             Soundeffect(se_boomerang_klonk, 75);
4221.             if (!Deaf)
4222.                 pline("Klonk!");
4223.             wake_nearto(gb.bhitpos.x, gb.bhitpos.y, 20);
4224.             break; /* boomerang falls on sink */
4225.         }
4226.         /* ct==0, initial position, we want next delta to be same;
4227.            ct==5, opposite position, repeat delta undoes first one */
4228.         if (ct % 5 != 0)
4229.             i = counterclockwise ? DIR_LEFT(i) : DIR_RIGHT(i);
4230.     }
4231.     tmp_at(DISP_END, 0); /* do not leave last symbol */
4232.     return (struct monst *) 0;
4233. }
4234. 
4235. /* used by buzz(); also used by munslime(muse.c); returns damage applied
4236.    to mon; note: caller is responsible for killing mon if damage is fatal */
4237. int
4238. zhitm(
4239.     struct monst *mon,  /* monster being hit */
4240.     int type,           /* zap or breath type */
4241.     int nd,             /* number of hit dice to use */
4242.     struct obj **ootmp) /* to return worn armor for caller to disintegrate */
4243. {
4244.     int tmp = 0, orig_dmg = 0; /* damage amount */
4245.     int damgtype = zaptype(type) % 10;
4246.     boolean sho_shieldeff = FALSE;
4247.     boolean spellcaster = is_hero_spell(type); /* maybe get a bonus! */
4248. 
4249.     *ootmp = (struct obj *) 0;
4250.     switch (damgtype) {
4251.     case ZT_MAGIC_MISSILE:
4252.         if (resists_magm(mon) || defended(mon, AD_MAGM)) {
4253.             sho_shieldeff = TRUE;
4254.             break;
4255.         }
4256.         tmp = d(nd, 6);
4257.         if (spellcaster)
4258.             tmp = spell_damage_bonus(tmp);
4259.         break;
4260.     case ZT_FIRE:
4261.         if (resists_fire(mon) || defended(mon, AD_FIRE)) {
4262.             sho_shieldeff = TRUE;
4263.             break;
4264.         }
4265.         tmp = d(nd, 6);
4266.         if (spellcaster)
4267.             tmp = spell_damage_bonus(tmp);
4268.         orig_dmg = tmp; /* includes spell bonus but not monster vuln to fire */
4269.         if (resists_cold(mon))
4270.             tmp += 7;
4271.         if (burnarmor(mon)) {
4272.             if (!rn2(3)) {
4273.                 tmp += destroy_items(mon, AD_FIRE, orig_dmg);
4274.                 ignite_items(mon->minvent);
4275.             }
4276.         }
4277.         break;
4278.     case ZT_COLD:
4279.         if (resists_cold(mon) || defended(mon, AD_COLD)) {
4280.             sho_shieldeff = TRUE;
4281.             break;
4282.         }
4283.         tmp = d(nd, 6);
4284.         if (spellcaster)
4285.             tmp = spell_damage_bonus(tmp);
4286.         orig_dmg = tmp; /* includes spell bonus but not monster vuln to cold */
4287.         if (resists_fire(mon))
4288.             tmp += d(nd, 3);
4289.         if (!rn2(3))
4290.             tmp += destroy_items(mon, AD_COLD, orig_dmg);
4291.         break;
4292.     case ZT_SLEEP:
4293.         /* resistance and shield effect and revealing concealed mimic are
4294.            handled by sleep_monst() */
4295.         tmp = 0;
4296.         (void) sleep_monst(mon, d(nd, 25),
4297.                            type == ZT_WAND(ZT_SLEEP) ? WAND_CLASS : '\0');
4298.         break;
4299.     case ZT_DEATH:                              /* death/disintegration */
4300.         if (abs(type) != ZT_BREATH(ZT_DEATH)) { /* death */
4301.             if (mon->data == &mons[PM_DEATH]) {
4302.                 healmon(mon, mon->mhpmax * 3 / 2, mon->mhpmax / 2);
4303.                 if (mon->mhpmax >= MAGIC_COOKIE)
4304.                     mon->mhpmax = MAGIC_COOKIE - 1;
4305.                 tmp = 0;
4306.                 break;
4307.             }
4308.             if (nonliving(mon->data) || is_demon(mon->data)
4309.                 || is_vampshifter(mon) || resists_magm(mon)) {
4310.                 /* similar to player */
4311.                 sho_shieldeff = TRUE;
4312.                 break;
4313.             }
4314.             type = -1; /* so they don't get saving throws */
4315.         } else {
4316.             struct obj *otmp2;
4317. 
4318.             if (resists_disint(mon) || defended(mon, AD_DISN)) {
4319.                 sho_shieldeff = TRUE;
4320.             } else if (mon->misc_worn_check & W_ARMS) {
4321.                 /* destroy shield; victim survives */
4322.                 *ootmp = which_armor(mon, W_ARMS);
4323.             } else if (mon->misc_worn_check & W_ARM) {
4324.                 /* destroy suit, also cloak if present */
4325.                 *ootmp = which_armor(mon, W_ARM);
4326.                 if ((otmp2 = which_armor(mon, W_ARMC)) != 0)
4327.                     m_useup(mon, otmp2);
4328.             } else {
4329.                 /* no suit, victim dies; destroy cloak
4330.                    and shirt now in case target gets life-saved */
4331.                 tmp = MAGIC_COOKIE;
4332.                 if ((otmp2 = which_armor(mon, W_ARMC)) != 0)
4333.                     m_useup(mon, otmp2);
4334.                 if ((otmp2 = which_armor(mon, W_ARMU)) != 0)
4335.                     m_useup(mon, otmp2);
4336.             }
4337.             type = -1; /* no saving throw wanted */
4338.             break;     /* not ordinary damage */
4339.         }
4340.         tmp = mon->mhp + 1;
4341.         break;
4342.     case ZT_LIGHTNING:
4343.         tmp = d(nd, 6);
4344.         if (spellcaster)
4345.             tmp = spell_damage_bonus(tmp);
4346.         orig_dmg = tmp;
4347.         if (resists_elec(mon) || defended(mon, AD_ELEC)) {
4348.             sho_shieldeff = TRUE;
4349.             tmp = 0;
4350.             /* can still blind the monster */
4351.         }
4352.         if (!resists_blnd(mon)
4353.             && !(type > 0 && engulfing_u(mon))
4354.             && nd > 2) {
4355.             /* sufficiently powerful lightning blinds monsters */
4356.             unsigned rnd_tmp = rnd(50);
4357.             mon->mcansee = 0;
4358.             if ((mon->mblinded + rnd_tmp) > 127)
4359.                 mon->mblinded = 127;
4360.             else
4361.                 mon->mblinded += rnd_tmp;
4362.         }
4363.         if (!rn2(3))
4364.             tmp += destroy_items(mon, AD_ELEC, orig_dmg);
4365.         break;
4366.     case ZT_POISON_GAS:
4367.         if (resists_poison(mon) || defended(mon, AD_DRST)) {
4368.             sho_shieldeff = TRUE;
4369.             break;
4370.         }
4371.         tmp = d(nd, 6);
4372.         break;
4373.     case ZT_ACID:
4374.         if (resists_acid(mon) || defended(mon, AD_ACID)) {
4375.             sho_shieldeff = TRUE;
4376.             break;
4377.         }
4378.         tmp = d(nd, 6);
4379.         if (!rn2(6))
4380.             acid_damage(MON_WEP(mon));
4381.         if (!rn2(6))
4382.             erode_armor(mon, ERODE_CORRODE);
4383.         break;
4384.     }
4385.     if (sho_shieldeff)
4386.         shieldeff(mon->mx, mon->my);
4387.     if (is_hero_spell(type) && (Role_if(PM_KNIGHT) && u.uhave.questart))
4388.         tmp *= 2;
4389.     if (tmp > 0 && type >= 0
4390.         && resist(mon, type < ZT_SPELL(0) ? WAND_CLASS : '\0', 0, NOTELL))
4391.         tmp /= 2;
4392.     if (tmp < 0)
4393.         tmp = 0; /* don't allow negative damage */
4394.     debugpline3("zapped monster hp = %d (= %d - %d)", mon->mhp - tmp,
4395.                 mon->mhp, tmp);
4396.     mon->mhp -= tmp;
4397.     return tmp;
4398. }
4399. 
4400. staticfn void
4401. zhitu(
4402.     int type, int nd,
4403.     const char *fltxt,
4404.     coordxy sx, coordxy sy)
4405. {
4406.     int dam = 0, abstyp = zaptype(type);
4407.     int orig_dam = 0;
4408. 
4409.     switch (abstyp % 10) {
4410.     case ZT_MAGIC_MISSILE:
4411.         if (Antimagic) {
4412.             shieldeff(sx, sy);
4413.             pline_The("missiles bounce off!");
4414.             monstseesu(M_SEEN_MAGR);
4415.         } else {
4416.             dam = d(nd, 6);
4417.             exercise(A_STR, FALSE);
4418.             monstunseesu(M_SEEN_MAGR);
4419.         }
4420.         break;
4421.     case ZT_FIRE:
4422.         orig_dam = d(nd, 6);
4423.         if (Fire_resistance) {
4424.             shieldeff(sx, sy);
4425.             You("don't feel hot!");
4426.             monstseesu(M_SEEN_FIRE);
4427.             ugolemeffects(AD_FIRE, orig_dam);
4428.         } else {
4429.             dam = orig_dam;
4430.             monstunseesu(M_SEEN_FIRE);
4431.         }
4432.         burn_away_slime();
4433.         if (burnarmor(&gy.youmonst)) { /* "body hit" */
4434.             if (!rn2(3))
4435.                 (void) destroy_items(&gy.youmonst, AD_FIRE, orig_dam);
4436.             if (!rn2(3))
4437.                 ignite_items(gi.invent);
4438.         }
4439.         break;
4440.     case ZT_COLD:
4441.         orig_dam = d(nd, 6);
4442.         if (Cold_resistance) {
4443.             shieldeff(sx, sy);
4444.             You("don't feel cold.");
4445.             monstseesu(M_SEEN_COLD);
4446.             ugolemeffects(AD_COLD, orig_dam);
4447.         } else {
4448.             dam = orig_dam;
4449.             monstunseesu(M_SEEN_COLD);
4450.         }
4451.         if (!rn2(3))
4452.             (void) destroy_items(&gy.youmonst, AD_COLD, orig_dam);
4453.         break;
4454.     case ZT_SLEEP:
4455.         if (Sleep_resistance) {
4456.             shieldeff(u.ux, u.uy);
4457.             You("don't feel sleepy.");
4458.             monstseesu(M_SEEN_SLEEP);
4459.         } else {
4460.             monstunseesu(M_SEEN_SLEEP);
4461.             fall_asleep(-d(nd, 25), TRUE); /* sleep ray */
4462.         }
4463.         break;
4464.     case ZT_DEATH:
4465.         if (abstyp == ZT_BREATH(ZT_DEATH)) {
4466.             boolean disn_prot = inventory_resistance_check(AD_DISN);
4467. 
4468.             if (Disint_resistance) {
4469.                 You("are not disintegrated.");
4470.                 monstseesu(M_SEEN_DISINT);
4471.                 break;
4472.             } else if (disn_prot) {
4473.                 break;
4474.             }
4475.             monstunseesu(M_SEEN_DISINT);
4476.             if (uarms) {
4477.                 /* destroy shield; other possessions are safe */
4478.                 (void) disintegrate_arm(uarms);
4479.                 break;
4480.             } else if (uarm) {
4481.                 /* destroy suit; if present, cloak goes too */
4482.                 if (uarmc)
4483.                     (void) disintegrate_arm(uarmc);
4484.                 (void) disintegrate_arm(uarm);
4485.                 break;
4486.             }
4487.             /* no shield or suit, you're dead; wipe out cloak
4488.                and/or shirt in case of life-saving or bones */
4489.             if (uarmc)
4490.                 (void) disintegrate_arm(uarmc);
4491.             if (uarmu)
4492.                 (void) disintegrate_arm(uarmu);
4493.         } else if (nonliving(gy.youmonst.data) || is_demon(gy.youmonst.data)) {
4494.             shieldeff(sx, sy);
4495.             You("seem unaffected.");
4496.             break;
4497.         } else if (Antimagic) {
4498.             shieldeff(sx, sy);
4499.             monstseesu(M_SEEN_MAGR);
4500.             You("aren't affected.");
4501.             break;
4502.         }
4503.         monstunseesu(M_SEEN_MAGR);
4504.         svk.killer.format = KILLED_BY_AN;
4505.         Strcpy(svk.killer.name, fltxt ? fltxt : "");
4506.         /* when killed by disintegration breath, don't leave corpse */
4507.         u.ugrave_arise = (type == -ZT_BREATH(ZT_DEATH)) ? -3 : NON_PM;
4508.         done(DIED);
4509.         return; /* lifesaved */
4510.     case ZT_LIGHTNING:
4511.         orig_dam = d(nd, 6);
4512.         if (Shock_resistance) {
4513.             shieldeff(sx, sy);
4514.             You("aren't affected.");
4515.             monstseesu(M_SEEN_ELEC);
4516.             ugolemeffects(AD_ELEC, orig_dam);
4517.         } else {
4518.             dam = orig_dam;
4519.             exercise(A_CON, FALSE);
4520.             monstunseesu(M_SEEN_ELEC);
4521.         }
4522.         if (!rn2(3))
4523.             (void) destroy_items(&gy.youmonst, AD_ELEC, orig_dam);
4524.         break;
4525.     case ZT_POISON_GAS:
4526.         poisoned("blast", A_DEX, "poisoned blast", 15, FALSE);
4527.         break;
4528.     case ZT_ACID:
4529.         if (Acid_resistance) {
4530.             pline_The("%s doesn't hurt.", hliquid("acid"));
4531.             monstseesu(M_SEEN_ACID);
4532.             dam = 0;
4533.         } else {
4534.             pline_The("%s burns!", hliquid("acid"));
4535.             dam = d(nd, 6);
4536.             exercise(A_STR, FALSE);
4537.             monstunseesu(M_SEEN_ACID);
4538.         }
4539.         /* using two weapons at once makes both of them more vulnerable */
4540.         if (!rn2(u.twoweap ? 3 : 6))
4541.             acid_damage(uwep);
4542.         if (u.twoweap && !rn2(3))
4543.             acid_damage(uswapwep);
4544.         if (!rn2(6))
4545.             erode_armor(&gy.youmonst, ERODE_CORRODE);
4546.         break;
4547.     }
4548. 
4549.     /*
4550.      * 5.0: when fatal, this used to yield "Killed by <fltxt>." without any
4551.      * information about who was responsible.  Now 'buzzer' is used to try
4552.      * to supply "zapped/cast/breathed by <mon> [imitating <other_mon>]."
4553.      *
4554.      * Room for improvement:  there is no monster available when player is
4555.      * hit by divine lighting or by Plane of Air thunderstorm so cause of
4556.      * death remains "killed by a bolt of lightning" w/o extra explanation.
4557.      *
4558.      * Wand of death, spell of finger of death, and disintegration breath
4559.      * don't use this routine so don't include 'inflicted by'.
4560.      */
4561.     {
4562.         char kbuf[BUFSZ];
4563.         struct obj *otmp = gc.current_wand;
4564.         /* fire horn and frost horn get handled as wands by caller */
4565.         const char *verb = (abstyp < 10) /* wand */
4566.                            ? ((otmp && otmp->oclass == TOOL_CLASS) ? "played"
4567.                               : "zapped")
4568.                            : (abstyp < 20) ? "cast"
4569.                              : (abstyp < 30) ? "exhaled"
4570.                                : "imagined"; /* should never happen */
4571. 
4572.         if (type < 0 || (type == 0 && gb.buzzer != 0)) {
4573.             /* if gb.buzzer is Null, kbuf[] will end up with just <fltxt> */
4574.             (void) death_inflicted_by(kbuf, fltxt, gb.buzzer);
4575.             /* change "death inflicted by mon" to "death <verb> by mon" */
4576.             if (gb.buzzer)
4577.                 (void) strsubst(kbuf, "inflicted", verb);
4578.         } else {
4579.             /* FIXME: "zapped by herself" is suitable for a rebound;
4580.                "zapped at herself" would be better if player explicitly
4581.                targeted hero */
4582.             Sprintf(kbuf, "%s %s by %sself", fltxt, verb, uhim());
4583.         }
4584.         /* Half_spell_damage protection yields half-damage for wands & spells,
4585.            including hero's own ricochets; breath attacks do full damage */
4586.         if (dam && Half_spell_damage && abstyp < 20)
4587.             dam = (dam + 1) / 2;
4588.         losehp(dam, kbuf, KILLED_BY_AN);
4589.     }
4590.     return;
4591. }
4592. 
4593. /*
4594.  * burn objects (such as scrolls and spellbooks) on floor
4595.  * at position x,y; return the number of objects burned
4596.  */
4597. int
4598. burn_floor_objects(
4599.     coordxy x, coordxy y,
4600.     boolean give_feedback, /* caller needs to decide about visibility checks */
4601.     boolean u_caused)
4602. {
4603.     struct obj *obj, *obj2;
4604.     long i, scrquan, delquan;
4605.     char buf1[BUFSZ], buf2[BUFSZ];
4606.     int cnt = 0;
4607. 
4608.     for (obj = svl.level.objects[x][y]; obj; obj = obj2) {
4609.         obj2 = obj->nexthere;
4610.         if (obj->oclass == SCROLL_CLASS || obj->oclass == SPBOOK_CLASS
4611.             || (obj->oclass == FOOD_CLASS
4612.                 && obj->otyp == GLOB_OF_GREEN_SLIME)) {
4613.             if (obj->otyp == SCR_FIRE || obj->otyp == SPE_FIREBALL
4614.                 || obj_resists(obj, 2, 100))
4615.                 continue;
4616.             scrquan = obj->quan; /* number present */
4617.             delquan = 0L;        /* number to destroy */
4618.             for (i = scrquan; i > 0L; i--)
4619.                 if (!rn2(3))
4620.                     delquan++;
4621.             if (delquan) {
4622.                 /* save name before potential delobj() */
4623.                 if (give_feedback) {
4624.                     obj->quan = 1L;
4625.                     Strcpy(buf1, u_at(x, y)
4626.                                      ? xname(obj)
4627.                                      : distant_name(obj, xname));
4628.                     obj->quan = 2L;
4629.                     Strcpy(buf2, u_at(x, y)
4630.                                      ? xname(obj)
4631.                                      : distant_name(obj, xname));
4632.                     obj->quan = scrquan;
4633.                 }
4634.                 /* useupf(), which charges, only if hero caused damage */
4635.                 if (u_caused)
4636.                     useupf(obj, delquan);
4637.                 else if (delquan < scrquan) {
4638.                     obj->quan -= delquan;
4639.                     obj->owt = weight(obj);
4640.                 } else
4641.                     delobj(obj);
4642.                 cnt += delquan;
4643.                 if (give_feedback) {
4644.                     if (delquan > 1L)
4645.                         pline("%ld %s burn.", delquan, buf2);
4646.                     else
4647.                         pline("%s burns.", An(buf1));
4648.                 }
4649.             }
4650.         }
4651.     }
4652.     /* This also ignites floor items, but does not change cnt
4653.        because they weren't consumed. */
4654.     ignite_items(svl.level.objects[x][y]);
4655.     return cnt;
4656. }
4657. 
4658. /* which direction a ray bounces.
4659.    current location is sx,sy, direction is ddx, ddy.
4660.    bounceback is 1/n chance of bouncing back.
4661.    caller must ensure sx,sy is a bouncing location: !ZAP_POS or closed_door
4662.  */
4663. staticfn void
4664. bounce_dir(coordxy sx, coordxy sy,
4665.            int *ddx, int *ddy,
4666.            int bounceback)
4667. {
4668.     if (!*ddx || !*ddy || (bounceback > 0 && !rn2(bounceback))) {
4669.         *ddx = -(*ddx);
4670.         *ddy = -(*ddy);
4671.     } else {
4672.         uchar rmn;
4673.         int bounce = 0;
4674.         coordxy lsy = sy - *ddy;
4675.         coordxy lsx = sx - *ddx;
4676. 
4677.         if (isok(sx, lsy) && ZAP_POS(rmn = levl[sx][lsy].typ)
4678.             && !closed_door(sx, lsy)
4679.             && (IS_ROOM(rmn) || (isok(sx + *ddx, lsy)
4680.                                  && ZAP_POS(levl[sx + *ddx][lsy].typ))))
4681.             bounce = 1;
4682.         if (isok(lsx, sy) && ZAP_POS(rmn = levl[lsx][sy].typ)
4683.             && !closed_door(lsx, sy)
4684.             && (IS_ROOM(rmn) || (isok(lsx, sy + *ddy)
4685.                                  && ZAP_POS(levl[lsx][sy + *ddy].typ))))
4686.             if (!bounce || rn2(2))
4687.                 bounce = 2;
4688.         switch (bounce) {
4689.         case 0:
4690.             *ddx = -(*ddx);
4691.             FALLTHROUGH;
4692.             /*FALLTHRU*/
4693.         case 1:
4694.             *ddy = -(*ddy);
4695.             break;
4696.         case 2:
4697.             *ddx = -(*ddx);
4698.             break;
4699.         }
4700.     }
4701. }
4702. 
4703. /* will zap/spell/breath attack score a hit against armor class `ac'? */
4704. staticfn int
4705. zap_hit(
4706.     int ac,
4707.     int type) /* either hero cast spell type or 0 */
4708. {
4709.     int chance = rn2(20);
4710.     int spell_bonus = type ? spell_hit_bonus(type) : 0;
4711. 
4712.     /* small chance for naked target to avoid being hit */
4713.     if (!chance)
4714.         return rnd(10) < ac + spell_bonus;
4715. 
4716.     /* very high armor protection does not achieve invulnerability */
4717.     ac = AC_VALUE(ac);
4718. 
4719.     return (3 - chance < ac + spell_bonus);
4720. }
4721. 
4722. staticfn void
4723. disintegrate_mon(
4724.     struct monst *mon,
4725.     int type, /* hero vs other */
4726.     const char *fltxt)
4727. {
4728.     struct obj *otmp, *otmp2, *m_amulet = mlifesaver(mon);
4729. 
4730.     if (canseemon(mon)) {
4731.         if (!m_amulet)
4732.             pline("%s is disintegrated!", Monnam(mon));
4733.         else
4734.             hit(fltxt, mon, "!");
4735.     }
4736. 
4737. /* note: worn amulet of life saving must be preserved in order to operate */
4738. #define oresist_disintegration(obj)                                       \
4739.     (objects[obj->otyp].oc_oprop == DISINT_RES || obj_resists(obj, 5, 50) \
4740.      || is_quest_artifact(obj) || obj == m_amulet)
4741. 
4742.     for (otmp = mon->minvent; otmp; otmp = otmp2) {
4743.         otmp2 = otmp->nobj;
4744.         if (!oresist_disintegration(otmp)) {
4745.             extract_from_minvent(mon, otmp, TRUE, TRUE);
4746.             obfree(otmp, (struct obj *) 0);
4747.         }
4748.     }
4749. 
4750. #undef oresist_disintegration
4751. 
4752.     if (type < 0)
4753.         monkilled(mon, (char *) 0, -AD_RBRE);
4754.     else
4755.         xkilled(mon, XKILL_NOMSG | XKILL_NOCORPSE);
4756. }
4757. 
4758. void
4759. ubuzz(int type, int nd)
4760. {
4761.     dobuzz(type, nd, u.ux, u.uy, u.dx, u.dy, TRUE, FALSE, FALSE);
4762. }
4763. 
4764. void
4765. buzz(int type, int nd, coordxy sx, coordxy sy, int dx, int dy)
4766. {
4767.     dobuzz(type, nd, sx, sy, dx, dy, TRUE, FALSE, FALSE);
4768. }
4769. 
4770. /*
4771.  * type ==   0 to   9 : you zapping a wand
4772.  * type ==  10 to  19 : you casting a spell
4773.  * type ==  20 to  29 : you breathing as a monster
4774.  * type == -10 to -19 : monster casting spell
4775.  * type == -20 to -29 : monster breathing at you
4776.  * type == -30 to -39 : monster zapping a wand
4777.  * called with dx = dy = 0 for vertical bolts
4778.  */
4779. void
4780. dobuzz(
4781.     int type,               /* 0..29 (by hero) or -39..-10 (by monster) */
4782.     int nd,                 /* damage strength ('number of dice') */
4783.     coordxy sx, coordxy sy, /* starting point */
4784.     int dx, int dy,         /* direction delta */
4785.     boolean sayhit, boolean saymiss, /* report out of sight hit/miss events */
4786.     boolean forcemiss)
4787. {
4788.     int range, fltyp = zaptype(type), damgtype = fltyp % 10;
4789.     coordxy lsx, lsy;
4790.     struct monst *mon;
4791.     coord save_bhitpos;
4792.     boolean shopdamage = FALSE,
4793.             fireball = (type == ZT_SPELL(ZT_FIRE)), /* set once */
4794.             gas_hit = FALSE; /* will be set during each iteration */
4795.     struct obj *otmp;
4796.     int spell_type;
4797.     int hdmgtype = Hallucination ? rn2(6) : damgtype;
4798. 
4799.     /* if it's a hero spell then get its SPE_TYPE */
4800.     spell_type = is_hero_spell(type) ? SPE_MAGIC_MISSILE + damgtype : 0;
4801. 
4802.     if (u.uswallow) {
4803.         int tmp;
4804. 
4805.         if (type < 0)
4806.             return;
4807.         tmp = zhitm(u.ustuck, type, nd, &otmp);
4808.         if (!u.ustuck) {
4809.             u.uswallow = 0;
4810.         } else {
4811.             pline("%s rips into %s%s", The(flash_str(fltyp, FALSE)),
4812.                   mon_nam(u.ustuck), exclam(tmp));
4813.             /* Using disintegration from the inside only makes a hole... */
4814.             if (tmp == MAGIC_COOKIE)
4815.                 u.ustuck->mhp = 0;
4816.             if (DEADMONSTER(u.ustuck))
4817.                 killed(u.ustuck);
4818.         }
4819.         return;
4820.     }
4821.     if (type < 0)
4822.         newsym(u.ux, u.uy);
4823.     range = rn1(7, 7);
4824.     if (dx == 0 && dy == 0)
4825.         range = 1;
4826.     save_bhitpos = gb.bhitpos;
4827. 
4828.     tmp_at(DISP_BEAM, zapdir_to_glyph(dx, dy, hdmgtype));
4829.     while (range-- > 0) {
4830.         lsx = sx;
4831.         sx += dx;
4832.         lsy = sy;
4833.         sy += dy;
4834.         if (!isok(sx, sy) || levl[sx][sy].typ == STONE)
4835.             goto make_bounce;
4836. 
4837.         mon = m_at(sx, sy);
4838.         if (cansee(sx, sy)) {
4839.             /* reveal/unreveal invisible monsters before tmp_at() */
4840.             if (mon && !canspotmon(mon))
4841.                 map_invisible(sx, sy);
4842.             else if (!mon)
4843.                 (void) unmap_invisible(sx, sy);
4844.             if (ZAP_POS(levl[sx][sy].typ)
4845.                 || (isok(lsx, lsy) && cansee(lsx, lsy)))
4846.                 tmp_at(sx, sy);
4847.             nh_delay_output(); /* wait a little */
4848.         }
4849. 
4850.         /* hit() and miss() need gb.bhitpos to match the target */
4851.         gb.bhitpos.x = sx, gb.bhitpos.y = sy;
4852.         gas_hit = (damgtype == ZT_POISON_GAS);
4853.         /* fireballs only damage when they explode; poison gas leaves
4854.            a trail of 1x1 clouds via zap_over_floor(), but that gets
4855.            skipped for a hit that is reflected so is deferred until we
4856.            know whether reflection is happening */
4857.         if (!fireball && !gas_hit) {
4858.             range += zap_over_floor(sx, sy, type, &shopdamage, TRUE, 0);
4859.             /* zap with fire -> melt ice -> drown monster, so monster
4860.                found and cached above might not be here any more */
4861.             mon = m_at(sx, sy);
4862.         }
4863. 
4864.         if (mon) {
4865.             if (fireball)
4866.                 break;
4867.             if (type >= 0)
4868.                 mon->mstrategy &= ~STRAT_WAITMASK;
4869.  buzzmonst:
4870.             gn.notonhead = (mon->mx != gb.bhitpos.x
4871.                             || mon->my != gb.bhitpos.y);
4872.             if (!forcemiss && zap_hit(find_mac(mon), spell_type)) {
4873.                 if (mon_reflects(mon, (char *) 0)) {
4874.                     if (cansee(mon->mx, mon->my)) {
4875.                         hit(flash_str(fltyp, FALSE), mon, exclam(0));
4876.                         shieldeff(mon->mx, mon->my);
4877.                         (void) mon_reflects(mon,
4878.                                             "But it reflects from %s %s!");
4879.                         gas_hit = FALSE;
4880.                     }
4881.                     dx = -dx;
4882.                     dy = -dy;
4883.                 } else {
4884.                     boolean mon_could_move = mon->mcanmove;
4885.                     int tmp = zhitm(mon, type, nd, &otmp);
4886. 
4887.                     if (is_rider(mon->data)
4888.                         && abs(type) == ZT_BREATH(ZT_DEATH)) {
4889.                         if (canseemon(mon)) {
4890.                             hit(flash_str(fltyp, FALSE), mon, ".");
4891.                             pline("%s disintegrates.", Monnam(mon));
4892.                             pline("%s body reintegrates before your %s!",
4893.                                   s_suffix(Monnam(mon)),
4894.                                   (eyecount(gy.youmonst.data) == 1)
4895.                                       ? body_part(EYE)
4896.                                       : makeplural(body_part(EYE)));
4897.                             pline("%s resurrects!", Monnam(mon));
4898.                         }
4899.                         mon->mhp = mon->mhpmax;
4900.                         break; /* Out of while loop */
4901.                     }
4902.                     if (mon->data == &mons[PM_DEATH] && damgtype == ZT_DEATH) {
4903.                         if (canseemon(mon)) {
4904.                             hit(flash_str(fltyp, FALSE), mon, ".");
4905.                             pline("%s absorbs the deadly %s!", Monnam(mon),
4906.                                   type == ZT_BREATH(ZT_DEATH) ? "blast"
4907.                                                               : "ray");
4908.                             pline("It seems even stronger than before.");
4909.                         }
4910.                         break; /* Out of while loop */
4911.                     }
4912. 
4913.                     if (tmp == MAGIC_COOKIE) { /* disintegration */
4914.                         disintegrate_mon(mon, type, flash_str(fltyp, FALSE));
4915.                     } else if (DEADMONSTER(mon)) {
4916.                         if (type < 0) {
4917.                             /* mon has just been killed by another monster */
4918.                             monkilled(mon, flash_str(fltyp, FALSE), AD_RBRE);
4919.                         } else {
4920.                             int xkflags = XKILL_GIVEMSG; /* killed(mon); */
4921. 
4922.                             /* killed by hero; we know 'type' isn't negative;
4923.                                if it's fire, highly flammable monsters leave
4924.                                no corpse; don't bother reporting that they
4925.                                "burn completely" -- unnecessary verbosity */
4926.                             if (damgtype == ZT_FIRE
4927.                                 /* paper golem or straw golem */
4928.                                 && completelyburns(mon->data))
4929.                                 xkflags |= XKILL_NOCORPSE;
4930.                             xkilled(mon, xkflags);
4931.                         }
4932.                     } else {
4933.                         if (!otmp) {
4934.                             /* normal non-fatal hit */
4935.                             if (sayhit || canseemon(mon))
4936.                                 hit(flash_str(fltyp, FALSE), mon, exclam(tmp));
4937.                         } else {
4938.                             /* some armor was destroyed; no damage done */
4939.                             if (canseemon(mon))
4940.                                 pline("%s %s is disintegrated!",
4941.                                       s_suffix(Monnam(mon)),
4942.                                       distant_name(otmp, xname));
4943.                             m_useup(mon, otmp);
4944.                         }
4945.                         if (mon_could_move && !mon->mcanmove) /* ZT_SLEEP */
4946.                             slept_monst(mon);
4947.                         if (damgtype != ZT_SLEEP)
4948.                             wakeup(mon, (type >= 0) ? TRUE : FALSE);
4949.                     }
4950.                 }
4951.                 range -= 2;
4952.             } else {
4953.                 if (saymiss
4954.                     || (canseemon(mon) && !disguised_as_non_mon(mon)))
4955.                     miss(flash_str(fltyp, FALSE), mon);
4956.             }
4957.         } else if (u_at(sx, sy) && range >= 0) {
4958.             nomul(0);
4959.             if (u.usteed && !rn2(3) && !mon_reflects(u.usteed, (char *) 0)) {
4960.                 mon = u.usteed;
4961.                 goto buzzmonst;
4962.             } else if (!forcemiss && zap_hit((int) u.uac, 0)) {
4963.                 range -= 2;
4964.                 pline_dir(xytodir(-dx, -dy), "%s hits you!",
4965.                           The(flash_str(fltyp, FALSE)));
4966.                 if (Reflecting) {
4967.                     if (!Blind) {
4968.                         (void) ureflects("But %s reflects from your %s!",
4969.                                          "it");
4970.                     } else
4971.                         pline("For some reason you are not affected.");
4972.                     monstseesu(M_SEEN_REFL);
4973.                     dx = -dx;
4974.                     dy = -dy;
4975.                     shieldeff(sx, sy);
4976.                     gas_hit = FALSE;
4977.                 } else {
4978.                     /* flash_str here only used for killer; suppress
4979.                      * hallucination */
4980.                     zhitu(type, nd, flash_str(fltyp, TRUE), sx, sy);
4981.                     monstunseesu(M_SEEN_REFL);
4982.                 }
4983.             } else if (!Blind) {
4984.                 pline("%s whizzes by you!", The(flash_str(fltyp, FALSE)));
4985.             } else if (damgtype == ZT_LIGHTNING) {
4986.                 Your("%s tingles.", body_part(ARM));
4987.             }
4988.             if (damgtype == ZT_LIGHTNING)
4989.                 (void) flashburn((long) d(nd, 50), TRUE);
4990.             stop_occupation();
4991.             nomul(0);
4992.         }
4993.         /* gas that missed or that hit without being reflected will leave
4994.            a 1x1 cloud here; the earlier zap_over_floor() was deferred */
4995.         if (gas_hit)
4996.             (void) zap_over_floor(sx, sy, type, &shopdamage, TRUE, 0);
4997. 
4998.         if (!ZAP_POS(levl[sx][sy].typ)
4999.             || (closed_door(sx, sy) && range >= 0)) {
5000.             int bchance;
5001. 
5002.  make_bounce:
5003.             bchance = (!isok(sx, sy) || levl[sx][sy].typ == STONE) ? 10
5004.                       : (In_mines(&u.uz) && IS_WALL(levl[sx][sy].typ)) ? 20
5005.                         : 75;
5006.             if ((--range > 0 && isok(lsx, lsy) && cansee(lsx, lsy))
5007.                 || fireball) {
5008.                 if (Is_airlevel(&u.uz)) { /* nothing to bounce off of */
5009.                     pline_The("%s vanishes into the aether!",
5010.                               flash_str(fltyp, FALSE));
5011.                     if (fireball)
5012.                         type = ZT_WAND(ZT_FIRE); /* skip pending fireball */
5013.                     break;
5014.                 } else if (fireball) {
5015.                     sx = lsx;
5016.                     sy = lsy;
5017.                     break; /* fireballs explode before the obstacle */
5018.                 } else
5019.                     pline_The("%s bounces!", flash_str(fltyp, FALSE));
5020.             }
5021.             bounce_dir(sx, sy, &dx, &dy, bchance);
5022.             tmp_at(DISP_CHANGE, zapdir_to_glyph(dx, dy, hdmgtype));
5023.         }
5024.     }
5025.     tmp_at(DISP_END, 0);
5026.     if (fireball)
5027.         explode(sx, sy, type, d(12, 6), 0, EXPL_FIERY);
5028.     if (shopdamage)
5029.         pay_for_damage(damgtype == ZT_FIRE ? "burn away"
5030.                        : damgtype == ZT_COLD ? "shatter"
5031.                          /* "damage" indicates wall rather than door */
5032.                          : damgtype == ZT_ACID ? "damage"
5033.                            : damgtype == ZT_DEATH ? "disintegrate"
5034.                              : "destroy",
5035.                        FALSE);
5036.     gb.bhitpos = save_bhitpos;
5037. }
5038. 
5039. void
5040. melt_ice(coordxy x, coordxy y, const char *msg)
5041. {
5042.     struct rm *lev = &levl[x][y];
5043.     struct obj *otmp;
5044.     struct monst *mtmp;
5045. 
5046.     if (!msg)
5047.         msg = "The ice crackles and melts.";
5048.     if (lev->typ == DRAWBRIDGE_UP || lev->typ == DRAWBRIDGE_DOWN) {
5049.         lev->drawbridgemask &= ~DB_ICE; /* revert to DB_MOAT */
5050.     } else { /* lev->typ == ICE */
5051.         lev->typ = (lev->icedpool == ICED_POOL ? POOL : MOAT);
5052.         lev->icedpool = 0;
5053.     }
5054.     spot_stop_timers(x, y, MELT_ICE_AWAY); /* no more ice to melt away */
5055.     if (t_at(x, y))
5056.         trap_ice_effects(x, y, TRUE); /* TRUE because ice_is_melting */
5057.     obj_ice_effects(x, y, FALSE);
5058.     unearth_objs(x, y);
5059.     if (Underwater)
5060.         vision_recalc(1);
5061.     newsym(x, y);
5062.     if (cansee(x, y) || u_at(x, y))
5063.         Norep("%s", msg);
5064.     if ((otmp = sobj_at(BOULDER, x, y)) != 0) {
5065.         if (cansee(x, y))
5066.             pline("%s settles...", An(xname(otmp)));
5067.         do {
5068.             obj_extract_self(otmp); /* boulder isn't being pushed */
5069.             if (!boulder_hits_pool(otmp, x, y, FALSE))
5070.                 impossible("melt_ice: no pool?");
5071.             /* try again if there's another boulder and pool didn't fill */
5072.         } while (is_pool(x, y) && (otmp = sobj_at(BOULDER, x, y)) != 0);
5073.         newsym(x, y);
5074.     }
5075.     if (u_at(x, y))
5076.         spoteffects(TRUE); /* possibly drown, notice objects */
5077.     else if (is_pool(x, y) && (mtmp = m_at(x, y)) != 0)
5078.         (void) minliquid(mtmp);
5079. }
5080. 
5081. #define MIN_ICE_TIME 50
5082. #define MAX_ICE_TIME 2000
5083. /*
5084.  * Usually start a melt_ice timer; sometimes the ice will become
5085.  * permanent instead.
5086.  */
5087. void
5088. start_melt_ice_timeout(
5089.     coordxy x, coordxy y,
5090.     long min_time) /* <x,y>'s old melt timeout (deleted by time we get here) */
5091. {
5092.     int when;
5093.     long where;
5094. 
5095.     when = (int) min_time;
5096.     if (when < MIN_ICE_TIME - 1)
5097.         when = MIN_ICE_TIME - 1;
5098. 
5099.     /* random timeout; surrounding ice locations ought to be a factor... */
5100.     while (++when <= MAX_ICE_TIME)
5101.         if (!rn2((MAX_ICE_TIME - when) + MIN_ICE_TIME))
5102.             break;
5103. 
5104.     /* if we're within MAX_ICE_TIME, install a melt timer;
5105.        otherwise, omit it to leave this ice permanent */
5106.     if (when <= MAX_ICE_TIME) {
5107.         where = ((long) x << 16) | (long) y;
5108.         (void) start_timer((long) when, TIMER_LEVEL, MELT_ICE_AWAY,
5109.                            long_to_any(where));
5110.     }
5111. }
5112. #undef MIN_ICE_TIME
5113. #undef MAX_ICE_TIME
5114. 
5115. /*
5116.  * Called when ice has melted completely away.
5117.  */
5118. void
5119. melt_ice_away(anything *arg, long timeout UNUSED)
5120. {
5121.     coordxy x, y;
5122.     long where = arg->a_long;
5123.     boolean save_mon_moving = svc.context.mon_moving; /* will be False */
5124. 
5125.     /* melt_ice -> minliquid -> mondead|xkilled shouldn't credit/blame hero */
5126.     svc.context.mon_moving = TRUE; /* hero isn't causing this ice to melt */
5127.     y = (coordxy) (where & 0xFFFF);
5128.     x = (coordxy) ((where >> 16) & 0xFFFF);
5129.     /* melt_ice does newsym when appropriate */
5130.     melt_ice(x, y, "Some ice melts away.");
5131.     svc.context.mon_moving = save_mon_moving;
5132. }
5133. 
5134. /* Burn floor scrolls, evaporate pools, etc... in a single square.
5135.  * Used both for normal bolts of fire, cold, etc... and for fireballs.
5136.  * Sets shopdamage to TRUE if a shop door is destroyed, and returns the
5137.  * amount by which range is reduced (value is negative and will be added
5138.  * to remaining range by caller; ignored by fireballs and poison gas).
5139.  */
5140. int
5141. zap_over_floor(
5142.     coordxy x, coordxy y,     /* location */
5143.     int type,                 /* damage type plus {wand|spell|breath} info */
5144.     boolean *shopdamage,      /* extra output if shop door is destroyed */
5145.     boolean ignoremon,        /* ignore any monster here */
5146.     short exploding_wand_typ) /* supplied when breaking a wand; or POT_OIL
5147.                                * when a lit potion of oil explodes */
5148. {
5149.     const char *zapverb;
5150.     struct monst *mon;
5151.     struct trap *t;
5152.     struct rm *lev = &levl[x][y];
5153.     boolean see_it = cansee(x, y), yourzap;
5154.     int rangemod = 0, damgtype = zaptype(type) % 10;
5155.     boolean lavawall = (lev->typ == LAVAWALL);
5156. 
5157.     if (type == PHYS_EXPL_TYPE) {
5158.         /* this won't have any effect on the floor */
5159.         return -1000; /* not a zap anyway, shouldn't matter */
5160.     }
5161. 
5162.     switch (damgtype) {
5163.     case ZT_FIRE:
5164.         t = t_at(x, y);
5165.         if (t && t->ttyp == WEB) {
5166.             /* a burning web is too flimsy to notice if you can't see it */
5167.             if (see_it)
5168.                 Norep("A web bursts into flames!");
5169.             (void) delfloortrap(t), t = (struct trap *) 0;
5170.             if (see_it)
5171.                 newsym(x, y);
5172.         }
5173.         if (is_ice(x, y)) {
5174.             melt_ice(x, y, (char *) 0);
5175.         } else if (is_pool(x, y)) {
5176.             boolean on_water_level = Is_waterlevel(&u.uz), msggiven = FALSE;
5177.             const char *msgtxt = (!Deaf)
5178.                                  ? "You hear hissing gas." /* Deaf-aware */
5179.                                  : (type >= 0)
5180.                                    ? "That seemed remarkably uneventful."
5181.                                    : (char *) 0;
5182. 
5183.             /* don't create steam clouds on Plane of Water; air bubble
5184.                movement and gas regions don't understand each other */
5185.             if (!on_water_level) {
5186.                 create_gas_cloud(x, y, rnd(5), 0); /* 1..5, no damg */
5187.                 if (iflags.last_msg == PLNMSG_ENVELOPED_IN_GAS)
5188.                     msggiven = TRUE;
5189.             }
5190. 
5191.             if (lev->typ != POOL) { /* MOAT or DRAWBRIDGE_UP or WATER */
5192.                 t = (struct trap *) 0;
5193.                 if (on_water_level)
5194.                     msgtxt = (see_it || !Deaf) ? "Some water boils." : 0;
5195.                 else if (see_it)
5196.                     msgtxt = "Some water evaporates.";
5197.             } else {
5198.                 rangemod -= 3;
5199.                 lev->typ = ROOM, lev->flags = 0;
5200.                 t = maketrap(x, y, PIT);
5201.                 /*if (t) -- this was before the vapor cloud was added --
5202.                       t->tseen = 1;*/
5203.                 if (see_it)
5204.                     msgtxt = "The water evaporates.";
5205.             }
5206.             if (msgtxt && !msggiven)
5207.                 Norep("%s", msgtxt);
5208. 
5209.             if (lev->typ == ROOM) { /* POOL changed to ROOM above */
5210.                 if ((mon = m_at(x, y)) != 0) {
5211.                     /* probably ought to do some hefty damage to any
5212.                        creature caught in boiling water;
5213.                        at a minimum, eels are forced out of hiding */
5214.                     if (is_swimmer(mon->data) && mon->mundetected) {
5215.                         mon->mundetected = 0;
5216.                     }
5217.                 }
5218.                 newsym(x, y);
5219.                 if (t) {
5220.                     /* if water walking/swimming/magical breathing, maybe fall
5221.                        into the new pit (after the water evaporation message);
5222.                        if flying or levitating, nothing will happen */
5223.                     if (u_at(x, y))
5224.                         dotrap(t, NO_TRAP_FLAGS);
5225.                     else if (mon)
5226.                         mintrap(mon, NO_TRAP_FLAGS);
5227.                 }
5228.             }
5229.         } else if (IS_FOUNTAIN(lev->typ)) {
5230.             create_gas_cloud(x, y, rnd(3), 0); /* 1..3, no damage */
5231.             if (see_it)
5232.                 pline("Steam billows from the fountain.");
5233.             rangemod -= 1;
5234.             dryup(x, y, type > 0);
5235.         }
5236.         break; /* ZT_FIRE */
5237. 
5238.     case ZT_COLD:
5239.         if (is_pool(x, y) || is_lava(x, y) || lavawall) {
5240.             boolean lava = (is_lava(x, y) || lavawall),
5241.                     moat = is_moat(x, y);
5242.             int chance = max(2, 5 + svl.level.flags.temperature * 10);
5243. 
5244.             if (IS_WATERWALL(lev->typ) || (lavawall && rn2(chance))) {
5245.                 /* For now, don't let WATER freeze. */
5246.                 Soundeffect(se_soft_crackling, 100);
5247.                 if (see_it)
5248.                     pline_The("%s freezes for a moment.",
5249.                               hliquid(lavawall ? "lava" : "water"));
5250.                 else
5251.                     You_hear("a soft crackling.");
5252.                 rangemod -= 1000; /* stop */
5253.             } else {
5254.                 char buf[BUFSZ];
5255. 
5256.                 Strcpy(buf, waterbody_name(x, y)); /* for MOAT */
5257.                 rangemod -= 3;
5258.                 if (lev->typ == DRAWBRIDGE_UP) {
5259.                     lev->drawbridgemask &= ~DB_UNDER; /* clear lava */
5260.                     lev->drawbridgemask |= (lava ? DB_FLOOR : DB_ICE);
5261.                 } else {
5262.                     lev->icedpool = lava ? 0
5263.                                          : (lev->typ == POOL) ? ICED_POOL
5264.                                                               : ICED_MOAT;
5265.                     if (lavawall) {
5266.                         if ((isok(x, y-1) && IS_WALL(levl[x][y-1].typ))
5267.                             || (isok(x, y+1) && IS_WALL(levl[x][y+1].typ)))
5268.                             lev->typ = VWALL;
5269.                         else
5270.                             lev->typ = HWALL;
5271.                         fix_wall_spines(max(0,x-1), max(0,y-1),
5272.                                         min(COLNO-1,x+1), min(ROWNO-1,y+1));
5273.                     } else {
5274.                         lev->typ = lava ? ROOM : ICE;
5275.                     }
5276.                 }
5277.                 bury_objs(x, y);
5278.                 if (!lava) {
5279.                     Soundeffect(se_soft_crackling, 30);
5280.                 }
5281.                 if (see_it) {
5282.                     if (lava)
5283.                         Norep("The %s cools and solidifies.",
5284.                               hliquid("lava"));
5285.                     else if (moat)
5286.                         Norep("The %s is bridged with ice!", buf);
5287.                     else
5288.                         Norep("The %s freezes.", hliquid("water"));
5289.                     newsym(x, y);
5290.                 } else if (!lava) {
5291.                     You_hear("a crackling sound.");
5292.                 }
5293.                 if (u_at(x, y)) {
5294.                     if (u.uinwater) { /* not just `if (Underwater)' */
5295.                         /* leave the no longer existent water */
5296.                         set_uinwater(0); /* u.uinwater = 0 */
5297.                         u.uundetected = 0;
5298.                         docrt();
5299.                         gv.vision_full_recalc = 1;
5300.                     } else if (u.utrap && u.utraptype == TT_LAVA) {
5301.                         if (Passes_walls) {
5302.                             You("pass through the now-solid rock.");
5303.                             reset_utrap(TRUE);
5304.                         } else {
5305.                             set_utrap(rn1(50, 20), TT_INFLOOR);
5306.                             You("are firmly stuck in the cooling rock.");
5307.                         }
5308.                     }
5309.                 } else if ((mon = m_at(x, y)) != 0) {
5310.                     /* probably ought to do some hefty damage to any
5311.                        non-ice creature caught in freezing water;
5312.                        at a minimum, eels are forced out of hiding */
5313.                     if (is_swimmer(mon->data) && mon->mundetected) {
5314.                         mon->mundetected = 0;
5315.                         newsym(x, y);
5316.                     }
5317.                 }
5318.                 if (!lava) {
5319.                     start_melt_ice_timeout(x, y, 0L);
5320.                     obj_ice_effects(x, y, TRUE);
5321.                 }
5322.             } /* ?WATER */
5323. 
5324.         } else if (is_ice(x, y)) {
5325.             long melt_time;
5326. 
5327.             /* Already ice here, so just firm it up. */
5328.             /* Now ensure that only ice that is already timed is affected */
5329.             if ((melt_time = spot_time_left(x, y, MELT_ICE_AWAY)) != 0L) {
5330.                 spot_stop_timers(x, y, MELT_ICE_AWAY);
5331.                 start_melt_ice_timeout(x, y, melt_time);
5332.             }
5333.         }
5334.         break; /* ZT_COLD */
5335. 
5336.     case ZT_POISON_GAS:
5337.         /* poison gas with range 1: green dragon/iron golem breath (AD_DRST);
5338.            caller is placing a series of 1x1 clouds along the zap's path;
5339.            <x,y> for wall locations might be included--reject those */
5340.         if (ZAP_POS(lev->typ))
5341.             (void) create_gas_cloud(x, y, 1, 8);
5342.         break;
5343. 
5344.     case ZT_LIGHTNING:
5345.         FALLTHROUGH;
5346.         /*FALLTHRU*/
5347.     case ZT_ACID:
5348.         if (lev->typ == IRONBARS) {
5349.             if (damgtype == ZT_LIGHTNING && rn2(10))
5350.                 break;
5351.             if ((lev->wall_info & W_NONDIGGABLE) != 0) {
5352.                 if (see_it)
5353.                     Norep("The %s %s somewhat but remain intact.",
5354.                           defsyms[S_bars].explanation,
5355.                           (damgtype == ZT_ACID) ? "corrode" : "melt");
5356.                 /* but nothing actually happens... */
5357.             } else {
5358.                 rangemod -= 3;
5359.                 if (see_it)
5360.                     Norep("The %s %s.", defsyms[S_bars].explanation,
5361.                           (damgtype == ZT_ACID) ? "corrode away" : "melt");
5362.                 dissolve_bars(x, y);
5363.                 if (*in_rooms(x, y, SHOPBASE)) {
5364.                     add_damage(x, y, (type >= 0) ? SHOP_BARS_COST : 0L);
5365.                     if (type >= 0)
5366.                         *shopdamage = TRUE;
5367.                 }
5368.             }
5369.         }
5370.         break; /* ZT_ACID */
5371. 
5372.     default:
5373.         break;
5374.     }
5375. 
5376.     /* set up zap text for possible door feedback; for exploding wand, we
5377.        want "the blast" rather than "your blast" even if hero caused it */
5378.     yourzap = (type >= 0 && !exploding_wand_typ);
5379.     zapverb = "blast"; /* breath attack or wand explosion */
5380.     if (!exploding_wand_typ) {
5381.         int ztype = zaptype(type); /* 0..29 for both hero and monsters */
5382. 
5383.         if (ztype < ZT_SPELL(0))
5384.             zapverb = "bolt"; /* wand zap */
5385.         else if (ztype < ZT_BREATH(0))
5386.             zapverb = "spell";
5387.     } else if (exploding_wand_typ == POT_OIL
5388.                || exploding_wand_typ == SCR_FIRE) {
5389.         /* breakobj() -> explode_oil() -> splatter_burning_oil()
5390.            -> explode(ZT_SPELL(ZT_FIRE), BURNING_OIL)
5391.            -> zap_over_floor(ZT_SPELL(ZT_FIRE), POT_OIL) */
5392.         /* leave zapverb as "blast"; exploding_wand_typ was nonzero, so
5393.            'yourzap' is FALSE and the result will be "the blast" */
5394.         exploding_wand_typ = 0; /* not actually an exploding wand */
5395.     }
5396. 
5397.     /* secret door gets revealed, converted into regular door */
5398.     if (levl[x][y].typ == SDOOR) {
5399.         cvt_sdoor_to_door(&levl[x][y]); /* .typ = DOOR */
5400.         recalc_block_point(x, y);
5401.         /* target spot will now pass closed_door() test below
5402.            (except on rogue level) */
5403.         newsym(x, y);
5404.         if (see_it)
5405.             pline("%s %s reveals a secret door.",
5406.                   yourzap ? "Your" : "The", zapverb);
5407.         else if (Is_rogue_level(&u.uz))
5408.             draft_message(FALSE); /* "You feel a draft." (open doorway) */
5409.     }
5410. 
5411.     /* regular door absorbs remaining zap range, possibly gets destroyed */
5412.     if (closed_door(x, y)) {
5413.         int new_doormask = -1;
5414.         const char *see_txt = 0, *sense_txt = 0, *hear_txt = 0;
5415. 
5416.         rangemod = -1000;
5417.         switch (damgtype) {
5418.         case ZT_FIRE:
5419.             new_doormask = D_NODOOR;
5420.             see_txt = "The door is consumed in flames!";
5421.             sense_txt = "smell smoke.";
5422.             break;
5423.         case ZT_COLD:
5424.             new_doormask = D_NODOOR;
5425.             see_txt = "The door freezes and shatters!";
5426.             hear_txt = "a deep cracking sound.";
5427.             break;
5428.         case ZT_DEATH:
5429.             /* death spells/wands don't disintegrate */
5430.             if (abs(type) != ZT_BREATH(ZT_DEATH))
5431.                 goto def_case;
5432.             new_doormask = D_NODOOR;
5433.             see_txt = "The door disintegrates!";
5434.             hear_txt = "crashing wood.";
5435.             break;
5436.         case ZT_LIGHTNING:
5437.             new_doormask = D_BROKEN;
5438.             see_txt = "The door splinters!";
5439.             hear_txt = "crackling.";
5440.             break;
5441.         default:
5442.  def_case:
5443.             if (exploding_wand_typ > 0) {
5444.                 /* Magical explosion from misc exploding wand */
5445.                 if (exploding_wand_typ == WAN_STRIKING) {
5446.                     new_doormask = D_BROKEN;
5447.                     see_txt = "The door crashes open!";
5448.                     sense_txt = "feel a burst of cool air.";
5449.                     break;
5450.                 }
5451.             }
5452.             if (see_it) {
5453.                 /* "the door absorbs the blast" would be
5454.                    inaccurate for an exploding wand since
5455.                    other adjacent locations still get hit */
5456.                 if (exploding_wand_typ)
5457.                     pline_The("door remains intact.");
5458.                 else
5459.                     pline_The("door absorbs %s %s!", yourzap ? "your" : "the",
5460.                               zapverb);
5461.             } else
5462.                 You_feel("vibrations.");
5463.             break;
5464.         }
5465.         if (new_doormask >= 0) { /* door gets broken */
5466.             if (*in_rooms(x, y, SHOPBASE)) {
5467.                 if (type >= 0) {
5468.                     add_damage(x, y, SHOP_DOOR_COST);
5469.                     *shopdamage = TRUE;
5470.                 } else /* caused by monster */
5471.                     add_damage(x, y, 0L);
5472.             }
5473.             lev->doormask = new_doormask;
5474.             recalc_block_point(x, y); /* vision */
5475.             if (see_it) {
5476.                 pline1(see_txt);
5477.                 newsym(x, y);
5478.             } else if (sense_txt) {
5479.                 You1(sense_txt);
5480.             } else if (hear_txt)
5481.                 You_hear1(hear_txt);
5482.             if (picking_at(x, y)) {
5483.                 stop_occupation();
5484.                 reset_pick();
5485.             }
5486.         }
5487.     }
5488. 
5489.     if (OBJ_AT(x, y) && damgtype == ZT_FIRE)
5490.         if (burn_floor_objects(x, y, FALSE, type > 0) && couldsee(x, y)) {
5491.             newsym(x, y);
5492.             You("%s of smoke.", !Blind ? "see a puff" : "smell a whiff");
5493.         }
5494.     if (!ignoremon && (mon = m_at(x, y)) != 0)
5495.         wakeup(mon, (type >= 0) ? TRUE : FALSE);
5496.     return rangemod;
5497. }
5498. 
5499. /* monster has cast flames or frost at target on <x,y>; called by mcastu() */
5500. void
5501. mon_spell_hits_spot(
5502.     struct monst *caster UNUSED,
5503.     int adtyp, /* canonical damage type */
5504.     coordxy x, coordxy y) /* so far, only used for targeting <u.ux,u.uy> */
5505. {
5506.     /* "shower of missiles" or [hypothetical] "acid rain" attack:
5507.        thoroughly clobber an engraving (unless its type makes it be
5508.        scuff-protected); zap_over_floor() doesn't handle this */
5509.     if (adtyp == AD_MAGM || adtyp == AD_ACID) {
5510.         struct engr *ep = engr_at(x, y);
5511.         char *etext = ep ? ep->engr_txt[actual_text] : NULL;
5512. 
5513.         if (etext)
5514.             wipe_engr_at(x, y, (int) strlen(etext) + d(6, 6), TRUE);
5515.         /* hero and player will still remember prior text until the spot
5516.            is re-examined (lookhere or move off and back on) */
5517.     }
5518. 
5519.     /* hit items and/or terrain; only matters for AD_FIRE and AD_COLD but
5520.        accept any basic damage type that zap_over_floor() might handle */
5521.     if (adtyp >= AD_MAGM && adtyp <= AD_ACID) {
5522.         boolean shopdummy = FALSE; /* zap_over_floor() requires this even
5523.                                     * though it's only used when zapdmgtyp
5524.                                     * is non-negative (hero's fault) */
5525.         int zt_typ = adtyp - 1,            /* convert AD_xxxx to ZT_xxxx */
5526.             zapdmgtyp = -ZT_SPELL(zt_typ); /* damage is from monster spell */
5527. 
5528.         (void) zap_over_floor(x, y, zapdmgtyp, &shopdummy, TRUE, 0);
5529.     } else {
5530.         impossible("Unsupported damage type (%d) for mon_spell_hits_spot.",
5531.                    adtyp);
5532.     }
5533. }
5534. 
5535. /* fractured by pick-axe or wand of striking or by vault guard or shopkeeper */
5536. void
5537. fracture_rock(struct obj *obj) /* no texts here! */
5538. {
5539.     coordxy x, y;
5540.     boolean by_you = !svc.context.mon_moving;
5541. 
5542.     if (by_you && get_obj_location(obj, &x, &y, 0) && costly_spot(x, y)) {
5543.         struct monst *shkp = 0;
5544.         char objroom = *in_rooms(x, y, SHOPBASE);
5545. 
5546.         if (billable(&shkp, obj, objroom, FALSE)) {
5547.             /* shop message says "you owe <shk> <$> for it!" so we need
5548.                to precede that with a message explaining what "it" is */
5549.             You("fracture %s %s.", s_suffix(shkname(shkp)), xname(obj));
5550.             /* breakobj won't destroy fracturing statue or boulder but
5551.                will charge for shop goods */
5552.             (void) breakobj(obj, x, y, TRUE, FALSE);
5553.         }
5554.     }
5555.     if (by_you && obj->otyp == BOULDER)
5556.         sokoban_guilt();
5557. 
5558.     obj->otyp = ROCK;
5559.     obj->oclass = GEM_CLASS;
5560.     obj->quan = (long) rn1(60, 7);
5561.     obj->owt = weight(obj);
5562.     obj->dknown = obj->bknown = obj->rknown = 0;
5563.     obj->known = objects[obj->otyp].oc_uses_known ? 0 : 1;
5564.     dealloc_oextra(obj);
5565. 
5566.     if (obj->where == OBJ_FLOOR) {
5567.         obj_extract_self(obj); /* move rocks back on top */
5568.         place_object(obj, obj->ox, obj->oy);
5569.         if (!does_block(obj->ox, obj->oy, &levl[obj->ox][obj->oy])) {
5570.             unblock_point(obj->ox, obj->oy);
5571.             /* need immediate update in case this is a striking/force bolt
5572.                zap that is about hit more things */
5573.             vision_recalc(0);
5574.         }
5575.         if (cansee(obj->ox, obj->oy))
5576.             newsym(obj->ox, obj->oy);
5577.     }
5578. }
5579. 
5580. /* handle statue hit by striking/force bolt/pick-axe */
5581. boolean
5582. break_statue(struct obj *obj)
5583. {
5584.     /* [obj is assumed to be on floor, so no get_obj_location() needed] */
5585.     struct trap *trap = t_at(obj->ox, obj->oy);
5586.     struct obj *item;
5587.     boolean by_you = !svc.context.mon_moving;
5588. 
5589.     if (trap && trap->ttyp == STATUE_TRAP
5590.         && activate_statue_trap(trap, obj->ox, obj->oy, TRUE))
5591.         return FALSE;
5592.     /* drop any objects contained inside the statue */
5593.     while ((item = obj->cobj) != 0) {
5594.         obj_extract_self(item);
5595.         place_object(item, obj->ox, obj->oy);
5596.     }
5597.     if (by_you && Role_if(PM_ARCHEOLOGIST)
5598.         && (obj->spe & CORPSTAT_HISTORIC)) {
5599.         You_feel("guilty about damaging such a historic statue.");
5600.         adjalign(-1);
5601.     }
5602.     obj->spe = 0;
5603.     fracture_rock(obj);
5604.     return TRUE;
5605. }
5606. 
5607. /* Return TRUE if obj is eligible to pass to maybe_destroy_item given
5608.  * the type of elemental damage it's being subjected to.
5609.  * Note that things like the Book of the Dead are eligible even though they
5610.  * won't get destroyed, because it will attempt to be destroyed but print a
5611.  * special message instead. */
5612. staticfn boolean
5613. destroyable(struct obj *obj, int adtyp)
5614. {
5615.     if (obj->oartifact) {
5616.         /* don't destroy artifacts */
5617.         return FALSE;
5618.     }
5619.     if (obj->in_use && obj->quan == 1L) {
5620.         /* not available for destroying */
5621.         return FALSE;
5622.     }
5623.     if (adtyp == AD_FIRE) {
5624.         /* fire-magic items are immune */
5625.         if (obj->otyp == SCR_FIRE || obj->otyp == SPE_FIREBALL) {
5626.             return FALSE;
5627.         }
5628.         if (obj->otyp == GLOB_OF_GREEN_SLIME || obj->oclass == POTION_CLASS
5629.             || obj->oclass == SCROLL_CLASS || obj->oclass == SPBOOK_CLASS) {
5630.             return TRUE;
5631.         }
5632.     } else if (adtyp == AD_COLD) {
5633.         /* non-water potions don't freeze and shatter */
5634.         if (obj->oclass == POTION_CLASS && obj->otyp != POT_OIL) {
5635.             return TRUE;
5636.         }
5637.     } else if (adtyp == AD_ELEC) {
5638.         if (obj->oclass != RING_CLASS && obj->oclass != WAND_CLASS) {
5639.             return FALSE;
5640.         }
5641.         /* electric-magic items are immune */
5642.         if (obj->otyp != RIN_SHOCK_RESISTANCE && obj->otyp != WAN_LIGHTNING) {
5643.             return TRUE;
5644.         }
5645.         /* There used to be a commented out bit of code that would exclude
5646.          * gc.current_wand, but it wasn't used, so it wasn't moved into this
5647.          * function. */
5648.     }
5649.     return FALSE;
5650. }
5651. 
5652. /* convert attack damage AD_foo to property resistance */
5653. staticfn int
5654. adtyp_to_prop(int dmgtyp)
5655. {
5656.     switch (dmgtyp) {
5657.     case AD_COLD:
5658.         return COLD_RES;
5659.     case AD_FIRE:
5660.         return FIRE_RES;
5661.     case AD_ELEC:
5662.         return SHOCK_RES;
5663.     case AD_ACID:
5664.         return ACID_RES;
5665.     case AD_DISN:
5666.         return DISINT_RES;
5667.     default:
5668.         break;
5669.     }
5670.     return 0; /* prop_types start at 1 */
5671. }
5672. 
5673. /* Is hero wearing or wielding an object with resistance to attack
5674.    damage type? Returns the percentage protection that the object gives. */
5675. int
5676. u_adtyp_resistance_obj(int dmgtyp)
5677. {
5678.     int prop = adtyp_to_prop(dmgtyp);
5679. 
5680.     if (!prop)
5681.         return 0;
5682. 
5683.     /* FIXME? these percentages (99 and 90) seem too high... */
5684. 
5685.     /* items that give an extrinsic resistance when worn or wielded or
5686.        carried give 99% protection to your items */
5687.     if ((u.uprops[prop].extrinsic & (W_ARMOR | W_ACCESSORY | W_WEP | W_ART))
5688.         != 0L)
5689.         return 99;
5690. 
5691.     /* worn dwarvish cloaks give 90% protection against heat and cold to
5692.        carried items */
5693.     if (uarmc && uarmc->otyp == DWARVISH_CLOAK
5694.         && (dmgtyp == AD_COLD || dmgtyp == AD_FIRE))
5695.         return 90;
5696. 
5697.     return 0;
5698. }
5699. 
5700. /* Rolls to see whether an object in inventory resists damage from the
5701.    given damage type, due to an equipped item protecting it. Use
5702.    u_adtyp_resistance_obj to discover whether objects are protected in
5703.    general (e.g. for enlightenment) and this function to actually do
5704.    the roll to see whether a specific object is protected.
5705. 
5706.    This function doesn't check for other reasons why an object might
5707.    be protected; you will usually need to do an obj_resists() call
5708.    too. */
5709. boolean
5710. inventory_resistance_check(int dmgtyp)
5711. {
5712.     int prob = u_adtyp_resistance_obj(dmgtyp);
5713. 
5714.     if (!prob)
5715.         return FALSE;
5716. 
5717.     return rn2(100) < prob;
5718. }
5719. 
5720. /* for enlightenment; currently only useful in wizard mode; cf from_what() */
5721. char *
5722. item_what(int dmgtyp)
5723. {
5724.     static char whatbuf[50];
5725.     const char *what = 0;
5726.     int prop = adtyp_to_prop(dmgtyp);
5727.     long xtrinsic = u.uprops[prop].extrinsic;
5728. 
5729.     whatbuf[0] = '\0';
5730.     if (wizard) {
5731.         if (!prop || !xtrinsic) {
5732.             ; /* 'what' stays Null */
5733.         } else if (xtrinsic & W_ARMC) {
5734.             what = cloak_simple_name(uarmc);
5735.         } else if (xtrinsic & W_ARM) {
5736.             what = suit_simple_name(uarm); /* "dragon {scales,mail}" */
5737.         } else if (xtrinsic & W_ARMU) {
5738.             what = shirt_simple_name(uarmu);
5739.         } else if (xtrinsic & W_ARMH) {
5740.             what = helm_simple_name(uarmh);
5741.         } else if (xtrinsic & W_ARMG) {
5742.             what = gloves_simple_name(uarmg);
5743.         } else if (xtrinsic & W_ARMF) {
5744.             what = boots_simple_name(uarmf);
5745.         } else if (xtrinsic & W_ARMS) {
5746.             what = shield_simple_name(uarms);
5747.         } else if (xtrinsic & (W_AMUL | W_TOOL)) {
5748.             what = simpleonames((xtrinsic & W_AMUL) ? uamul : ublindf);
5749.         } else if (xtrinsic & W_RING) {
5750.             if ((xtrinsic & W_RING) == W_RING) /* both */
5751.                 what = "rings";
5752.             else
5753.                 what = simpleonames((xtrinsic & W_RINGL) ? uleft : uright);
5754.         } else if (xtrinsic & W_WEP) {
5755.             what = simpleonames(uwep);
5756.         }
5757.         /* format the output to be ready for enl_msg() to append it to
5758.            "Your items {are,were} protected against <damage-type>" */
5759.         if (what) /* strlen(what) will be less than 30 */
5760.             Sprintf(whatbuf, " by your %.40s", what);
5761.     }
5762.     return whatbuf;
5763. }
5764. 
5765. /*
5766.  * destroy_strings[dindx][0:singular,1:plural,2:killer_reason]
5767.  *      [0] freezing potion
5768.  *      [1] boiling potion other than oil
5769.  *      [2] boiling potion of oil
5770.  *      [3] burning scroll
5771.  *      [4] burning spellbook
5772.  *      [5] shocked ring
5773.  *      [6] shocked wand
5774.  * (books, rings, and wands don't stack so don't need plural form;
5775.  *  crumbling ring doesn't do damage so doesn't need killer reason)
5776.  * externally referenced from trap.c.
5777.  */
5778. const char *const destroy_strings[][3] = {
5779.     /* also used in trap.c */
5780.     { "freezes and shatters", "freeze and shatter", "shattered potion" },
5781.     { "boils and explodes", "boil and explode", "boiling potion" },
5782.     { "ignites and explodes", "ignite and explode", "exploding potion" },
5783.     { "catches fire and burns", "catch fire and burn", "burning scroll" },
5784.     { "catches fire and burns", "", "burning book" },
5785.     { "turns to dust and vanishes", "", "" },
5786.     { "breaks apart and explodes", "", "exploding wand" },
5787. };
5788. 
5789. /* guts of destroy_items();
5790.    caller must decide whether obj is eligible, though there's one case (Book
5791.    of the Dead) in which an eligible item shouldn't be destroyed (it prints a
5792.    special message instead).
5793.    Returns the amount of damage done, but it's used differently depending on
5794.    whether it's the player or a monster having an item destroyed: players lose
5795.    the HP and possibly die in this function, and the return value is unused,
5796.    whereas monsters return the damage to their caller to be taken off later */
5797. staticfn int
5798. maybe_destroy_item(
5799.     struct monst *carrier,
5800.     struct obj *obj,
5801.     int dmgtyp)
5802. {
5803.     long i, cnt, quan;
5804.     int dmg, xresist, skip, dindx;
5805.     const char *mult;
5806.     boolean u_carry = (carrier == &gy.youmonst);
5807.     boolean vis = !u_carry && canseemon(carrier);
5808.     boolean chargeit = FALSE;
5809. 
5810.     xresist = skip = 0;
5811.     /* lint suppression */
5812.     dmg = dindx = 0;
5813.     quan = 0L;
5814. 
5815.     /* external worn item protects inventory? */
5816.     if (u_carry && inventory_resistance_check(dmgtyp))
5817.         return 0;
5818. 
5819.     switch (dmgtyp) {
5820.     case AD_COLD:
5821.         quan = obj->quan;
5822.         dindx = 0;
5823.         dmg = rnd(4);
5824.         break;
5825.     case AD_FIRE:
5826.         xresist = (obj->oclass != POTION_CLASS
5827.                    && obj->otyp != GLOB_OF_GREEN_SLIME
5828.                    && (u_carry ? Fire_resistance : resists_fire(carrier)));
5829.         if (obj->otyp == SPE_BOOK_OF_THE_DEAD) {
5830.             skip = 1;
5831.             if (u_carry ? !Blind : vis) {
5832.                 pline("%s glows a strange %s, but remains intact.",
5833.                       The(u_carry ? xname(obj) : distant_name(obj, xname)),
5834.                       hcolor("dark red"));
5835.             }
5836.             break;
5837.         }
5838.         quan = obj->quan;
5839.         switch (obj->oclass) {
5840.         case POTION_CLASS:
5841.             dindx = (obj->otyp != POT_OIL) ? 1 : 2;
5842.             dmg = rnd(6);
5843.             break;
5844.         case SCROLL_CLASS:
5845.             dindx = 3;
5846.             dmg = 1;
5847.             break;
5848.         case SPBOOK_CLASS:
5849.             dindx = 4;
5850.             dmg = 1;
5851.             break;
5852.         case FOOD_CLASS: /* only GLOB_OF_GREEN_SLIME */
5853.             dindx = 1; /* boil and explode */
5854.             dmg = (obj->owt + 19) / 20;
5855.             break;
5856.         }
5857.         break;
5858.     case AD_ELEC:
5859.         xresist = (obj->oclass != RING_CLASS
5860.                    && (u_carry ? Shock_resistance : resists_elec(carrier)));
5861.         quan = obj->quan;
5862.         switch (obj->oclass) {
5863.         case RING_CLASS:
5864.             if (((obj->owornmask & W_RING) && uarmg && !is_metallic(uarmg))
5865.                 || obj->otyp == RIN_SHOCK_RESISTANCE) {
5866.                 skip++;
5867.                 break;
5868.             } else if (objects[obj->otyp].oc_charged && rn2(3)) {
5869.                 chargeit = TRUE;
5870.                 break;
5871.             }
5872.             dindx = 5;
5873.             dmg = 0;
5874.             break;
5875.         case WAND_CLASS:
5876.             dindx = 6;
5877.             dmg = rnd(10);
5878.             break;
5879.         }
5880.         break;
5881.     default:
5882.         skip = 1; /* just in case ineligible damage type gets through... */
5883.         impossible("maybe_destroy_item with unexpected dmgtyp %d", dmgtyp);
5884.         break;
5885.     }
5886. 
5887.     if (chargeit) {
5888.         /* FIXME: recharge only handles items in hero's inventory */
5889.         if (u_carry)
5890.             recharge(obj, 0);
5891.     } else if (!skip) {
5892.         char osym = obj->oclass; /* for checking glob of slime after it's
5893.                                        destroyed */
5894.         if (obj->in_use)
5895.             --quan; /* one will be used up elsewhere */
5896.         for (i = cnt = 0L; i < quan; i++)
5897.             if (!rn2(3))
5898.                 cnt++;
5899. 
5900.         if (!cnt)
5901.             return 0;
5902. 
5903.         if (u_carry || vis) {
5904.             mult = (cnt == 1L) ? ((quan == 1L) ? "" /* 1 of 1 */
5905.                                   : "One of ")      /* 1 of N */
5906.                    : ((cnt < quan) ? "Some of "     /* n of N */
5907.                       : (quan == 2L) ? "Both of "   /* 2 of 2 */
5908.                         : "All of ");               /* N of N */
5909.             pline("%s%s %s!", mult,
5910.                   (cnt == 1L && quan == 1L) ? Yname2(obj) : yname(obj),
5911.                   destroy_strings[dindx][(cnt > 1L)]);
5912.         }
5913.         if (u_carry) { /* effects that happen only to the player */
5914.             if (osym == POTION_CLASS && dmgtyp != AD_COLD
5915.                 && (!breathless(gy.youmonst.data)
5916.                     || haseyes(gy.youmonst.data))) {
5917.                 potionbreathe(obj);
5918.             }
5919.             if (obj->owornmask) { /* m_useup handles these for monster */
5920.                 if (obj->owornmask & W_RING) /* ring being worn */
5921.                     Ring_gone(obj);
5922.                 else
5923.                     setnotworn(obj);
5924.             }
5925.             if (obj == gc.current_wand) {
5926.                 gc.current_wand = 0; /* destroyed */
5927.             }
5928.         }
5929.         for (i = 0; i < cnt; i++) {
5930.             if (u_carry)
5931.                 useup(obj);
5932.             else
5933.                 m_useup(carrier, obj);
5934.         }
5935.         if (dmg) {
5936.             if (!u_carry) {
5937.                 return xresist ? 0 : dmg;
5938.             }
5939.             if (xresist) {
5940.                 You("aren't hurt!");
5941.             } else {
5942.                 const char *how = destroy_strings[dindx][2];
5943.                 boolean one = (cnt == 1L);
5944. 
5945.                 if (dmgtyp == AD_FIRE && osym == FOOD_CLASS)
5946.                     how = "exploding glob of slime";
5947.                 losehp(dmg, one ? how : (const char *) makeplural(how),
5948.                        one ? KILLED_BY_AN : KILLED_BY);
5949.                 exercise(A_STR, FALSE);
5950.             }
5951.         }
5952.     }
5953.     return dmg;
5954. }
5955. 
5956. /* scaling factor; dmg/5 stacks will be subjected to destroy_items() */
5957. #define DMG_DESTROY_SCALE 5
5958. /* largest amount of stacks that will be destroyed in a single call */
5959. #define MAX_ITEMS_DESTROYED 20
5960. 
5961. /* target items of specified class in mon's inventory for possible destruction
5962.    return total amount of damage inflicted, though this is unused if mon is
5963.    the player */
5964. int
5965. destroy_items(
5966.     struct monst *mon, /* monster whose invent is being subjected to
5967.                         * destruction */
5968.     int dmgtyp,        /* AD_**** - currently only cold, fire, elec */
5969.     int dmg_in)        /* the amount of HP damage the attack dealt */
5970. {
5971.     struct obj *obj;
5972.     int i, defer;
5973.     int limit; /* max amount of item stacks destroyed, based on damage */
5974.     struct {
5975.         unsigned oid;
5976.         struct obj *otmp;
5977.         boolean deferred;
5978.     } items_to_destroy[MAX_ITEMS_DESTROYED];
5979.     int elig_stacks = 0; /* number of destroyable objects found so far */
5980.     boolean u_carry = (mon == &gy.youmonst);
5981.     /* this is a struct obj** because we might destroy the first item in it */
5982.     struct obj **objchn = u_carry ? &gi.invent : &mon->minvent;
5983.     int dmg_out = 0; /* damage caused by items getting destroyed */
5984.     xint8 where = NOBJ_STATES;
5985. 
5986.     /* initialize items_to_destroy */
5987.     for (i = 0; i < MAX_ITEMS_DESTROYED; ++i) {
5988.         /* 0 should not be a valid o_id for anything */
5989.         items_to_destroy[i].oid = 0;
5990.         items_to_destroy[i].otmp = (struct obj *) 0;
5991.         items_to_destroy[i].deferred = FALSE;
5992.     }
5993. 
5994.     /* don't straight up destroy all items with an equal chance; limit it
5995.        based on the amount of damage being dealt by the source of the item
5996.        destruction */
5997.     limit = dmg_in / DMG_DESTROY_SCALE;
5998.     if (dmg_in % DMG_DESTROY_SCALE > rn2(DMG_DESTROY_SCALE)) {
5999.         limit++; /* dmg = 9: 20% chance of limit=1, 80% of limit=2, etc */
6000.     }
6001.     if (limit > MAX_ITEMS_DESTROYED) {
6002.         /* in case of incredibly high damage, prevent from overflowing
6003.          * items_to_destroy */
6004.         limit = MAX_ITEMS_DESTROYED;
6005.     }
6006.     if (limit < 1) {
6007.         return 0; /* nothing destroyed */
6008.     }
6009. 
6010.     /* Sometimes destroying an item can change inventory aside from
6011.      * the item itself (cited case was a potion of unholy water; when
6012.      * boiled, potionbreathe() caused hero to transform into were-beast
6013.      * form and that resulted in dropping or destroying some worn armor).
6014.      *
6015.      * Unlike other uses of the object bypass mechanism, destroy_items()
6016.      * can be called multiple times for the same event.  So we have to
6017.      * explicitly clear it before each use and hope no other section of
6018.      * code expects it to retain previous value.
6019.      *
6020.      * Destruction of a ring of levitation or form change which pushes
6021.      * off levitation boots could drop hero onto a fire trap that
6022.      * could destroy other items and we'll get called recursively.  Or
6023.      * onto a trap which transports hero elsewhere, which won't disrupt
6024.      * traversal but could yield message sequencing issues.  So we
6025.      * defer handling such things until after rest of inventory has
6026.      * been processed.  If some other combination of items and events
6027.      * triggers a recursive call, rest of inventory after the triggering
6028.      * item will be skipped by the outer call since the inner one will
6029.      * have set the bypass bits of the whole list.
6030.      *
6031.      * [Unfortunately, death while poly'd into flyer and subsequent
6032.      * rehumanization could also drop hero onto a trap, and there's no
6033.      * straightforward way to defer that.  Things could be improved by
6034.      * redoing this to use two passes, first to collect a list or array
6035.      * of o_id and quantity of what is targeted for destruction,
6036.      * second pass to handle the destruction.]
6037.      */
6038.     bypass_objlist(*objchn, FALSE); /* clear bypass bit for invent */
6039. 
6040.     while ((obj = nxt_unbypassed_obj(*objchn)) != 0) {
6041.         if (!destroyable(obj, dmgtyp))
6042.             continue; /* this dmg type can't destroy this obj */
6043. 
6044.         /* obj is eligible; maybe add it to items_to_destroy */
6045.         i = (elig_stacks < limit) ? elig_stacks : rn2(elig_stacks);
6046.         /* do this afterwards to avoid not filling items_to_destroy[0] */
6047.         elig_stacks++;
6048.         if (i < 0 || i >= limit) {
6049.             /* random index was too high; mollify analyzer by including < 0 */
6050.             continue;
6051.         }
6052.         items_to_destroy[i].oid = obj->o_id;
6053.         items_to_destroy[i].otmp = obj;
6054.         if (where == NOBJ_STATES)
6055.             where = obj->where;
6056.         else if (where != obj->where)
6057.             impossible("destroy_item: items in multiple chains");
6058. 
6059.         /* if loss of this item might dump us onto a trap, hold off
6060.            until later because potential recursive destroy_items() will
6061.            result in setting bypass bits on whole chain--we would skip
6062.            the rest as already processed once control returns here */
6063.         if (u_carry
6064.             && ((obj->owornmask != 0L
6065.                  && (objects[obj->otyp].oc_oprop == LEVITATION
6066.                      || objects[obj->otyp].oc_oprop == FLYING))
6067.                 /* destroyed wands and potions of polymorph don't trigger
6068.                    polymorph so don't need to be deferred */
6069.                 || (obj->otyp == POT_WATER && ismnum(u.ulycn)
6070.                     && (Upolyd ? obj->blessed : obj->cursed)))) {
6071.             items_to_destroy[i].deferred = TRUE;
6072.         } else {
6073.             items_to_destroy[i].deferred = FALSE;
6074.         }
6075.     }
6076.     if (elig_stacks > limit) {
6077.         elig_stacks = limit; /* so we can loop up to elig_stacks */
6078.     }
6079.     for (defer = 0; defer <= 1; ++defer) {
6080.         /* if we saved some items for later (most likely just a worn ring
6081.            of levitation) and they're still in inventory, handle them on the
6082.            second iteration of the loop */
6083.         for (i = 0; i < elig_stacks; ++i) {
6084.             obj = items_to_destroy[i].otmp;
6085.             if (obj && obj->o_id == items_to_destroy[i].oid
6086.                 && obj->where == where
6087.                 && (items_to_destroy[i].deferred == (defer == 1))) {
6088.                 dmg_out += maybe_destroy_item(mon, obj, dmgtyp);
6089.                 items_to_destroy[i].otmp = (struct obj *) 0;
6090.             }
6091.         }
6092.     }
6093.     /* almost certainly not everything was destroyed; clear bypass bit after
6094.        it was set earlier */
6095.     bypass_objlist(*objchn, FALSE);
6096.     return dmg_out;
6097. }
6098. 
6099. int
6100. resist(struct monst *mtmp, char oclass, int damage, int tell)
6101. {
6102.     int resisted;
6103.     int alev, dlev;
6104. 
6105.     /* fake players always pass resistance test against Conflict
6106.        (this doesn't guarantee that they're never affected by it) */
6107.     if (oclass == RING_CLASS && !damage && !tell && is_mplayer(mtmp->data))
6108.         return 1;
6109. 
6110.     /* attack level */
6111.     switch (oclass) {
6112.     case WAND_CLASS:
6113.         alev = 12;
6114.         break;
6115.     case TOOL_CLASS:
6116.         alev = 10;
6117.         break; /* instrument */
6118.     case WEAPON_CLASS:
6119.         alev = 10;
6120.         break; /* artifact */
6121.     case SCROLL_CLASS:
6122.         alev = 9;
6123.         break;
6124.     case POTION_CLASS:
6125.         alev = 6;
6126.         break;
6127.     case RING_CLASS:
6128.         alev = 5;
6129.         break;
6130.     default:
6131.         alev = u.ulevel;
6132.         break; /* spell */
6133.     }
6134.     /* defense level */
6135.     dlev = (int) mtmp->m_lev;
6136.     if (dlev > 50)
6137.         dlev = 50;
6138.     else if (dlev < 1)
6139.         dlev = is_mplayer(mtmp->data) ? u.ulevel : 1;
6140. 
6141.     resisted = rn2(100 + alev - dlev) < mtmp->data->mr;
6142.     if (resisted) {
6143.         if (tell)
6144.             shieldeff_mon(mtmp);
6145.         damage = (damage + 1) / 2;
6146.     }
6147. 
6148.     if (damage) {
6149.         mtmp->mhp -= damage;
6150.         if (DEADMONSTER(mtmp)) {
6151.             if (gm.m_using)
6152.                 monkilled(mtmp, "", AD_RBRE);
6153.             else
6154.                 killed(mtmp);
6155.         }
6156.     }
6157.     return resisted;
6158. }
6159. 
6160. #define MAXWISHTRY 5
6161. 
6162. DISABLE_WARNING_FORMAT_NONLITERAL
6163. 
6164. staticfn void
6165. wishcmdassist(int triesleft)
6166. {
6167.     static NEARDATA const char *
6168.         wishinfo[] = {
6169.   "Wish details:",
6170.   "",
6171.   "Enter the name of an object, such as \"potion of monster detection\",",
6172.   "\"scroll labeled README\", \"elven mithril-coat\", or \"Grimtooth\"",
6173.   "(without the quotes).",
6174.   "",
6175.   "For object types which come in stacks, you may specify a plural name",
6176.   "such as \"potions of healing\", or specify a count, such as \"1000 gold",
6177.   "pieces\", although that aspect of your wish might not be granted.",
6178.   "",
6179.   "You may also specify various prefix values which might be used to",
6180.   "modify the item, such as \"uncursed\" or \"rustproof\" or \"+1\".",
6181.   "Most modifiers shown when viewing your inventory can be specified.",
6182.   "",
6183.   "You may specify 'nothing' to explicitly decline this wish.",
6184.   0,
6185.     },
6186.         preserve_wishless[] = "Doing so will preserve 'wishless' conduct.",
6187.         retry_info[] =
6188.                     "If you specify an unrecognized object name %s%s time%s,",
6189.         retry_too[] = "a randomly chosen item will be granted.",
6190.         suppress_cmdassist[] =
6191.             "(Suppress this assistance with !cmdassist in your config file.)",
6192.         *cardinals[] = { "zero",  "one",  "two", "three", "four", "five" },
6193.         too_many[] = "too many";
6194.     int i;
6195.     winid win;
6196.     char buf[BUFSZ];
6197. 
6198.     win = create_nhwindow(NHW_TEXT);
6199.     if (!win)
6200.         return;
6201.     for (i = 0; i < SIZE(wishinfo) - 1; ++i)
6202.         putstr(win, 0, wishinfo[i]);
6203.     if (!u.uconduct.wishes)
6204.         putstr(win, 0, preserve_wishless);
6205.     putstr(win, 0, "");
6206.     Sprintf(buf, retry_info,
6207.             (triesleft >= 0 && triesleft < SIZE(cardinals))
6208.                ? cardinals[triesleft]
6209.                : too_many,
6210.             (triesleft < MAXWISHTRY) ? " more" : "",
6211.             plur(triesleft));
6212.     putstr(win, 0, buf);
6213.     putstr(win, 0, retry_too);
6214.     putstr(win, 0, "");
6215.     if (iflags.cmdassist)
6216.         putstr(win, 0, suppress_cmdassist);
6217.     display_nhwindow(win, TRUE);
6218.     destroy_nhwindow(win);
6219. }
6220. 
6221. #define MAX_WISH_HISTORY 20
6222. static char *wish_history[MAX_WISH_HISTORY] = { NULL };
6223. static int wish_history_idx = 0;
6224. 
6225. /* add string to wish history list */
6226. void
6227. wish_history_add(char *buf)
6228. {
6229. #ifdef DEBUG
6230.     int i;
6231. 
6232.     if (!wizard)
6233.         return;
6234. 
6235.     for (i = 0; i < MAX_WISH_HISTORY; i++) {
6236.         int idx = (wish_history_idx + i) % MAX_WISH_HISTORY;
6237. 
6238.         if (!wish_history[idx])
6239.             continue;
6240.         if (!strncmpi(wish_history[idx], buf, strlen(wish_history[idx])))
6241.             break;
6242. 
6243.     }
6244. 
6245.     if (i == MAX_WISH_HISTORY) {
6246.         int idx = (wish_history_idx + i) % MAX_WISH_HISTORY;
6247. 
6248.         if (wish_history[idx])
6249.             free(wish_history[idx]);
6250.         wish_history[idx] = (char *) alloc(strlen(buf) + 1);
6251.         strcpy(wish_history[idx], buf);
6252.         wish_history_idx = (wish_history_idx + 1) % MAX_WISH_HISTORY;
6253.     }
6254. #endif /* DEBUG */
6255. }
6256. 
6257. /* release any old wish text; called from freedynamicdata(save.c) */
6258. void
6259. wish_history_flush(void)
6260. {
6261. #ifdef DEBUG
6262.     int idx;
6263. 
6264.     for (idx = 0; idx < MAX_WISH_HISTORY; ++idx) {
6265.         if (wish_history[idx])
6266.             free((genericptr_t) wish_history[idx]), wish_history[idx] = NULL;
6267.     }
6268.     wish_history_idx = 0;
6269. #endif
6270. }
6271. 
6272. /* shows menu of previous wishes, copies selected into buf, max BUFSZ len.
6273.    buf is not modified, if nothing was selected. */
6274. staticfn void
6275. wish_history_menu(char *buf)
6276. {
6277. #ifdef DEBUG
6278.     winid win;
6279.     anything any;
6280.     int i = 0, npick;
6281.     menu_item *picks = (menu_item *) 0;
6282.     int idx;
6283. 
6284.     win = create_nhwindow(NHW_MENU);
6285.     start_menu(win, MENU_BEHAVE_STANDARD);
6286.     any = cg.zeroany;
6287. 
6288.     for (i = MAX_WISH_HISTORY-1; i >= 0; i--) {
6289.         idx = (wish_history_idx + i) % MAX_WISH_HISTORY;
6290.         if (wish_history[idx]) {
6291.             any.a_int = (i + 1);
6292.             add_menu(win, &nul_glyphinfo, &any, '\0', 0, ATR_NONE, NO_COLOR,
6293.                      wish_history[idx], MENU_ITEMFLAGS_NONE);
6294.         }
6295.     }
6296. 
6297.     end_menu(win, "Wish what?");
6298.     npick = select_menu(win, PICK_ONE, &picks);
6299.     destroy_nhwindow(win);
6300.     if (npick > 0) {
6301.         i = picks->item.a_int;
6302.         i--;
6303.         idx = (wish_history_idx + i) % MAX_WISH_HISTORY;
6304. 
6305.         if (wish_history[idx])
6306.             strcpy(buf, wish_history[idx]);
6307.     }
6308. #endif /* DEBUG */
6309. }
6310. 
6311. RESTORE_WARNING_FORMAT_NONLITERAL
6312. 
6313. void
6314. makewish(void)
6315. {
6316.     char buf[BUFSZ] = DUMMY;
6317.     char bufcpy[BUFSZ], wish[BUFSZ], promptbuf[QBUFSZ];
6318.     struct obj *otmp, nothing;
6319.     long maybe_LL_arti;
6320.     int tries = 0;
6321.     long oldwisharti = u.uconduct.wisharti;
6322. 
6323.     svc.context.resume_wish = 0;
6324.     promptbuf[0] = '\0';
6325.     nothing = cg.zeroobj; /* lint suppression; only its address matters */
6326.     if (flags.verbose)
6327.         You("may wish for an object.");
6328.  retry:
6329.     Strcpy(promptbuf, "For what do you wish");
6330.     if (iflags.cmdassist && tries > 0)
6331.         Strcat(promptbuf, " (enter 'help' for assistance)");
6332.     Strcat(promptbuf, "?");
6333. 
6334.     if (iflags.menu_requested && wish_history[0] && (tries == 0))
6335.         wish_history_menu(buf);
6336.     else
6337.         getlin(promptbuf, buf);
6338. 
6339.     if (iflags.term_gone) {
6340.         if (!iflags.debug_fuzzer)
6341.             svc.context.resume_wish = 1;
6342.         return;
6343.     }
6344. 
6345.     (void) mungspaces(buf);
6346.     if (buf[0] == '\033') {
6347.         buf[0] = '\0';
6348.     } else if (!strcmpi(buf, "help")) {
6349.         wishcmdassist(MAXWISHTRY - tries);
6350.         buf[0] = '\0'; /* for EDIT_GETLIN */
6351.         goto retry;
6352.     }
6353.     /*
6354.      *  Note: if they wished for and got a non-object successfully,
6355.      *  otmp == &hands_obj.  That includes an artifact which has been
6356.      *  denied. Wishing for "nothing" requires a separate value to remain
6357.      *  distinct.
6358.      */
6359.     strcpy(bufcpy, buf);
6360.     otmp = readobjnam(buf, &nothing);
6361.     if (!otmp) {
6362.         pline("Nothing fitting that description exists in the game.");
6363.         if (++tries < MAXWISHTRY)
6364.             goto retry;
6365.         pline1(thats_enough_tries);
6366.         otmp = readobjnam((char *) 0, (struct obj *) 0);
6367.         if (!otmp)
6368.             return; /* for safety; should never happen */
6369.     } else if (otmp == &nothing) {
6370.         /* explicitly wished for "nothing", presumably attempting
6371.            to retain wishless conduct */
6372.         livelog_printf(LL_WISH, "declined to make a wish");
6373.         return;
6374.     } else if (otmp == &hands_obj) {
6375.         wish_history_add(bufcpy);
6376.         /* wizard mode terrain wish: skip livelogging, etc */
6377.         return;
6378.     }
6379.     wish_history_add(bufcpy);
6380. 
6381.     if (otmp->oartifact) {
6382.         /* update artifact bookkeeping; doesn't produce a livelog event */
6383.         artifact_origin(otmp, ONAME_WISH | ONAME_KNOW_ARTI);
6384.     }
6385. 
6386.     /* wisharti conduct handled in readobjnam() */
6387.     maybe_LL_arti = ((oldwisharti < u.uconduct.wisharti) ? LL_ARTIFACT : 0L);
6388.     Snprintf(wish, sizeof wish, "\"%s\", got \"%s\"", bufcpy, doname(otmp));
6389.     /* KMH, conduct */
6390.     if (!u.uconduct.wishes++)
6391.         livelog_printf((LL_CONDUCT | LL_WISH | maybe_LL_arti),
6392.                        "made %s first wish - %s", uhis(), wish);
6393.     else if (!oldwisharti && u.uconduct.wisharti)
6394.         livelog_printf((LL_CONDUCT | LL_WISH | LL_ARTIFACT),
6395.                        "made %s first artifact wish - %s", uhis(), wish);
6396.     else
6397.         livelog_printf((LL_WISH | maybe_LL_arti), "wished for %s", wish);
6398.     /* TODO? maybe generate a second event describing what was received since
6399.        these just echo player's request rather than show actual result */
6400. 
6401.     if (otmp->otyp == CORPSE && !u_safe_from_fatal_corpse(otmp, st_all))
6402.         otmp->wishedfor = 1;
6403. 
6404.     const char *verb = ((Is_airlevel(&u.uz) || u.uinwater)
6405.                         ? "slip"
6406.                         : (otmp->otyp == CORPSE && otmp->wishedfor)
6407.                           ? "materialize" : "drop"),
6408.                *oops_msg = (u.uswallow
6409.                             ? "Oops!  %s out of your reach!"
6410.                             : (Is_airlevel(&u.uz) || Is_waterlevel(&u.uz)
6411.                                || levl[u.ux][u.uy].typ < IRONBARS
6412.                                || levl[u.ux][u.uy].typ >= ICE)
6413.                                ? "Oops!  %s away from you!"
6414.                                : !(otmp->otyp == CORPSE && otmp->wishedfor)
6415.                                  ? "Oops!  %s to the floor!"
6416.                                  : "Careful! %s on the floor!");
6417. 
6418.     /* The(aobjnam()) is safe since otmp is unidentified -dlc */
6419.     (void) hold_another_object(otmp, oops_msg, The(aobjnam(otmp, verb)),
6420.                                (const char *) 0);
6421.     u.ublesscnt += rn1(100, 50); /* the gods take notice */
6422. }
6423. 
6424. /* Fills buf with the appropriate string for this ray.
6425.  * In the hallucination case, insert "blast of <silly thing>".
6426.  * Assumes that the caller will specify typ in the appropriate range for
6427.  * wand/spell/breath weapon. */
6428. const char*
6429. flash_str(
6430.     int typ,
6431.     boolean nohallu) /* suppress hallucination (for death reasons) */
6432. {
6433.     static char fltxt[BUFSZ];
6434. 
6435.     typ = zaptype(typ);
6436.     if (Hallucination && !nohallu) {
6437.         /* always return "blast of foo" for simplicity;
6438.            this could be extended with hallucinatory rays, but probably
6439.            not worth it at this time */
6440.         Sprintf(fltxt, "blast of %s", rnd_hallublast());
6441.     } else {
6442.         Strcpy(fltxt, flash_types[typ]);
6443.     }
6444.     return fltxt;
6445. }
6446. 
6447. /*zap.c*/