Source:NetHack 3.6.6/src/teleport.c

From NetHackWiki
Jump to navigation Jump to search

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

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

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

1. /* NetHack 3.6	teleport.c	$NHDT-Date: 1576281515 2019/12/13 23:58:35 $  $NHDT-Branch: NetHack-3.6 $:$NHDT-Revision: 1.95 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Robert Patrick Rankin, 2011. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. 
8. STATIC_DCL boolean FDECL(tele_jump_ok, (int, int, int, int));
9. STATIC_DCL boolean FDECL(teleok, (int, int, BOOLEAN_P));
10. STATIC_DCL void NDECL(vault_tele);
11. STATIC_DCL boolean FDECL(rloc_pos_ok, (int, int, struct monst *));
12. STATIC_DCL void FDECL(mvault_tele, (struct monst *));
13. 
14. /* non-null when teleporting via having read this scroll */
15. STATIC_VAR struct obj *telescroll = 0;
16. 
17. /*
18.  * Is (x,y) a good position of mtmp?  If mtmp is NULL, then is (x,y) good
19.  * for an object?
20.  *
21.  * This function will only look at mtmp->mdat, so makemon, mplayer, etc can
22.  * call it to generate new monster positions with fake monster structures.
23.  */
24. boolean
25. goodpos(x, y, mtmp, gpflags)
26. int x, y;
27. struct monst *mtmp;
28. unsigned gpflags;
29. {
30.     struct permonst *mdat = (struct permonst *) 0;
31.     boolean ignorewater = ((gpflags & MM_IGNOREWATER) != 0);
32. 
33.     if (!isok(x, y))
34.         return FALSE;
35. 
36.     /* in many cases, we're trying to create a new monster, which
37.      * can't go on top of the player or any existing monster.
38.      * however, occasionally we are relocating engravings or objects,
39.      * which could be co-located and thus get restricted a bit too much.
40.      * oh well.
41.      */
42.     if (x == u.ux && y == u.uy
43.         && mtmp != &youmonst && (mtmp != u.ustuck || !u.uswallow)
44.         && (!u.usteed || mtmp != u.usteed))
45.         return FALSE;
46. 
47.     if (mtmp) {
48.         struct monst *mtmp2 = m_at(x, y);
49. 
50.         /* Be careful with long worms.  A monster may be placed back in
51.          * its own location.  Normally, if m_at() returns the same monster
52.          * that we're trying to place, the monster is being placed in its
53.          * own location.  However, that is not correct for worm segments,
54.          * because all the segments of the worm return the same m_at().
55.          * Actually we overdo the check a little bit--a worm can't be placed
56.          * in its own location, period.  If we just checked for mtmp->mx
57.          * != x || mtmp->my != y, we'd miss the case where we're called
58.          * to place the worm segment and the worm's head is at x,y.
59.          */
60.         if (mtmp2 && (mtmp2 != mtmp || mtmp->wormno))
61.             return FALSE;
62. 
63.         mdat = mtmp->data;
64.         if (is_pool(x, y) && !ignorewater) {
65.             /* [what about Breathless?] */
66.             if (mtmp == &youmonst)
67.                 return (Swimming || Amphibious
68.                         || (!Is_waterlevel(&u.uz)
69.                             /* water on the Plane of Water has no surface
70.                                so there's no way to be on or above that */
71.                             && (Levitation || Flying || Wwalking)));
72.             else
73.                 return (is_swimmer(mdat)
74.                         || (!Is_waterlevel(&u.uz)
75.                             && (is_floater(mdat) || is_flyer(mdat)
76.                                 || is_clinger(mdat))));
77.         } else if (mdat->mlet == S_EEL && rn2(13) && !ignorewater) {
78.             return FALSE;
79.         } else if (is_lava(x, y)) {
80.             /* 3.6.3: floating eye can levitate over lava but it avoids
81.                that due the effect of the heat causing it to dry out */
82.             if (mdat == &mons[PM_FLOATING_EYE])
83.                 return FALSE;
84.             else if (mtmp == &youmonst)
85.                 return (Levitation || Flying
86.                         || (Fire_resistance && Wwalking && uarmf
87.                             && uarmf->oerodeproof)
88.                         || (Upolyd && likes_lava(youmonst.data)));
89.             else
90.                 return (is_floater(mdat) || is_flyer(mdat)
91.                         || likes_lava(mdat));
92.         }
93.         if (passes_walls(mdat) && may_passwall(x, y))
94.             return TRUE;
95.         if (amorphous(mdat) && closed_door(x, y))
96.             return TRUE;
97.     }
98.     if (!accessible(x, y)) {
99.         if (!(is_pool(x, y) && ignorewater))
100.             return FALSE;
101.     }
102. 
103.     if (sobj_at(BOULDER, x, y) && (!mdat || !throws_rocks(mdat)))
104.         return FALSE;
105.     return TRUE;
106. }
107. 
108. /*
109.  * "entity next to"
110.  *
111.  * Attempt to find a good place for the given monster type in the closest
112.  * position to (xx,yy).  Do so in successive square rings around (xx,yy).
113.  * If there is more than one valid position in the ring, choose one randomly.
114.  * Return TRUE and the position chosen when successful, FALSE otherwise.
115.  */
116. boolean
117. enexto(cc, xx, yy, mdat)
118. coord *cc;
119. register xchar xx, yy;
120. struct permonst *mdat;
121. {
122.     return enexto_core(cc, xx, yy, mdat, NO_MM_FLAGS);
123. }
124. 
125. boolean
126. enexto_core(cc, xx, yy, mdat, entflags)
127. coord *cc;
128. xchar xx, yy;
129. struct permonst *mdat;
130. unsigned entflags;
131. {
132. #define MAX_GOOD 15
133.     coord good[MAX_GOOD], *good_ptr;
134.     int x, y, range, i;
135.     int xmin, xmax, ymin, ymax, rangemax;
136.     struct monst fakemon; /* dummy monster */
137.     boolean allow_xx_yy = (boolean) ((entflags & GP_ALLOW_XY) != 0);
138. 
139.     entflags &= ~GP_ALLOW_XY;
140.     if (!mdat) {
141.         debugpline0("enexto() called with null mdat");
142.         /* default to player's original monster type */
143.         mdat = &mons[u.umonster];
144.     }
145.     fakemon = zeromonst;
146.     set_mon_data(&fakemon, mdat); /* set up for goodpos */
147. 
148.     /* used to use 'if (range > ROWNO && range > COLNO) return FALSE' below,
149.        so effectively 'max(ROWNO, COLNO)' which performs useless iterations
150.        (possibly many iterations if <xx,yy> is in the center of the map) */
151.     xmax = max(xx - 1, (COLNO - 1) - xx);
152.     ymax = max(yy - 0, (ROWNO - 1) - yy);
153.     rangemax = max(xmax, ymax);
154.     /* setup: no suitable spots yet, first iteration checks adjacent spots */
155.     good_ptr = good;
156.     range = 1;
157.     /*
158.      * Walk around the border of the square with center (xx,yy) and
159.      * radius range.  Stop when we find at least one valid position.
160.      */
161.     do {
162.         xmin = max(1, xx - range);
163.         xmax = min(COLNO - 1, xx + range);
164.         ymin = max(0, yy - range);
165.         ymax = min(ROWNO - 1, yy + range);
166. 
167.         for (x = xmin; x <= xmax; x++) {
168.             if (goodpos(x, ymin, &fakemon, entflags)) {
169.                 good_ptr->x = x;
170.                 good_ptr->y = ymin;
171.                 /* beware of accessing beyond segment boundaries.. */
172.                 if (good_ptr++ == &good[MAX_GOOD - 1])
173.                     goto full;
174.             }
175.             if (goodpos(x, ymax, &fakemon, entflags)) {
176.                 good_ptr->x = x;
177.                 good_ptr->y = ymax;
178.                 if (good_ptr++ == &good[MAX_GOOD - 1])
179.                     goto full;
180.             }
181.         }
182.         /* 3.6.3: this used to use 'ymin+1' which left top row unchecked */
183.         for (y = ymin; y < ymax; y++) {
184.             if (goodpos(xmin, y, &fakemon, entflags)) {
185.                 good_ptr->x = xmin;
186.                 good_ptr->y = y;
187.                 if (good_ptr++ == &good[MAX_GOOD - 1])
188.                     goto full;
189.             }
190.             if (goodpos(xmax, y, &fakemon, entflags)) {
191.                 good_ptr->x = xmax;
192.                 good_ptr->y = y;
193.                 if (good_ptr++ == &good[MAX_GOOD - 1])
194.                     goto full;
195.             }
196.         }
197.     } while (++range <= rangemax && good_ptr == good);
198. 
199.     /* return False if we exhausted 'range' without finding anything */
200.     if (good_ptr == good) {
201.         /* 3.6.3: earlier versions didn't have the option to try <xx,yy>,
202.            and left 'cc' uninitialized when returning False */
203.         cc->x = xx, cc->y = yy;
204.         /* if every spot other than <xx,yy> has failed, try <xx,yy> itself */
205.         if (allow_xx_yy && goodpos(xx, yy, &fakemon, entflags)) {
206.             return TRUE; /* 'cc' is set */
207.         } else {
208.             debugpline3("enexto(\"%s\",%d,%d) failed", mdat->mname, xx, yy);
209.             return FALSE;
210.         }
211.     }
212. 
213.  full:
214.     /* we've got between 1 and SIZE(good) candidates; choose one */
215.     i = rn2((int) (good_ptr - good));
216.     cc->x = good[i].x;
217.     cc->y = good[i].y;
218.     return TRUE;
219. }
220. 
221. /*
222.  * Check for restricted areas present in some special levels.  (This might
223.  * need to be augmented to allow deliberate passage in wizard mode, but
224.  * only for explicitly chosen destinations.)
225.  */
226. STATIC_OVL boolean
227. tele_jump_ok(x1, y1, x2, y2)
228. int x1, y1, x2, y2;
229. {
230.     if (!isok(x2, y2))
231.         return FALSE;
232.     if (dndest.nlx > 0) {
233.         /* if inside a restricted region, can't teleport outside */
234.         if (within_bounded_area(x1, y1, dndest.nlx, dndest.nly, dndest.nhx,
235.                                 dndest.nhy)
236.             && !within_bounded_area(x2, y2, dndest.nlx, dndest.nly,
237.                                     dndest.nhx, dndest.nhy))
238.             return FALSE;
239.         /* and if outside, can't teleport inside */
240.         if (!within_bounded_area(x1, y1, dndest.nlx, dndest.nly, dndest.nhx,
241.                                  dndest.nhy)
242.             && within_bounded_area(x2, y2, dndest.nlx, dndest.nly, dndest.nhx,
243.                                    dndest.nhy))
244.             return FALSE;
245.     }
246.     if (updest.nlx > 0) { /* ditto */
247.         if (within_bounded_area(x1, y1, updest.nlx, updest.nly, updest.nhx,
248.                                 updest.nhy)
249.             && !within_bounded_area(x2, y2, updest.nlx, updest.nly,
250.                                     updest.nhx, updest.nhy))
251.             return FALSE;
252.         if (!within_bounded_area(x1, y1, updest.nlx, updest.nly, updest.nhx,
253.                                  updest.nhy)
254.             && within_bounded_area(x2, y2, updest.nlx, updest.nly, updest.nhx,
255.                                    updest.nhy))
256.             return FALSE;
257.     }
258.     return TRUE;
259. }
260. 
261. STATIC_OVL boolean
262. teleok(x, y, trapok)
263. register int x, y;
264. boolean trapok;
265. {
266.     if (!trapok) {
267.         /* allow teleportation onto vibrating square, it's not a real trap */
268.         struct trap *trap = t_at(x, y);
269. 
270.         if (trap && trap->ttyp != VIBRATING_SQUARE)
271.             return FALSE;
272.     }
273.     if (!goodpos(x, y, &youmonst, 0))
274.         return FALSE;
275.     if (!tele_jump_ok(u.ux, u.uy, x, y))
276.         return FALSE;
277.     if (!in_out_region(x, y))
278.         return FALSE;
279.     return TRUE;
280. }
281. 
282. void
283. teleds(nux, nuy, allow_drag)
284. register int nux, nuy;
285. boolean allow_drag;
286. {
287.     boolean ball_active, ball_still_in_range;
288.     struct monst *vault_guard = vault_occupied(u.urooms) ? findgd() : 0;
289. 
290.     if (u.utraptype == TT_BURIEDBALL) {
291.         /* unearth it */
292.         buried_ball_to_punishment();
293.     }
294.     ball_active = (Punished && uball->where != OBJ_FREE);
295.     ball_still_in_range = FALSE;
296. 
297.     /* If they have to move the ball, then drag if allow_drag is true;
298.      * otherwise they are teleporting, so unplacebc().
299.      * If they don't have to move the ball, then always "drag" whether or
300.      * not allow_drag is true, because we are calling that function, not
301.      * to drag, but to move the chain.  *However* there are some dumb
302.      * special cases:
303.      *    0                          0
304.      *   _X  move east       ----->  X_
305.      *    @                           @
306.      * These are permissible if teleporting, but not if dragging.  As a
307.      * result, drag_ball() needs to know about allow_drag and might end
308.      * up dragging the ball anyway.  Also, drag_ball() might find that
309.      * dragging the ball is completely impossible (ball in range but there's
310.      * rock in the way), in which case it teleports the ball on its own.
311.      */
312.     if (ball_active) {
313.         if (!carried(uball) && distmin(nux, nuy, uball->ox, uball->oy) <= 2) {
314.             ball_still_in_range = TRUE; /* don't have to move the ball */
315.         } else {
316.             /* have to move the ball */
317.             if (!allow_drag || distmin(u.ux, u.uy, nux, nuy) > 1) {
318.                 /* we should not have dist > 1 and allow_drag at the same
319.                  * time, but just in case, we must then revert to teleport.
320.                  */
321.                 allow_drag = FALSE;
322.                 unplacebc();
323.             }
324.         }
325.     }
326.     reset_utrap(FALSE);
327.     u.ustuck = 0;
328.     u.ux0 = u.ux;
329.     u.uy0 = u.uy;
330. 
331.     if (!hideunder(&youmonst) && youmonst.data->mlet == S_MIMIC) {
332.         /* mimics stop being unnoticed */
333.         youmonst.m_ap_type = M_AP_NOTHING;
334.     }
335. 
336.     if (u.uswallow) {
337.         u.uswldtim = u.uswallow = 0;
338.         if (Punished && !ball_active) {
339.             /* ensure ball placement, like unstuck */
340.             ball_active = TRUE;
341.             allow_drag = FALSE;
342.         }
343.         docrt();
344.     }
345.     if (ball_active) {
346.         if (ball_still_in_range || allow_drag) {
347.             int bc_control;
348.             xchar ballx, bally, chainx, chainy;
349.             boolean cause_delay;
350. 
351.             if (drag_ball(nux, nuy, &bc_control, &ballx, &bally, &chainx,
352.                           &chainy, &cause_delay, allow_drag)) {
353.                 move_bc(0, bc_control, ballx, bally, chainx, chainy);
354.             } else {
355.                 /* dragging fails if hero is encumbered beyond 'burdened' */
356.                 allow_drag = FALSE; /* teleport b&c to hero's new spot */
357.                 unplacebc(); /* to match placebc() below */
358.             }
359.         }
360.     }
361.     /* must set u.ux, u.uy after drag_ball(), which may need to know
362.        the old position if allow_drag is true... */
363.     u_on_newpos(nux, nuy); /* set u.<x,y>, usteed-><mx,my>; cliparound() */
364.     fill_pit(u.ux0, u.uy0);
365.     if (ball_active) {
366.         if (!ball_still_in_range && !allow_drag)
367.             placebc();
368.     }
369.     initrack(); /* teleports mess up tracking monsters without this */
370.     update_player_regions();
371.     /*
372.      *  Make sure the hero disappears from the old location.  This will
373.      *  not happen if she is teleported within sight of her previous
374.      *  location.  Force a full vision recalculation because the hero
375.      *  is now in a new location.
376.      */
377.     newsym(u.ux0, u.uy0);
378.     see_monsters();
379.     vision_full_recalc = 1;
380.     nomul(0);
381.     vision_recalc(0); /* vision before effects */
382.     /* if terrain type changes, levitation or flying might become blocked
383.        or unblocked; might issue message, so do this after map+vision has
384.        been updated for new location instead of right after u_on_newpos() */
385.     if (levl[u.ux][u.uy].typ != levl[u.ux0][u.uy0].typ)
386.         switch_terrain();
387.     if (telescroll) {
388.         /* when teleporting by scroll, we need to handle discovery
389.            now before getting feedback about any objects at our
390.            destination since we might land on another such scroll */
391.         if (distu(u.ux0, u.uy0) >= 16 || !couldsee(u.ux0, u.uy0))
392.             learnscroll(telescroll);
393.         else
394.             telescroll = 0; /* no discovery by scrolltele()'s caller */
395.     }
396.     /* sequencing issue:  we want guard's alarm, if any, to occur before
397.        room entry message, if any, so need to check for vault exit prior
398.        to spoteffects; but spoteffects() sets up new value for u.urooms
399.        and vault code depends upon that value, so we need to fake it */
400.     if (vault_guard) {
401.         char save_urooms[5]; /* [sizeof u.urooms] */
402. 
403.         Strcpy(save_urooms, u.urooms);
404.         Strcpy(u.urooms, in_rooms(u.ux, u.uy, VAULT));
405.         /* if hero has left vault, make guard notice */
406.         if (!vault_occupied(u.urooms))
407.             uleftvault(vault_guard);
408.         Strcpy(u.urooms, save_urooms); /* reset prior to spoteffects() */
409.     }
410.     /* possible shop entry message comes after guard's shrill whistle */
411.     spoteffects(TRUE);
412.     invocation_message();
413. }
414. 
415. boolean
416. safe_teleds(allow_drag)
417. boolean allow_drag;
418. {
419.     register int nux, nuy, tcnt = 0;
420. 
421.     do {
422.         nux = rnd(COLNO - 1);
423.         nuy = rn2(ROWNO);
424.     } while (!teleok(nux, nuy, (boolean) (tcnt > 200)) && ++tcnt <= 400);
425. 
426.     if (tcnt <= 400) {
427.         teleds(nux, nuy, allow_drag);
428.         return TRUE;
429.     } else
430.         return FALSE;
431. }
432. 
433. STATIC_OVL void
434. vault_tele()
435. {
436.     register struct mkroom *croom = search_special(VAULT);
437.     coord c;
438. 
439.     if (croom && somexy(croom, &c) && teleok(c.x, c.y, FALSE)) {
440.         teleds(c.x, c.y, FALSE);
441.         return;
442.     }
443.     tele();
444. }
445. 
446. boolean
447. teleport_pet(mtmp, force_it)
448. register struct monst *mtmp;
449. boolean force_it;
450. {
451.     register struct obj *otmp;
452. 
453.     if (mtmp == u.usteed)
454.         return FALSE;
455. 
456.     if (mtmp->mleashed) {
457.         otmp = get_mleash(mtmp);
458.         if (!otmp) {
459.             impossible("%s is leashed, without a leash.", Monnam(mtmp));
460.             goto release_it;
461.         }
462.         if (otmp->cursed && !force_it) {
463.             yelp(mtmp);
464.             return FALSE;
465.         } else {
466.             Your("leash goes slack.");
467.  release_it:
468.             m_unleash(mtmp, FALSE);
469.             return TRUE;
470.         }
471.     }
472.     return TRUE;
473. }
474. 
475. /* teleport the hero via some method other than scroll of teleport */
476. void
477. tele()
478. {
479.     (void) scrolltele((struct obj *) 0);
480. }
481. 
482. /* teleport the hero; return true if scroll of teleportation should become
483.    discovered; teleds() will usually do the actual discovery, since the
484.    outcome sometimes depends upon destination and discovery needs to be
485.    performed before arrival, in case we land on another teleport scroll */
486. boolean
487. scrolltele(scroll)
488. struct obj *scroll;
489. {
490.     coord cc;
491.     boolean result = FALSE; /* don't learn scroll */
492. 
493.     /* Disable teleportation in stronghold && Vlad's Tower */
494.     if (level.flags.noteleport) {
495.         if (!wizard) {
496.             pline("A mysterious force prevents you from teleporting!");
497.             return TRUE;
498.         }
499.     }
500. 
501.     /* don't show trap if "Sorry..." */
502.     if (!Blinded)
503.         make_blinded(0L, FALSE);
504. 
505.     if ((u.uhave.amulet || On_W_tower_level(&u.uz)) && !rn2(3)) {
506.         You_feel("disoriented for a moment.");
507.         if (!wizard || yn("Override?") != 'y')
508.             return FALSE;
509.     }
510.     if ((Teleport_control && !Stunned) || wizard) {
511.         if (unconscious()) {
512.             pline("Being unconscious, you cannot control your teleport.");
513.         } else {
514.             char whobuf[BUFSZ];
515. 
516.             Strcpy(whobuf, "you");
517.             if (u.usteed)
518.                 Sprintf(eos(whobuf), " and %s", mon_nam(u.usteed));
519.             pline("Where do %s want to be teleported?", whobuf);
520.             cc.x = u.ux;
521.             cc.y = u.uy;
522.             if (getpos(&cc, TRUE, "the desired position") < 0)
523.                 return TRUE; /* abort */
524.             /* possible extensions: introduce a small error if
525.                magic power is low; allow transfer to solid rock */
526.             if (teleok(cc.x, cc.y, FALSE)) {
527.                 /* for scroll, discover it regardless of destination */
528.                 if (scroll)
529.                     learnscroll(scroll);
530.                 teleds(cc.x, cc.y, FALSE);
531.                 return TRUE;
532.             }
533.             pline("Sorry...");
534.             result = TRUE;
535.         }
536.     } else if (scroll && scroll->blessed) {
537.         /* (this used to be handled in seffects()) */
538.         if (yn("Do you wish to teleport?") == 'n')
539.             return TRUE;
540.         result = TRUE;
541.     }
542. 
543.     telescroll = scroll;
544.     (void) safe_teleds(FALSE);
545.     /* teleds() will leave telescroll intact iff random destination
546.        is far enough away for scroll discovery to be warranted */
547.     if (telescroll)
548.         result = TRUE;
549.     telescroll = 0; /* reset */
550.     return result;
551. }
552. 
553. /* ^T command; 'm ^T' == choose among several teleport modes */
554. int
555. dotelecmd()
556. {
557.     long save_HTele, save_ETele;
558.     int res, added, hidden;
559.     boolean ignore_restrictions = FALSE;
560. /* also defined in spell.c */
561. #define NOOP_SPELL  0
562. #define HIDE_SPELL  1
563. #define ADD_SPELL   2
564. #define UNHIDESPELL 3
565. #define REMOVESPELL 4
566. 
567.     /* normal mode; ignore 'm' prefix if it was given */
568.     if (!wizard)
569.         return dotele(FALSE);
570. 
571.     added = hidden = NOOP_SPELL;
572.     save_HTele = HTeleportation, save_ETele = ETeleportation;
573.     if (!iflags.menu_requested) {
574.         ignore_restrictions = TRUE;
575.     } else {
576.         static const struct tporttypes {
577.             char menulet;
578.             const char *menudesc;
579.         } tports[] = {
580.             /*
581.              * Potential combinations:
582.              *  1) attempt ^T without intrinsic, not know spell;
583.              *  2) via intrinsic, not know spell, obey restrictions;
584.              *  3) via intrinsic, not know spell, ignore restrictions;
585.              *  4) via intrinsic, know spell, obey restrictions;
586.              *  5) via intrinsic, know spell, ignore restrictions;
587.              *  6) via spell, not have intrinsic, obey restrictions;
588.              *  7) via spell, not have intrinsic, ignore restrictions;
589.              *  8) force, obey other restrictions;
590.              *  9) force, ignore restrictions.
591.              * We only support the 1st (t), 2nd (n), 6th (s), and 9th (w).
592.              *
593.              * This ignores the fact that there is an experience level
594.              * (or poly-form) requirement which might make normal ^T fail.
595.              */
596.             { 'n', "normal ^T on demand; no spell, obey restrictions" },
597.             { 's', "via spellcast; no intrinsic teleport" },
598.             { 't', "try ^T without having it; no spell" },
599.             { 'w', "debug mode; ignore restrictions" }, /* trad wizard mode */
600.         };
601.         menu_item *picks = (menu_item *) 0;
602.         anything any;
603.         winid win;
604.         int i, tmode;
605. 
606.         win = create_nhwindow(NHW_MENU);
607.         start_menu(win);
608.         any = zeroany;
609.         for (i = 0; i < SIZE(tports); ++i) {
610.             any.a_int = (int) tports[i].menulet;
611.             add_menu(win, NO_GLYPH, &any, (char) any.a_int, 0, ATR_NONE,
612.                      tports[i].menudesc,
613.                      (tports[i].menulet == 'w') ? MENU_SELECTED
614.                                                 : MENU_UNSELECTED);
615.         }
616.         end_menu(win, "Which way do you want to teleport?");
617.         i = select_menu(win, PICK_ONE, &picks);
618.         destroy_nhwindow(win);
619.         if (i > 0) {
620.             tmode = picks[0].item.a_int;
621.             /* if we got 2, use the one which wasn't preselected */
622.             if (i > 1 && tmode == 'w')
623.                 tmode = picks[1].item.a_int;
624.             free((genericptr_t) picks);
625.         } else if (i == 0) {
626.             /* preselected one was explicitly chosen and got toggled off */
627.             tmode = 'w';
628.         } else { /* ESC */
629.             return 0;
630.         }
631.         switch (tmode) {
632.         case 'n':
633.             HTeleportation |= I_SPECIAL; /* confer intrinsic teleportation */
634.             hidden = tport_spell(HIDE_SPELL); /* hide teleport-away */
635.             break;
636.         case 's':
637.             HTeleportation = ETeleportation = 0L; /* suppress intrinsic */
638.             added = tport_spell(ADD_SPELL); /* add teleport-away */
639.             break;
640.         case 't':
641.             HTeleportation = ETeleportation = 0L; /* suppress intrinsic */
642.             hidden = tport_spell(HIDE_SPELL); /* hide teleport-away */
643.             break;
644.         case 'w':
645.             ignore_restrictions = TRUE;
646.             break;
647.         }
648.     }
649. 
650.     /* if dotele() can be fatal, final disclosure might lie about
651.        intrinsic teleportation; we should be able to live with that
652.        since the menu finagling is only applicable in wizard mode */
653.     res = dotele(ignore_restrictions);
654. 
655.     HTeleportation = save_HTele;
656.     ETeleportation = save_ETele;
657.     if (added != NOOP_SPELL || hidden != NOOP_SPELL)
658.         /* can't both be non-NOOP so addition will yield the non-NOOP one */
659.         (void) tport_spell(added + hidden - NOOP_SPELL);
660. 
661.     return res;
662. }
663. 
664. int
665. dotele(break_the_rules)
666. boolean break_the_rules; /* True: wizard mode ^T */
667. {
668.     struct trap *trap;
669.     const char *cantdoit;
670.     boolean trap_once = FALSE;
671. 
672.     trap = t_at(u.ux, u.uy);
673.     if (trap && (!trap->tseen || trap->ttyp != TELEP_TRAP))
674.         trap = 0;
675. 
676.     if (trap) {
677.         trap_once = trap->once; /* trap may get deleted, save this */
678.         if (trap->once) {
679.             pline("This is a vault teleport, usable once only.");
680.             if (yn("Jump in?") == 'n') {
681.                 trap = 0;
682.             } else {
683.                 deltrap(trap);
684.                 newsym(u.ux, u.uy);
685.             }
686.         }
687.         if (trap)
688.             You("%s onto the teleportation trap.",
689.                 locomotion(youmonst.data, "jump"));
690.     }
691.     if (!trap) {
692.         boolean castit = FALSE;
693.         register int sp_no = 0, energy = 0;
694. 
695.         if (!Teleportation || (u.ulevel < (Role_if(PM_WIZARD) ? 8 : 12)
696.                                && !can_teleport(youmonst.data))) {
697.             /* Try to use teleport away spell.
698.                Prior to 3.6.2 this used to require that you know the spellbook
699.                (probably just intended as an optimization to skip the
700.                lookup loop) but it is possible to know and cast a spell
701.                after forgetting its book due to amnesia. */
702.             for (sp_no = 0; sp_no < MAXSPELL; sp_no++)
703.                 if (spl_book[sp_no].sp_id == SPE_TELEPORT_AWAY)
704.                     break;
705.             /* casting isn't inhibited by being Stunned (...it ought to be) */
706.             castit = (sp_no < MAXSPELL && !Confusion);
707.             if (!castit && !break_the_rules) {
708.                 You("%s.",
709.                     !Teleportation ? ((sp_no < MAXSPELL)
710.                                         ? "can't cast that spell"
711.                                         : "don't know that spell")
712.                                    : "are not able to teleport at will");
713.                 return 0;
714.             }
715.         }
716. 
717.         cantdoit = 0;
718.         /* 3.6.2: the magic numbers for hunger, strength, and energy
719.            have been changed to match the ones used in spelleffects().
720.            Also, failing these tests used to return 1 and use a move
721.            even though casting failure due to these reasons doesn't.
722.            [Note: this spellev() is different from the one in spell.c
723.            but they both yield the same result.] */
724. #define spellev(spell_otyp) ((int) objects[spell_otyp].oc_level)
725.         energy = 5 * spellev(SPE_TELEPORT_AWAY);
726.         if (break_the_rules) {
727.             if (!castit)
728.                 energy = 0;
729.             /* spell will cost more if carrying the Amulet, but the
730.                amount is rnd(2 * energy) so we can't know by how much;
731.                average is twice the normal cost, but could be triple;
732.                the extra energy is spent even if that results in not
733.                having enough to cast (which also uses the move) */
734.             else if (u.uen < energy)
735.                 u.uen = energy;
736.         } else if (u.uhunger <= 10) {
737.             cantdoit = "are too weak from hunger";
738.         } else if (ACURR(A_STR) < 4) {
739.             cantdoit = "lack the strength";
740.         } else if (energy > u.uen) {
741.             cantdoit = "lack the energy";
742.         }
743.         if (cantdoit) {
744.             You("%s %s.", cantdoit,
745.                 castit ? "for a teleport spell" : "to teleport");
746.             return 0;
747.         } else if (check_capacity(
748.                        "Your concentration falters from carrying so much.")) {
749.             return 1; /* this failure in spelleffects() also uses the move */
750.         }
751. 
752.         if (castit) {
753.             /* energy cost is deducted in spelleffects() */
754.             exercise(A_WIS, TRUE);
755.             if (spelleffects(sp_no, TRUE))
756.                 return 1;
757.             else if (!break_the_rules)
758.                 return 0;
759.         } else {
760.             /* bypassing spelleffects(); apply energy cost directly */
761.             u.uen -= energy;
762.             context.botl = 1;
763.         }
764.     }
765. 
766.     if (next_to_u()) {
767.         if (trap && trap_once)
768.             vault_tele();
769.         else
770.             tele();
771.         (void) next_to_u();
772.     } else {
773.         You("%s", shudder_for_moment);
774.         return 0;
775.     }
776.     if (!trap)
777.         morehungry(100);
778.     return 1;
779. }
780. 
781. void
782. level_tele()
783. {
784.     register int newlev;
785.     d_level newlevel;
786.     const char *escape_by_flying = 0; /* when surviving dest of -N */
787.     char buf[BUFSZ];
788.     boolean force_dest = FALSE;
789. 
790.     if (iflags.debug_fuzzer)
791.         goto random_levtport;
792.     if ((u.uhave.amulet || In_endgame(&u.uz) || In_sokoban(&u.uz))
793.         && !wizard) {
794.         You_feel("very disoriented for a moment.");
795.         return;
796.     }
797.     if ((Teleport_control && !Stunned) || wizard) {
798.         char qbuf[BUFSZ];
799.         int trycnt = 0;
800. 
801.         Strcpy(qbuf, "To what level do you want to teleport?");
802.         do {
803.             if (iflags.menu_requested) {
804.                 /* wizard mode 'm ^V' skips prompting on first pass
805.                    (note: level Tport via menu won't have any second pass) */
806.                 iflags.menu_requested = FALSE;
807.                 if (wizard)
808.                     goto levTport_menu;
809.             }
810.             if (++trycnt == 2) {
811.                 if (wizard)
812.                     Strcat(qbuf, " [type a number, name, or ? for a menu]");
813.                 else
814.                     Strcat(qbuf, " [type a number or name]");
815.             }
816.             *buf = '\0'; /* EDIT_GETLIN: if we're on second or later pass,
817.                             the previous input was invalid so don't use it
818.                             as getlin()'s preloaded default answer */
819.             getlin(qbuf, buf);
820.             if (!strcmp(buf, "\033")) { /* cancelled */
821.                 if (Confusion && rnl(5)) {
822.                     pline("Oops...");
823.                     goto random_levtport;
824.                 }
825.                 return;
826.             } else if (!strcmp(buf, "*")) {
827.                 goto random_levtport;
828.             } else if (Confusion && rnl(5)) {
829.                 pline("Oops...");
830.                 goto random_levtport;
831.             }
832.             if (wizard && !strcmp(buf, "?")) {
833.                 schar destlev;
834.                 xchar destdnum;
835. 
836.  levTport_menu:
837.                 destlev = 0;
838.                 destdnum = 0;
839.                 newlev = (int) print_dungeon(TRUE, &destlev, &destdnum);
840.                 if (!newlev)
841.                     return;
842. 
843.                 newlevel.dnum = destdnum;
844.                 newlevel.dlevel = destlev;
845.                 if (In_endgame(&newlevel) && !In_endgame(&u.uz)) {
846.                     struct obj *amu;
847. 
848.                     if (!u.uhave.amulet
849.                         && (amu = mksobj(AMULET_OF_YENDOR, TRUE, FALSE))
850.                                != 0) {
851.                         /* ordinarily we'd use hold_another_object()
852.                            for something like this, but we don't want
853.                            fumbling or already full pack to interfere */
854.                         amu = addinv(amu);
855.                         prinv("Endgame prerequisite:", amu, 0L);
856.                     }
857.                 }
858.                 force_dest = TRUE;
859.             } else if ((newlev = lev_by_name(buf)) == 0)
860.                 newlev = atoi(buf);
861.         } while (!newlev && !digit(buf[0])
862.                  && (buf[0] != '-' || !digit(buf[1])) && trycnt < 10);
863. 
864.         /* no dungeon escape via this route */
865.         if (newlev == 0) {
866.             if (trycnt >= 10)
867.                 goto random_levtport;
868.             if (ynq("Go to Nowhere.  Are you sure?") != 'y')
869.                 return;
870.             You("%s in agony as your body begins to warp...",
871.                 is_silent(youmonst.data) ? "writhe" : "scream");
872.             display_nhwindow(WIN_MESSAGE, FALSE);
873.             You("cease to exist.");
874.             if (invent)
875.                 Your("possessions land on the %s with a thud.",
876.                      surface(u.ux, u.uy));
877.             killer.format = NO_KILLER_PREFIX;
878.             Strcpy(killer.name, "committed suicide");
879.             done(DIED);
880.             pline("An energized cloud of dust begins to coalesce.");
881.             Your("body rematerializes%s.",
882.                  invent ? ", and you gather up all your possessions" : "");
883.             return;
884.         }
885. 
886.         /* if in Knox and the requested level > 0, stay put.
887.          * we let negative values requests fall into the "heaven" loop.
888.          */
889.         if (Is_knox(&u.uz) && newlev > 0 && !force_dest) {
890.             You1(shudder_for_moment);
891.             return;
892.         }
893.         /* if in Quest, the player sees "Home 1", etc., on the status
894.          * line, instead of the logical depth of the level.  controlled
895.          * level teleport request is likely to be relativized to the
896.          * status line, and consequently it should be incremented to
897.          * the value of the logical depth of the target level.
898.          *
899.          * we let negative values requests fall into the "heaven" loop.
900.          */
901.         if (In_quest(&u.uz) && newlev > 0)
902.             newlev = newlev + dungeons[u.uz.dnum].depth_start - 1;
903.     } else { /* involuntary level tele */
904.  random_levtport:
905.         newlev = random_teleport_level();
906.         if (newlev == depth(&u.uz)) {
907.             You1(shudder_for_moment);
908.             return;
909.         }
910.     }
911. 
912.     if (u.utrap && u.utraptype == TT_BURIEDBALL)
913.         buried_ball_to_punishment();
914. 
915.     if (!next_to_u() && !force_dest) {
916.         You1(shudder_for_moment);
917.         return;
918.     }
919.     if (In_endgame(&u.uz)) { /* must already be wizard */
920.         int llimit = dunlevs_in_dungeon(&u.uz);
921. 
922.         if (newlev >= 0 || newlev <= -llimit) {
923.             You_cant("get there from here.");
924.             return;
925.         }
926.         newlevel.dnum = u.uz.dnum;
927.         newlevel.dlevel = llimit + newlev;
928.         schedule_goto(&newlevel, FALSE, FALSE, 0, (char *) 0, (char *) 0);
929.         return;
930.     }
931. 
932.     killer.name[0] = 0; /* still alive, so far... */
933. 
934.     if (iflags.debug_fuzzer && newlev < 0)
935.         goto random_levtport;
936.     if (newlev < 0 && !force_dest) {
937.         if (*u.ushops0) {
938.             /* take unpaid inventory items off of shop bills */
939.             in_mklev = TRUE; /* suppress map update */
940.             u_left_shop(u.ushops0, TRUE);
941.             /* you're now effectively out of the shop */
942.             *u.ushops0 = *u.ushops = '\0';
943.             in_mklev = FALSE;
944.         }
945.         if (newlev <= -10) {
946.             You("arrive in heaven.");
947.             verbalize("Thou art early, but we'll admit thee.");
948.             killer.format = NO_KILLER_PREFIX;
949.             Strcpy(killer.name, "went to heaven prematurely");
950.         } else if (newlev == -9) {
951.             You_feel("deliriously happy.");
952.             pline("(In fact, you're on Cloud 9!)");
953.             display_nhwindow(WIN_MESSAGE, FALSE);
954.         } else
955.             You("are now high above the clouds...");
956. 
957.         if (killer.name[0]) {
958.             ; /* arrival in heaven is pending */
959.         } else if (Levitation) {
960.             escape_by_flying = "float gently down to earth";
961.         } else if (Flying) {
962.             escape_by_flying = "fly down to the ground";
963.         } else {
964.             pline("Unfortunately, you don't know how to fly.");
965.             You("plummet a few thousand feet to your death.");
966.             Sprintf(killer.name,
967.                     "teleported out of the dungeon and fell to %s death",
968.                     uhis());
969.             killer.format = NO_KILLER_PREFIX;
970.         }
971.     }
972. 
973.     if (killer.name[0]) { /* the chosen destination was not survivable */
974.         d_level lsav;
975. 
976.         /* set specific death location; this also suppresses bones */
977.         lsav = u.uz;   /* save current level, see below */
978.         u.uz.dnum = 0; /* main dungeon */
979.         u.uz.dlevel = (newlev <= -10) ? -10 : 0; /* heaven or surface */
980.         done(DIED);
981.         /* can only get here via life-saving (or declining to die in
982.            explore|debug mode); the hero has now left the dungeon... */
983.         escape_by_flying = "find yourself back on the surface";
984.         u.uz = lsav; /* restore u.uz so escape code works */
985.     }
986. 
987.     /* calls done(ESCAPED) if newlevel==0 */
988.     if (escape_by_flying) {
989.         You("%s.", escape_by_flying);
990.         newlevel.dnum = 0;   /* specify main dungeon */
991.         newlevel.dlevel = 0; /* escape the dungeon */
992.         /* [dlevel used to be set to 1, but it doesn't make sense to
993.             teleport out of the dungeon and float or fly down to the
994.             surface but then actually arrive back inside the dungeon] */
995.     } else if (u.uz.dnum == medusa_level.dnum
996.                && newlev >= dungeons[u.uz.dnum].depth_start
997.                                 + dunlevs_in_dungeon(&u.uz)) {
998.         if (!(wizard && force_dest))
999.             find_hell(&newlevel);
1000.     } else {
1001.         /* if invocation did not yet occur, teleporting into
1002.          * the last level of Gehennom is forbidden.
1003.          */
1004.         if (!wizard && Inhell && !u.uevent.invoked
1005.             && newlev >= (dungeons[u.uz.dnum].depth_start
1006.                           + dunlevs_in_dungeon(&u.uz) - 1)) {
1007.             newlev = dungeons[u.uz.dnum].depth_start
1008.                      + dunlevs_in_dungeon(&u.uz) - 2;
1009.             pline("Sorry...");
1010.         }
1011.         /* no teleporting out of quest dungeon */
1012.         if (In_quest(&u.uz) && newlev < depth(&qstart_level))
1013.             newlev = depth(&qstart_level);
1014.         /* the player thinks of levels purely in logical terms, so
1015.          * we must translate newlev to a number relative to the
1016.          * current dungeon.
1017.          */
1018.         if (!(wizard && force_dest))
1019.             get_level(&newlevel, newlev);
1020.     }
1021.     schedule_goto(&newlevel, FALSE, FALSE, 0, (char *) 0, (char *) 0);
1022.     /* in case player just read a scroll and is about to be asked to
1023.        call it something, we can't defer until the end of the turn */
1024.     if (u.utotype && !context.mon_moving)
1025.         deferred_goto();
1026. }
1027. 
1028. void
1029. domagicportal(ttmp)
1030. register struct trap *ttmp;
1031. {
1032.     struct d_level target_level;
1033. 
1034.     if (u.utrap && u.utraptype == TT_BURIEDBALL)
1035.         buried_ball_to_punishment();
1036. 
1037.     if (!next_to_u()) {
1038.         You1(shudder_for_moment);
1039.         return;
1040.     }
1041. 
1042.     /* if landed from another portal, do nothing */
1043.     /* problem: level teleport landing escapes the check */
1044.     if (!on_level(&u.uz, &u.uz0))
1045.         return;
1046. 
1047.     You("activated a magic portal!");
1048. 
1049.     /* prevent the poor shnook, whose amulet was stolen while in
1050.      * the endgame, from accidently triggering the portal to the
1051.      * next level, and thus losing the game
1052.      */
1053.     if (In_endgame(&u.uz) && !u.uhave.amulet) {
1054.         You_feel("dizzy for a moment, but nothing happens...");
1055.         return;
1056.     }
1057. 
1058.     target_level = ttmp->dst;
1059.     schedule_goto(&target_level, FALSE, FALSE, 1,
1060.                   "You feel dizzy for a moment, but the sensation passes.",
1061.                   (char *) 0);
1062. }
1063. 
1064. void
1065. tele_trap(trap)
1066. struct trap *trap;
1067. {
1068.     if (In_endgame(&u.uz) || Antimagic) {
1069.         if (Antimagic)
1070.             shieldeff(u.ux, u.uy);
1071.         You_feel("a wrenching sensation.");
1072.     } else if (!next_to_u()) {
1073.         You1(shudder_for_moment);
1074.     } else if (trap->once) {
1075.         deltrap(trap);
1076.         newsym(u.ux, u.uy); /* get rid of trap symbol */
1077.         vault_tele();
1078.     } else
1079.         tele();
1080. }
1081. 
1082. void
1083. level_tele_trap(trap, trflags)
1084. struct trap *trap;
1085. unsigned trflags;
1086. {
1087.     char verbbuf[BUFSZ];
1088. 
1089.     if ((trflags & VIASITTING) != 0)
1090.         Strcpy(verbbuf, "trigger"); /* follows "You sit down." */
1091.     else
1092.         Sprintf(verbbuf, "%s onto",
1093.                 Levitation ? (const char *) "float"
1094.                            : locomotion(youmonst.data, "step"));
1095.     You("%s a level teleport trap!", verbbuf);
1096. 
1097.     if (Antimagic) {
1098.         shieldeff(u.ux, u.uy);
1099.     }
1100.     if (Antimagic || In_endgame(&u.uz)) {
1101.         You_feel("a wrenching sensation.");
1102.         return;
1103.     }
1104.     if (!Blind)
1105.         You("are momentarily blinded by a flash of light.");
1106.     else
1107.         You("are momentarily disoriented.");
1108.     deltrap(trap);
1109.     newsym(u.ux, u.uy); /* get rid of trap symbol */
1110.     level_tele();
1111. }
1112. 
1113. /* check whether monster can arrive at location <x,y> via Tport (or fall) */
1114. STATIC_OVL boolean
1115. rloc_pos_ok(x, y, mtmp)
1116. register int x, y; /* coordinates of candidate location */
1117. struct monst *mtmp;
1118. {
1119.     register int xx, yy;
1120. 
1121.     if (!goodpos(x, y, mtmp, 0))
1122.         return FALSE;
1123.     /*
1124.      * Check for restricted areas present in some special levels.
1125.      *
1126.      * `xx' is current column; if 0, then `yy' will contain flag bits
1127.      * rather than row:  bit #0 set => moving upwards; bit #1 set =>
1128.      * inside the Wizard's tower.
1129.      */
1130.     xx = mtmp->mx;
1131.     yy = mtmp->my;
1132.     if (!xx) {
1133.         /* no current location (migrating monster arrival) */
1134.         if (dndest.nlx && On_W_tower_level(&u.uz))
1135.             return (((yy & 2) != 0)
1136.                     /* inside xor not within */
1137.                     ^ !within_bounded_area(x, y, dndest.nlx, dndest.nly,
1138.                                            dndest.nhx, dndest.nhy));
1139.         if (updest.lx && (yy & 1) != 0) /* moving up */
1140.             return (within_bounded_area(x, y, updest.lx, updest.ly,
1141.                                         updest.hx, updest.hy)
1142.                     && (!updest.nlx
1143.                         || !within_bounded_area(x, y, updest.nlx, updest.nly,
1144.                                                 updest.nhx, updest.nhy)));
1145.         if (dndest.lx && (yy & 1) == 0) /* moving down */
1146.             return (within_bounded_area(x, y, dndest.lx, dndest.ly,
1147.                                         dndest.hx, dndest.hy)
1148.                     && (!dndest.nlx
1149.                         || !within_bounded_area(x, y, dndest.nlx, dndest.nly,
1150.                                                 dndest.nhx, dndest.nhy)));
1151.     } else {
1152.         /* [try to] prevent a shopkeeper or temple priest from being
1153.            sent out of his room (caller might resort to goodpos() if
1154.            we report failure here, so this isn't full prevention) */
1155.         if (mtmp->isshk && inhishop(mtmp)) {
1156.             if (levl[x][y].roomno != ESHK(mtmp)->shoproom)
1157.                 return FALSE;
1158.         } else if (mtmp->ispriest && inhistemple(mtmp)) {
1159.             if (levl[x][y].roomno != EPRI(mtmp)->shroom)
1160.                 return FALSE;
1161.         }
1162.         /* current location is <xx,yy> */
1163.         if (!tele_jump_ok(xx, yy, x, y))
1164.             return FALSE;
1165.     }
1166.     /* <x,y> is ok */
1167.     return TRUE;
1168. }
1169. 
1170. /*
1171.  * rloc_to()
1172.  *
1173.  * Pulls a monster from its current position and places a monster at
1174.  * a new x and y.  If oldx is 0, then the monster was not in the
1175.  * levels.monsters array.  However, if oldx is 0, oldy may still have
1176.  * a value because mtmp is a migrating_mon.  Worm tails are always
1177.  * placed randomly around the head of the worm.
1178.  */
1179. void
1180. rloc_to(mtmp, x, y)
1181. struct monst *mtmp;
1182. register int x, y;
1183. {
1184.     register int oldx = mtmp->mx, oldy = mtmp->my;
1185.     boolean resident_shk = mtmp->isshk && inhishop(mtmp);
1186. 
1187.     if (x == mtmp->mx && y == mtmp->my && m_at(x, y) == mtmp)
1188.         return; /* that was easy */
1189. 
1190.     if (oldx) { /* "pick up" monster */
1191.         if (mtmp->wormno) {
1192.             remove_worm(mtmp);
1193.         } else {
1194.             remove_monster(oldx, oldy);
1195.             newsym(oldx, oldy); /* update old location */
1196.         }
1197.     }
1198. 
1199.     memset(mtmp->mtrack, 0, sizeof mtmp->mtrack);
1200.     place_monster(mtmp, x, y); /* put monster down */
1201.     update_monster_region(mtmp);
1202. 
1203.     if (mtmp->wormno) /* now put down tail */
1204.         place_worm_tail_randomly(mtmp, x, y);
1205. 
1206.     if (u.ustuck == mtmp) {
1207.         if (u.uswallow) {
1208.             u_on_newpos(mtmp->mx, mtmp->my);
1209.             docrt();
1210.         } else if (distu(mtmp->mx, mtmp->my) > 2) {
1211.            unstuck(mtmp);
1212.         }
1213.     }
1214. 
1215.     newsym(x, y);      /* update new location */
1216.     set_apparxy(mtmp); /* orient monster */
1217. 
1218.     /* shopkeepers will only teleport if you zap them with a wand of
1219.        teleportation or if they've been transformed into a jumpy monster;
1220.        the latter only happens if you've attacked them with polymorph */
1221.     if (resident_shk && !inhishop(mtmp))
1222.         make_angry_shk(mtmp, oldx, oldy);
1223. }
1224. 
1225. /* place a monster at a random location, typically due to teleport */
1226. /* return TRUE if successful, FALSE if not */
1227. boolean
1228. rloc(mtmp, suppress_impossible)
1229. struct monst *mtmp; /* mx==0 implies migrating monster arrival */
1230. boolean suppress_impossible;
1231. {
1232.     register int x, y, trycount;
1233. 
1234.     if (mtmp == u.usteed) {
1235.         tele();
1236.         return TRUE;
1237.     }
1238. 
1239.     if (mtmp->iswiz && mtmp->mx) { /* Wizard, not just arriving */
1240.         if (!In_W_tower(u.ux, u.uy, &u.uz))
1241.             x = xupstair, y = yupstair;
1242.         else if (!xdnladder) /* bottom level of tower */
1243.             x = xupladder, y = yupladder;
1244.         else
1245.             x = xdnladder, y = ydnladder;
1246.         /* if the wiz teleports away to heal, try the up staircase,
1247.            to block the player's escaping before he's healed
1248.            (deliberately use `goodpos' rather than `rloc_pos_ok' here) */
1249.         if (goodpos(x, y, mtmp, 0))
1250.             goto found_xy;
1251.     }
1252. 
1253.     trycount = 0;
1254.     do {
1255.         x = rn1(COLNO - 3, 2);
1256.         y = rn2(ROWNO);
1257.         if ((trycount < 500) ? rloc_pos_ok(x, y, mtmp)
1258.                              : goodpos(x, y, mtmp, 0))
1259.             goto found_xy;
1260.     } while (++trycount < 1000);
1261. 
1262.     /* last ditch attempt to find a good place */
1263.     for (x = 2; x < COLNO - 1; x++)
1264.         for (y = 0; y < ROWNO; y++)
1265.             if (goodpos(x, y, mtmp, 0))
1266.                 goto found_xy;
1267. 
1268.     /* level either full of monsters or somehow faulty */
1269.     if (!suppress_impossible)
1270.         impossible("rloc(): couldn't relocate monster");
1271.     return FALSE;
1272. 
1273.  found_xy:
1274.     rloc_to(mtmp, x, y);
1275.     return TRUE;
1276. }
1277. 
1278. STATIC_OVL void
1279. mvault_tele(mtmp)
1280. struct monst *mtmp;
1281. {
1282.     struct mkroom *croom = search_special(VAULT);
1283.     coord c;
1284. 
1285.     if (croom && somexy(croom, &c) && goodpos(c.x, c.y, mtmp, 0)) {
1286.         rloc_to(mtmp, c.x, c.y);
1287.         return;
1288.     }
1289.     (void) rloc(mtmp, TRUE);
1290. }
1291. 
1292. boolean
1293. tele_restrict(mon)
1294. struct monst *mon;
1295. {
1296.     if (level.flags.noteleport) {
1297.         if (canseemon(mon))
1298.             pline("A mysterious force prevents %s from teleporting!",
1299.                   mon_nam(mon));
1300.         return TRUE;
1301.     }
1302.     return FALSE;
1303. }
1304. 
1305. void
1306. mtele_trap(mtmp, trap, in_sight)
1307. struct monst *mtmp;
1308. struct trap *trap;
1309. int in_sight;
1310. {
1311.     char *monname;
1312. 
1313.     if (tele_restrict(mtmp))
1314.         return;
1315.     if (teleport_pet(mtmp, FALSE)) {
1316.         /* save name with pre-movement visibility */
1317.         monname = Monnam(mtmp);
1318. 
1319.         /* Note: don't remove the trap if a vault.  Other-
1320.          * wise the monster will be stuck there, since
1321.          * the guard isn't going to come for it...
1322.          */
1323.         if (trap->once)
1324.             mvault_tele(mtmp);
1325.         else
1326.             (void) rloc(mtmp, TRUE);
1327. 
1328.         if (in_sight) {
1329.             if (canseemon(mtmp))
1330.                 pline("%s seems disoriented.", monname);
1331.             else
1332.                 pline("%s suddenly disappears!", monname);
1333.             seetrap(trap);
1334.         }
1335.     }
1336. }
1337. 
1338. /* return 0 if still on level, 3 if not */
1339. int
1340. mlevel_tele_trap(mtmp, trap, force_it, in_sight)
1341. struct monst *mtmp;
1342. struct trap *trap;
1343. boolean force_it;
1344. int in_sight;
1345. {
1346.     int tt = (trap ? trap->ttyp : NO_TRAP);
1347. 
1348.     if (mtmp == u.ustuck) /* probably a vortex */
1349.         return 0;         /* temporary? kludge */
1350.     if (teleport_pet(mtmp, force_it)) {
1351.         d_level tolevel;
1352.         int migrate_typ = MIGR_RANDOM;
1353. 
1354.         if (is_hole(tt)) {
1355.             if (Is_stronghold(&u.uz)) {
1356.                 assign_level(&tolevel, &valley_level);
1357.             } else if (Is_botlevel(&u.uz)) {
1358.                 if (in_sight && trap->tseen)
1359.                     pline("%s avoids the %s.", Monnam(mtmp),
1360.                           (tt == HOLE) ? "hole" : "trap");
1361.                 return 0;
1362.             } else {
1363.                 get_level(&tolevel, depth(&u.uz) + 1);
1364.             }
1365.         } else if (tt == MAGIC_PORTAL) {
1366.             if (In_endgame(&u.uz) && (mon_has_amulet(mtmp)
1367.                                       || is_home_elemental(mtmp->data)
1368.                                       || rn2(7))) {
1369.                 if (in_sight && mtmp->data->mlet != S_ELEMENTAL) {
1370.                     pline("%s seems to shimmer for a moment.", Monnam(mtmp));
1371.                     seetrap(trap);
1372.                 }
1373.                 return 0;
1374.             } else {
1375.                 assign_level(&tolevel, &trap->dst);
1376.                 migrate_typ = MIGR_PORTAL;
1377.             }
1378.         } else if (tt == LEVEL_TELEP || tt == NO_TRAP) {
1379.             int nlev;
1380. 
1381.             if (mon_has_amulet(mtmp) || In_endgame(&u.uz)
1382.                 /* NO_TRAP is used when forcing a monster off the level;
1383.                    onscary(0,0,) is true for the Wizard, Riders, lawful
1384.                    minions, Angels of any alignment, shopkeeper or priest
1385.                    currently inside his or her own special room */
1386.                 || (tt == NO_TRAP && onscary(0, 0, mtmp))) {
1387.                 if (in_sight)
1388.                     pline("%s seems very disoriented for a moment.",
1389.                           Monnam(mtmp));
1390.                 return 0;
1391.             }
1392.             if (tt == NO_TRAP) {
1393.                 /* creature is being forced off the level to make room;
1394.                    it will try to return to this level (at a random spot
1395.                    rather than its current one) if the level is left by
1396.                    the hero and then revisited */
1397.                 assign_level(&tolevel, &u.uz);
1398.             } else {
1399.                 nlev = random_teleport_level();
1400.                 if (nlev == depth(&u.uz)) {
1401.                     if (in_sight)
1402.                         pline("%s shudders for a moment.", Monnam(mtmp));
1403.                     return 0;
1404.                 }
1405.                 get_level(&tolevel, nlev);
1406.             }
1407.         } else {
1408.             impossible("mlevel_tele_trap: unexpected trap type (%d)", tt);
1409.             return 0;
1410.         }
1411. 
1412.         if (in_sight) {
1413.             pline("Suddenly, %s disappears out of sight.", mon_nam(mtmp));
1414.             if (trap)
1415.                 seetrap(trap);
1416.         }
1417.         migrate_to_level(mtmp, ledger_no(&tolevel), migrate_typ, (coord *) 0);
1418.         return 3; /* no longer on this level */
1419.     }
1420.     return 0;
1421. }
1422. 
1423. /* place object randomly, returns False if it's gone (eg broken) */
1424. boolean
1425. rloco(obj)
1426. register struct obj *obj;
1427. {
1428.     register xchar tx, ty, otx, oty;
1429.     boolean restricted_fall;
1430.     int try_limit = 4000;
1431. 
1432.     if (obj->otyp == CORPSE && is_rider(&mons[obj->corpsenm])) {
1433.         if (revive_corpse(obj))
1434.             return FALSE;
1435.     }
1436. 
1437.     obj_extract_self(obj);
1438.     otx = obj->ox;
1439.     oty = obj->oy;
1440.     restricted_fall = (otx == 0 && dndest.lx);
1441.     do {
1442.         tx = rn1(COLNO - 3, 2);
1443.         ty = rn2(ROWNO);
1444.         if (!--try_limit)
1445.             break;
1446.     } while (!goodpos(tx, ty, (struct monst *) 0, 0)
1447.              || (restricted_fall
1448.                  && (!within_bounded_area(tx, ty, dndest.lx, dndest.ly,
1449.                                           dndest.hx, dndest.hy)
1450.                      || (dndest.nlx
1451.                          && within_bounded_area(tx, ty,
1452.                                                 dndest.nlx, dndest.nly,
1453.                                                 dndest.nhx, dndest.nhy))))
1454.              /* on the Wizard Tower levels, objects inside should
1455.                 stay inside and objects outside should stay outside */
1456.              || (dndest.nlx && On_W_tower_level(&u.uz)
1457.                  && within_bounded_area(tx, ty, dndest.nlx, dndest.nly,
1458.                                         dndest.nhx, dndest.nhy)
1459.                     != within_bounded_area(otx, oty, dndest.nlx, dndest.nly,
1460.                                            dndest.nhx, dndest.nhy)));
1461. 
1462.     if (flooreffects(obj, tx, ty, "fall")) {
1463.         /* update old location since flooreffects() couldn't;
1464.            unblock_point() for boulder handled by obj_extract_self() */
1465.         newsym(otx, oty);
1466.         return FALSE;
1467.     } else if (otx == 0 && oty == 0) {
1468.         ; /* fell through a trap door; no update of old loc needed */
1469.     } else {
1470.         if (costly_spot(otx, oty)
1471.             && (!costly_spot(tx, ty)
1472.                 || !index(in_rooms(tx, ty, 0), *in_rooms(otx, oty, 0)))) {
1473.             if (costly_spot(u.ux, u.uy)
1474.                 && index(u.urooms, *in_rooms(otx, oty, 0)))
1475.                 addtobill(obj, FALSE, FALSE, FALSE);
1476.             else
1477.                 (void) stolen_value(obj, otx, oty, FALSE, FALSE);
1478.         }
1479.         newsym(otx, oty); /* update old location */
1480.     }
1481.     place_object(obj, tx, ty);
1482.     /* note: block_point() for boulder handled by place_object() */
1483.     newsym(tx, ty);
1484.     return TRUE;
1485. }
1486. 
1487. /* Returns an absolute depth */
1488. int
1489. random_teleport_level()
1490. {
1491.     int nlev, max_depth, min_depth, cur_depth = (int) depth(&u.uz);
1492. 
1493.     /* [the endgame case can only occur in wizard mode] */
1494.     if (!rn2(5) || Is_knox(&u.uz) || In_endgame(&u.uz))
1495.         return cur_depth;
1496. 
1497.     /* What I really want to do is as follows:
1498.      * -- If in a dungeon that goes down, the new level is to be restricted
1499.      *    to [top of parent, bottom of current dungeon]
1500.      * -- If in a dungeon that goes up, the new level is to be restricted
1501.      *    to [top of current dungeon, bottom of parent]
1502.      * -- If in a quest dungeon or similar dungeon entered by portals,
1503.      *    the new level is to be restricted to [top of current dungeon,
1504.      *    bottom of current dungeon]
1505.      * The current behavior is not as sophisticated as that ideal, but is
1506.      * still better what we used to do, which was like this for players
1507.      * but different for monsters for no obvious reason.  Currently, we
1508.      * must explicitly check for special dungeons.  We check for Knox
1509.      * above; endgame is handled in the caller due to its different
1510.      * message ("disoriented").
1511.      * --KAA
1512.      * 3.4.2: explicitly handle quest here too, to fix the problem of
1513.      * monsters sometimes level teleporting out of it into main dungeon.
1514.      * Also prevent monsters reaching the Sanctum prior to invocation.
1515.      */
1516.     if (In_quest(&u.uz)) {
1517.         int bottom = dunlevs_in_dungeon(&u.uz),
1518.             qlocate_depth = qlocate_level.dlevel;
1519. 
1520.         /* if hero hasn't reached the middle locate level yet,
1521.            no one can randomly teleport past it */
1522.         if (dunlev_reached(&u.uz) < qlocate_depth)
1523.             bottom = qlocate_depth;
1524.         min_depth = dungeons[u.uz.dnum].depth_start;
1525.         max_depth = bottom + (dungeons[u.uz.dnum].depth_start - 1);
1526.     } else {
1527.         min_depth = 1;
1528.         max_depth =
1529.             dunlevs_in_dungeon(&u.uz) + (dungeons[u.uz.dnum].depth_start - 1);
1530.         /* can't reach Sanctum if the invocation hasn't been performed */
1531.         if (Inhell && !u.uevent.invoked)
1532.             max_depth -= 1;
1533.     }
1534. 
1535.     /* Get a random value relative to the current dungeon */
1536.     /* Range is 1 to current+3, current not counting */
1537.     nlev = rn2(cur_depth + 3 - min_depth) + min_depth;
1538.     if (nlev >= cur_depth)
1539.         nlev++;
1540. 
1541.     if (nlev > max_depth) {
1542.         nlev = max_depth;
1543.         /* teleport up if already on bottom */
1544.         if (Is_botlevel(&u.uz))
1545.             nlev -= rnd(3);
1546.     }
1547.     if (nlev < min_depth) {
1548.         nlev = min_depth;
1549.         if (nlev == cur_depth) {
1550.             nlev += rnd(3);
1551.             if (nlev > max_depth)
1552.                 nlev = max_depth;
1553.         }
1554.     }
1555.     return nlev;
1556. }
1557. 
1558. /* you teleport a monster (via wand, spell, or poly'd q.mechanic attack);
1559.    return false iff the attempt fails */
1560. boolean
1561. u_teleport_mon(mtmp, give_feedback)
1562. struct monst *mtmp;
1563. boolean give_feedback;
1564. {
1565.     coord cc;
1566. 
1567.     if (mtmp->ispriest && *in_rooms(mtmp->mx, mtmp->my, TEMPLE)) {
1568.         if (give_feedback)
1569.             pline("%s resists your magic!", Monnam(mtmp));
1570.         return FALSE;
1571.     } else if (level.flags.noteleport && u.uswallow && mtmp == u.ustuck) {
1572.         if (give_feedback)
1573.             You("are no longer inside %s!", mon_nam(mtmp));
1574.         unstuck(mtmp);
1575.         (void) rloc(mtmp, TRUE);
1576.     } else if (is_rider(mtmp->data) && rn2(13)
1577.                && enexto(&cc, u.ux, u.uy, mtmp->data))
1578.         rloc_to(mtmp, cc.x, cc.y);
1579.     else
1580.         (void) rloc(mtmp, TRUE);
1581.     return TRUE;
1582. }
1583. 
1584. /*teleport.c*/