Source:NetHack 5.0.0/src/hack.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to hack.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/hack.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	hack.c	$NHDT-Date: 1763708572 2025/11/20 23:02:52 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.494 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Derek S. Ray, 2015. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #include "hack.h"
7. #include "extern.h"
8. 
9. /* #define DEBUG */ /* uncomment for debugging */
10. 
11. staticfn boolean could_move_onto_boulder(coordxy, coordxy);
12. staticfn void dopush(coordxy, coordxy, coordxy, coordxy, struct obj *,
13.                      boolean);
14. staticfn void cannot_push_msg(struct obj *, coordxy, coordxy);
15. staticfn int cannot_push(struct obj *, coordxy, coordxy);
16. staticfn void rock_disappear_msg(struct obj *);
17. staticfn void moverock_done(coordxy, coordxy);
18. staticfn int moverock(void);
19. staticfn int moverock_core(coordxy, coordxy);
20. staticfn void dosinkfall(void);
21. staticfn boolean findtravelpath(int);
22. staticfn boolean trapmove(coordxy, coordxy, struct trap *);
23. staticfn int QSORTCALLBACK notice_mons_cmp(const genericptr,
24.                                            const genericptr) NONNULLPTRS;
25. staticfn schar u_simple_floortyp(coordxy, coordxy);
26. staticfn boolean swim_move_danger(coordxy, coordxy);
27. staticfn boolean domove_bump_mon(struct monst *, int) NONNULLARG1;
28. staticfn boolean domove_attackmon_at(struct monst *, coordxy, coordxy,
29.                                    boolean *) NONNULLPTRS;
30. staticfn boolean domove_fight_ironbars(coordxy, coordxy);
31. staticfn boolean domove_fight_web(coordxy, coordxy);
32. staticfn boolean domove_swap_with_pet(struct monst *,
33.                                     coordxy, coordxy) NONNULLARG1;
34. staticfn boolean domove_fight_empty(coordxy, coordxy);
35. staticfn boolean air_turbulence(void);
36. staticfn void slippery_ice_fumbling(void);
37. staticfn boolean impaired_movement(coordxy *, coordxy *) NONNULLPTRS;
38. staticfn boolean avoid_moving_on_trap(coordxy, coordxy, boolean);
39. staticfn boolean avoid_moving_on_liquid(coordxy, coordxy, boolean);
40. staticfn boolean avoid_running_into_trap_or_liquid(coordxy, coordxy);
41. staticfn boolean avoid_trap_andor_region(coordxy, coordxy);
42. staticfn boolean move_out_of_bounds(coordxy, coordxy);
43. staticfn boolean carrying_too_much(void);
44. staticfn boolean escape_from_sticky_mon(coordxy, coordxy);
45. staticfn void domove_core(void);
46. staticfn void maybe_smudge_engr(coordxy, coordxy, coordxy, coordxy);
47. staticfn struct monst *monstinroom(struct permonst *, int) NONNULLARG1;
48. staticfn boolean furniture_present(int, int);
49. staticfn void move_update(boolean);
50. staticfn int pickup_checks(void);
51. staticfn void maybe_wail(void);
52. staticfn boolean water_turbulence(coordxy *, coordxy *);
53. staticfn int QSORTCALLBACK cmp_weights(const void *, const void *);
54. 
55. #define IS_SHOP(x) (svr.rooms[x].rtype >= SHOPBASE)
56. 
57. /* XXX: if more sources of water walking than just boots are added,
58.    cause_known(insight.c) should be externified and used for this */
59. #define Known_wwalking \
60.     (uarmf && uarmf->otyp == WATER_WALKING_BOOTS \
61.      && objects[WATER_WALKING_BOOTS].oc_name_known \
62.      && !u.usteed)
63. #define Known_lwalking \
64.     (Known_wwalking && Fire_resistance \
65.      && uarmf->oerodeproof && uarmf->rknown)
66. 
67. /* mode values for findtravelpath() */
68. #define TRAVP_TRAVEL 0
69. #define TRAVP_GUESS  1
70. #define TRAVP_VALID  2
71. 
72. anything *
73. uint_to_any(unsigned ui)
74. {
75.     gt.tmp_anything = cg.zeroany;
76.     gt.tmp_anything.a_uint = ui;
77.     return &gt.tmp_anything;
78. }
79. 
80. anything *
81. long_to_any(long lng)
82. {
83.     gt.tmp_anything = cg.zeroany;
84.     gt.tmp_anything.a_long = lng;
85.     return &gt.tmp_anything;
86. }
87. 
88. anything *
89. monst_to_any(struct monst *mtmp)
90. {
91.     gt.tmp_anything = cg.zeroany;
92.     gt.tmp_anything.a_monst = mtmp;
93.     return &gt.tmp_anything;
94. }
95. 
96. anything *
97. obj_to_any(struct obj *obj)
98. {
99.     gt.tmp_anything = cg.zeroany;
100.     gt.tmp_anything.a_obj = obj;
101.     return &gt.tmp_anything;
102. }
103. 
104. boolean
105. revive_nasty(coordxy x, coordxy y, const char *msg)
106. {
107.     struct obj *otmp = 0, *otmp2 = 0;
108.     struct monst *mtmp;
109.     coord cc;
110.     boolean revived = FALSE;
111. 
112.     for (otmp = svl.level.objects[x][y]; otmp; otmp = otmp2) {
113.         otmp2 = otmp->nexthere;
114.         if (otmp->otyp == CORPSE
115.             && (is_rider(&mons[otmp->corpsenm])
116.                 || otmp->corpsenm == PM_WIZARD_OF_YENDOR)) {
117.             /* move any living monster already at that location */
118.             if ((mtmp = m_at(x, y)) && enexto(&cc, x, y, mtmp->data))
119.                 rloc_to(mtmp, cc.x, cc.y);
120.             if (msg)
121.                 Norep("%s", msg);
122.             revived = revive_corpse(otmp);
123.         }
124.     }
125. 
126.     /* this location might not be safe, if not, move revived monster */
127.     if (revived) {
128.         mtmp = m_at(x, y);
129.         if (mtmp && !goodpos(x, y, mtmp, 0)
130.             && enexto(&cc, x, y, mtmp->data)) {
131.             rloc_to(mtmp, cc.x, cc.y);
132.         }
133.         /* else impossible? */
134.     }
135. 
136.     return revived;
137. }
138. 
139. #define squeezeablylightinvent() (!gi.invent \
140.     || inv_weight() <= (WT_SQUEEZABLE_INV * -1))
141. 
142. /* can hero move onto a spot containing one or more boulders?
143.    used for m<dir> and travel and during boulder push failure */
144. staticfn boolean
145. could_move_onto_boulder(coordxy sx, coordxy sy)
146. {
147.     /* can if able to phaze through rock (must be poly'd, so not riding) */
148.     if (Passes_walls)
149.         return TRUE;
150.     /* can't when riding */
151.     if (u.usteed)
152.         return FALSE;
153.     /* can if a giant, unless doing so allows hero to pass into a
154.        diagonal squeeze at the same time */
155.     if (throws_rocks(gy.youmonst.data))
156.         return (!u.dx || !u.dy || !(IS_OBSTRUCTED(levl[u.ux][sy].typ)
157.                                     && IS_OBSTRUCTED(levl[sx][u.uy].typ)));
158.     /* can if tiny (implies carrying very little else couldn't move at all) */
159.     if (verysmall(gy.youmonst.data))
160.         return TRUE;
161.     /* can squeeze to spot if carrying extremely little, otherwise can't */
162.     return squeezeablylightinvent();
163. }
164. 
165. staticfn void
166. dopush(
167.     coordxy sx,
168.     coordxy sy,
169.     coordxy rx,
170.     coordxy ry,
171.     struct obj *otmp,
172.     boolean costly)
173. {
174.     struct monst *shkp;
175. 
176.     {
177.         const char *what;
178.         boolean givemesg, easypush;
179.         /* give boulder pushing feedback if this is a different
180.            boulder than the last one pushed or if it's been at
181.            least 2 turns since we last pushed this boulder;
182.            unlike with Norep(), intervening messages don't cause
183.            it to repeat, only doing something else in the meantime */
184.         if (otmp->o_id != gb.bldrpush_oid) {
185.             gb.bldrpushtime = svm.moves + 1L;
186.             gb.bldrpush_oid = otmp->o_id;
187.         }
188.         givemesg = (svm.moves > gb.bldrpushtime + 2L
189.                     || svm.moves < gb.bldrpushtime);
190.         what = givemesg ? the(xname(otmp)) : 0;
191.         if (!u.usteed) {
192.             easypush = throws_rocks(gy.youmonst.data);
193.             if (givemesg)
194.                 pline("With %s effort you move %s.",
195.                       easypush ? "little" : "great", what);
196.             if (!easypush)
197.                 exercise(A_STR, TRUE);
198.         } else {
199.             if (givemesg)
200.                 pline("%s moves %s.", YMonnam(u.usteed), what);
201.         }
202.         gb.bldrpushtime = svm.moves;
203.     }
204. 
205.     /* Move the boulder *after* the message. */
206.     if (glyph_is_invisible(levl[rx][ry].glyph))
207.         unmap_object(rx, ry);
208.     otmp->next_boulder = 0;
209.     movobj(otmp, rx, ry); /* does newsym(rx,ry) */
210.     if (Blind) {
211.         feel_location(rx, ry);
212.         feel_location(sx, sy);
213.     } else {
214.         newsym(sx, sy);
215.     }
216.     /* maybe adjust bill if boulder was pushed across shop boundary;
217.        normally otmp->unpaid would not apply because otmp isn't in
218.        hero's inventory, but addtobill() sets it and subfrombill()
219.        clears it */
220.     if (costly && !costly_spot(rx, ry)) {
221.         /* pushing from inside shop to its boundary (or free spot) */
222.         addtobill(otmp, FALSE, FALSE, FALSE);
223.     } else if (!costly && costly_spot(rx, ry) && otmp->unpaid
224.                && ((shkp = shop_keeper(*in_rooms(rx, ry, SHOPBASE)))
225.                    != 0)
226.                && onshopbill(otmp, shkp, TRUE)) {
227.         /* this can happen if hero pushes boulder from farther inside
228.            shop into shop's free spot (which will add it to the bill),
229.            then teleports or Passes_walls to doorway (without exiting
230.            the shop), and then pushes the boulder from the free spot
231.            back into the shop; it's contingent upon the shopkeeper not
232.            "muttering an incantation" to fracture the boulder while it
233.            is unpaid at the free spot */
234.         subfrombill(otmp, shkp);
235.     } else if (otmp->unpaid
236.                && (shkp = find_objowner(otmp, sx, sy)) != 0
237.                && !strchr(in_rooms(rx, ry, SHOPBASE),
238.                           ESHK(shkp)->shoproom)) {
239.         /* once the boulder is fully out of the shop, so that it's
240.          * impossible to change your mind and push it back in without
241.          * leaving and triggering Kops, switch it to stolen_value */
242.         stolen_value(otmp, sx, sy, TRUE, FALSE);
243.     }
244. }
245. 
246. staticfn void
247. cannot_push_msg(struct obj *otmp, coordxy sx, coordxy sy)
248. {
249.     const char *what;
250. 
251.     what = the(xname(otmp));
252.     if (u.usteed)
253.         pline("%s tries to move %s, but cannot.",
254.               YMonnam(u.usteed), what);
255.     else
256.         You("try to move %s, but in vain.", what);
257.     if (Blind)
258.         feel_location(sx, sy);
259. }
260. 
261. staticfn int
262. cannot_push(struct obj *otmp, coordxy sx, coordxy sy)
263. {
264.     if (throws_rocks(gy.youmonst.data)) {
265.         boolean
266.             canpickup = (!Sokoban
267.                          /* similar exception as in can_lift():
268.                             when poly'd into a giant, you can
269.                             pick up a boulder if you have a free
270.                             slot or into the overflow ('#') slot
271.                             unless already carrying at least one */
272.                         && (inv_cnt(FALSE) < invlet_basic
273.                                || !carrying(BOULDER))),
274.             willpickup = (canpickup
275.                           && (flags.pickup && !svc.context.nopick)
276.                           && autopick_testobj(otmp, TRUE));
277. 
278.         if (u.usteed && P_SKILL(P_RIDING) < P_BASIC) {
279.             You("aren't skilled enough to %s %s from %s.",
280.                 willpickup ? "pick up" : "push aside",
281.                 the(xname(otmp)), y_monnam(u.usteed));
282.         } else {
283.             /*
284.              * will pick up:  you easily pick it up
285.              * can but won't: you maneuver over it and could pick it up
286.              * can't pick up: you maneuver over it (possibly followed
287.              *     by feedback from failed auto-pickup attempt)
288.              */
289.             pline("However, you %s%s.",
290.                   willpickup ? "easily pick it up"
291.                              : "maneuver over it",
292.                   (canpickup && !willpickup)
293.                              ? " and could pick it up"
294.                              : "");
295.             /* similar to dropping everything and squeezing onto
296.                a Sokoban boulder's spot, moving to same breaks the
297.                Sokoban rules because on next step you could go
298.                past it without pushing it to plug a pit or hole */
299.             sokoban_guilt();
300.         }
301.         return 0;
302.     }
303. 
304.     if (could_move_onto_boulder(sx, sy)) {
305.         pline(
306.            "However, you can squeeze yourself into a small opening.");
307.         sokoban_guilt();
308.         return 0;
309.     } else {
310.         return -1;
311.     }
312. }
313. 
314. staticfn void
315. rock_disappear_msg(struct obj *otmp)
316. {
317.     if (u.usteed)
318.         pline("%s pushes %s and suddenly it disappears!",
319.                 YMonnam(u.usteed), the(xname(otmp)));
320.     else
321.         You("push %s and suddenly it disappears!",
322.             the(xname(otmp)));
323. 
324. }
325. 
326. staticfn void
327. moverock_done(coordxy sx, coordxy sy)
328. {
329.     struct obj *otmp;
330.     for (otmp = svl.level.objects[sx][sy]; otmp; otmp = otmp->nexthere)
331.         if (otmp->otyp == BOULDER)
332.             otmp->next_boulder = 0; /* resume normal xname() for this obj */
333. }
334. 
335. staticfn int
336. moverock(void)
337. {
338.     coordxy sx, sy;
339.     int ret;
340. 
341.     sx = u.ux + u.dx, sy = u.uy + u.dy; /* boulder starting position */
342.     ret = moverock_core(sx, sy);
343.     moverock_done(sx, sy);
344.     return ret;
345. }
346. 
347. staticfn int
348. moverock_core(coordxy sx, coordxy sy)
349. {
350.     coordxy rx, ry;
351.     struct obj *otmp;
352.     struct trap *ttmp;
353.     struct monst *mtmp;
354.     boolean costly, firstboulder = TRUE;
355. 
356.     while ((otmp = sobj_at(BOULDER, sx, sy)) != 0) {
357. 
358.         if (Blind && glyph_to_obj(glyph_at(sx, sy)) != BOULDER) {
359.             pline("That feels like a boulder.");
360.             map_object(otmp, TRUE);
361.             nomul(0);
362.             return -1;
363.         }
364. 
365.         /* when otmp->next_boulder is 1, xname() will format it as
366.            "next boulder" instead of just "boulder"; affects
367.            boulder_hits_pool()'s messages as well as messages below */
368.         otmp->next_boulder = firstboulder ? 0 : 1;
369.         /* FIXME?  'firstboulder' should be reset to True if this boulder
370.            isn't the first and the previous one is named differently from
371.            this one.  Probably not worth bothering with... */
372.         firstboulder = FALSE;
373. 
374.         /* make sure that this boulder is visible as the top object */
375.         if (otmp != svl.level.objects[sx][sy])
376.             movobj(otmp, sx, sy);
377. 
378.         rx = u.ux + 2 * u.dx; /* boulder destination position */
379.         ry = u.uy + 2 * u.dy;
380.         nomul(0);
381. 
382.         /* using m<dir> towards an adjacent boulder steps over/onto it if
383.            poly'd into a giant or squeezes under/beside it if small/light
384.            enough but is a no-op in other circumstances unless move attempt
385.            reveals an unseen boulder or lack of remembered, unseen monster */
386.         if (svc.context.nopick) {
387.             int oldglyph = glyph_at(sx, sy); /* before feel_location() */
388.             int res;
389. 
390.             feel_location(sx, sy); /* same for all 3 if/else-if/else cases */
391.             if (throws_rocks(gy.youmonst.data)) {
392.                 /* player has used 'm<dir>' to move, so step to boulder's
393.                    spot without pushing it; hero is poly'd into a giant,
394.                    so exotic forms of locomotion are out, but might be
395.                    levitating (ring, potion, spell) or flying (amulet) */
396.                 You("%s over a boulder here.", u_locomotion("step"));
397.                 /* ["over" seems weird on air level but what else to say?] */
398.                 sokoban_guilt();
399.                 res = 0; /* move to <sx,sy> */
400.             } else if (could_move_onto_boulder(sx, sy)) {
401.                 You("squeeze yourself %s the boulder.",
402.                     Flying ? "over" : "against");
403.                 sokoban_guilt();
404.                 res = 0; /* move to <sx,sy> */
405.             } else {
406.                 There("is a boulder in your way.");
407.                 /* use a move if hero learns something; see test_move() for
408.                    how/why 'context.door_opened' is being dragged into this */
409.                 if (glyph_at(sx, sy) != oldglyph)
410.                     svc.context.door_opened = svc.context.move = TRUE;
411.                 res = -1; /* don't move to <sx,sy>, so no soko guilt */
412.             }
413.             return res;
414.         }
415.         if (Levitation || Is_airlevel(&u.uz)) {
416.             /* FIXME?  behavior in an air bubble on the water level should
417.                be similar to being on the air level; both cases probably
418.                ought to let push attempt proceed when flying (which implies
419.                not levitating) */
420.             if (Blind)
421.                 feel_location(sx, sy);
422.             You("don't have enough leverage to push %s.", the(xname(otmp)));
423.             /* Give them a chance to climb over it? */
424.             return -1;
425.         }
426.         if (verysmall(gy.youmonst.data) && !u.usteed) {
427.             if (Blind)
428.                 feel_location(sx, sy);
429.             pline("You're too small to push that %s.", xname(otmp));
430.             return cannot_push(otmp, sx, sy);
431.         }
432.         if (isok(rx, ry) && !IS_OBSTRUCTED(levl[rx][ry].typ)
433.             && levl[rx][ry].typ != IRONBARS
434.             && (!IS_DOOR(levl[rx][ry].typ) || !(u.dx && u.dy)
435.                 || doorless_door(rx, ry)) && !sobj_at(BOULDER, rx, ry)) {
436.             ttmp = t_at(rx, ry);
437.             mtmp = m_at(rx, ry);
438.             costly = (costly_spot(sx, sy)
439.                       && shop_keeper(*in_rooms(sx, sy, SHOPBASE)));
440. 
441.             /* KMH -- Sokoban doesn't let you push boulders diagonally */
442.             if (Sokoban && u.dx && u.dy) {
443.                 if (Blind)
444.                     feel_location(sx, sy);
445.                 pline("%s won't roll diagonally on this %s.",
446.                       The(xname(otmp)), surface(sx, sy));
447.                 return cannot_push(otmp, sx, sy);
448.             }
449. 
450.             if (revive_nasty(rx, ry,
451.                              "You sense movement on the other side.")) {
452.                 return -1;
453.             }
454. 
455.             if (mtmp && !noncorporeal(mtmp->data)
456.                 && (!mtmp->mtrapped || !(ttmp && is_pit(ttmp->ttyp)))) {
457.                 boolean deliver_part1 = FALSE;
458. 
459.                 if (Blind)
460.                     feel_location(sx, sy);
461.                 if (canspotmon(mtmp)) {
462.                     pline("There's %s on the other side.", a_monnam(mtmp));
463.                     deliver_part1 = TRUE;
464.                 } else {
465.                     Soundeffect(se_monster_behind_boulder, 50);
466.                     You_hear("a monster behind %s.", the(xname(otmp)));
467.                     if (!Deaf)
468.                         deliver_part1 = TRUE;
469.                     map_invisible(rx, ry);
470.                 }
471.                 if (flags.verbose) {
472.                     char you_or_steed[BUFSZ];
473. 
474.                     Strcpy(you_or_steed,
475.                            u.usteed ? y_monnam(u.usteed) : "you");
476.                     pline("%s%s cannot move %s.",
477.                           deliver_part1 ? "Perhaps that's why " : "",
478.                           deliver_part1 ? you_or_steed
479.                                         : upstart(you_or_steed),
480.                           deliver_part1 ? "it" : the(xname(otmp)));
481.                 }
482.                 return cannot_push(otmp, sx, sy);
483.             }
484. 
485.             if (closed_door(rx, ry)) {
486.                 cannot_push_msg(otmp, sx, sy);
487.                 return cannot_push(otmp, sx, sy);
488.             }
489. 
490.             /* at this point the boulder should be able to move (though
491.                potentially into something like a trap, pool, or lava) */
492. 
493.             /* rumbling disturbs buried zombies */
494.             disturb_buried_zombies(sx, sy);
495. 
496.             if (ttmp) {
497.                 int newlev = 0; /* lint suppression */
498.                 d_level dest;
499. 
500.                 /* if a trap operates on the boulder, don't attempt
501.                    to move any others at this location; return -1
502.                    if another boulder is in hero's way, or 0 if he
503.                    should advance to the vacated boulder position */
504.                 switch (ttmp->ttyp) {
505.                 case LANDMINE:
506.                     if (rn2(10)) {
507.                         obj_extract_self(otmp);
508.                         place_object(otmp, rx, ry);
509.                         newsym(sx, sy);
510.                         pline("%s!  %s %s land mine.",
511.                               /* "kablam" is a variation of "ka-boom" or
512.                                  "kablooey", rather cartoonish descriptions
513.                                  of the sound of an explosion, but give it
514.                                  even when deaf if hero sees the explosion */
515.                               (!Deaf || !Blind) ? "KAABLAMM!!"
516.                               /* use an alternate exclamation when feeling
517.                                  the floor/ground/whatever shake (or maybe
518.                                  a weak shockwave if levitating or flying) */
519.                                                 : "Gadzooks",
520.                               Tobjnam(otmp, "trigger"),
521.                               ttmp->madeby_u ? "your" : "a");
522.                         blow_up_landmine(ttmp);
523.                         /* if the boulder remains, it should fill the pit */
524.                         fill_pit(u.ux, u.uy);
525.                         if (cansee(rx, ry))
526.                             newsym(rx, ry);
527.                         return sobj_at(BOULDER, sx, sy) ? -1 : 0;
528.                     }
529.                     break;
530.                 case SPIKED_PIT:
531.                 case PIT:
532.                     obj_extract_self(otmp);
533.                     /* vision kludge to get messages right;
534.                        the pit will temporarily be seen even
535.                        if this is one among multiple boulders */
536.                     if (!Blind)
537.                         gv.viz_array[ry][rx] |= IN_SIGHT;
538.                     if (!flooreffects(otmp, rx, ry, "fall")) {
539.                         place_object(otmp, rx, ry);
540.                     }
541.                     if (mtmp && !Blind)
542.                         newsym(rx, ry);
543.                     return sobj_at(BOULDER, sx, sy) ? -1 : 0;
544.                 case HOLE:
545.                 case TRAPDOOR:
546.                     Soundeffect(se_kerplunk_boulder_gone, 40);
547.                     if (Blind)
548.                         pline("Kerplunk!  You no longer feel %s.",
549.                               the(xname(otmp)));
550.                     else
551.                         pline("%s%s and %s a %s in the %s!",
552.                               Tobjnam(otmp, (ttmp->ttyp == TRAPDOOR)
553.                                                 ? "trigger"
554.                                                 : "fall"),
555.                               (ttmp->ttyp == TRAPDOOR) ? "" : " into",
556.                               otense(otmp, "plug"),
557.                               (ttmp->ttyp == TRAPDOOR) ? "trap door" : "hole",
558.                               surface(rx, ry));
559.                     deltrap(ttmp);
560.                     useupf(otmp, 1L);
561.                     bury_objs(rx, ry);
562.                     levl[rx][ry].wall_info &= ~W_NONDIGGABLE;
563.                     levl[rx][ry].candig = 1;
564.                     if (cansee(rx, ry))
565.                         newsym(rx, ry);
566.                     return sobj_at(BOULDER, sx, sy) ? -1 : 0;
567.                 case LEVEL_TELEP:
568.                     /* 20% chance of picking current level; 100% chance for
569.                        that if in single-level branch (Knox) or in endgame */
570.                     newlev = random_teleport_level();
571.                     /* if trap doesn't work, skip "disappears" message */
572.                     if (newlev == depth(&u.uz)) {
573.                         dopush(sx, sy, rx, ry, otmp, costly);
574.                         continue;
575.                     }
576.                     FALLTHROUGH;
577.                     /*FALLTHRU*/
578.                 case TELEP_TRAP:
579.                     rock_disappear_msg(otmp);
580.                     otmp->next_boulder = 0; /* reset before moving it */
581.                     if (ttmp->ttyp == TELEP_TRAP) {
582.                         (void) rloco(otmp);
583.                     } else {
584.                         if (costly)
585.                             stolen_value(otmp, rx, ry, !ttmp->tseen, FALSE);
586.                         obj_extract_self(otmp);
587.                         add_to_migration(otmp);
588.                         get_level(&dest, newlev);
589.                         otmp->ox = dest.dnum;
590.                         otmp->oy = dest.dlevel;
591.                         otmp->owornmask = (long) MIGR_RANDOM;
592.                     }
593.                     seetrap(ttmp);
594.                     return sobj_at(BOULDER, sx, sy) ? -1 : 0;
595.                 case ROLLING_BOULDER_TRAP:
596.                 {
597.                     int tox = rx;
598.                     int toy = ry;
599.                     /* the boulder continues until it reaches one of
600.                        the trap's launch spots or hits a wall / out-of-bounds */
601.                     while (isok(tox + u.dx, toy + u.dy)) {
602.                         tox += u.dx;
603.                         toy += u.dy;
604.                         if (tox == ttmp->launch.x && toy == ttmp->launch.y)
605.                             break;
606.                         if (tox == ttmp->launch2.x && toy == ttmp->launch2.y)
607.                             break;
608.                     }
609.                     pline("%s away from you!",
610.                           Tobjnam(otmp, "suddenly roll"));
611.                     feeltrap(ttmp);
612.                     launch_obj(BOULDER, sx, sy, tox, toy, ROLL | LAUNCH_KNOWN);
613.                     return sobj_at(BOULDER, sx, sy) ? -1 : 0;
614.                 }
615.                 default:
616.                     break; /* boulder not affected by this trap */
617.                 }
618.             }
619. 
620.             if (boulder_hits_pool(otmp, rx, ry, TRUE))
621.                 continue;
622. 
623.             /*
624.              * Re-link at top of fobj chain so that pile order is preserved
625.              * when level is restored.
626.              */
627.             if (otmp != fobj) {
628.                 remove_object(otmp);
629.                 place_object(otmp, otmp->ox, otmp->oy);
630.             }
631.             dopush(sx, sy, rx, ry, otmp, costly);
632.         } else {
633.             cannot_push_msg(otmp, sx, sy);
634.             return cannot_push(otmp, sx, sy);
635.         }
636.     }
637.     return 0;
638. }
639. 
640. /*
641.  *  still_chewing()
642.  *
643.  *  Chew on a wall, door, or boulder.  [What about statues?]
644.  *  Returns TRUE if still eating, FALSE when done.
645.  */
646. int
647. still_chewing(coordxy x, coordxy y)
648. {
649.     struct rm *lev = &levl[x][y];
650.     struct obj *boulder = sobj_at(BOULDER, x, y);
651.     const char *digtxt = (char *) 0, *dmgtxt = (char *) 0;
652. 
653.     if (svc.context.digging.down) /* not continuing prev dig (w/ pick-axe) */
654.         (void) memset((genericptr_t) &svc.context.digging, 0,
655.                       sizeof (struct dig_info));
656. 
657.     if (!boulder
658.         && ((IS_OBSTRUCTED(lev->typ) && !may_dig(x, y))
659.             /* may_dig() checks W_NONDIGGABLE but doesn't handle iron bars */
660.             || (lev->typ == IRONBARS && (lev->wall_info & W_NONDIGGABLE)))) {
661.         You("hurt your teeth on the %s.",
662.             (lev->typ == IRONBARS)
663.                 ? "bars"
664.                 : IS_TREE(lev->typ)
665.                     ? "tree"
666.                     : "hard stone");
667.         nomul(0);
668.         return 1;
669.     } else if (lev->typ == IRONBARS
670.                && metallivorous(gy.youmonst.data) && u.uhunger > 1500) {
671.         /* finishing eating via 'morehungry()' doesn't handle choking */
672.         You("are too full to eat the bars.");
673.         nomul(0);
674.         return 1;
675.     } else if (!svc.context.digging.chew
676.                || svc.context.digging.pos.x != x
677.                || svc.context.digging.pos.y != y
678.                || !on_level(&svc.context.digging.level, &u.uz)) {
679.         svc.context.digging.down = FALSE;
680.         svc.context.digging.chew = TRUE;
681.         svc.context.digging.warned = FALSE;
682.         svc.context.digging.pos.x = x;
683.         svc.context.digging.pos.y = y;
684.         assign_level(&svc.context.digging.level, &u.uz);
685.         /* solid rock takes more work & time to dig through */
686.         svc.context.digging.effort =
687.             (IS_OBSTRUCTED(lev->typ) && !IS_TREE(lev->typ) ? 30 : 60) + u.udaminc;
688.         You("start chewing %s %s.",
689.             (boulder || IS_TREE(lev->typ) || lev->typ == IRONBARS)
690.                 ? "on a"
691.                 : "a hole in the",
692.             boulder
693.                 ? "boulder"
694.                 : IS_TREE(lev->typ)
695.                     ? "tree"
696.                     : IS_OBSTRUCTED(lev->typ)
697.                         ? "rock"
698.                         : (lev->typ == IRONBARS)
699.                             ? "bar"
700.                             : "door");
701.         watch_dig((struct monst *) 0, x, y, FALSE);
702.         return 1;
703.     } else if ((svc.context.digging.effort += (30 + u.udaminc)) <= 100) {
704.         if (flags.verbose)
705.             You("%s chewing on the %s.",
706.                 svc.context.digging.chew ? "continue" : "begin",
707.                 boulder
708.                     ? "boulder"
709.                     : IS_TREE(lev->typ)
710.                         ? "tree"
711.                         : IS_OBSTRUCTED(lev->typ)
712.                             ? "rock"
713.                             : (lev->typ == IRONBARS)
714.                                 ? "bars"
715.                                 : "door");
716.         svc.context.digging.chew = TRUE;
717.         watch_dig((struct monst *) 0, x, y, FALSE);
718.         return 1;
719.     }
720. 
721.     /* Okay, you've chewed through something */
722.     if (!u.uconduct.food++)
723.         livelog_printf(LL_CONDUCT,
724.                        "ate for the first time, by chewing through %s",
725.                        boulder ? "a boulder"
726.                        : IS_TREE(lev->typ) ? "a tree"
727.                          : IS_OBSTRUCTED(lev->typ) ? "rock"
728.                            : (lev->typ == IRONBARS) ? "iron bars"
729.                              : "a door");
730.     u.uhunger += rnd(20);
731. 
732.     if (boulder) {
733.         delobj(boulder);         /* boulder goes bye-bye */
734.         You("eat the boulder."); /* yum */
735. 
736.         /*
737.          *  The location could still block because of
738.          *      1. More than one boulder
739.          *      2. Boulder stuck in a wall/stone/door.
740.          *
741.          *  [perhaps use does_block() below (from vision.c)]
742.          */
743.         if (IS_OBSTRUCTED(lev->typ) || closed_door(x, y)
744.             || sobj_at(BOULDER, x, y)) {
745.             block_point(x, y); /* delobj will unblock the point */
746.             /* reset dig state */
747.             (void) memset((genericptr_t) &svc.context.digging, 0,
748.                           sizeof (struct dig_info));
749.             return 1;
750.         }
751. 
752.     } else if (IS_WALL(lev->typ)) {
753.         if (*in_rooms(x, y, SHOPBASE)) {
754.             add_damage(x, y, SHOP_WALL_DMG);
755.             dmgtxt = "damage";
756.         }
757.         digtxt = "chew a hole in the wall.";
758.         if (svl.level.flags.is_maze_lev) {
759.             lev->typ = ROOM;
760.         } else if (svl.level.flags.is_cavernous_lev && !in_town(x, y)) {
761.             lev->typ = CORR;
762.         } else {
763.             lev->typ = DOOR;
764.             lev->doormask = D_NODOOR;
765.         }
766.     } else if (IS_TREE(lev->typ)) {
767.         digtxt = "chew through the tree.";
768.         lev->typ = ROOM;
769.     } else if (lev->typ == IRONBARS) {
770.         if (metallivorous(gy.youmonst.data)) { /* should always be True here */
771.             /* arbitrary amount; unlike proper eating, nutrition is
772.                bestowed in a lump sum at the end */
773.             int nut = (int) objects[HEAVY_IRON_BALL].oc_weight;
774. 
775.             /* lesshungry() requires that victual be set up, so skip it;
776.                morehungry() of a negative amount will increase nutrition
777.                without any possibility of choking to death on the meal;
778.                updates hunger state and requests status update if changed */
779.             morehungry(-nut);
780.         }
781.         digtxt = u_at(x, y)
782.                  ? "devour the iron bars."
783.                  : "eat through the bars.";
784.         dissolve_bars(x, y);
785.     } else if (lev->typ == SDOOR) {
786.         if (lev->doormask & D_TRAPPED) {
787.             lev->doormask = D_NODOOR;
788.             b_trapped("secret door", NO_PART);
789.         } else {
790.             digtxt = "chew through the secret door.";
791.             lev->doormask = D_BROKEN;
792.         }
793.         lev->typ = DOOR;
794. 
795.     } else if (IS_DOOR(lev->typ)) {
796.         if (*in_rooms(x, y, SHOPBASE)) {
797.             add_damage(x, y, SHOP_DOOR_COST);
798.             dmgtxt = "break";
799.         }
800.         if (lev->doormask & D_TRAPPED) {
801.             lev->doormask = D_NODOOR;
802.             b_trapped("door", NO_PART);
803.         } else {
804.             digtxt = "chew through the door.";
805.             lev->doormask = D_BROKEN;
806.         }
807. 
808.     } else { /* STONE or SCORR */
809.         digtxt = "chew a passage through the rock.";
810.         lev->typ = CORR;
811.     }
812. 
813.     recalc_block_point(x, y); /* vision */
814.     newsym(x, y);
815.     if (digtxt)
816.         You1(digtxt); /* after newsym */
817.     if (dmgtxt)
818.         pay_for_damage(dmgtxt, FALSE);
819.     (void) memset((genericptr_t) &svc.context.digging, 0,
820.                   sizeof (struct dig_info));
821.     return 0;
822. }
823. 
824. void
825. movobj(struct obj *obj, coordxy ox, coordxy oy)
826. {
827.     /* optimize by leaving on the fobj chain? */
828.     remove_object(obj);
829.     maybe_unhide_at(obj->ox, obj->oy);
830.     newsym(obj->ox, obj->oy);
831.     place_object(obj, ox, oy);
832.     newsym(ox, oy);
833. }
834. 
835. staticfn void
836. dosinkfall(void)
837. {
838.     static const char fell_on_sink[] = "fell onto a sink";
839.     struct obj *obj;
840.     int dmg;
841.     boolean lev_boots = (uarmf && uarmf->otyp == LEVITATION_BOOTS),
842.             innate_lev = ((HLevitation & (FROMOUTSIDE | FROMFORM)) != 0L),
843.             /* to handle being chained to buried iron ball, trying to
844.                levitate but being blocked, then moving onto adjacent sink;
845.                no need to worry about being blocked by terrain because we
846.                couldn't be over a sink at the same time */
847.             blockd_lev = (BLevitation == I_SPECIAL),
848.             ufall = (!innate_lev && !blockd_lev
849.                      && !(HFlying || EFlying)); /* BFlying */
850. 
851.     if (!ufall) {
852.         You((innate_lev || blockd_lev) ? "wobble unsteadily for a moment."
853.                                        : "gain control of your flight.");
854.     } else {
855.         long save_ELev = ELevitation, save_HLev = HLevitation;
856. 
857.         /* fake removal of levitation in advance so that final
858.            disclosure will be right in case this turns out to
859.            be fatal; fortunately the fact that rings and boots
860.            are really still worn has no effect on bones data */
861.         ELevitation = HLevitation = 0L;
862.         You("crash to the floor!");
863.         dmg = rn1(8, 25 - (int) ACURR(A_CON));
864.         losehp(Maybe_Half_Phys(dmg), fell_on_sink, NO_KILLER_PREFIX);
865.         exercise(A_DEX, FALSE);
866.         selftouch("Falling, you");
867.         for (obj = svl.level.objects[u.ux][u.uy]; obj; obj = obj->nexthere)
868.             if (obj->oclass == WEAPON_CLASS || is_weptool(obj)) {
869.                 You("fell on %s.", doname(obj));
870.                 losehp(Maybe_Half_Phys(rnd(3)), fell_on_sink,
871.                        NO_KILLER_PREFIX);
872.                 exercise(A_CON, FALSE);
873.             }
874.         ELevitation = save_ELev;
875.         HLevitation = save_HLev;
876.     }
877. 
878.     /*
879.      * Interrupt multi-turn putting on/taking off of armor (in which
880.      * case we reached the sink due to being teleported while busy;
881.      * in 3.4.3, Boots_on()/Boots_off() [called via (*afternmv)() when
882.      * 'multi' reaches 0] triggered a crash if we were donning/doffing
883.      * levitation boots [because the Boots_off() below causes 'uarmf'
884.      * to be null by the time 'afternmv' gets called]).
885.      *
886.      * Interrupt donning/doffing if we fall onto the sink, or if the
887.      * code below is going to remove levitation boots even when we
888.      * haven't fallen (innate floating or flying becoming unblocked).
889.      */
890.     if (ufall || lev_boots) {
891.         (void) stop_donning(lev_boots ? uarmf : (struct obj *) 0);
892.         /* recalculate in case uarmf just got set to null */
893.         lev_boots = (uarmf && uarmf->otyp == LEVITATION_BOOTS);
894.     }
895. 
896.     /* remove worn levitation items */
897.     ELevitation &= ~W_ARTI;
898.     HLevitation &= ~(I_SPECIAL | TIMEOUT);
899.     HLevitation++;
900.     if (uleft && uleft->otyp == RIN_LEVITATION) {
901.         obj = uleft;
902.         Ring_off(obj);
903.         off_msg(obj);
904.     }
905.     if (uright && uright->otyp == RIN_LEVITATION) {
906.         obj = uright;
907.         Ring_off(obj);
908.         off_msg(obj);
909.     }
910.     if (lev_boots) {
911.         obj = uarmf;
912.         (void) Boots_off();
913.         off_msg(obj);
914.     }
915.     HLevitation--;
916.     /* probably moot; we're either still levitating or went
917.        through float_down(), but make sure BFlying is up to date */
918.     float_vs_flight();
919. }
920. 
921. /* intended to be called only on ROCKs or TREEs */
922. boolean
923. may_dig(coordxy x, coordxy y)
924. {
925.     struct rm *lev = &levl[x][y];
926. 
927.     return (boolean) !((IS_STWALL(lev->typ) || IS_TREE(lev->typ))
928.                        && (lev->wall_info & W_NONDIGGABLE));
929. }
930. 
931. boolean
932. may_passwall(coordxy x, coordxy y)
933. {
934.     return (boolean) !(IS_STWALL(levl[x][y].typ)
935.                        && (levl[x][y].wall_info & W_NONPASSWALL));
936. }
937. 
938. boolean
939. bad_rock(struct permonst *mdat, coordxy x, coordxy y)
940. {
941.     return (boolean) ((Sokoban && sobj_at(BOULDER, x, y))
942.                       || (IS_OBSTRUCTED(levl[x][y].typ)
943.                           && (!tunnels(mdat) || needspick(mdat)
944.                               || !may_dig(x, y))
945.                           && !(passes_walls(mdat) && may_passwall(x, y))));
946. }
947. 
948. /* caller has already decided that it's a tight diagonal; check whether a
949.    monster--who might be the hero--can fit through, and if not then return
950.    the reason why:  1: can't fit, 2: possessions won't fit, 3: sokoban
951.    returns 0 if we can squeeze through */
952. int
953. cant_squeeze_thru(struct monst *mon)
954. {
955.     int amt;
956.     struct permonst *ptr = mon->data;
957. 
958.     if ((mon == &gy.youmonst) ? Passes_walls : passes_walls(ptr))
959.         return 0;
960. 
961.     /* too big? */
962.     if (bigmonst(ptr)
963.         && !(amorphous(ptr) || is_whirly(ptr) || noncorporeal(ptr)
964.              || slithy(ptr) || can_fog(mon)))
965.         return 1;
966. 
967.     /* lugging too much junk? */
968.     amt = (mon == &gy.youmonst) ? inv_weight() + weight_cap()
969.                                : curr_mon_load(mon);
970.     if (amt > WT_TOOMUCH_DIAGONAL)
971.         return 2;
972. 
973.     /* Sokoban restriction applies to hero only */
974.     if (mon == &gy.youmonst && Sokoban)
975.         return 3;
976. 
977.     /* can squeeze through */
978.     return 0;
979. }
980. 
981. boolean
982. invocation_pos(coordxy x, coordxy y)
983. {
984.     return (boolean) (Invocation_lev(&u.uz)
985.                       && x == svi.inv_pos.x && y == svi.inv_pos.y);
986. }
987. 
988. /* return TRUE if (ux+dx,uy+dy) is an OK place to move;
989.    mode is one of DO_MOVE, TEST_MOVE, TEST_TRAV, or TEST_TRAP */
990. boolean
991. test_move(
992.     coordxy ux, coordxy uy,
993.     coordxy dx, coordxy dy, /* these are -1|0|+1, not coordinates */
994.     int mode)
995. {
996.     coordxy x = ux + dx;
997.     coordxy y = uy + dy;
998.     struct rm *tmpr;
999.     struct rm *ust;
1000. 
1001.     svc.context.door_opened = FALSE;
1002. 
1003.     if (!isok(x, y))
1004.         return FALSE;
1005. 
1006.     tmpr = &levl[x][y];
1007. 
1008.     /*
1009.      *  Check for physical obstacles.  First, the place we are going.
1010.      */
1011.     if (IS_OBSTRUCTED(tmpr->typ) || tmpr->typ == IRONBARS) {
1012.         if (Blind && mode == DO_MOVE)
1013.             feel_location(x, y);
1014.         if (Passes_walls && may_passwall(x, y)) {
1015.             ; /* do nothing */
1016.         } else if (Underwater) {
1017.             /* note: if water_friction() changes direction due to
1018.                turbulence, new target destination will always be water,
1019.                so we won't get here, hence don't need to worry about
1020.                "there" being somewhere the player isn't sure of */
1021.             if (mode == DO_MOVE)
1022.                 There("is an obstacle there.");
1023.             return FALSE;
1024.         } else if (tmpr->typ == IRONBARS) {
1025.             if (mode == DO_MOVE
1026.                 && (dmgtype(gy.youmonst.data, AD_RUST)
1027.                     || dmgtype(gy.youmonst.data, AD_CORR)
1028.                     || metallivorous(gy.youmonst.data))
1029.                 && still_chewing(x, y)) {
1030.                 return FALSE;
1031.             }
1032.             if (!(Passes_walls || passes_bars(gy.youmonst.data))) {
1033.                 if (mode == DO_MOVE && flags.mention_walls)
1034.                     You("cannot pass through the bars.");
1035.                 return FALSE;
1036.             }
1037.         } else if (tunnels(gy.youmonst.data)
1038.                    && !needspick(gy.youmonst.data)) {
1039.             /* Eat the rock. */
1040.             if (mode == DO_MOVE && still_chewing(x, y))
1041.                 return FALSE;
1042.         } else if (flags.autodig && !svc.context.run && !svc.context.nopick
1043.                    && uwep && is_pick(uwep)) {
1044.             /* MRKR: Automatic digging when wielding the appropriate tool */
1045.             if (mode == DO_MOVE)
1046.                 (void) use_pick_axe2(uwep);
1047.             return FALSE;
1048.         } else {
1049.             if (mode == DO_MOVE) {
1050.                 if (is_db_wall(x, y)) {
1051.                     pline("That drawbridge is up!");
1052.                 } else if (Passes_walls && !may_passwall(x, y)
1053.                            && In_sokoban(&u.uz)) {
1054.                     /* soko restriction stays even after puzzle is solved */
1055.                     pline_The("Sokoban walls resist your ability.");
1056.                 } else if (flags.mention_walls) {
1057.                     char buf[BUFSZ];
1058.                     int glyph = back_to_glyph(x, y),
1059.                         sym = glyph_is_cmap(glyph) ? glyph_to_cmap(glyph)
1060.                                                    : -1;
1061. 
1062.                     if (sym == S_stone)
1063.                         Strcpy(buf, "solid stone");
1064.                     else if (sym >= 0)
1065.                         Strcpy(buf, an(defsyms[sym].explanation));
1066.                     else
1067.                         Sprintf(buf, "impossible [background glyph=%d]",
1068.                                 glyph);
1069.                     pline_dir(xytodir(dx, dy), "It's %s.", buf);
1070.                 }
1071.             }
1072.             return FALSE;
1073.         }
1074.     } else if (IS_DOOR(tmpr->typ)) {
1075.         if (closed_door(x, y)) {
1076.             if (Blind && mode == DO_MOVE)
1077.                 feel_location(x, y);
1078.             if (Passes_walls) {
1079.                 ; /* do nothing */
1080.             } else if (can_ooze(&gy.youmonst)) {
1081.                 if (mode == DO_MOVE)
1082.                     You("ooze under the door.");
1083.             } else if (Underwater) {
1084.                 if (mode == DO_MOVE)
1085.                     pline("There is an obstacle there.");
1086.                 return FALSE;
1087.             } else if (tunnels(gy.youmonst.data)
1088.                        && !needspick(gy.youmonst.data)) {
1089.                 /* Eat the door. */
1090.                 if (mode == DO_MOVE && still_chewing(x, y))
1091.                     return FALSE;
1092.             } else {
1093.                 if (mode == DO_MOVE) {
1094.                     if (amorphous(gy.youmonst.data))
1095.                         You("try to ooze under the door,"
1096.                             " but can't squeeze your possessions through.");
1097.                     if (flags.autoopen && !svc.context.run
1098.                         && !Confusion && !Stunned && !Fumbling) {
1099.                         int tmp = doopen_indir(x, y);
1100.                         /* if 'autounlock' includes Kick, we might have a
1101.                            kick at the door queued up after doopen_indir() */
1102.                         struct _cmd_queue *cq = cmdq_peek(CQ_CANNED);
1103. 
1104.                         if (tmp == ECMD_OK && cq && cq->typ == CMDQ_EXTCMD
1105.                             && cq->ec_entry == ext_func_tab_from_func(dokick))
1106.                             /* door hasn't been opened, but fake it so that
1107.                                canned kick will be executed as next command */
1108.                             svc.context.door_opened = TRUE;
1109.                         else
1110.                             svc.context.door_opened = !closed_door(x, y);
1111.                         svc.context.move = (ux != u.ux || uy != u.uy);
1112.                     } else if (x == ux || y == uy) {
1113.                         if (Blind || Stunned || ACURR(A_DEX) < 10
1114.                             || Fumbling) {
1115.                             if (u.usteed) {
1116.                                 You_cant("lead %s through that closed door.",
1117.                                          y_monnam(u.usteed));
1118.                             } else {
1119.                                 pline("Ouch!  You bump into a door.");
1120.                                 exercise(A_DEX, FALSE);
1121.                             }
1122.                             /* use current move; needed for the "ouch" case
1123.                                but done for steed case too for consistency;
1124.                                we haven't opened a door but we're going to
1125.                                return False and without having 'door_opened'
1126.                                set, 'move' would get reset by caller */
1127.                             svc.context.door_opened = svc.context.move = TRUE;
1128.                             /* since we've just lied about successfully
1129.                                moving, we need to manually stop running */
1130.                             nomul(0);
1131.                         } else
1132.                             pline("That door is closed.");
1133.                     }
1134.                 } else if (mode == TEST_TRAV || mode == TEST_TRAP)
1135.                     goto testdiag;
1136.                 return FALSE;
1137.             }
1138.         } else {
1139.  testdiag:
1140.             if (dx && dy && !Passes_walls
1141.                 && (!doorless_door(x, y) || block_door(x, y))) {
1142.                 /* Diagonal moves into a door are not allowed. */
1143.                 if (mode == DO_MOVE) {
1144.                     if (Blind)
1145.                         feel_location(x, y);
1146.                     if (Underwater || flags.mention_walls)
1147.                         You_cant("move diagonally into an intact doorway.");
1148.                 }
1149.                 return FALSE;
1150.             }
1151.         }
1152.     }
1153.     if (dx && dy && bad_rock(gy.youmonst.data, ux, y)
1154.         && bad_rock(gy.youmonst.data, x, uy)) {
1155.         /* Move at a diagonal. */
1156.         switch (cant_squeeze_thru(&gy.youmonst)) {
1157.         case 3:
1158.             if (mode == DO_MOVE)
1159.                 You("cannot pass that way.");
1160.             return FALSE;
1161.         case 2:
1162.             if (mode == DO_MOVE)
1163.                 You("are carrying too much to get through.");
1164.             return FALSE;
1165.         case 1:
1166.             if (mode == DO_MOVE)
1167.                 Your("body is too large to fit through.");
1168.             return FALSE;
1169.         default:
1170.             break; /* can squeeze through */
1171.         }
1172.     } else if (dx && dy && worm_cross(ux, uy, x, y)) {
1173.         /* consecutive long worm segments are at <ux,y> and <x,uy> */
1174.         if (mode == DO_MOVE)
1175.             pline("%s is in your way.", YMonnam(m_at(ux, y)));
1176.         return FALSE;
1177.     }
1178.     /* Pick travel path that does not require crossing a trap.
1179.      * Avoid water and lava using the usual running rules.
1180.      * (but not u.ux/u.uy because findtravelpath walks toward u.ux/u.uy) */
1181.     if (svc.context.run == 8 && (mode != DO_MOVE) && !u_at(x, y)) {
1182.         struct trap *t = t_at(x, y);
1183. 
1184.         if (t && t->tseen && t->ttyp != VIBRATING_SQUARE)
1185.             return (mode == TEST_TRAP);
1186. 
1187.         /* FIXME: should be using lastseentyp[x][y] rather than seen vector
1188.          */
1189.         if ((levl[x][y].seenv && is_pool_or_lava(x, y)) /* known pool/lava */
1190.             && ((IS_WATERWALL(levl[x][y].typ) /* never enter wall of liquid */
1191.                  || levl[x][y].typ == LAVAWALL)
1192.                 /* don't enter pool or lava (must be one of the two to
1193.                    get here) unless flying or levitating or have known
1194.                    water-walking for pool or known lava-walking and
1195.                    already be on/over lava for lava */
1196.                 || !(Levitation || Flying
1197.                      || (is_pool(x, y) ? Known_wwalking
1198.                          : (Known_lwalking && is_lava(u.ux, u.uy))))))
1199.             return (mode == TEST_TRAP);
1200.     }
1201. 
1202.     if (mode == TEST_TRAP)
1203.         return FALSE; /* do not move through traps */
1204. 
1205.     ust = &levl[ux][uy];
1206. 
1207.     /* Now see if other things block our way . . */
1208.     if (dx && dy && !Passes_walls && IS_DOOR(ust->typ)
1209.         && (!doorless_door(ux, uy) || block_entry(x, y))) {
1210.         /* Can't move at a diagonal out of a doorway with door. */
1211.         if (mode == DO_MOVE && flags.mention_walls)
1212.             You_cant("move diagonally out of an intact doorway.");
1213.         return FALSE;
1214.     }
1215. 
1216.     if (sobj_at(BOULDER, x, y) && (Sokoban || !Passes_walls)) {
1217.         if (mode != TEST_TRAV && svc.context.run >= 2
1218.             && !(Blind || Hallucination) && !could_move_onto_boulder(x, y)) {
1219.             if (mode == DO_MOVE && flags.mention_walls)
1220.                 pline_dir(xytodir(dx,dy), "A boulder blocks your path.");
1221.             return FALSE;
1222.         }
1223.         if (mode == DO_MOVE) {
1224.             /* tunneling monsters will chew before pushing */
1225.             if (tunnels(gy.youmonst.data) && !needspick(gy.youmonst.data)
1226.                 && !Sokoban) {
1227.                 if (still_chewing(x, y))
1228.                     return FALSE;
1229.             } else if (moverock() < 0)
1230.                 return FALSE;
1231.         } else if (mode == TEST_TRAV) {
1232.             struct obj *obj;
1233. 
1234.             /* never travel through boulders in Sokoban */
1235.             if (Sokoban)
1236.                 return FALSE;
1237. 
1238.             /* don't pick two boulders in a row, unless there's a way thru */
1239.             if (sobj_at(BOULDER, ux, uy) && !Sokoban) {
1240.                 if (!Passes_walls
1241.                     && !could_move_onto_boulder(ux, uy)
1242.                     && !(tunnels(gy.youmonst.data)
1243.                          && !needspick(gy.youmonst.data))
1244.                     && !carrying(PICK_AXE) && !carrying(DWARVISH_MATTOCK)
1245.                     && !((obj = carrying(WAN_DIGGING))
1246.                          && !objects[obj->otyp].oc_name_known))
1247.                     return FALSE;
1248.             }
1249.         }
1250.         /* assume you'll be able to push it when you get there... */
1251.     }
1252. 
1253.     /* OK, it is a legal place to move. */
1254.     return TRUE;
1255. }
1256. 
1257. /*
1258.  * Find a path from the destination (u.tx,u.ty) back to (u.ux,u.uy).
1259.  * A shortest path is returned.  If guess is TRUE, consider various
1260.  * inaccessible locations as valid intermediate path points.
1261.  * Returns TRUE if a path was found.
1262.  * gt.travelmap keeps track of map locations we've moved through
1263.  * this travel session. It will be cleared once the travel stops.
1264.  */
1265. staticfn boolean
1266. findtravelpath(int mode)
1267. {
1268.     if (!gt.travelmap)
1269.         gt.travelmap = selection_new();
1270.     /* if travel to adjacent, reachable location, use normal movement rules */
1271.     if ((mode == TRAVP_TRAVEL || mode == TRAVP_VALID) && svc.context.travel1
1272.         /* was '&& distmin(u.ux, u.uy, u.tx, u.ty) == 1' */
1273.         && next2u(u.tx, u.ty) /* one step away */
1274.         /* handle restricted diagonals */
1275.         && crawl_destination(u.tx, u.ty)) {
1276.         end_running(FALSE);
1277.         if (test_move(u.ux, u.uy, u.tx - u.ux, u.ty - u.uy, TEST_MOVE)) {
1278.             if (mode == TRAVP_TRAVEL) {
1279.                 u.dx = u.tx - u.ux;
1280.                 u.dy = u.ty - u.uy;
1281.                 nomul(0);
1282.                 iflags.travelcc.x = iflags.travelcc.y = 0;
1283.             }
1284.             return TRUE;
1285.         }
1286.         if (mode == TRAVP_TRAVEL)
1287.             svc.context.run = 8;
1288.     }
1289.     if (u.tx != u.ux || u.ty != u.uy) {
1290.         coordxy travel[COLNO][ROWNO];
1291.         coordxy travelstepx[2][COLNO * ROWNO];
1292.         coordxy travelstepy[2][COLNO * ROWNO];
1293.         coordxy tx, ty, ux, uy;
1294.         int n = 1;      /* max offset in travelsteps */
1295.         int set = 0;    /* two sets current and previous */
1296.         int radius = 1; /* search radius */
1297.         int i;
1298. 
1299.         /* If guessing, first find an "obvious" goal location.  The obvious
1300.          * goal is the position the player knows of, or might figure out
1301.          * (couldsee) that is closest to the target on a straight path.
1302.          */
1303.         if (mode == TRAVP_GUESS || mode == TRAVP_VALID) {
1304.             tx = u.ux;
1305.             ty = u.uy;
1306.             ux = u.tx;
1307.             uy = u.ty;
1308.         } else {
1309.             tx = u.tx;
1310.             ty = u.ty;
1311.             ux = u.ux;
1312.             uy = u.uy;
1313.         }
1314. 
1315.  noguess:
1316.         (void) memset((genericptr_t) travel, 0, sizeof travel);
1317.         travelstepx[0][0] = tx;
1318.         travelstepy[0][0] = ty;
1319. 
1320.         while (n != 0) {
1321.             int nn = 0;
1322. 
1323.             for (i = 0; i < n; i++) {
1324.                 int dir;
1325.                 coordxy x = travelstepx[set][i];
1326.                 coordxy y = travelstepy[set][i];
1327.                 /* no diagonal movement for grid bugs */
1328.                 int dirmax = NODIAG(u.umonnum) ? 4 : N_DIRS;
1329.                 boolean alreadyrepeated = FALSE;
1330. 
1331.                 for (dir = 0; dir < dirmax; ++dir) {
1332.                     coordxy nx = x + xdir[dirs_ord[dir]];
1333.                     coordxy ny = y + ydir[dirs_ord[dir]];
1334. 
1335.                     /*
1336.                      * When guessing and trying to travel as close as possible
1337.                      * to an unreachable target space, don't include spaces
1338.                      * that would never be picked as a guessed target in the
1339.                      * travel matrix describing hero-reachable spaces.
1340.                      * This stops travel from getting confused and moving
1341.                      * the hero back and forth in certain degenerate
1342.                      * configurations of sight-blocking obstacles, e.g.
1343.                      *
1344.                      *  T         1. Dig this out and carry enough to not be
1345.                      *   ####       able to squeeze through diagonal gaps.
1346.                      *   #--.---    Stand at @ and target travel at space T.
1347.                      *    @.....
1348.                      *    |.....
1349.                      *
1350.                      *  T         2. couldsee() marks spaces marked a and x
1351.                      *   ####       as eligible guess spaces to move the hero
1352.                      *   a--.---    towards.  Space a is closest to T, so it
1353.                      *    @xxxxx    gets chosen.  Travel system moves @ right
1354.                      *    |xxxxx    to travel to space a.
1355.                      *
1356.                      *  T         3. couldsee() marks spaces marked b, c and x
1357.                      *   ####       as eligible guess spaces to move the hero
1358.                      *   a--c---    towards.  Since findtravelpath() is called
1359.                      *    b@xxxx    repeatedly during travel, it doesn't
1360.                      *    |xxxxx    remember that it wanted to go to space a,
1361.                      *              so in comparing spaces b and c, b is
1362.                      *              chosen, since it seems like the closest
1363.                      *              eligible space to T. Travel system moves @
1364.                      *              left to go to space b.
1365.                      *
1366.                      *            4. Go to 2.
1367.                      *
1368.                      * By limiting the travel matrix here, space a in the
1369.                      * example above is never included in it, preventing
1370.                      * the cycle.
1371.                      */
1372.                     if (!isok(nx, ny)
1373.                         || ((mode == TRAVP_GUESS) && !couldsee(nx, ny)))
1374.                         continue;
1375.                     if ((!Passes_walls && !can_ooze(&gy.youmonst)
1376.                          && closed_door(x, y))
1377.                         || (sobj_at(BOULDER, x, y)
1378.                             && !could_move_onto_boulder(x, y))
1379.                         || test_move(x, y, nx - x, ny - y, TEST_TRAP)) {
1380.                         /* closed doors and boulders usually cause a delay,
1381.                            so prefer another path; however, giants and tiny
1382.                            creatures can use m<dir> to move onto a boulder's
1383.                            spot without pushing, so allow boulders for them */
1384.                         if (travel[x][y] > radius - 3) {
1385.                             if (!alreadyrepeated) {
1386.                                 travelstepx[1 - set][nn] = x;
1387.                                 travelstepy[1 - set][nn] = y;
1388.                                 /* don't change travel matrix! */
1389.                                 nn++;
1390.                                 alreadyrepeated = TRUE;
1391.                             }
1392.                             continue;
1393.                         }
1394.                     }
1395.                     if (test_move(x, y, nx - x, ny - y, TEST_TRAV)
1396.                         && (levl[nx][ny].seenv
1397.                             || (!Blind && couldsee(nx, ny)))) {
1398.                         if (nx == ux && ny == uy) {
1399.                             if (mode == TRAVP_TRAVEL || mode == TRAVP_VALID) {
1400.                                 boolean visited
1401.                                     = selection_getpoint(x, y, gt.travelmap);
1402.                                 u.dx = x - ux;
1403.                                 u.dy = y - uy;
1404.                                 if (mode == TRAVP_TRAVEL
1405.                                     && ((x == u.tx && y == u.ty)
1406.                                         || visited)) {
1407.                                     nomul(0);
1408.                                     /* reset run so domove run checks work */
1409.                                     svc.context.run = 8;
1410.                                     if (visited)
1411.                                         You("stop, unsure which way to go.");
1412.                                     else
1413.                                         iflags.travelcc.x
1414.                                         = iflags.travelcc.y = 0;
1415.                                 }
1416.                                 selection_setpoint(u.ux, u.uy,
1417.                                                    gt.travelmap, 1);
1418.                                 return TRUE;
1419.                             }
1420.                         } else if (!travel[nx][ny]) {
1421.                             travelstepx[1 - set][nn] = nx;
1422.                             travelstepy[1 - set][nn] = ny;
1423.                             travel[nx][ny] = radius;
1424.                             nn++;
1425.                         }
1426.                     }
1427.                 }
1428.             }
1429. 
1430. #ifdef DEBUG
1431.             if (iflags.trav_debug) {
1432.                 /* Use of warning glyph is arbitrary. It stands out. */
1433.                 tmp_at(DISP_ALL, warning_to_glyph(1));
1434.                 for (i = 0; i < nn; ++i) {
1435.                     tmp_at(travelstepx[1 - set][i], travelstepy[1 - set][i]);
1436.                 }
1437.                 nh_delay_output();
1438.                 if (flags.runmode == RUN_CRAWL) {
1439.                     nh_delay_output();
1440.                     nh_delay_output();
1441.                 }
1442.                 tmp_at(DISP_END, 0);
1443.             }
1444. #endif /* DEBUG */
1445. 
1446.             n = nn;
1447.             set = 1 - set;
1448.             radius++;
1449.         }
1450. 
1451.         /* if guessing, find best location in travel matrix and go there */
1452.         if (mode == TRAVP_GUESS) {
1453.             int px = tx, py = ty; /* pick location */
1454.             int dist, nxtdist, d2, nd2;
1455.             int ctrav, ptrav = COLNO*ROWNO;
1456. 
1457.             dist = distmin(ux, uy, tx, ty);
1458.             d2 = dist2(ux, uy, tx, ty);
1459.             for (tx = 1; tx < COLNO; ++tx)
1460.                 for (ty = 0; ty < ROWNO; ++ty)
1461.                     if (couldsee(tx, ty) && (ctrav = travel[tx][ty]) > 0) {
1462.                         nxtdist = distmin(ux, uy, tx, ty);
1463.                         if (nxtdist == dist && ctrav < ptrav) {
1464.                             nd2 = dist2(ux, uy, tx, ty);
1465.                             if (nd2 < d2) {
1466.                                 /* prefer non-zigzag path */
1467.                                 px = tx;
1468.                                 py = ty;
1469.                                 d2 = nd2;
1470.                                 ptrav = ctrav;
1471.                             }
1472.                         } else if (nxtdist < dist) {
1473.                             px = tx;
1474.                             py = ty;
1475.                             dist = nxtdist;
1476.                             d2 = dist2(ux, uy, tx, ty);
1477.                             ptrav = ctrav;
1478.                         }
1479.                     }
1480. 
1481.             if (u_at(px, py)) {
1482.                 /* no guesses, just go in the general direction */
1483.                 u.dx = sgn(u.tx - u.ux);
1484.                 u.dy = sgn(u.ty - u.uy);
1485.                 if (test_move(u.ux, u.uy, u.dx, u.dy, TEST_MOVE)) {
1486.                     selection_setpoint(u.ux, u.uy, gt.travelmap, 1);
1487.                     return TRUE;
1488.                 }
1489.                 goto found;
1490.             }
1491. #ifdef DEBUG
1492.             if (iflags.trav_debug) {
1493.                 /* Use of warning glyph is arbitrary. It stands out. */
1494.                 tmp_at(DISP_ALL, warning_to_glyph(2));
1495.                 tmp_at(px, py);
1496.                 nh_delay_output();
1497.                 if (flags.runmode == RUN_CRAWL) {
1498.                     nh_delay_output();
1499.                     nh_delay_output();
1500.                     nh_delay_output();
1501.                     nh_delay_output();
1502.                 }
1503.                 tmp_at(DISP_END, 0);
1504.             }
1505. #endif /* DEBUG */
1506.             tx = px;
1507.             ty = py;
1508.             ux = u.ux;
1509.             uy = u.uy;
1510.             set = 0;
1511.             n = radius = 1;
1512.             mode = TRAVP_TRAVEL;
1513.             goto noguess;
1514.         }
1515.         return FALSE;
1516.     }
1517. 
1518.  found:
1519.     u.dx = 0;
1520.     u.dy = 0;
1521.     nomul(0);
1522.     return FALSE;
1523. }
1524. 
1525. boolean
1526. is_valid_travelpt(coordxy x, coordxy y)
1527. {
1528.     int tx = u.tx;
1529.     int ty = u.ty;
1530.     boolean ret;
1531.     int glyph = glyph_at(x,y);
1532. 
1533.     if (u_at(x, y))
1534.         return TRUE;
1535.     if (isok(x,y) && glyph_is_cmap(glyph) && S_stone == glyph_to_cmap(glyph)
1536.         && !levl[x][y].seenv)
1537.         return FALSE;
1538.     u.tx = x;
1539.     u.ty = y;
1540.     ret = findtravelpath(TRAVP_VALID);
1541.     u.tx = tx;
1542.     u.ty = ty;
1543.     return ret;
1544. }
1545. 
1546. /* try to escape being stuck in a trapped state by walking out of it;
1547.    return true iff moving should continue to intended destination
1548.    (all failures and most successful escapes leave hero at original spot) */
1549. staticfn boolean
1550. trapmove(
1551.     coordxy x, coordxy y, /* targeted destination, <u.ux+u.dx,u.uy+u.dy> */
1552.     struct trap *desttrap) /* nonnull if another trap at <x,y> */
1553. {
1554.     boolean anchored = FALSE;
1555.     const char *predicament, *culprit;
1556.     char *steedname = !u.usteed ? (char *) 0 : y_monnam(u.usteed);
1557. 
1558.     if (!u.utrap)
1559.         return TRUE; /* sanity check */
1560. 
1561.     /*
1562.      * Note: caller should call reset_utrap() when we set u.utrap to 0.
1563.      */
1564. 
1565.     switch (u.utraptype) {
1566.     case TT_BEARTRAP:
1567.         if (flags.verbose) {
1568.             predicament = "caught in a bear trap";
1569.             if (u.usteed)
1570.                 Norep("%s is %s.", upstart(steedname), predicament);
1571.             else
1572.                 Norep("You are %s.", predicament);
1573.         }
1574.         /* [why does diagonal movement give quickest escape?] */
1575.         if ((u.dx && u.dy) || !rn2(5))
1576.             u.utrap--;
1577.         if (!u.utrap)
1578.             goto wriggle_free;
1579.         break;
1580.     case TT_PIT:
1581.         if (desttrap && desttrap->tseen
1582.             && is_pit(desttrap->ttyp))
1583.             return TRUE; /* move into adjacent pit */
1584.         /* try to escape; position stays same regardless of success */
1585.         climb_pit();
1586.         break;
1587.     case TT_WEB:
1588.         if (u_wield_art(ART_STING)) {
1589.             /* escape trap but don't move and don't destroy it */
1590.             u.utrap = 0; /* caller will call reset_utrap() */
1591.             pline("Sting cuts through the web!");
1592.             break;
1593.         }
1594.         if (--u.utrap) {
1595.             if (flags.verbose) {
1596.                 predicament = "stuck to the web";
1597.                 if (u.usteed)
1598.                     Norep("%s is %s.", upstart(steedname), predicament);
1599.                 else
1600.                     Norep("You are %s.", predicament);
1601.             }
1602.         } else {
1603.             if (u.usteed)
1604.                 pline("%s breaks out of the web.", upstart(steedname));
1605.             else
1606.                 You("disentangle yourself.");
1607.         }
1608.         break;
1609.     case TT_LAVA:
1610.         if (flags.verbose) {
1611.             predicament = "stuck in the lava";
1612.             if (u.usteed)
1613.                 Norep("%s is %s.", upstart(steedname), predicament);
1614.             else
1615.                 Norep("You are %s.", predicament);
1616.         }
1617.         if (!is_lava(x, y)) {
1618.             u.utrap--;
1619.             if ((u.utrap & 0xff) == 0) {
1620.                 u.utrap = 0;
1621.                 if (u.usteed)
1622.                     You("lead %s to the edge of the %s.", steedname,
1623.                         hliquid("lava"));
1624.                 else
1625.                     You("pull yourself to the edge of the %s.",
1626.                         hliquid("lava"));
1627.             }
1628.         }
1629.         u.umoved = TRUE;
1630.         break;
1631.     case TT_INFLOOR:
1632.     case TT_BURIEDBALL:
1633.         anchored = (u.utraptype == TT_BURIEDBALL);
1634.         if (anchored) {
1635.             coord cc;
1636. 
1637.             cc.x = u.ux, cc.y = u.uy;
1638.             /* can move normally within radius 1 of buried ball */
1639.             if (buried_ball(&cc) && dist2(x, y, cc.x, cc.y) <= 2) {
1640.                 /* ugly hack: we need to issue some message here
1641.                    in case "you are chained to the buried ball"
1642.                    was the most recent message given, otherwise
1643.                    our next attempt to move out of tether range
1644.                    after this successful move would have its
1645.                    can't-do-that message suppressed by Norep */
1646.                 if (flags.verbose)
1647.                     Norep("You move within the chain's reach.");
1648.                 return TRUE;
1649.             }
1650.         }
1651.         if (--u.utrap) {
1652.             if (flags.verbose) {
1653.                 if (anchored) {
1654.                     predicament = "chained to the";
1655.                     culprit = "buried ball";
1656.                 } else {
1657.                     predicament = "stuck in the";
1658.                     culprit = surface(u.ux, u.uy);
1659.                 }
1660.                 if (u.usteed) {
1661.                     if (anchored)
1662.                         Norep("You and %s are %s %s.", steedname, predicament,
1663.                               culprit);
1664.                     else
1665.                         Norep("%s is %s %s.", upstart(steedname), predicament,
1666.                               culprit);
1667.                 } else
1668.                     Norep("You are %s %s.", predicament, culprit);
1669.             }
1670.         } else {
1671.  wriggle_free:
1672.             if (u.usteed)
1673.                 pline("%s finally %s free.", upstart(steedname),
1674.                       !anchored ? "lurches" : "wrenches the ball");
1675.             else
1676.                 You("finally %s free.",
1677.                     !anchored ? "wriggle" : "wrench the ball");
1678.             if (anchored)
1679.                 buried_ball_to_punishment();
1680.         }
1681.         break;
1682.     case TT_NONE:
1683.         impossible("trapmove: trapped in nothing?");
1684.         break;
1685.     default:
1686.         impossible("trapmove: stuck in unknown trap? (%d)",
1687.                    (int) u.utraptype);
1688.         break;
1689.     }
1690.     return FALSE;
1691. }
1692. 
1693. boolean
1694. u_rooted(void)
1695. {
1696.     if (!gy.youmonst.data->mmove) {
1697.         You("are rooted %s.",
1698.             Levitation || Is_airlevel(&u.uz) || Is_waterlevel(&u.uz)
1699.                 ? "in place"
1700.                 : "to the ground");
1701.         nomul(0);
1702.         return TRUE;
1703.     }
1704.     return FALSE;
1705. }
1706. 
1707. void
1708. notice_mon(struct monst *mtmp)
1709. {
1710.     if (a11y.mon_notices && !a11y.mon_notices_blocked) {
1711.         boolean spot = canspotmon(mtmp)
1712.             && !(is_hider(mtmp->data)
1713.                  && (mtmp->mundetected
1714.                      || M_AP_TYPE(mtmp) == M_AP_FURNITURE
1715.                      || M_AP_TYPE(mtmp) == M_AP_OBJECT));
1716. 
1717.         if (spot && !mtmp->mspotted && !DEADMONSTER(mtmp)) {
1718.             mtmp->mspotted = TRUE;
1719.             set_msg_xy(mtmp->mx, mtmp->my);
1720.             You("%s %s.", canseemon(mtmp) ? "see" : "notice",
1721.                 x_monnam(mtmp,
1722.                      mtmp->mtame ? ARTICLE_YOUR
1723.                      : (!has_mgivenname(mtmp)
1724.                         && !type_is_pname(mtmp->data)) ? ARTICLE_A
1725.                      : ARTICLE_NONE,
1726.                      (mtmp->mpeaceful && !mtmp->mtame) ? "peaceful" : 0,
1727.                      has_mgivenname(mtmp) ? SUPPRESS_SADDLE : 0, FALSE));
1728.         } else if (!spot) {
1729.             mtmp->mspotted = FALSE;
1730.         }
1731.     }
1732. }
1733. 
1734. staticfn int QSORTCALLBACK
1735. notice_mons_cmp(const genericptr ptr1, const genericptr ptr2)
1736. {
1737.     const struct monst *m1 = *(const struct monst **) ptr1,
1738.         *m2 = *(const struct monst **) ptr2;
1739. 
1740.     return (distu(m1->mx, m1->my) - distu(m2->mx, m2->my));
1741. }
1742. 
1743. void
1744. notice_all_mons(boolean reset)
1745. {
1746.     if (a11y.mon_notices && !a11y.mon_notices_blocked) {
1747.         struct monst *mtmp;
1748.         struct monst **arr = NULL;
1749.         int j, i = 0, cnt = 0;
1750. 
1751.         for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
1752.             if (DEADMONSTER(mtmp))
1753.                 continue;
1754.             if (canspotmon(mtmp))
1755.                 cnt++;
1756.             else if (reset)
1757.                 mtmp->mspotted = FALSE;
1758.         }
1759.         if (!cnt)
1760.             return;
1761. 
1762.         arr = (struct monst **) alloc(cnt * sizeof (struct monst *));
1763. 
1764.         for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
1765.             if (DEADMONSTER(mtmp))
1766.                 continue;
1767.             if (!canspotmon(mtmp))
1768.                 mtmp->mspotted = FALSE;
1769.             else if (i < cnt)
1770.                 arr[i++] = mtmp;
1771.         }
1772. 
1773.         if (i) {
1774.             qsort((genericptr_t) arr, (size_t) i, sizeof *arr,
1775.                   notice_mons_cmp);
1776. 
1777.             for (j = 0; j < i; j++)
1778.                 notice_mon(arr[j]);
1779.         }
1780. 
1781.         free(arr);
1782.     }
1783. }
1784. 
1785. /* maybe disturb buried zombies when an object is dropped or thrown nearby */
1786. void
1787. impact_disturbs_zombies(struct obj *obj, boolean violent)
1788. {
1789.     /* if object won't make a noticeable impact, let buried zombies rest */
1790.     if (obj->owt < (violent ? 10U : 100U) || is_flimsy(obj))
1791.         return;
1792. 
1793.     disturb_buried_zombies(obj->ox, obj->oy);
1794. }
1795. 
1796. /* reduce zombification timeout of buried zombies around px, py */
1797. void
1798. disturb_buried_zombies(coordxy x, coordxy y)
1799. {
1800.     struct obj *otmp;
1801.     long t;
1802. 
1803.     for (otmp = svl.level.buriedobjlist; otmp; otmp = otmp->nobj) {
1804.         if (otmp->otyp == CORPSE && otmp->timed
1805.             && otmp->ox >= x - 1 && otmp->ox <= x + 1
1806.             && otmp->oy >= y - 1 && otmp->oy <= y + 1
1807.             && (t = peek_timer(ZOMBIFY_MON, obj_to_any(otmp))) > 0) {
1808.             t = stop_timer(ZOMBIFY_MON, obj_to_any(otmp));
1809.             (void) start_timer(max(1, (t*2/3)), TIMER_OBJECT,
1810.                                ZOMBIFY_MON, obj_to_any(otmp));
1811.         }
1812.     }
1813. }
1814. 
1815. /* return an appropriate locomotion word for hero */
1816. const char *
1817. u_locomotion(const char *def)
1818. {
1819.     boolean capitalize = (*def == highc(*def));
1820. 
1821.     /* regular locomotion() takes a monster type rather than a specific
1822.        monster, so can't tell whether it is operating on hero;
1823.        its is_flyer() and is_floater() tests wouldn't work on hero except
1824.        when hero is polymorphed and not wearing an amulet of flying
1825.        or boots/ring/spell of levitation */
1826.     return Levitation ? (capitalize ? "Float" : "float")
1827.            : Flying ? (capitalize ? "Fly" : "fly")
1828.              : locomotion(gy.youmonst.data, def);
1829. }
1830. 
1831. /* Return a simplified floor solid/liquid state based on hero's state */
1832. staticfn schar
1833. u_simple_floortyp(coordxy x, coordxy y)
1834. {
1835.     boolean u_in_air = (Levitation || Flying || !grounded(gy.youmonst.data));
1836. 
1837.     if (is_waterwall(x, y))
1838.         return WATER; /* wall of water, fly/lev does not matter */
1839.     if (levl[x][y].typ == LAVAWALL)
1840.         return LAVAWALL; /* wall of lava, fly/lev does not matter */
1841.     if (!u_in_air) {
1842.         if (is_pool(x, y))
1843.             return POOL;
1844.         if (is_lava(x, y))
1845.             return LAVAPOOL;
1846.     }
1847.     return ROOM;
1848. }
1849. 
1850. /* maybe show a helpful gameplay tip? returns True if tip gets shown */
1851. boolean
1852. handle_tip(int tip)
1853. {
1854.     if (!flags.tips)
1855.         return FALSE;
1856. 
1857.     if (tip >= 0 && tip < NUM_TIPS && !(svc.context.tips & (1 << tip))) {
1858.         svc.context.tips |= (1 << tip);
1859.         /* the "Tip:" prefix is a hint to use of OPTIONS=!tips to suppress */
1860.         switch (tip) {
1861.         case TIP_ENHANCE:
1862.             pline("(Tip: use the #enhance command to advance them.)");
1863.             break;
1864.         case TIP_SWIM:
1865.             pline("(Tip: use '%s' prefix to step in if you really want to.)",
1866.                   visctrl(cmd_from_func(do_reqmenu)));
1867.             break;
1868.         case TIP_UNTRAP_MON:
1869.             pline("(Tip: perhaps #untrap would help?)");
1870.             break;
1871.         case TIP_GETPOS:
1872.             l_nhcore_call(NHCORE_GETPOS_TIP);
1873.             break;
1874.         default:
1875.             impossible("Unknown tip in handle_tip(%i)", tip);
1876.             break;
1877.         }
1878.         return TRUE;
1879.     }
1880.     return FALSE;
1881. }
1882. 
1883. /* Is it dangerous for hero to move to x,y due to water or lava? */
1884. staticfn boolean
1885. swim_move_danger(coordxy x, coordxy y)
1886. {
1887.     schar newtyp = u_simple_floortyp(x, y);
1888.     boolean liquid_wall = IS_WATERWALL(newtyp) || newtyp == LAVAWALL;
1889. 
1890.     if (Underwater && (is_pool(x,y) || IS_WATERWALL(newtyp)))
1891.         return FALSE;
1892. 
1893.     if ((newtyp != u_simple_floortyp(u.ux, u.uy))
1894.         && !Stunned && !Confusion && levl[x][y].seenv
1895.         && (is_pool(x, y) || is_lava(x, y) || liquid_wall)) {
1896. 
1897.         /* FIXME: This can be exploited to identify ring of fire resistance
1898.          * if the player is wearing it unidentified and has identified
1899.          * fireproof boots of water walking and is walking over lava. However,
1900.          * this is such a marginal case that it may not be worth fixing. */
1901.         if ((is_pool(x, y) && !Known_wwalking)
1902.             /* is_lava(ux,uy): don't move onto/over lava with known
1903.                lava-walking because it isn't completely safe, but do
1904.                continue to move over lava if already doing so */
1905.             || (is_lava(x, y) && !Known_lwalking && !is_lava(u.ux, u.uy))
1906.             || liquid_wall) {
1907.             if (svc.context.nopick) {
1908.                 /* moving with m-prefix */
1909.                 svc.context.tips |= (1 << TIP_SWIM);
1910.                 return FALSE;
1911.             } else if (ParanoidSwim || liquid_wall) {
1912.                 You("avoid %s into the %s.",
1913.                     ing_suffix(u_locomotion("step")),
1914.                     waterbody_name(x, y));
1915.                 (void) handle_tip(TIP_SWIM);
1916.                 return TRUE;
1917.             }
1918.         }
1919.     }
1920.     return FALSE;
1921. }
1922. 
1923. /* moving with 'm' prefix, bump into a monster? */
1924. staticfn boolean
1925. domove_bump_mon(struct monst *mtmp, int glyph)
1926. {
1927.     /* If they used a 'm' command, trying to move onto a monster
1928.      * prints the below message and wastes a turn.  The exception is
1929.      * if the monster is unseen and the player doesn't remember an
1930.      * invisible monster--then, we fall through to do_attack() and
1931.      * attack_check(), which still wastes a turn, but prints a
1932.      * different message and makes the player remember the monster.
1933.      */
1934.     if (svc.context.nopick && !svc.context.travel
1935.         && (canspotmon(mtmp) || glyph_is_invisible(glyph)
1936.             || glyph_is_warning(glyph))) {
1937.         if (M_AP_TYPE(mtmp) && !Protection_from_shape_changers
1938.             && !sensemon(mtmp))
1939.             stumble_onto_mimic(mtmp);
1940.         else if (mtmp->mpeaceful && !Hallucination)
1941.             /* m_monnam(): "dog" or "Fido", no "invisible dog" or "it" */
1942.             pline("Pardon me, %s.", m_monnam(mtmp));
1943.         else
1944.             You("move right into %s.", mon_nam(mtmp));
1945.         return TRUE;
1946.     }
1947.     return FALSE;
1948. }
1949. 
1950. /* hero is moving, do we maybe attack a monster at (x,y)?
1951.    returns TRUE if hero movement is used up.
1952.    sets displaceu, if hero and monster could swap places instead.
1953. */
1954. staticfn boolean
1955. domove_attackmon_at(
1956.     struct monst *mtmp,
1957.     coordxy x, coordxy y,
1958.     boolean *displaceu)
1959. {
1960.     /* assert(mtmp != NULL) */
1961.     /* only attack if we know it's there
1962.      * or if we used the 'F' command to fight blindly
1963.      * or if it hides_under, in which case we call do_attack() to print
1964.      * the Wait! message.
1965.      * This is different from ceiling hiders, who aren't handled in
1966.      * do_attack().
1967.      */
1968.     if (svc.context.forcefight || !mtmp->mundetected || sensemon(mtmp)
1969.         || ((hides_under(mtmp->data) || mtmp->data->mlet == S_EEL)
1970.             && !is_safemon(mtmp))) {
1971.         /* target monster might decide to switch places with you... */
1972.         *displaceu = (mtmp->data == &mons[PM_DISPLACER_BEAST] && !rn2(2)
1973.                       && mtmp->mux == u.ux0 && mtmp->muy == u.uy0
1974.                       && !helpless(mtmp)
1975.                       && !mtmp->meating && !mtmp->mtrapped
1976.                       && !u.utrap && !u.ustuck && !u.usteed
1977.                       && !(u.dx && u.dy
1978.                            && (NODIAG(u.umonnum)
1979.                                || (bad_rock(mtmp->data, x, u.uy0)
1980.                                    && bad_rock(mtmp->data, u.ux0, y))
1981.                                || (bad_rock(gy.youmonst.data, u.ux0, y)
1982.                                    && bad_rock(gy.youmonst.data, x, u.uy0))))
1983.                       && goodpos(u.ux0, u.uy0, mtmp, GP_ALLOW_U));
1984.         /* if not displacing, try to attack; note that it might evade;
1985.            also, we don't attack tame or peaceful when safemon() */
1986.         if (!*displaceu) {
1987.             if (do_attack(mtmp))
1988.                 return TRUE;
1989.         }
1990.     }
1991.     return FALSE;
1992. }
1993. 
1994. /* force-fight iron bars with your weapon? */
1995. staticfn boolean
1996. domove_fight_ironbars(coordxy x, coordxy y)
1997. {
1998.     if (svc.context.forcefight && levl[x][y].typ == IRONBARS && uwep) {
1999.         struct obj *obj = uwep;
2000.         unsigned breakflags = (BRK_BY_HERO | BRK_FROM_INV | BRK_MELEE);
2001. 
2002.         if (breaktest(obj)) {
2003.             if (obj->quan > 1L)
2004.                 obj = splitobj(obj, 1L);
2005.             else
2006.                 setuwep((struct obj *) 0);
2007.             freeinv(obj);
2008.             breakflags |= BRK_KNOWN2BREAK;
2009.         } else {
2010.             breakflags |= BRK_KNOWN2NOTBREAK;
2011.         }
2012. 
2013.         hit_bars(&obj, u.ux, u.uy, x, y, breakflags);
2014.         return TRUE;
2015.     }
2016.     return FALSE;
2017. }
2018. 
2019. /* force-fight a spider web with your weapon */
2020. staticfn boolean
2021. domove_fight_web(coordxy x, coordxy y)
2022. {
2023.     struct trap *trap = t_at(x, y);
2024. 
2025.     if (svc.context.forcefight && trap && trap->ttyp == WEB && trap->tseen) {
2026.         int wtype = uwep_skill_type(),
2027.             /* minus_2: restricted or unskilled: -1, basic: 0, skilled: 1,
2028.                expert: 2, master: 3, grandmaster: 4 */
2029.             wskill_minus_2 = max(P_SKILL(wtype), P_UNSKILLED) - 2,
2030.             /* higher value is worse for player; for weaponless, adjust the
2031.                chance to succeed rather than maybe make two tries */
2032.             roll = rn2(uwep ? 20 : (45 - 5 * wskill_minus_2));
2033. 
2034.         if (uwep && (u_wield_art(ART_STING)
2035.                      || (uwep->oartifact && attacks(AD_FIRE, uwep)))) {
2036.             /* guaranteed success */
2037.             pline("%s %s through the web!", bare_artifactname(uwep),
2038.                   u_wield_art(ART_STING) ? "cuts" : "burns");
2039. 
2040.         /* is_blade() includes daggers (which are classified as PIERCE)
2041.            but doesn't include axes and slashing polearms */
2042.         } else if (uwep && !is_blade(uwep)
2043.                    && (!u.twoweap || !is_blade(uswapwep))) {
2044.             char *uwepstr = 0, *scndstr = 0, uwepbuf[BUFSZ], scndbuf[BUFSZ];
2045.             boolean onewep;
2046. 
2047.             /* when dual wielding, second weapon will only be mentioned
2048.                if it has a different type description from primary */
2049.             Strcpy(uwepbuf, weapon_descr(uwep));
2050.             Strcpy(scndbuf, u.twoweap ? weapon_descr(uswapwep) : "");
2051.             onewep = !*scndbuf || !strcmp(uwepbuf, scndbuf);
2052.             if (!strcmpi(uwepbuf, "armor") || !strcmpi(uwepbuf, "food")
2053.                 || !strcmpi(uwepbuf, "venom")) { /* as-is */
2054.                 /* non-weapon item wielded, of a type where an() would
2055.                    result in weird phrasing; dual wield not possible */
2056.                 uwepstr = uwepbuf;
2057.             } else if (uwep->quan == 1L /* singular */
2058.                        /* unless secondary is suppressed due to same type */
2059.                        && !(u.twoweap && onewep)) {
2060.                 uwepstr = an(uwepbuf);
2061.             } else { /* plural */
2062.                 uwepstr = makeplural(uwepbuf);
2063.             }
2064.             if (!onewep) {
2065.                 assert(uswapwep != NULL);
2066.                 scndstr = (uswapwep->quan == 1L) ? an(scndbuf)
2067.                                                  : makeplural(scndbuf);
2068.             }
2069.             You_cant("cut a web with %s%s%s!", uwepstr,
2070.                      !onewep ? " or " : "", !onewep ? scndstr : "");
2071.             return TRUE;
2072. 
2073.         /* weapon is ok; check whether hit is successful */
2074.         } else if (roll > (acurrstr() - 2 /* 1..19 */
2075.                            /* for weaponless, 'roll' was adjusted above */
2076.                            + (uwep ? uwep->spe + wskill_minus_2 : 0))) {
2077.             /* TODO: add failures, maybe make an occupation? */
2078.             You("%s ineffectually at some of the strands.",
2079.                 uwep ? "hack" : "thrash");
2080.             return TRUE;
2081. 
2082.         /* hit has succeeded */
2083.         } else {
2084.             You("%s through the web.", uwep ? "cut" : "punch");
2085.             /* doesn't break "never hit with a wielded weapon" conduct */
2086.             use_skill(wtype, 1);
2087.         }
2088. 
2089.         deltrap(trap);
2090.         newsym(x, y);
2091.         return TRUE;
2092.     }
2093.     return FALSE;
2094. }
2095. 
2096. /* maybe swap places with a pet? returns TRUE if swapped places */
2097. staticfn boolean
2098. domove_swap_with_pet(
2099.     struct monst *mtmp,
2100.     coordxy x, coordxy y)
2101. {
2102.     struct trap *trap;
2103.     /* if it turns out we can't actually move */
2104.     boolean didnt_move = FALSE;
2105.     boolean u_with_boulder = (sobj_at(BOULDER, u.ux, u.uy) != 0);
2106. 
2107.     /* seemimic/newsym should be done before moving hero, otherwise
2108.        the display code will draw the hero here before we possibly
2109.        cancel the swap below (we can ignore steed mx,my here) */
2110.     u.ux = u.ux0, u.uy = u.uy0;
2111.     mtmp->mundetected = 0;
2112.     if (M_AP_TYPE(mtmp))
2113.         seemimic(mtmp);
2114.     u.ux = mtmp->mx, u.uy = mtmp->my; /* resume swapping positions */
2115. 
2116.     trap = mtmp->mtrapped ? t_at(mtmp->mx, mtmp->my) : 0;
2117.     if (!trap)
2118.         mtmp->mtrapped = 0;
2119. 
2120.     if (mtmp->mtrapped && is_pit(trap->ttyp)
2121.         && sobj_at(BOULDER, trap->tx, trap->ty)) {
2122.         /* can't swap places with pet pinned in a pit by a boulder */
2123.         didnt_move = TRUE;
2124.     } else if (u.ux0 != x && u.uy0 != y && NODIAG(mtmp->data - mons)) {
2125.         /* can't swap places when pet can't move to your spot */
2126.         You("stop.  %s can't move diagonally.", YMonnam(mtmp));
2127.         didnt_move = TRUE;
2128.     } else if (u_with_boulder
2129.                && !(verysmall(mtmp->data)
2130.                     && (!mtmp->minvent || curr_mon_load(mtmp) <= 600))) {
2131.         /* can't swap places when pet won't fit there with the boulder */
2132.         You("stop.  %s won't fit into the same spot that you're at.",
2133.             YMonnam(mtmp));
2134.         didnt_move = TRUE;
2135.     } else if (u.ux0 != x && u.uy0 != y && bad_rock(mtmp->data, x, u.uy0)
2136.                && bad_rock(mtmp->data, u.ux0, y)
2137.                && (bigmonst(mtmp->data) || (curr_mon_load(mtmp) > 600))) {
2138.         /* can't swap places when pet won't fit thru the opening */
2139.         You("stop.  %s won't fit through.", YMonnam(mtmp));
2140.         didnt_move = TRUE;
2141.     } else if (mtmp->mpeaceful && mtmp->mtrapped) {
2142.         /* all mtame are also mpeaceful, so this affects pets too */
2143.         assert(trap != NULL); /* implied by mtrapped */
2144.         const char *what = trapname(trap->ttyp, FALSE), *which = "that ";
2145.         char anbuf[10];
2146. 
2147.         if (!trap->tseen) {
2148.             feeltrap(trap); /* show on map once mtmp is out of the way */
2149.             which = just_an(anbuf, what); /* "a " or "an " */
2150.         }
2151.         You("stop.  %s can't move out of %s%s.", YMonnam(mtmp), which, what);
2152.         (void) handle_tip(TIP_UNTRAP_MON);
2153.         didnt_move = TRUE;
2154.     } else if (mtmp->mpeaceful
2155.                && (!goodpos(u.ux0, u.uy0, mtmp, 0)
2156.                    || t_at(u.ux0, u.uy0) != NULL
2157.                    || mundisplaceable(mtmp))) {
2158.         /* displacing peaceful into unsafe or trapped space, or trying to
2159.            displace quest leader, Oracle, shk, priest, or vault guard */
2160.         You("stop.  %s doesn't want to swap places.", YMonnam(mtmp));
2161.         didnt_move = TRUE;
2162.     } else {
2163.         mtmp->mtrapped = 0;
2164.         remove_monster(x, y);
2165.         place_monster(mtmp, u.ux0, u.uy0);
2166.         newsym(x, y);
2167.         newsym(u.ux0, u.uy0);
2168. 
2169.         You("%s %s.", mtmp->mpeaceful ? "swap places with" : "frighten",
2170.             x_monnam(mtmp,
2171.                      mtmp->mtame ? ARTICLE_YOUR
2172.                      : (!has_mgivenname(mtmp)
2173.                         && !type_is_pname(mtmp->data)) ? ARTICLE_THE
2174.                      : ARTICLE_NONE,
2175.                      (mtmp->mpeaceful && !mtmp->mtame) ? "peaceful" : 0,
2176.                      has_mgivenname(mtmp) ? SUPPRESS_SADDLE : 0, FALSE));
2177. 
2178.         /* check for displacing it into pools and traps */
2179.         switch (minliquid(mtmp) ? Trap_Killed_Mon
2180.                 : mintrap(mtmp, NO_TRAP_FLAGS)) {
2181.         case Trap_Effect_Finished:
2182.             break;
2183.         case Trap_Caught_Mon: /* trapped */
2184.         case Trap_Moved_Mon: /* changed levels */
2185.             /* there's already been a trap message, reinforce it */
2186.             abuse_dog(mtmp);
2187.             adjalign(-3);
2188.             break;
2189.         case Trap_Killed_Mon:
2190.             /* drowned or died...
2191.              * you killed your pet by direct action, so get experience
2192.              * and possibly penalties;
2193.              * we want the level gain message, if it happens, to occur
2194.              * before the guilt message below
2195.              */
2196.             {
2197.                 /* minliquid() and mintrap() call mondead() rather than
2198.                    killed() so we duplicate some of the latter here */
2199.                 int tmp, mndx;
2200. 
2201.                 if (!u.uconduct.killer++)
2202.                     livelog_printf(LL_CONDUCT, "killed for the first time");
2203.                 mndx = monsndx(mtmp->data);
2204.                 tmp = experience(mtmp, (int) svm.mvitals[mndx].died);
2205.                 more_experienced(tmp, 0);
2206.                 newexplevel(); /* will decide if you go up */
2207.             }
2208.             /* That's no way to treat a pet!  Your god gets angry.
2209.              *
2210.              * [This has always been pretty iffy.  Why does your
2211.              * patron deity care at all, let alone enough to get mad?]
2212.              */
2213.             if (rn2(4)) {
2214.                 You_feel("guilty about losing your pet like this.");
2215.                 u.ugangr++;
2216.                 adjalign(-15);
2217.             }
2218.             break;
2219.         default:
2220.             impossible("that's strange, unknown mintrap result!");
2221.             break;
2222.         }
2223.     }
2224.     return !didnt_move;
2225. }
2226. 
2227. /* force-fight (x,y) which doesn't have anything to fight */
2228. staticfn boolean
2229. domove_fight_empty(coordxy x, coordxy y)
2230. {
2231.     static const char unknown_obstacle[] = "an unknown obstacle";
2232.     boolean off_edge = !isok(x, y);
2233.     int glyph = !off_edge ? glyph_at(x, y) : GLYPH_UNEXPLORED;
2234. 
2235.     if (off_edge)
2236.         x = 0, y = 1; /* for forcefight against the edge of the map; make
2237.                        * sure 'bad' coordinates are within array bounds in
2238.                        * case a bounds check gets overlooked; avoid <0,0>
2239.                        * because m_at() might find a vault guard there */
2240. 
2241.     /* specifying 'F' with no monster wastes a turn */
2242.     if (svc.context.forcefight
2243.         /* remembered an 'I' && didn't use a move command */
2244.         || (glyph_is_invisible(glyph) && !m_at(x, y)
2245.             && !svc.context.nopick)) {
2246.         struct obj *boulder = 0;
2247.         boolean explo = (Upolyd && attacktype(gy.youmonst.data, AT_EXPL)),
2248.                 solid = (off_edge || (!accessible(x, y)
2249.                                       || IS_FURNITURE(levl[x][y].typ)));
2250.         char buf[BUFSZ];
2251. 
2252.         if (off_edge) {
2253.             /* treat as if solid rock, even on planes' levels */
2254.             Strcpy(buf, unknown_obstacle);
2255.             goto futile;
2256.         }
2257. 
2258.         if (!Underwater) {
2259.             boulder = sobj_at(BOULDER, x, y);
2260.             /* if a statue is displayed at the target location,
2261.                player is attempting to attack it [and boulder
2262.                handling below is suitable for handling that] */
2263.             if (glyph_is_statue(glyph)
2264.                 || (Hallucination && glyph_is_monster(glyph)))
2265.                 boulder = sobj_at(STATUE, x, y);
2266. 
2267.             /* force fight at boulder/statue or wall/door while wielding
2268.                pick:  start digging to break the boulder or wall */
2269.             if (svc.context.forcefight
2270.                 /* can we dig? */
2271.                 && uwep && dig_typ(uwep, x, y)
2272.                 /* should we dig? */
2273.                 && !glyph_is_invisible(glyph) && !glyph_is_monster(glyph)) {
2274.                 (void) use_pick_axe2(uwep);
2275.                 return TRUE;
2276.             }
2277.         }
2278. 
2279.         /* about to become known empty -- remove 'I' if present */
2280.         unmap_object(x, y);
2281.         if (boulder)
2282.             map_object(boulder, TRUE);
2283.         newsym(x, y);
2284.         glyph = glyph_at(x, y); /* might have just changed */
2285.         nhUse(glyph);
2286. 
2287.         if (boulder) {
2288.             Strcpy(buf, ansimpleoname(boulder));
2289.         } else if (Underwater && !is_pool(x, y)) {
2290.             /* Underwater, targeting non-water; the map just shows blank
2291.                because you don't see remembered terrain while underwater;
2292.                although the hero can attack an adjacent monster this way,
2293.                assume he can't reach out far enough to distinguish terrain */
2294.             Sprintf(buf, "%s",
2295.                     (Is_waterlevel(&u.uz) && levl[x][y].typ == AIR)
2296.                          ? "an air bubble"
2297.                          : "nothing");
2298.         } else if (solid) {
2299.             /* glyph might indicate unseen terrain if hero is blind;
2300.                unlike searching, this won't reveal what that terrain is;
2301.                5.0: used to say "solid rock" for STONE, but that made it be
2302.                different from unmapped walls outside of rooms (and was wrong
2303.                on arboreal levels) */
2304.             if (levl[x][y].seenv || IS_STWALL(levl[x][y].typ)
2305.                 || levl[x][y].typ == SDOOR || levl[x][y].typ == SCORR) {
2306.                 glyph = back_to_glyph(x, y);
2307.                 Strcpy(buf, the(defsyms[glyph_to_cmap(glyph)].explanation));
2308.             } else {
2309.                 Strcpy(buf, unknown_obstacle);
2310.             }
2311.             /* note: 'solid' is misleadingly named and catches pools
2312.                of water and lava as well as rock and walls;
2313.                5.0: furniture too */
2314.         } else {
2315.             Strcpy(buf, "thin air");
2316.         }
2317. 
2318.  futile:
2319.         You("%s%s %s.",
2320.             !(boulder || solid) ? "" : !explo ? "harmlessly " : "futilely ",
2321.             explo ? "explode at" : "attack", buf);
2322. 
2323.         nomul(0);
2324.         if (explo) {
2325.             struct attack *attk
2326.                        = attacktype_fordmg(gy.youmonst.data, AT_EXPL, AD_ANY);
2327. 
2328.             /* no monster has been attacked so we have bypassed explum() */
2329.             wake_nearto(u.ux, u.uy, 7 * 7); /* same radius as explum() */
2330.             if (attk)
2331.                 explum((struct monst *) 0, attk);
2332.             u.mh = -1; /* dead in the current form */
2333.             rehumanize();
2334.         }
2335.         return TRUE;
2336.     }
2337.     return FALSE;
2338. }
2339. 
2340. /* does the plane of air disturb movement? */
2341. staticfn boolean
2342. air_turbulence(void)
2343. {
2344.     if (Is_airlevel(&u.uz) && rn2(4) && !Levitation && !Flying) {
2345.         switch (rn2(3)) {
2346.         case 0:
2347.             You("tumble in place.");
2348.             exercise(A_DEX, FALSE);
2349.             break;
2350.         case 1:
2351.             You_cant("control your movements very well.");
2352.             break;
2353.         case 2:
2354.             pline("It's hard to walk in thin air.");
2355.             exercise(A_DEX, TRUE);
2356.             break;
2357.         }
2358.         return TRUE;
2359.     }
2360.     return FALSE;
2361. }
2362. 
2363. /* does water disturb the movement? */
2364. staticfn boolean
2365. water_turbulence(coordxy *x, coordxy *y)
2366. {
2367.     if (u.uinwater) {
2368.         int wtcap;
2369.         int wtmod = (Swimming ? MOD_ENCUMBER : SLT_ENCUMBER);
2370. 
2371.         water_friction();
2372.         if (!u.dx && !u.dy) {
2373.             nomul(0);
2374.             return TRUE;
2375.         }
2376.         *x = u.ux + u.dx;
2377.         *y = u.uy + u.dy;
2378. 
2379.         /* are we trying to move out of water while carrying too much? */
2380.         if (isok(*x, *y) && !is_pool(*x, *y) && !Is_waterlevel(&u.uz)
2381.             && (wtcap = near_capacity()) > wtmod) {
2382.             /* when escaping from drowning you need to be unencumbered
2383.                in order to crawl out of water, but when not drowning,
2384.                doing so while encumbered is feasible; if in an aquatic
2385.                form, stressed or less is allowed; otherwise (magical
2386.                breathing), only burdened is allowed */
2387.             You("are carrying too much to climb out of the water.");
2388.             nomul(0);
2389.             return TRUE;
2390.         }
2391.     }
2392.     return FALSE;
2393. }
2394. 
2395. staticfn void
2396. slippery_ice_fumbling(void)
2397. {
2398.     boolean on_ice = !Levitation && is_ice(u.ux, u.uy);
2399.     struct monst *iceskater = u.usteed ? u.usteed : &gy.youmonst;
2400. 
2401.     if (on_ice) {
2402.         if ((uarmf && objdescr_is(uarmf, "snow boots"))
2403.             || resists_cold(iceskater) || Flying
2404.             || is_floater(iceskater->data) || is_clinger(iceskater->data)
2405.             || is_whirly(iceskater->data)) {
2406.             on_ice = FALSE;
2407.         } else if (!rn2(Cold_resistance ? 3 : 2)) {
2408.             HFumbling |= FROMOUTSIDE;
2409.             HFumbling &= ~TIMEOUT;
2410.             HFumbling += 1; /* slip on next move */
2411.         }
2412.     }
2413.     if (!on_ice && (HFumbling & FROMOUTSIDE))
2414.         HFumbling &= ~FROMOUTSIDE;
2415. }
2416. 
2417. boolean
2418. u_maybe_impaired(void)
2419. {
2420.     return (Stunned || (Confusion && !rn2(5)));
2421. }
2422. 
2423. /* change movement dir if impaired. return TRUE if can't move */
2424. staticfn boolean
2425. impaired_movement(coordxy *x, coordxy *y)
2426. {
2427.     if (u_maybe_impaired()) {
2428.         int tries = 0;
2429. 
2430.         do {
2431.             if (tries++ > 50) {
2432.                 nomul(0);
2433.                 return TRUE;
2434.             }
2435.             confdir(TRUE);
2436.             *x = u.ux + u.dx;
2437.             *y = u.uy + u.dy;
2438.         } while (!isok(*x, *y) || bad_rock(gy.youmonst.data, *x, *y));
2439.     }
2440.     return FALSE;
2441. }
2442. 
2443. staticfn boolean
2444. avoid_moving_on_trap(coordxy x, coordxy y, boolean msg)
2445. {
2446.     struct trap *trap;
2447. 
2448.     if ((trap = t_at(x, y)) && trap->tseen
2449.         /* the vibrating square is implemented as a trap but treated as if
2450.            it were a type of terrain */
2451.         && trap->ttyp != VIBRATING_SQUARE) {
2452.         if (msg && flags.mention_walls) {
2453.             set_msg_xy(x, y);
2454.             You("stop in front of %s.",
2455.                 an(trapname(trap->ttyp, FALSE)));
2456.         }
2457.         return TRUE;
2458.     }
2459.     return FALSE;
2460. }
2461. 
2462. staticfn boolean
2463. avoid_moving_on_liquid(
2464.     coordxy x, coordxy y,
2465.     boolean msg)
2466. {
2467.     boolean in_air = (Levitation || Flying);
2468. 
2469.     /* don't stop if you're not on a transition between terrain types... */
2470.     if ((levl[x][y].typ == levl[u.ux][u.uy].typ
2471.          /* or you are using shift-dir running and the transition isn't
2472.             dangerous... */
2473.          || (svc.context.run < 2 && (!is_lava(x, y) || in_air))
2474.          || svc.context.travel)
2475.         /* and you know you won't fall in */
2476.         && (in_air || Known_lwalking || (is_pool(x, y) && Known_wwalking))
2477.         && !(IS_WATERWALL(levl[x][y].typ) || levl[x][y].typ == LAVAWALL)) {
2478.         /* XXX: should send 'is_clinger(gy.youmonst.data)' here once clinging
2479.            polyforms are allowed to move over water */
2480.         return FALSE; /* liquid is safe to traverse */
2481.     } else if (is_pool_or_lava(x, y) && levl[x][y].seenv) {
2482.         if (msg && flags.mention_walls) {
2483.             set_msg_xy(x, y);
2484.             You("stop at the edge of the %s.",
2485.                 hliquid(is_pool(x,y) ? "water" : "lava"));
2486.         }
2487.         return TRUE;
2488.     }
2489.     return FALSE;
2490. }
2491. 
2492. /* when running/rushing, avoid stepping on a known trap or pool of liquid.
2493.    returns TRUE if avoided. */
2494. staticfn boolean
2495. avoid_running_into_trap_or_liquid(coordxy x, coordxy y)
2496. {
2497.     boolean would_stop = (svc.context.run >= 2);
2498.     if (!svc.context.run)
2499.         return FALSE;
2500. 
2501.     if (avoid_moving_on_trap(x,y, would_stop)
2502.         || (Blind && avoid_moving_on_liquid(x,y, would_stop))) {
2503.         nomul(0);
2504.         if (would_stop)
2505.             svc.context.move = 0;
2506.         return would_stop;
2507.     }
2508.     return FALSE;
2509. }
2510. 
2511. /* if paranoid_confirm:Trap is enabled, check whether the next step forward
2512.    needs player confirmation due to visible region or discovered trap;
2513.    result: True => stop moving, False => proceed */
2514. staticfn boolean
2515. avoid_trap_andor_region(coordxy x, coordxy y)
2516. {
2517.     char qbuf[QBUFSZ];
2518.     NhRegion *newreg, *oldreg;
2519.     struct trap *trap = NULL;
2520. 
2521.     /* treat entering a visible gas cloud region like entering a trap;
2522.        there could be a known trap as well as a region at the target spot;
2523.        if so, ask about entring the region first; even though this could
2524.        lead to two consecutive confirmation prompts, the situation seems
2525.        to be too uncommon to warrant a separate case with combined
2526.        trap+region confirmation */
2527.     if (ParanoidTrap && !Blind && !Stunned && !Confusion && !Hallucination
2528.         /* skip if player used 'm' prefix or is moving recklessly */
2529.         && (!svc.context.nopick || svc.context.run)
2530.         /* check for region(s) */
2531.         && (newreg = visible_region_at(x, y)) != 0
2532.         && ((oldreg = visible_region_at(u.ux, u.uy)) == 0
2533.             /* if moving from one region into another, only ask for
2534.                confirmation if the one potentially being entered inflicts
2535.                damage (poison gas) and the one being exited doesn't (vapor) */
2536.             || (reg_damg(newreg) > 0 && reg_damg(oldreg) == 0))
2537.         /* check whether attempted move will be viable */
2538.         && test_move(u.ux, u.uy, u.dx, u.dy, TEST_MOVE)
2539.         /* we don't override confirmation for poison resistance since the
2540.            region also hinders hero's vision even if/when no damage is done */
2541.     ) {
2542.         Snprintf(qbuf, sizeof qbuf, "%s into that %s cloud?",
2543.                  u_locomotion("step"),
2544.                  (reg_damg(newreg) > 0) ? "poison gas" : "vapor");
2545.         if (!paranoid_query(ParanoidConfirm, upstart(qbuf))) {
2546.             nomul(0);
2547.             svc.context.move = 0;
2548.             return TRUE;
2549.         }
2550.     }
2551. 
2552.     /* maybe ask player for confirmation before walking into known trap */
2553.     if (ParanoidTrap && !Stunned && !Confusion
2554.         /* skip if player used 'm' prefix or is moving recklessly */
2555.         && (!svc.context.nopick || svc.context.run)
2556.         /* check for discovered trap */
2557.         && (trap = t_at(x, y)) != 0 && trap->tseen
2558.         /* check whether attempted move will be viable */
2559.         && test_move(u.ux, u.uy, u.dx, u.dy, TEST_MOVE)
2560.         /* override confirmation if the trap is harmless to the hero */
2561.         && (immune_to_trap(&gy.youmonst, trap->ttyp) != TRAP_CLEARLY_IMMUNE
2562.             /* Hallucination: all traps still show as ^, but the
2563.                hero can't tell what they are, so treat as dangerous */
2564.             || Hallucination)) {
2565.         int traptype = (Hallucination ? rnd(TRAPNUM - 1) : (int) trap->ttyp);
2566.         boolean into = into_vs_onto(traptype);
2567. 
2568.         Snprintf(qbuf, sizeof qbuf, "Really %s %s that %s?",
2569.                  u_locomotion("step"), into ? "into" : "onto",
2570.                  defsyms[trap_to_defsym(traptype)].explanation);
2571.         /* handled like paranoid_confirm:pray; when paranoid_confirm:trap
2572.            isn't set, don't ask at all but if it is set (checked above),
2573.            ask via y/n if parnoid_confirm:confirm isn't also set or via
2574.            yes/no if it is */
2575.         if (!paranoid_query(ParanoidConfirm, qbuf)) {
2576.             nomul(0);
2577.             svc.context.move = 0;
2578.             return TRUE;
2579.         }
2580.     }
2581.     return FALSE;
2582. }
2583. 
2584. /* trying to move out-of-bounds? */
2585. staticfn boolean
2586. move_out_of_bounds(coordxy x, coordxy y)
2587. {
2588.     if (!isok(x, y)) {
2589.         if (svc.context.forcefight)
2590.             return domove_fight_empty(x, y);
2591. 
2592.         if (flags.mention_walls) {
2593.             coordxy dx = u.dx, dy = u.dy;
2594. 
2595.             if (dx && dy) { /* diagonal */
2596.                 /* only as far as possible diagonally if in very
2597.                    corner; otherwise just report whichever of the
2598.                    cardinal directions has reached its limit */
2599.                 if (isok(x, u.uy))
2600.                     dx = 0;
2601.                 else if (isok(u.ux, y))
2602.                     dy = 0;
2603.             }
2604.             You("have already gone as far %s as possible.",
2605.                 directionname(xytodir(dx, dy)));
2606.         }
2607.         nomul(0);
2608.         svc.context.move = 0;
2609.         return TRUE;
2610.     }
2611.     return FALSE;
2612. }
2613. 
2614. /* carrying too much to be able to move? */
2615. staticfn boolean
2616. carrying_too_much(void)
2617. {
2618.     int wtcap;
2619. 
2620.     if (((wtcap = near_capacity()) >= OVERLOADED
2621.          || (wtcap > SLT_ENCUMBER
2622.              && (Upolyd ? (u.mh < 5 && u.mh != u.mhmax)
2623.                         : (u.uhp < 10 && u.uhp != u.uhpmax))))
2624.         && !Is_airlevel(&u.uz)) {
2625.         if (wtcap < OVERLOADED) {
2626.             You("don't have enough stamina to move.");
2627.             exercise(A_CON, FALSE);
2628.         } else
2629.             You("collapse under your load.");
2630.         nomul(0);
2631.         return TRUE;
2632.     }
2633.     return FALSE;
2634. }
2635. 
2636. /* try to pull free from sticking monster, or you release a monster
2637.    you're sticking to. returns TRUE if you lose your movement. */
2638. staticfn boolean
2639. escape_from_sticky_mon(coordxy x, coordxy y)
2640. {
2641.     if (u.ustuck && (x != u.ustuck->mx || y != u.ustuck->my)) {
2642.         struct monst *mtmp;
2643. 
2644.         if (!m_next2u(u.ustuck)) {
2645.             /* perhaps it fled (or was teleported or ... ) */
2646.             set_ustuck((struct monst *) 0);
2647.         } else if (sticks(gy.youmonst.data)) {
2648.             /* When polymorphed into a sticking monster,
2649.              * u.ustuck means it's stuck to you, not you to it.
2650.              */
2651.             mtmp = u.ustuck;
2652.             set_ustuck((struct monst *) 0);
2653.             You("release %s.", y_monnam(mtmp));
2654.         } else {
2655.             /* If holder is asleep or paralyzed:
2656.              *      37.5% chance of getting away,
2657.              *      12.5% chance of waking/releasing it;
2658.              * otherwise:
2659.              *       7.5% chance of getting away.
2660.              * [strength ought to be a factor]
2661.              * If holder is tame and there is no conflict,
2662.              * guaranteed escape.
2663.              */
2664.             switch (rn2(!u.ustuck->mcanmove ? 8 : 40)) {
2665.             case 3:
2666.                 if (!u.ustuck->mcanmove) {
2667.                     /* it's free to move on next turn */
2668.                     u.ustuck->mfrozen = 1;
2669.                     u.ustuck->msleeping = 0;
2670.                 }
2671.                 FALLTHROUGH;
2672.                 /*FALLTHRU*/
2673.             default:
2674.                 if (Conflict || u.ustuck->mconf || !u.ustuck->mtame) {
2675.                     You("cannot escape from %s!", y_monnam(u.ustuck));
2676.                     nomul(0);
2677.                     return TRUE;
2678.                 }
2679.                 FALLTHROUGH;
2680.                 /*FALLTHRU*/
2681.             case 0:
2682.             case 1:
2683.             case 2:
2684.                 mtmp = u.ustuck;
2685.                 set_ustuck((struct monst *) 0);
2686.                 You("pull free from %s.", y_monnam(mtmp));
2687.                 break;
2688.             }
2689.         }
2690.     }
2691.     return FALSE;
2692. }
2693. 
2694. void
2695. domove(void)
2696. {
2697.         coordxy ux1 = u.ux, uy1 = u.uy;
2698. 
2699.         gd.domove_succeeded = 0L;
2700.         domove_core();
2701.         /* gd.domove_succeeded is available to make assessments now */
2702.         if ((gd.domove_succeeded & (DOMOVE_RUSH | DOMOVE_WALK)) != 0) {
2703.             maybe_smudge_engr(ux1, uy1, u.ux, u.uy);
2704.             maybe_adjust_hero_bubble();
2705.         }
2706.         gd.domove_attempting = 0L;
2707. 
2708.         gk.kickedloc.x = 0, gk.kickedloc.y = 0;
2709. }
2710. 
2711. staticfn void
2712. domove_core(void)
2713. {
2714.     struct monst *mtmp;
2715.     struct rm *tmpr;
2716.     coordxy x, y;
2717.     int glyph;
2718.     coordxy chainx = 0, chainy = 0,
2719.             ballx = 0, bally = 0;       /* ball&chain new positions */
2720.     int bc_control = 0;                 /* control for ball&chain */
2721.     boolean cause_delay = FALSE,        /* dragging ball will skip a move */
2722.             displaceu = FALSE;          /* involuntary swap */
2723. 
2724.     if (svc.context.travel) {
2725.         if (!findtravelpath(TRAVP_TRAVEL))
2726.             (void) findtravelpath(TRAVP_GUESS);
2727.         svc.context.travel1 = 0;
2728.     }
2729. 
2730.     if (carrying_too_much())
2731.         return;
2732. 
2733.     if (u.uswallow) {
2734.         u.dx = u.dy = 0;
2735.         x = u.ustuck->mx, y = u.ustuck->my;
2736.         u_on_newpos(x, y); /* set u.ux,uy and handle CLIPPING */
2737.         mtmp = u.ustuck;
2738.     } else {
2739.         if (air_turbulence())
2740.             return;
2741. 
2742.         /* check slippery ice */
2743.         slippery_ice_fumbling();
2744. 
2745.         x = u.ux + u.dx;
2746.         y = u.uy + u.dy;
2747.         if (impaired_movement(&x, &y))
2748.             return;
2749. 
2750.         /* turbulence might alter your actual destination */
2751.         if (water_turbulence(&x, &y))
2752.             return;
2753. 
2754.         if (move_out_of_bounds(x, y))
2755.             return;
2756. 
2757.         if (avoid_running_into_trap_or_liquid(x, y))
2758.             return;
2759. 
2760.         if (escape_from_sticky_mon(x, y))
2761.             return;
2762. 
2763.         mtmp = m_at(x, y);
2764.         if (mtmp && !is_safemon(mtmp)) {
2765.             /* Don't attack if you're running, and can see it */
2766.             /* It's fine to displace pets, though */
2767.             /* We should never get here if forcefight */
2768.             if (svc.context.run && ((!Blind && mon_visible(mtmp)
2769.                                  && ((M_AP_TYPE(mtmp) != M_AP_FURNITURE
2770.                                       && M_AP_TYPE(mtmp) != M_AP_OBJECT)
2771.                                      || Protection_from_shape_changers))
2772.                                 || sensemon(mtmp))) {
2773.                 nomul(0);
2774.                 svc.context.move = 0;
2775.                 return;
2776.             }
2777.         }
2778.     }
2779. 
2780.     u.ux0 = u.ux;
2781.     u.uy0 = u.uy;
2782.     gb.bhitpos.x = x;
2783.     gb.bhitpos.y = y;
2784.     tmpr = &levl[x][y];
2785.     glyph = glyph_at(x, y);
2786. 
2787.     if (mtmp) {
2788.         /* don't stop travel when displacing pets; if the
2789.            displace fails for some reason, do_attack() in uhitm.c
2790.            will stop travel rather than domove */
2791.         if (!is_safemon(mtmp) || svc.context.forcefight)
2792.             nomul(0);
2793. 
2794.         if (domove_bump_mon(mtmp, glyph))
2795.             return;
2796. 
2797.         /* attack monster */
2798.         if (domove_attackmon_at(mtmp, x, y, &displaceu))
2799.             return;
2800.     }
2801. 
2802.     if (!displaceu) {
2803. 
2804.         if (domove_fight_ironbars(x, y))
2805.             return;
2806. 
2807.         if (domove_fight_web(x, y))
2808.             return;
2809. 
2810.         if (domove_fight_empty(x, y))
2811.             return;
2812. 
2813.         (void) unmap_invisible(x, y);
2814.         /* not attacking an animal, so we try to move */
2815.         if ((u.dx || u.dy) && u.usteed && stucksteed(FALSE)) {
2816.             nomul(0);
2817.             return;
2818.         }
2819. 
2820.         if (u_rooted())
2821.             return;
2822. 
2823.         /* handling for paranoid_confirm:Trap which doubles as
2824.            paranoid_confirm:Region */
2825.         if (ParanoidTrap) {
2826.             if (avoid_trap_andor_region(x, y))
2827.                 return;
2828.         }
2829. 
2830.         if (u.utrap) { /* when u.utrap is True, displaceu is False */
2831.             boolean moved = trapmove(x, y, (struct trap *) NULL);
2832. 
2833.             if (!u.utrap) {
2834.                 disp.botl = TRUE;
2835.                 reset_utrap(TRUE); /* might resume levitation or flight */
2836.             }
2837.             /* might not have escaped, or did escape but remain in the same
2838.                spot */
2839.             if (!moved)
2840.                 return;
2841.         }
2842. 
2843.         if (!test_move(u.ux, u.uy, x - u.ux, y - u.uy, DO_MOVE)) {
2844.             if (!svc.context.door_opened) {
2845.                 svc.context.move = 0;
2846.                 nomul(0);
2847.             }
2848.             return;
2849.         }
2850. 
2851.         /* Is it dangerous to swim in water or lava? */
2852.         if (swim_move_danger(x, y)) {
2853.             svc.context.move = 0;
2854.             nomul(0);
2855.             return;
2856.         }
2857. 
2858.     } /* !dislacedu */
2859. 
2860.     /* Move ball and chain.  */
2861.     if (Punished)
2862.         if (!drag_ball(x, y, &bc_control, &ballx, &bally, &chainx, &chainy,
2863.                        &cause_delay, TRUE))
2864.             return;
2865. 
2866.     /* Check regions entering/leaving */
2867.     if (!in_out_region(x, y))
2868.         return;
2869. 
2870.     mtmp = m_at(x, y);
2871.     /* mtmp can be null at this point */
2872. 
2873.     /* tentatively move the hero plus steed; leave CLIPPING til later */
2874.     u.ux += u.dx;
2875.     u.uy += u.dy;
2876. 
2877.     m_postmove_effect(&gy.youmonst);
2878. 
2879.     if (u.usteed) {
2880.         u.usteed->mx = u.ux;
2881.         u.usteed->my = u.uy;
2882.         /* [if move attempt ends up being blocked, should training count?] */
2883.         exercise_steed(); /* train riding skill */
2884.     }
2885. 
2886.     if (mtmp) {
2887.         if (displaceu) {
2888.             boolean noticed_it = (canspotmon(mtmp)
2889.                                   || glyph_is_invisible(glyph)
2890.                                   || glyph_is_warning(glyph));
2891. 
2892.             remove_monster(u.ux, u.uy);
2893.             place_monster(mtmp, u.ux0, u.uy0);
2894.             newsym(u.ux, u.uy);
2895.             newsym(u.ux0, u.uy0);
2896.             /* monst still knows where hero is */
2897.             mtmp->mux = u.ux, mtmp->muy = u.uy;
2898. 
2899.             pline("%s swaps places with you...",
2900.                   !noticed_it ? Something : YMonnam(mtmp));
2901.             if (!canspotmon(mtmp))
2902.                 map_invisible(u.ux0, u.uy0);
2903.             /* monster chose to swap places; hero doesn't get any credit
2904.                or blame if something bad happens to it */
2905.             svc.context.mon_moving = 1;
2906.             if (!minliquid(mtmp))
2907.                 (void) mintrap(mtmp, NO_TRAP_FLAGS);
2908.             svc.context.mon_moving = 0;
2909. 
2910.         /*
2911.          * If safepet at destination then move the pet to the hero's
2912.          * previous location using the same conditions as in do_attack().
2913.          * there are special extenuating circumstances:
2914.          * (1) if the pet dies then your god angers,
2915.          * (2) if the pet gets trapped then your god may disapprove.
2916.          *
2917.          * Ceiling-hiding pets are skipped by this section of code, to
2918.          * be caught by the normal falling-monster code.
2919.          */
2920.         } else if (is_safemon(mtmp)
2921.                    && !(is_hider(mtmp->data) && mtmp->mundetected)) {
2922.             if (!domove_swap_with_pet(mtmp, x, y)) {
2923.                 u.ux = u.ux0, u.uy = u.uy0; /* didn't move after all */
2924.                 /* could skip this since we're about to call u_on_newpos() */
2925.                 if (u.usteed)
2926.                     u.usteed->mx = u.ux, u.usteed->my = u.uy;
2927.             }
2928.         }
2929.     }  /* mtmp != NULL */
2930. 
2931.     /* tentative move above didn't handle CLIPPING, in case there was a
2932.        monster in the way and the move attempt ended up being blocked;
2933.        do a full re-position now, possibly back to where hero started */
2934.     u_on_newpos(u.ux, u.uy);
2935. 
2936.     reset_occupations();
2937.     if (svc.context.run) {
2938.         if (svc.context.run < 8)
2939.             if (IS_DOOR(tmpr->typ) || IS_OBSTRUCTED(tmpr->typ)
2940.                 || IS_FURNITURE(tmpr->typ))
2941.                 nomul(0);
2942.     }
2943. 
2944.     /* your tread on the ground may disturb the slumber of nearby zombies */
2945.     if (!Levitation && !Flying && !Stealth
2946.         && gy.youmonst.data->cwt >= (WT_ELF / 2))
2947.         disturb_buried_zombies(u.ux, u.uy);
2948. 
2949.     if (hides_under(gy.youmonst.data) || gy.youmonst.data->mlet == S_EEL
2950.         || u.dx || u.dy)
2951.         (void) hideunder(&gy.youmonst);
2952. 
2953.     /*
2954.      * Mimics (or whatever) become noticeable if they move and are
2955.      * imitating something that doesn't move.  We could extend this
2956.      * to non-moving monsters...
2957.      */
2958.     if ((u.dx || u.dy) && (U_AP_TYPE == M_AP_OBJECT
2959.                            || U_AP_TYPE == M_AP_FURNITURE))
2960.         gy.youmonst.m_ap_type = M_AP_NOTHING;
2961. 
2962.     check_leash(u.ux0, u.uy0);
2963. 
2964.     if (u.ux0 != u.ux || u.uy0 != u.uy) {
2965.         /* let caller know so that an evaluation may take place */
2966.         gd.domove_succeeded |=
2967.                 (gd.domove_attempting & (DOMOVE_RUSH | DOMOVE_WALK));
2968.         u.umoved = TRUE;
2969.         /* Clean old position -- vision_recalc() will print our new one. */
2970.         newsym(u.ux0, u.uy0);
2971.         /* Since the hero has moved, adjust what can be seen/unseen. */
2972.         vision_recalc(1); /* Do the work now in the recover time. */
2973.         invocation_message();
2974.     }
2975. 
2976.     if (Punished) /* put back ball and chain */
2977.         move_bc(0, bc_control, ballx, bally, chainx, chainy);
2978. 
2979.     if (u.umoved)
2980.         spoteffects(TRUE);
2981. 
2982.     /* delay next move because of ball dragging */
2983.     /* must come after we finished picking up, in spoteffects() */
2984.     if (cause_delay) {
2985.         nomul(-2);
2986.         gm.multi_reason = "dragging an iron ball";
2987.         gn.nomovemsg = "";
2988.     }
2989. 
2990.     runmode_delay_output();
2991. }
2992. 
2993. /* delay output based on value of runmode,
2994.    if hero is running or doing a multi-turn action */
2995. void
2996. runmode_delay_output(void)
2997. {
2998.     if ((svc.context.run || gm.multi) && flags.runmode != RUN_TPORT) {
2999.         /* for tport mode, don't display anything until we've stopped;
3000.            for normal (leap) mode, update display every 7th step
3001.            (relative to turn counter; ought to be to start of running);
3002.            for walk and crawl (visual debugging) modes, update the
3003.            display after every step */
3004.         if (flags.runmode != RUN_LEAP || !(svm.moves % 7L)) {
3005.             /* moveloop() suppresses time_botl when running */
3006.             disp.time_botl = flags.time;
3007.             curs_on_u();
3008.             nh_delay_output();
3009.             if (flags.runmode == RUN_CRAWL) {
3010.                 nh_delay_output();
3011.                 nh_delay_output();
3012.                 nh_delay_output();
3013.                 nh_delay_output();
3014.             }
3015.         }
3016.     }
3017. }
3018. 
3019. staticfn void
3020. maybe_smudge_engr(coordxy x1, coordxy y1, coordxy x2, coordxy y2)
3021. {
3022.     struct engr *ep;
3023. 
3024.     if (can_reach_floor(TRUE)) {
3025.         if ((ep = engr_at(x1, y1)) && ep->engr_type != HEADSTONE)
3026.             wipe_engr_at(x1, y1, rnd(5), FALSE);
3027.         if ((x2 != x1 || y2 != y1)
3028.                 && (ep = engr_at(x2, y2)) && ep->engr_type != HEADSTONE)
3029.             wipe_engr_at(x2, y2, rnd(5), FALSE);
3030.     }
3031. }
3032. 
3033. /* HP loss or passing out from overexerting yourself */
3034. void
3035. overexert_hp(void)
3036. {
3037.     int *hp = (!Upolyd ? &u.uhp : &u.mh);
3038. 
3039.     if (*hp > 1) {
3040.         *hp -= 1;
3041.         disp.botl = TRUE;
3042.     } else {
3043.         You("pass out from exertion!");
3044.         exercise(A_CON, FALSE);
3045.         fall_asleep(-10, FALSE);
3046.     }
3047. }
3048. 
3049. /* combat increases metabolism */
3050. boolean
3051. overexertion(void)
3052. {
3053.     /* this used to be part of domove() when moving to a monster's
3054.        position, but is now called by do_attack() so that it doesn't
3055.        execute if you decline to attack a peaceful monster */
3056.     gethungry();
3057.     if ((svm.moves % 3L) != 0L && near_capacity() >= HVY_ENCUMBER) {
3058.         overexert_hp();
3059.     }
3060.     return (boolean) (gm.multi < 0); /* might have fainted (forced to sleep) */
3061. }
3062. 
3063. void
3064. invocation_message(void)
3065. {
3066.     /* a special clue-msg when on the Invocation position */
3067.     if (invocation_pos(u.ux, u.uy) && !On_stairs(u.ux, u.uy)) {
3068.         char buf[BUFSZ];
3069.         struct obj *otmp = carrying(CANDELABRUM_OF_INVOCATION);
3070. 
3071.         nomul(0); /* stop running or travelling */
3072.         if (u.usteed)
3073.             Sprintf(buf, "beneath %s", y_monnam(u.usteed));
3074.         else if (Levitation || Flying)
3075.             Strcpy(buf, "beneath you");
3076.         else
3077.             Sprintf(buf, "under your %s", makeplural(body_part(FOOT)));
3078. 
3079.         You_feel("a strange vibration %s.", buf);
3080.         u.uevent.uvibrated = 1;
3081.         if (otmp && otmp->spe == 7 && otmp->lamplit)
3082.             pline("%s %s!", The(xname(otmp)),
3083.                   Blind ? "throbs palpably" : "glows with a strange light");
3084.     }
3085. }
3086. 
3087. /* for status: set up iflags.terrain_typ, an index into terrain_descrp[];
3088.    some types need fixing up  */
3089. void
3090. classify_terrain(void)
3091. {
3092.     struct rm *lev = &levl[u.ux][u.uy];
3093.     int typ = svl.lastseentyp[u.ux][u.uy]; /* lev->typ */
3094. 
3095.     /*
3096.      * If the terrain under the hero is different now from what it
3097.      * was on the previous check, bring iflags.terrain_typ up to date
3098.      * and request a status update.  Unless hero is running--then the
3099.      * update request will be suppressed.
3100.      */
3101. 
3102.     if (Underwater) {
3103.         typ = xSUBMERGED;
3104.     } else {
3105.         switch (typ) {
3106.         case STONE:
3107.             if (svl.level.flags.arboreal)
3108.                 typ = TREE;
3109.             break;
3110.         case CORR:
3111.         case ROOM:
3112.             /* this matches surface() but 'floor' is odd in many places */
3113.             typ = !Is_earthlevel(&u.uz) ? xFLOOR : xGROUND;
3114.             break;
3115.         case DOOR:
3116.             /* defaults to "doorway" (door-less or broken) */
3117.             if ((lev->doormask & D_ISOPEN) != 0)
3118.                 typ = xOPENDOOR;
3119.             else if ((lev->doormask & (D_CLOSED | D_LOCKED | D_TRAPPED)) != 0)
3120.                 typ = xSHUTDOOR;
3121.             break;
3122.         case DRAWBRIDGE_UP:
3123.             /* ICE, MOAT, LAVA, or 'STONE' (which ought to be 'room') */
3124.             typ = db_under_typ(lev->drawbridgemask);
3125.             if (typ == STONE || typ == ROOM)
3126.                 typ = xGROUND;
3127.             break;
3128.         case MOAT:
3129.             /* moat and swamp handling match waterbody_name()'s result */
3130.             if (Is_medusa_level(&u.uz))
3131.                 typ = xSEA;
3132.             else if (Is_juiblex_level(&u.uz))
3133.                 typ = xSWAMP;
3134.             break;
3135.         case WATER:
3136.             if (!Is_waterlevel(&u.uz))
3137.                 typ = xWATERWALL;
3138.             break;
3139. #if 0   /* don't bother -- Passes_walls for hero is rare, moving
3140.          * from one type of wall to another even rarer, and the
3141.          * cost of some extra once per move status updates is low */
3142.         case VWALL:
3143.         case HWALL:
3144.         case TLCORNER:
3145.         case TRCORNER:
3146.         case BLCORNER:
3147.         case BRCORNER:
3148.         case CROSSWALL:
3149.         case TUWALL:
3150.         case TDWALL:
3151.         case TLWALL:
3152.         case TRWALL:
3153.         case SDOOR: /* (note: lastseentyp[][] never yields SDOOR) */
3154.             /* any wall type would do, terrain_descr[] is "Wall" for all;
3155.                forcing just one avoids false 'changed' detection below if
3156.                hero with Passes_walls ability moves from one to another */
3157.             typ = VWALL;
3158.             break;
3159. #endif
3160.         default:
3161.             break;
3162.         }
3163.     }
3164. 
3165.     if (typ != iflags.terrain_typ) {
3166.         /* terrain at hero's spot is different */
3167.         iflags.terrain_typ = typ;
3168.         /* request a status update unless hero is running */
3169.         if (flags.terrainstatus && !svc.context.run)
3170.             disp.botl = TRUE;
3171.     }
3172. }
3173. 
3174. /* moving onto different terrain;
3175.    might be going into solid rock, inhibiting levitation or flight,
3176.    or coming back out of such, reinstating levitation/flying */
3177. void
3178. switch_terrain(void)
3179. {
3180.     struct rm *lev = &levl[u.ux][u.uy];
3181.     boolean blocklev = (IS_OBSTRUCTED(lev->typ) || closed_door(u.ux, u.uy)
3182.                         || IS_WATERWALL(lev->typ)
3183.                         || lev->typ == LAVAWALL),
3184.             was_levitating = !!Levitation, was_flying = !!Flying;
3185. 
3186.     if (blocklev) {
3187.         /* called from spoteffects(), stop levitating but skip float_down() */
3188.         if (Levitation)
3189.             You_cant("levitate in here.");
3190.         BLevitation |= FROMOUTSIDE;
3191.     } else if (BLevitation) {
3192.         BLevitation &= ~FROMOUTSIDE;
3193.         /* we're probably levitating now; if not, we must be chained
3194.            to a buried iron ball so get float_up() feedback for that */
3195.         if (Levitation || BLevitation)
3196.             float_up();
3197.     }
3198.     /* the same terrain that blocks levitation also blocks flight */
3199.     if (blocklev) {
3200.         if (Flying)
3201.             You_cant("fly in here.");
3202.         BFlying |= FROMOUTSIDE;
3203.     } else if (BFlying) {
3204.         BFlying &= ~FROMOUTSIDE;
3205.         float_vs_flight(); /* maybe toggle (BFlying & I_SPECIAL) */
3206.         /* [minor bug: we don't know whether this is beginning flight or
3207.            resuming it; that could be tracked so that this message could
3208.            be adjusted to "resume flying", but isn't worth the effort...] */
3209.         if (Flying)
3210.             You("start flying.");
3211.     }
3212.     if ((!!Levitation ^ was_levitating) || (!!Flying ^ was_flying))
3213.         disp.botl = TRUE; /* update Lev/Fly status condition */
3214. 
3215.     if (flags.terrainstatus)
3216.         classify_terrain();
3217. }
3218. 
3219. /* set or clear u.uinwater */
3220. void
3221. set_uinwater(int in_out)
3222. {
3223.     if (in_out != (int) u.uinwater) {
3224.         u.uinwater = in_out ? 1 : 0;
3225.         switch_terrain();
3226.     }
3227. }
3228. 
3229. /* extracted from spoteffects; called by spoteffects to check for entering or
3230.    leaving a pool of water/lava, and by moveloop to check for staying on one;
3231.    returns true to skip rest of spoteffects */
3232. boolean
3233. pooleffects(
3234.     boolean newspot) /* true if called by spoteffects */
3235. {
3236.     /* check for leaving water */
3237.     if (u.uinwater) {
3238.         boolean still_inwater = FALSE; /* assume we're getting out */
3239. 
3240.         if (!is_pool(u.ux, u.uy)) {
3241.             if (Is_waterlevel(&u.uz)) {
3242.                 You("pop into an air bubble.");
3243.                 iflags.last_msg = PLNMSG_BACK_ON_GROUND;
3244.             } else if (is_lava(u.ux, u.uy)) {
3245.                 You("leave the %s...", hliquid("water")); /* oops! */
3246.             } else {
3247.                 back_on_ground(FALSE);
3248.             }
3249.         } else if (Is_waterlevel(&u.uz)) {
3250.             still_inwater = TRUE;
3251.         } else if (Levitation) {
3252.             You("pop out of the %s like a cork!", hliquid("water"));
3253.         } else if (Flying) {
3254.             You("fly out of the %s.", hliquid("water"));
3255.         } else if (Wwalking) {
3256.             You("slowly rise above the surface.");
3257.         } else {
3258.             still_inwater = TRUE;
3259.         }
3260.         if (!still_inwater) {
3261.             boolean was_underwater = (Underwater && !Is_waterlevel(&u.uz));
3262. 
3263.             set_uinwater(0); /* u.uinwater = 0; leave the water */
3264.             if (was_underwater) { /* restore vision */
3265.                 docrt();
3266.                 gv.vision_full_recalc = 1;
3267.             }
3268.         }
3269.     }
3270. 
3271.     /* check for entering water or lava */
3272.     if (!u.ustuck && !Levitation && !Flying && is_pool_or_lava(u.ux, u.uy)) {
3273.         if (u.usteed && !grounded(u.usteed->data)) {
3274.             /* floating or clinging steed keeps hero safe (is_flyer() test
3275.                is redundant; it can't be true since Flying yielded false) */
3276.             return FALSE;
3277.         } else if (u.usteed) {
3278.             /* steed enters pool */
3279.             dismount_steed(Underwater ? DISMOUNT_FELL : DISMOUNT_GENERIC);
3280.             /* dismount_steed() -> float_down() -> pickup()
3281.                (float_down doesn't do autopickup on Air or Water) */
3282.             if (Is_airlevel(&u.uz) || Is_waterlevel(&u.uz))
3283.                 return FALSE;
3284.             /* even if we actually end up at same location, float_down()
3285.                has already done trap and pickup actions of spoteffects() */
3286.             if (newspot)
3287.                 check_special_room(FALSE); /* spoteffects */
3288.             return TRUE;
3289.         }
3290.         /* not mounted */
3291. 
3292.         /* if hiding on ceiling then don't automatically enter pool */
3293.         if (Upolyd && ceiling_hider(&mons[u.umonnum]) && u.uundetected)
3294.             return FALSE;
3295. 
3296.         /* drown(),lava_effects() return true if hero changes
3297.            location while surviving the problem */
3298.         if (is_lava(u.ux, u.uy)) {
3299.             if (lava_effects())
3300.                 return TRUE;
3301.         } else if ((!Wwalking || is_waterwall(u.ux,u.uy))
3302.                    && (newspot || !u.uinwater
3303.                        || !(Swimming || Amphibious || Breathless))) {
3304.             if (drown())
3305.                 return TRUE;
3306.         }
3307.     }
3308.     return FALSE;
3309. }
3310. 
3311. void
3312. spoteffects(boolean pick)
3313. {
3314.     static int inspoteffects = 0;
3315.     static coord spotloc;
3316.     static int spotterrain;
3317.     static struct trap *spottrap = (struct trap *) 0;
3318.     static unsigned spottraptyp = NO_TRAP;
3319. 
3320.     struct monst *mtmp;
3321.     struct trap *trap = t_at(u.ux, u.uy);
3322.     int trapflag = iflags.failing_untrap ? FAILEDUNTRAP : 0;
3323. 
3324.     /* prevent recursion from affecting the hero all over again
3325.        [hero poly'd to iron golem enters water here, drown() inflicts
3326.        damage that triggers rehumanize() which calls spoteffects()...] */
3327.     if (inspoteffects && u_at(spotloc.x, spotloc.y)
3328.         /* except when reason is transformed terrain (ice -> water) */
3329.         && spotterrain == levl[u.ux][u.uy].typ
3330.         /* or transformed trap (land mine -> pit) */
3331.         && (!spottrap || !trap || trap->ttyp == spottraptyp))
3332.         return;
3333.     /* when float_down() puts hero into lava and she teleports out,
3334.        defer spoteffects() until after "you are back on solid <surface>" */
3335.     if (iflags.in_lava_effects)
3336.         return;
3337. 
3338.     ++inspoteffects;
3339.     spotterrain = levl[u.ux][u.uy].typ;
3340.     spotloc.x = u.ux, spotloc.y = u.uy;
3341. 
3342.     /* moving onto different terrain might cause Lev or Fly to toggle;
3343.       level change sets <ux0,uy0> to <ux,uy>, so this spotterrain
3344.       check always fails then, but it also sets iflags.terrain_typ */
3345.     if (spotterrain != levl[u.ux0][u.uy0].typ
3346.         || iflags.terrain_typ == MAX_TYPE)
3347.         switch_terrain();
3348. 
3349.     if (pooleffects(TRUE))
3350.         goto spotdone;
3351. 
3352.     check_special_room(FALSE);
3353.     if (IS_SINK(levl[u.ux][u.uy].typ) && Levitation)
3354.         dosinkfall();
3355.     if (!gi.in_steed_dismounting) { /* if dismounting, check again later */
3356.         boolean pit;
3357. 
3358.         /* if levitation is due to time out at the end of this
3359.            turn, allowing it to do so could give the perception
3360.            that a trap here is being triggered twice, so adjust
3361.            the timeout to prevent that */
3362.         if (trap && (HLevitation & TIMEOUT) == 1L
3363.             && !(ELevitation || (HLevitation & ~(I_SPECIAL | TIMEOUT)))) {
3364.             if (rn2(2)) { /* defer timeout */
3365.                 incr_itimeout(&HLevitation, 1L);
3366.             } else { /* timeout early */
3367.                 if (float_down(I_SPECIAL | TIMEOUT, 0L)) {
3368.                     /* levitation has ended; we've already triggered
3369.                        any trap and [usually] performed autopickup */
3370.                     trap = 0;
3371.                     pick = FALSE;
3372.                 }
3373.             }
3374.         }
3375.         /*
3376.          * If not a pit, pickup before triggering trap.
3377.          * If pit, trigger trap before pickup.
3378.          */
3379.         pit = (trap && is_pit(trap->ttyp));
3380.         if (pick && !pit)
3381.             (void) pickup(1);
3382. 
3383.         if (trap) {
3384.             /*
3385.              * dotrap on a fire trap calls melt_ice() which triggers
3386.              * spoteffects() (again) which can trigger the same fire
3387.              * trap (again).  Use static spottrap to prevent that.
3388.              * We track spottraptyp because some traps morph (landmine
3389.              * to pit) and any new trap type should get triggered.
3390.              */
3391.             if (!spottrap || spottraptyp != trap->ttyp) {
3392.                 spottrap = trap;
3393.                 spottraptyp = trap->ttyp;
3394.                 dotrap(trap, trapflag); /* fall into arrow trap, etc. */
3395.                 spottrap = (struct trap *) 0;
3396.                 spottraptyp = NO_TRAP;
3397.             }
3398.         }
3399.         if (pick && pit)
3400.             (void) pickup(1);
3401.     }
3402.     /* Warning alerts you to ice danger */
3403.     if (Warning && is_ice(u.ux, u.uy)) {
3404.         static const char *const icewarnings[] = {
3405.             "The ice seems very soft and slushy.",
3406.             "You feel the ice shift beneath you!",
3407.             "The ice, is gonna BREAK!", /* The Dead Zone */
3408.         };
3409.         long time_left = spot_time_left(u.ux, u.uy, MELT_ICE_AWAY);
3410. 
3411.         if (time_left && time_left < 15L)
3412.             pline("%s", icewarnings[(time_left < 5L) ? 2
3413.                                     : (time_left < 10L) ? 1
3414.                                       : 0]);
3415.     }
3416. 
3417.     if ((mtmp = m_at(u.ux, u.uy)) != 0 && !u.uswallow) {
3418.         mtmp->mundetected = mtmp->msleeping = 0;
3419.         switch (mtmp->data->mlet) {
3420.         case S_PIERCER:
3421.             pline("%s suddenly drops from the %s!", Amonnam(mtmp),
3422.                   ceiling(u.ux, u.uy));
3423.             if (mtmp->mtame) { /* jumps to greet you, not attack */
3424.                 ;
3425.             } else if (hard_helmet(uarmh)) {
3426.                 pline("Its blow glances off your %s.",
3427.                       helm_simple_name(uarmh));
3428.             } else if (u.uac + 3 <= rnd(20)) {
3429.                 You("are almost hit by %s!",
3430.                     x_monnam(mtmp, ARTICLE_A, "falling", 0, TRUE));
3431.             } else {
3432.                 int dmg;
3433. 
3434.                 You("are hit by %s!",
3435.                     x_monnam(mtmp, ARTICLE_A, "falling", 0, TRUE));
3436.                 dmg = d(4, 6);
3437.                 if (Half_physical_damage)
3438.                     dmg = (dmg + 1) / 2;
3439.                 mdamageu(mtmp, dmg);
3440.             }
3441.             break;
3442.         default: /* monster surprises you. */
3443.             if (mtmp->mtame)
3444.                 pline("%s jumps near you from the %s.", Amonnam(mtmp),
3445.                       ceiling(u.ux, u.uy));
3446.             else if (mtmp->mpeaceful) {
3447.                 You("surprise %s!",
3448.                     Blind && !sensemon(mtmp) ? something : a_monnam(mtmp));
3449.                 mtmp->mpeaceful = 0;
3450.             } else
3451.                 pline("%s attacks you by surprise!", Amonnam(mtmp));
3452.             break;
3453.         }
3454.         mnexto(mtmp, RLOC_NOMSG); /* have to move the monster */
3455.     }
3456.  spotdone:
3457.     if (!--inspoteffects) {
3458.         spotterrain = STONE; /* 0 */
3459.         spotloc.x = spotloc.y = 0;
3460.     }
3461.     return;
3462. }
3463. 
3464. /* returns first matching monster */
3465. staticfn struct monst *
3466. monstinroom(struct permonst *mdat, int roomno)
3467. {
3468.     struct monst *mtmp;
3469. 
3470.     for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
3471.         if (DEADMONSTER(mtmp))
3472.             continue;
3473.         if (mtmp->data == mdat
3474.             && strchr(in_rooms(mtmp->mx, mtmp->my, 0), roomno + ROOMOFFSET))
3475.             return mtmp;
3476.     }
3477.     return (struct monst *) 0;
3478. }
3479. 
3480. /* check whether room contains a particular type of furniture */
3481. staticfn boolean
3482. furniture_present(int furniture, int roomno)
3483. {
3484.     int x, y, lx, ly, hx, hy;
3485.     struct mkroom *sroom = &svr.rooms[roomno];
3486. 
3487.     ly = sroom->ly, hy = sroom->hy;
3488.     lx = sroom->lx; hx = sroom->hx;
3489.     /* the inside_room() check handles irregularly shaped rooms */
3490.     for (y = ly; y <= hy; ++y)
3491.         for (x = lx; x <= hx; ++x)
3492.             if (levl[x][y].typ == furniture && inside_room(sroom, x, y))
3493.                 return TRUE;
3494.     return FALSE;
3495. }
3496. 
3497. char *
3498. in_rooms(coordxy x, coordxy y, int typewanted)
3499. {
3500.     static char buf[5];
3501.     char rno = 0, *ptr = &buf[4];
3502.     int typefound, min_x, min_y, max_x, max_y_offset, step;
3503.     struct rm *lev;
3504. 
3505. #define goodtype(rno) \
3506.     (!typewanted                                                   \
3507.      || (typefound = svr.rooms[rno - ROOMOFFSET].rtype) == typewanted  \
3508.      || (typewanted == SHOPBASE && typefound > SHOPBASE))
3509. 
3510.     switch (rno = levl[x][y].roomno) {
3511.     case NO_ROOM:
3512.         return ptr;
3513.     case SHARED:
3514.         step = 2;
3515.         break;
3516.     case SHARED_PLUS:
3517.         step = 1;
3518.         break;
3519.     default: /* i.e. a regular room # */
3520.         if (goodtype(rno))
3521.             *(--ptr) = rno;
3522.         return ptr;
3523.     }
3524. 
3525.     min_x = x - 1;
3526.     max_x = x + 1;
3527.     if (x < 1)
3528.         min_x += step;
3529.     else if (x >= COLNO)
3530.         max_x -= step;
3531. 
3532.     min_y = y - 1;
3533.     max_y_offset = 2;
3534.     if (min_y < 0) {
3535.         min_y += step;
3536.         max_y_offset -= step;
3537.     } else if ((min_y + max_y_offset) >= ROWNO)
3538.         max_y_offset -= step;
3539. 
3540.     for (x = min_x; x <= max_x; x += step) {
3541.         lev = &levl[x][min_y];
3542.         y = 0;
3543.         if ((rno = lev[y].roomno) >= ROOMOFFSET && !strchr(ptr, rno)
3544.             && goodtype(rno))
3545.             *(--ptr) = rno;
3546.         y += step;
3547.         if (y > max_y_offset)
3548.             continue;
3549.         if ((rno = lev[y].roomno) >= ROOMOFFSET && !strchr(ptr, rno)
3550.             && goodtype(rno))
3551.             *(--ptr) = rno;
3552.         y += step;
3553.         if (y > max_y_offset)
3554.             continue;
3555.         if ((rno = lev[y].roomno) >= ROOMOFFSET && !strchr(ptr, rno)
3556.             && goodtype(rno))
3557.             *(--ptr) = rno;
3558.     }
3559.     return ptr;
3560. }
3561. 
3562. /* is (x,y) in a town? */
3563. boolean
3564. in_town(coordxy x, coordxy y)
3565. {
3566.     struct mkroom *sroom;
3567.     boolean has_subrooms = FALSE;
3568. 
3569.     if (!svl.level.flags.has_town)
3570.         return FALSE;
3571. 
3572.     /*
3573.      * See if (x,y) is in a room with subrooms, if so, assume it's the
3574.      * town.  If there are no subrooms, the whole level is in town.
3575.      */
3576.     for (sroom = &svr.rooms[0]; sroom->hx > 0; sroom++) {
3577.         if (sroom->nsubrooms > 0) {
3578.             has_subrooms = TRUE;
3579.             if (inside_room(sroom, x, y))
3580.                 return TRUE;
3581.         }
3582.     }
3583. 
3584.     return !has_subrooms;
3585. }
3586. 
3587. staticfn void
3588. move_update(boolean newlev)
3589. {
3590.     char c, *ptr1, *ptr2, *ptr3, *ptr4;
3591. 
3592.     Strcpy(u.urooms0, u.urooms);
3593.     Strcpy(u.ushops0, u.ushops);
3594.     if (newlev) {
3595.         (void) memset(u.urooms, '\0', sizeof u.urooms);
3596.         (void) memset(u.uentered, '\0', sizeof u.uentered);
3597.         (void) memset(u.ushops, '\0', sizeof u.ushops);
3598.         (void) memset(u.ushops_entered, '\0', sizeof u.ushops_entered);
3599.         Strcpy(u.ushops_left, u.ushops0);
3600.         return;
3601.     }
3602.     Strcpy(u.urooms, in_rooms(u.ux, u.uy, 0));
3603. 
3604.     for (ptr1 = u.urooms, ptr2 = u.uentered,
3605.          ptr3 = u.ushops, ptr4 = u.ushops_entered; *ptr1; ptr1++) {
3606.         c = *ptr1;
3607.         if (!strchr(u.urooms0, c))
3608.             *ptr2++ = c;
3609.         if (IS_SHOP(c - ROOMOFFSET)) {
3610.             *ptr3++ = c;
3611.             if (!strchr(u.ushops0, c))
3612.                 *ptr4++ = c;
3613.         }
3614.     }
3615.     *ptr2 = '\0', *ptr3 = '\0', *ptr4 = '\0';
3616. 
3617.     /* filter u.ushops0 -> u.ushops_left */
3618.     for (ptr1 = u.ushops0, ptr2 = u.ushops_left; *ptr1; ptr1++)
3619.         if (!strchr(u.ushops, *ptr1))
3620.             *ptr2++ = *ptr1;
3621.     *ptr2 = '\0';
3622. }
3623. 
3624. /* possibly deliver a one-time room entry message */
3625. void
3626. check_special_room(boolean newlev)
3627. {
3628.     struct monst *mtmp;
3629.     char *ptr;
3630. 
3631.     move_update(newlev);
3632. 
3633.     if (*u.ushops0)
3634.         u_left_shop(u.ushops_left, newlev);
3635. 
3636.     /*
3637.      * Check for attaining 'entered Mine Town' achievement.
3638.      * Most of the Mine Town variations have the town in one large room
3639.      * containing a bunch of subrooms; we check for entering that large
3640.      * room.  However, two of the variations cover the whole level rather
3641.      * than include a room with subrooms.  We need to check for town entry
3642.      * before the possible early return for not having entered a room in
3643.      * case we have arrived in the town but have not entered any room.
3644.      *
3645.      * TODO: change the minetn variants which don't include any town
3646.      * boundary to have such.
3647.      */
3648.     if (svl.level.flags.has_town && !svc.context.achieveo.minetn_reached
3649.         && In_mines(&u.uz) && in_town(u.ux, u.uy)) {
3650.         record_achievement(ACH_TOWN);
3651.         svc.context.achieveo.minetn_reached = TRUE;
3652.     }
3653. 
3654.     if (!*u.uentered && !*u.ushops_entered) /* implied by newlev */
3655.         return; /* no entrance messages necessary */
3656. 
3657.     /* Did we just enter a shop? */
3658.     if (*u.ushops_entered)
3659.         u_entered_shop(u.ushops_entered);
3660. 
3661.     for (ptr = &u.uentered[0]; *ptr; ptr++) {
3662.         int roomno = *ptr - ROOMOFFSET, rt = svr.rooms[roomno].rtype;
3663.         boolean msg_given = TRUE;
3664. 
3665.         /* Did we just enter some other special room? */
3666.         /* vault.c insists that a vault remain a VAULT,
3667.          * and temples should remain TEMPLEs,
3668.          * but everything else gives a message only the first time */
3669.         switch (rt) {
3670.         case ZOO:
3671.             pline("Welcome to David's treasure zoo!");
3672.             break;
3673.         case SWAMP:
3674.             pline("It %s rather %s down here.", Blind ? "feels" : "looks",
3675.                   Blind ? "humid" : "muddy");
3676.             break;
3677.         case COURT:
3678.             You("enter an opulent%s room!",
3679.                 /* the throne room in Sam quest home level lacks a throne */
3680.                 !furniture_present(THRONE, roomno) ? "" : " throne");
3681.             break;
3682.         case LEPREHALL:
3683.             You("enter a leprechaun hall!");
3684.             break;
3685.         case MORGUE:
3686.             if (midnight()) {
3687.                 const char *run = u_locomotion("Run");
3688. 
3689.                 pline("%s away!  %s away!", run, run);
3690.             } else
3691.                 You("have an uncanny feeling...");
3692.             break;
3693.         case BEEHIVE:
3694.             You("enter a giant beehive!");
3695.             break;
3696.         case COCKNEST:
3697.             You("enter a disgusting nest!");
3698.             break;
3699.         case ANTHOLE:
3700.             You("enter an anthole!");
3701.             break;
3702.         case BARRACKS:
3703.             if (monstinroom(&mons[PM_SOLDIER], roomno)
3704.                 || monstinroom(&mons[PM_SERGEANT], roomno)
3705.                 || monstinroom(&mons[PM_LIEUTENANT], roomno)
3706.                 || monstinroom(&mons[PM_CAPTAIN], roomno))
3707.                 You("enter a military barracks!");
3708.             else
3709.                 You("enter an abandoned barracks.");
3710.             break;
3711.         case DELPHI: {
3712.             struct monst *oracle = monstinroom(&mons[PM_ORACLE], roomno);
3713. 
3714.             if (oracle) {
3715.                 SetVoice(oracle, 0, 80, 0);
3716.                 if (!oracle->mpeaceful)
3717.                     verbalize("You're in Delphi, %s.", svp.plname);
3718.                 else
3719.                     verbalize("%s, %s, welcome to Delphi!",
3720.                               Hello((struct monst *) 0), svp.plname);
3721.             } else
3722.                 msg_given = FALSE;
3723.             break;
3724.         }
3725.         case TEMPLE:
3726.             intemple(roomno + ROOMOFFSET);
3727.             FALLTHROUGH;
3728.         /*FALLTHRU*/
3729.         default:
3730.             msg_given = (rt == TEMPLE || rt >= SHOPBASE);
3731.             rt = 0;
3732.             break;
3733.         }
3734.         if (msg_given)
3735.             room_discovered(roomno);
3736. 
3737.         if (rt != 0) {
3738.             svr.rooms[roomno].rtype = OROOM;
3739.             if (!search_special(rt)) {
3740.                 /* No more room of that type */
3741.                 switch (rt) {
3742.                 case COURT:
3743.                     svl.level.flags.has_court = 0;
3744.                     break;
3745.                 case SWAMP:
3746.                     svl.level.flags.has_swamp = 0;
3747.                     break;
3748.                 case MORGUE:
3749.                     svl.level.flags.has_morgue = 0;
3750.                     break;
3751.                 case ZOO:
3752.                     svl.level.flags.has_zoo = 0;
3753.                     break;
3754.                 case BARRACKS:
3755.                     svl.level.flags.has_barracks = 0;
3756.                     break;
3757.                 case TEMPLE:
3758.                     svl.level.flags.has_temple = 0;
3759.                     break;
3760.                 case BEEHIVE:
3761.                     svl.level.flags.has_beehive = 0;
3762.                     break;
3763.                 }
3764.             }
3765.             if (rt == COURT || rt == SWAMP || rt == MORGUE || rt == ZOO)
3766.                 for (mtmp = fmon; mtmp; mtmp = mtmp->nmon) {
3767.                     if (DEADMONSTER(mtmp))
3768.                         continue;
3769.                     if (!isok(mtmp->mx,mtmp->my)
3770.                         || roomno != (int) levl[mtmp->mx][mtmp->my].roomno)
3771.                         continue;
3772.                     if (!Stealth && !rn2(3)) {
3773.                         wake_msg(mtmp, FALSE);
3774.                         mtmp->msleeping = 0;
3775.                     }
3776.                 }
3777.         }
3778.     }
3779.     return;
3780. }
3781. 
3782. /* returns
3783.    1 = cannot pickup, time taken
3784.    0 = cannot pickup, no time taken
3785.   -1 = do normal pickup
3786.   -2 = loot the monster */
3787. staticfn int
3788. pickup_checks(void)
3789. {
3790.     struct trap *traphere;
3791. 
3792.     /* uswallow case added by GAN 01/29/87 */
3793.     if (u.uswallow) {
3794.         if (!u.ustuck->minvent) {
3795.             if (digests(u.ustuck->data)) {
3796.                 You("pick up %s tongue.", s_suffix(mon_nam(u.ustuck)));
3797.                 pline("But it's kind of slimy, so you drop it.");
3798.             } else
3799.                 You("don't %s anything in here to pick up.",
3800.                     Blind ? "feel" : "see");
3801.             return 1;
3802.         } else {
3803.             return -2; /* loot the monster inventory */
3804.         }
3805.     }
3806.     if (is_pool(u.ux, u.uy)) {
3807.         if (Wwalking || is_floater(gy.youmonst.data)
3808.             || is_clinger(gy.youmonst.data) || (Flying && !Breathless)) {
3809.             You("cannot dive into the %s to pick things up.",
3810.                 hliquid("water"));
3811.             return 0;
3812.         } else if (!Underwater) {
3813.             You_cant("even see the bottom, let alone pick up %s.", something);
3814.             return 0;
3815.         }
3816.     }
3817.     if (is_lava(u.ux, u.uy)) {
3818.         if (Wwalking || is_floater(gy.youmonst.data)
3819.             || is_clinger(gy.youmonst.data) || (Flying && !Breathless)) {
3820.             You_cant("reach the bottom to pick things up.");
3821.             return 0;
3822.         } else if (!likes_lava(gy.youmonst.data)) {
3823.             You("would burn to a crisp trying to pick things up.");
3824.             return 0;
3825.         }
3826.     }
3827.     if (!OBJ_AT(u.ux, u.uy)) {
3828.         struct rm *lev = &levl[u.ux][u.uy];
3829. 
3830.         if (IS_THRONE(lev->typ))
3831.             pline("It must weigh%s a ton!", lev->looted ? " almost" : "");
3832.         else if (IS_SINK(lev->typ))
3833.             pline_The("plumbing connects it to the floor.");
3834.         else if (IS_GRAVE(lev->typ))
3835.             You("don't need a gravestone.  Yet.");
3836.         else if (IS_FOUNTAIN(lev->typ))
3837.             You("could drink the %s...", hliquid("water"));
3838.         else if (IS_DOOR(lev->typ) && (lev->doormask & D_ISOPEN))
3839.             pline("It won't come off the hinges.");
3840.         else if (IS_ALTAR(lev->typ))
3841.             pline("Moving the altar would be a very bad idea.");
3842.         else if (lev->typ == STAIRS)
3843.             pline_The("stairs are solidly affixed.");
3844.         else
3845.             There("is nothing here to pick up.");
3846.         return 0;
3847.     }
3848.     traphere = t_at(u.ux, u.uy);
3849.     if (!can_reach_floor(traphere && is_pit(traphere->ttyp))) {
3850.         /* if there's a hole here, any objects here clearly aren't at
3851.            the bottom so only check for pits */
3852.         if (traphere && uteetering_at_seen_pit(traphere)) {
3853.             You("cannot reach the bottom of the pit.");
3854.         } else if (u.usteed && P_SKILL(P_RIDING) < P_BASIC) {
3855.             rider_cant_reach();
3856.         } else if (Blind) {
3857.             You("cannot reach anything here.");
3858.         } else {
3859.             const char *surf = surface(u.ux, u.uy);
3860. 
3861.             if (traphere) {
3862.                 if (traphere->ttyp == HOLE)
3863.                     surf = "edge of the hole";
3864.                 else if (traphere->ttyp == TRAPDOOR)
3865.                     surf = "trap door";
3866.             }
3867.             You("cannot reach the %s.", surf);
3868.         }
3869.         return 0;
3870.     }
3871.     return -1; /* can do normal pickup */
3872. }
3873. 
3874. /* the #pickup command */
3875. int
3876. dopickup(void)
3877. {
3878.     int count, tmpcount, ret;
3879. 
3880.     count = (int) gc.command_count;
3881.     gm.multi = 0; /* always reset */
3882. 
3883.     if ((ret = pickup_checks()) >= 0) {
3884.         return ret ? ECMD_TIME : ECMD_OK;
3885.     } else if (ret == -2) {
3886.         tmpcount = -count;
3887.         return loot_mon(u.ustuck, &tmpcount, (boolean *) 0) ? ECMD_TIME
3888.                                                             : ECMD_OK;
3889.     } /* else ret == -1 */
3890. 
3891.     return pickup(-count) ? ECMD_TIME : ECMD_OK;
3892. }
3893. 
3894. /* stop running if we see something interesting next to us */
3895. /* turn around a corner if that is the only way we can proceed */
3896. /* do not turn left or right twice */
3897. void
3898. lookaround(void)
3899. {
3900.     coordxy x, y;
3901.     coordxy i, x0 = 0, y0 = 0, m0 = 1, i0 = 9;
3902.     int corrct = 0, noturn = 0;
3903.     struct monst *mtmp;
3904. 
3905.     /* Grid bugs stop if trying to move diagonal, even if blind.  Maybe */
3906.     /* they polymorphed while in the middle of a long move. */
3907.     if (NODIAG(u.umonnum) && u.dx && u.dy) {
3908.         You("cannot move diagonally.");
3909.         nomul(0);
3910.         return;
3911.     }
3912. 
3913.     if (Blind || svc.context.run == 0)
3914.         return;
3915.     for (x = u.ux - 1; x <= u.ux + 1; x++)
3916.         for (y = u.uy - 1; y <= u.uy + 1; y++) {
3917.             boolean infront = (x == u.ux + u.dx && y == u.uy + u.dy);
3918. 
3919.             /* ignore out of bounds, and our own location */
3920.             if (!isok(x, y) || u_at(x, y))
3921.                 continue;
3922.             /* (grid bugs) ignore diagonals */
3923.             if (NODIAG(u.umonnum) && x != u.ux && y != u.uy)
3924.                 continue;
3925. 
3926.             /* can we see a monster there? */
3927.             if ((mtmp = m_at(x, y)) != 0
3928.                 && M_AP_TYPE(mtmp) != M_AP_FURNITURE
3929.                 && M_AP_TYPE(mtmp) != M_AP_OBJECT
3930.                 && mon_visible(mtmp)) {
3931.                 /* running movement and not a hostile monster */
3932.                 /* OR it blocks our move direction and we're not traveling */
3933.                 if ((svc.context.run != 1 && !is_safemon(mtmp))
3934.                     || (infront && !svc.context.travel)) {
3935.                     if (flags.mention_walls)
3936.                         pline_xy(x, y, "%s blocks your path.",
3937.                                  upstart(a_monnam(mtmp)));
3938.                     goto stop;
3939.                 }
3940.             }
3941. 
3942.             /* stone is never interesting */
3943.             if (levl[x][y].typ == STONE)
3944.                 continue;
3945.             /* ignore the square we're moving away from */
3946.             if (x == u.ux - u.dx && y == u.uy - u.dy)
3947.                 continue;
3948. 
3949.             /* stop for traps, sometimes */
3950.             if (avoid_moving_on_trap(x, y,
3951.                                      (infront && svc.context.run > 1))) {
3952.                 if (svc.context.run == 1)
3953.                     goto bcorr; /* if you must */
3954.                 if (infront)
3955.                     goto stop;
3956.             }
3957. 
3958.             /* more uninteresting terrain */
3959.             if (IS_OBSTRUCTED(levl[x][y].typ) || levl[x][y].typ == ROOM
3960.                 || IS_AIR(levl[x][y].typ) || levl[x][y].typ == ICE) {
3961.                 continue;
3962.             } else if (closed_door(x, y) || (mtmp && is_door_mappear(mtmp))) {
3963.                 /* a closed door? */
3964.                 /* ignore if diagonal */
3965.                 if (x != u.ux && y != u.uy)
3966.                     continue;
3967.                 if (svc.context.run != 1 && !svc.context.travel) {
3968.                     if (flags.mention_walls) {
3969.                         set_msg_xy(x, y);
3970.                         You("stop in front of the door.");
3971.                     }
3972.                     goto stop;
3973.                 }
3974.                 /* orthogonal to a closed door, consider it a corridor */
3975.                 goto bcorr;
3976.             } else if (levl[x][y].typ == CORR) {
3977.                 /* corridor */
3978.  bcorr:
3979.                 if (levl[u.ux][u.uy].typ != ROOM) {
3980.                     /* running or traveling */
3981.                     if (svc.context.run == 1 || svc.context.run == 3
3982.                         || svc.context.run == 8) {
3983.                         /* distance from x,y to location we're moving to */
3984.                         i = dist2(x, y, u.ux + u.dx, u.uy + u.dy);
3985.                         /* ignore if not on or directly adjacent to it */
3986.                         if (i > 2)
3987.                             continue;
3988.                         /* x,y is (adjacent to) the location we're moving to;
3989.                            if we've seen one corridor, and x,y is not directly
3990.                            orthogonally next to it, mark noturn */
3991.                         if (corrct == 1 && dist2(x, y, x0, y0) != 1)
3992.                             noturn = 1;
3993.                         /* if previous x,y was diagonal, now x,y is
3994.                            orthogonal (or this is first time we're here) */
3995.                         if (i < i0) {
3996.                             i0 = i;
3997.                             x0 = x;
3998.                             y0 = y;
3999.                             m0 = mtmp ? 1 : 0;
4000.                         }
4001.                     }
4002.                     corrct++;
4003.                 }
4004.                 continue;
4005.             } else if (is_pool_or_lava(x, y)) {
4006.                 if (infront && avoid_moving_on_liquid(x, y, TRUE))
4007.                     goto stop;
4008.                 continue;
4009.             } else { /* e.g. objects or trap or stairs */
4010.                 if (svc.context.run == 1)
4011.                     goto bcorr;
4012.                 if (svc.context.run == 8)
4013.                     continue;
4014.                 if (mtmp)
4015.                     continue; /* d */
4016.                 if (((x == u.ux - u.dx) && (y != u.uy + u.dy))
4017.                     || ((y == u.uy - u.dy) && (x != u.ux + u.dx)))
4018.                     continue;
4019.             }
4020.  stop:
4021.             nomul(0);
4022.             return;
4023.         } /* end for loops */
4024. 
4025.     if (corrct > 1 && svc.context.run == 2) {
4026.         if (flags.mention_walls)
4027.             pline_The("corridor widens here.");
4028.         goto stop;
4029.     }
4030.     if ((svc.context.run == 1 || svc.context.run == 3 || svc.context.run == 8)
4031.         && !noturn && !m0 && i0
4032.         && (corrct == 1 || (corrct == 2 && i0 == 1))) {
4033.         /* make sure that we do not turn too far */
4034.         if (i0 == 2) {
4035.             if (u.dx == y0 - u.uy && u.dy == u.ux - x0)
4036.                 i = 2; /* straight turn right */
4037.             else
4038.                 i = -2; /* straight turn left */
4039.         } else if (u.dx && u.dy) {
4040.             if ((u.dx == u.dy && y0 == u.uy) || (u.dx != u.dy && y0 != u.uy))
4041.                 i = -1; /* half turn left */
4042.             else
4043.                 i = 1; /* half turn right */
4044.         } else {
4045.             if ((x0 - u.ux == y0 - u.uy && !u.dy)
4046.                 || (x0 - u.ux != y0 - u.uy && u.dy))
4047.                 i = 1; /* half turn right */
4048.             else
4049.                 i = -1; /* half turn left */
4050.         }
4051. 
4052.         i += u.last_str_turn;
4053.         if (i <= 2 && i >= -2) {
4054.             u.last_str_turn = i;
4055.             u.dx = x0 - u.ux;
4056.             u.dy = y0 - u.uy;
4057.         }
4058.     }
4059. }
4060. 
4061. /* check for a doorway which lacks its door (NODOOR or BROKEN) */
4062. boolean
4063. doorless_door(coordxy x, coordxy y)
4064. {
4065.     struct rm *lev_p = &levl[x][y];
4066. 
4067.     if (!IS_DOOR(lev_p->typ))
4068.         return FALSE;
4069.     /* all rogue level doors are doorless but disallow diagonal access, so
4070.        we treat them as if their non-existent doors were actually present */
4071.     if (Is_rogue_level(&u.uz))
4072.         return FALSE;
4073.     return !(lev_p->doormask & ~(D_NODOOR | D_BROKEN));
4074. }
4075. 
4076. /* used by drown() to check whether hero can crawl from water to <x,y>;
4077.    also used by findtravelpath() when destination is one step away */
4078. boolean
4079. crawl_destination(coordxy x, coordxy y)
4080. {
4081.     /* is location ok in general? */
4082.     if (!goodpos(x, y, &gy.youmonst, 0))
4083.         return FALSE;
4084. 
4085.     /* orthogonal movement is unrestricted when destination is ok */
4086.     if (x == u.ux || y == u.uy)
4087.         return TRUE;
4088. 
4089.     /* diagonal movement has some restrictions */
4090.     if (NODIAG(u.umonnum))
4091.         return FALSE; /* poly'd into a grid bug... */
4092.     if (Passes_walls)
4093.         return TRUE; /* or a xorn... */
4094.     /* pool could be next to a door, conceivably even inside a shop */
4095.     if (IS_DOOR(levl[x][y].typ) && (!doorless_door(x, y) || block_door(x, y)))
4096.         return FALSE;
4097.     /* finally, are we trying to squeeze through a too-narrow gap? */
4098.     return !(bad_rock(gy.youmonst.data, u.ux, y)
4099.              && bad_rock(gy.youmonst.data, x, u.uy)
4100.              && cant_squeeze_thru(&gy.youmonst));
4101. }
4102. 
4103. /* something like lookaround, but we are not running */
4104. /* react only to monsters that might hit us */
4105. int
4106. monster_nearby(void)
4107. {
4108.     coordxy x, y;
4109.     struct monst *mtmp;
4110. 
4111.     /* Also see the similar check in dochugw() in monmove.c */
4112.     for (x = u.ux - 1; x <= u.ux + 1; x++)
4113.         for (y = u.uy - 1; y <= u.uy + 1; y++) {
4114.             if (!isok(x, y) || u_at(x, y))
4115.                 continue;
4116.             if ((mtmp = m_at(x, y)) != 0
4117.                 && M_AP_TYPE(mtmp) != M_AP_FURNITURE
4118.                 && M_AP_TYPE(mtmp) != M_AP_OBJECT
4119.                 && (Hallucination
4120.                     || (!mtmp->mpeaceful && !noattacks(mtmp->data)))
4121.                 && (!is_hider(mtmp->data) || !mtmp->mundetected)
4122.                 && !helpless(mtmp)
4123.                 && !onscary(u.ux, u.uy, mtmp) && canspotmon(mtmp))
4124.                 return 1;
4125.         }
4126.     return 0;
4127. }
4128. 
4129. void
4130. end_running(boolean and_travel)
4131. {
4132.     /* moveloop() suppresses time_botl when context.run is non-zero; when
4133.        running stops, update 'time' even if other botl status is unchanged */
4134.     if (svc.context.run) {
4135.         svc.context.run = 0;
4136.         if (flags.time)
4137.             disp.time_botl = TRUE;
4138.         /* classify_terrain() suppresses setting disp.botl when
4139.            running; after that, it can no longer compare current terrain
4140.            against iflaga.terrain_typ to detect a change, so recompute */
4141.         if (flags.terrainstatus) {
4142.             iflags.terrain_typ = MAX_TYPE; /* "none of the above" value */
4143.             classify_terrain();
4144.         }
4145.     }
4146. 
4147.     /* 'context.mv' isn't travel but callers who want to end travel
4148.        all clear it too */
4149.     if (and_travel)
4150.         svc.context.travel = svc.context.travel1 = svc.context.mv = 0;
4151.     if (gt.travelmap) {
4152.         selection_free(gt.travelmap, TRUE);
4153.         gt.travelmap = NULL;
4154.     }
4155.     /* cancel multi */
4156.     if (gm.multi > 0)
4157.         gm.multi = 0;
4158. }
4159. 
4160. void
4161. nomul(int nval)
4162. {
4163.     if (gm.multi < nval)
4164.         return;              /* This is a bug fix by ab@unido */
4165.     disp.botl |= (gm.multi >= 0);
4166.     u.uinvulnerable = FALSE; /* Kludge to avoid ctrl-C bug -dlc */
4167.     u.usleep = 0;
4168.     gm.multi = nval;
4169.     if (nval == 0)
4170.         gm.multi_reason = NULL, gm.multireasonbuf[0] = '\0';
4171.     end_running(TRUE);
4172.     cmdq_clear(CQ_CANNED);
4173. }
4174. 
4175. /* called when a non-movement, multi-turn action has completed */
4176. void
4177. unmul(const char *msg_override)
4178. {
4179.     disp.botl = TRUE;
4180.     gm.multi = 0; /* caller will usually have done this already */
4181.     if (msg_override)
4182.         gn.nomovemsg = msg_override;
4183.     else if (!gn.nomovemsg)
4184.         gn.nomovemsg = You_can_move_again;
4185.     if (*gn.nomovemsg) {
4186.         pline("%s", gn.nomovemsg);
4187.         /* follow "you survived that attempt on your life" with a message
4188.            about current form if it's not the default; primarily for
4189.            life-saving while turning into green slime but is also a reminder
4190.            if life-saved while poly'd and Unchanging (explore or wizard mode
4191.            declining to die since can't be both Unchanging and Lifesaved) */
4192.         if (Upolyd && !strncmpi(gn.nomovemsg, "You survived that ", 18))
4193.             You("are %s.",
4194.                 an(pmname(&mons[u.umonnum], Ugender))); /* (ignore Hallu) */
4195.     }
4196.     gn.nomovemsg = 0;
4197.     u.usleep = 0;
4198.     gm.multi_reason = NULL, gm.multireasonbuf[0] = '\0';
4199. 
4200.     if (ga.afternmv) {
4201.         int (*f)(void) = ga.afternmv;
4202. 
4203.         /* clear afternmv before calling it (to override the
4204.            encumbrance hack for levitation--see weight_cap()) */
4205.         ga.afternmv = (int (*)(void)) 0;
4206.         (void) (*f)();
4207.     }
4208. }
4209. 
4210. staticfn void
4211. maybe_wail(void)
4212. {
4213.     static short powers[] = { TELEPORT, SEE_INVIS, POISON_RES, COLD_RES,
4214.                               SHOCK_RES, FIRE_RES, SLEEP_RES, DISINT_RES,
4215.                               TELEPORT_CONTROL, STEALTH, FAST, INVIS };
4216. 
4217.     if (svm.moves <= gw.wailmsg + 50)
4218.         return;
4219. 
4220.     gw.wailmsg = svm.moves;
4221.     if (Role_if(PM_WIZARD) || Race_if(PM_ELF) || Role_if(PM_VALKYRIE)) {
4222.         const char *who;
4223.         int i, powercnt;
4224. 
4225.         who = (Role_if(PM_WIZARD) || Role_if(PM_VALKYRIE)) ? gu.urole.name.m
4226.                                                            : "Elf";
4227.         if (u.uhp == 1) {
4228.             pline("%s is about to die.", who);
4229.         } else {
4230.             for (i = 0, powercnt = 0; i < SIZE(powers); ++i)
4231.                 if (u.uprops[powers[i]].intrinsic & INTRINSIC)
4232.                     ++powercnt;
4233. 
4234.             pline((powercnt >= 4) ? "%s, all your powers will be lost..."
4235.                                   : "%s, your life force is running out.",
4236.                   who);
4237.         }
4238.     } else {
4239.         Soundeffect(se_wailing_of_the_banshee, 75);
4240.         You_hear(u.uhp == 1 ? "the wailing of the Banshee..."
4241.                             : "the howling of the CwnAnnwn...");
4242.     }
4243. }
4244. 
4245. /* show a message how much damage you received */
4246. void
4247. showdamage(int dmg)
4248. {
4249.     if (!iflags.showdamage || !dmg)
4250.         return;
4251. 
4252.     pline("[HP %i, %i left]", -dmg, Upolyd ? u.mh : u.uhp);
4253. }
4254. 
4255. void
4256. losehp(int n, const char *knam, schar k_format)
4257. {
4258. #if 0   /* code below is prepared to handle negative 'loss' so don't add this
4259.          * until we've verified that no callers intentionally rely on that */
4260.     if (n <= 0) {
4261.         impossible("hero losing %d hit points due to \"%s\"?", n, knam);
4262.         return;
4263.     }
4264. #endif
4265.     disp.botl = TRUE; /* u.uhp or u.mh is changing */
4266.     end_running(TRUE);
4267.     if (Upolyd) {
4268.         u.mh -= n;
4269.         showdamage(n);
4270.         if (u.mhmax < u.mh)
4271.             u.mhmax = u.mh;
4272.         if (u.mh < 1)
4273.             rehumanize();
4274.         else if (n > 0 && u.mh * 10 < u.mhmax && Unchanging)
4275.             maybe_wail();
4276.         return;
4277.     }
4278. 
4279.     u.uhp -= n;
4280.     showdamage(n);
4281.     if (u.uhp > u.uhpmax)
4282.         u.uhpmax = u.uhp; /* perhaps n was negative */
4283.     if (u.uhp < 1) {
4284.         svk.killer.format = k_format;
4285.         if (svk.killer.name != knam) /* the thing that killed you */
4286.             Strcpy(svk.killer.name, knam ? knam : "");
4287.         urgent_pline("You die...");
4288.         done(DIED);
4289.     } else if (n > 0 && u.uhp * 10 < u.uhpmax) {
4290.         maybe_wail();
4291.     }
4292. }
4293. 
4294. int
4295. weight_cap(void)
4296. {
4297.     long carrcap, save_ELev = ELevitation, save_BLev = BLevitation;
4298. 
4299.     /* boots take multiple turns to wear but any properties they
4300.        confer are enabled at the start rather than the end; that
4301.        causes message sequencing issues for boots of levitation
4302.        so defer their encumbrance benefit until they're fully worn */
4303.     if (ga.afternmv == Boots_on && (ELevitation & W_ARMF) != 0L) {
4304.         ELevitation &= ~W_ARMF;
4305.         float_vs_flight(); /* in case Levitation is blocking Flying */
4306.     }
4307.     /* levitation is blocked by being trapped in the floor, but it still
4308.        functions enough in that situation to enhance carrying capacity */
4309.     BLevitation &= ~I_SPECIAL;
4310. 
4311.     carrcap = (WT_WEIGHTCAP_STRCON * (ACURRSTR + ACURR(A_CON)))
4312.                + WT_WEIGHTCAP_SPARE;
4313.     if (Upolyd) {
4314.         /* consistent with can_carry() in mon.c */
4315.         if (gy.youmonst.data->mlet == S_NYMPH)
4316.             carrcap = MAX_CARR_CAP;
4317.         else if (!gy.youmonst.data->cwt)
4318.             carrcap = (carrcap * (long) gy.youmonst.data->msize) / MZ_HUMAN;
4319.         else if (!strongmonst(gy.youmonst.data)
4320.                  || (strongmonst(gy.youmonst.data)
4321.                      && (gy.youmonst.data->cwt > WT_HUMAN)))
4322.             carrcap = (carrcap * (long) gy.youmonst.data->cwt / WT_HUMAN);
4323.     }
4324. 
4325.     if (Levitation || Is_airlevel(&u.uz) /* pugh@cornell */
4326.         || (u.usteed && strongmonst(u.usteed->data))) {
4327.         carrcap = MAX_CARR_CAP;
4328.     } else {
4329.         if (carrcap > MAX_CARR_CAP)
4330.             carrcap = MAX_CARR_CAP;
4331.         if (!Flying) {
4332.             if (EWounded_legs & LEFT_SIDE)
4333.                 carrcap -= WT_WOUNDEDLEG_REDUCT;
4334.             if (EWounded_legs & RIGHT_SIDE)
4335.                 carrcap -= WT_WOUNDEDLEG_REDUCT;
4336.         }
4337.     }
4338. 
4339.     if (ELevitation != save_ELev || BLevitation != save_BLev) {
4340.         ELevitation = save_ELev;
4341.         BLevitation = save_BLev;
4342.         float_vs_flight();
4343.     }
4344. 
4345.     return (int) max(carrcap, 1L); /* never return 0 */
4346. }
4347. 
4348. /* returns how far beyond the normal capacity the player is currently. */
4349. /* inv_weight() is negative if the player is below normal capacity. */
4350. int
4351. inv_weight(void)
4352. {
4353.     struct obj *otmp = gi.invent;
4354.     int wt = 0;
4355. 
4356.     while (otmp) {
4357.         if (otmp->oclass == COIN_CLASS)
4358.             wt += (int) (((long) otmp->quan + 50L) / 100L);
4359.         else if (otmp->otyp != BOULDER || !throws_rocks(gy.youmonst.data))
4360.             wt += otmp->owt;
4361.         otmp = otmp->nobj;
4362.     }
4363.     gw.wc = weight_cap();
4364.     return (wt - gw.wc);
4365. }
4366. 
4367. /*
4368.  * Returns 0 if below normal capacity, or the number of "capacity units"
4369.  * over the normal capacity the player is loaded.  Max is 5.
4370.  */
4371. int
4372. calc_capacity(int xtra_wt)
4373. {
4374.     int cap, wt = inv_weight() + xtra_wt;
4375. 
4376.     if (wt <= 0)
4377.         return UNENCUMBERED;
4378.     if (gw.wc <= 1)
4379.         return OVERLOADED;
4380.     cap = (wt * 2 / gw.wc) + 1;
4381.     return min(cap, OVERLOADED);
4382. }
4383. 
4384. int
4385. near_capacity(void)
4386. {
4387.     return calc_capacity(0);
4388. }
4389. 
4390. int
4391. max_capacity(void)
4392. {
4393.     int wt = inv_weight();
4394. 
4395.     return (wt - (2 * gw.wc));
4396. }
4397. 
4398. boolean
4399. check_capacity(const char *str)
4400. {
4401.     if (near_capacity() >= EXT_ENCUMBER) {
4402.         if (str)
4403.             pline1(str);
4404.         else
4405.             You_cant("do that while carrying so much stuff.");
4406.         return 1;
4407.     }
4408.     return 0;
4409. }
4410. 
4411. struct weight_table_entry {
4412.     unsigned wtyp; /* 1 = monst, 2 = obj */
4413.     const char *nm; /* 0-6 = weight in ascii; 7 - end = name */
4414.     int wt, idx;
4415.     boolean unique;
4416. };
4417. 
4418. static struct weight_table_entry *weightlist;
4419. 
4420. void
4421. dump_weights(void)
4422. {
4423.     int i, cnt = 0, nmwidth = 49, mcount = NUMMONS, ocount = NUM_OBJECTS;
4424.     char nmbuf[BUFSZ], nmbufbase[BUFSZ];
4425.     size_t num_entries = (size_t) (mcount + ocount);
4426. 
4427.     weightlist = (struct weight_table_entry *)
4428.                 alloc(sizeof (struct weight_table_entry) * num_entries);
4429.     decl_globals_init();
4430.     init_objects();
4431.     for (i = 0; i < mcount; ++i) {
4432.         if (i != PM_LONG_WORM_TAIL) {
4433.             boolean cm;
4434. 
4435.             weightlist[cnt].wt = (int) mons[i].cwt;
4436.             weightlist[cnt].idx = i;
4437.             weightlist[cnt].wtyp = 1;
4438.             weightlist[cnt].unique = ((mons[i].geno & G_UNIQ) != 0);
4439.             Snprintf(nmbuf, sizeof nmbuf, "%07u", weightlist[cnt].wt);
4440.             cm = CapitalMon(mons[i].pmnames[NEUTRAL]);
4441.             Snprintf(&nmbuf[7], sizeof nmbuf - 7, "%s%s", "the body of ",
4442.                      (cm)                     ? the(mons[i].pmnames[NEUTRAL])
4443.                      : weightlist[cnt].unique ? mons[i].pmnames[NEUTRAL]
4444.                                               : an(mons[i].pmnames[NEUTRAL]));
4445.             weightlist[cnt].nm = dupstr(nmbuf);
4446.             cnt++;
4447.         }
4448.     }
4449.     for (i = 0; i < ocount; ++i) {
4450.         const char *oc_name = (i == SLIME_MOLD) ? "slime mold"
4451.                               : obj_descr[i].oc_name;
4452.         int wt = (int) objects[i].oc_weight;
4453. 
4454.         if (wt && oc_name) {
4455.             weightlist[cnt].idx = i;
4456.             weightlist[cnt].wt = wt;
4457.             weightlist[cnt].wtyp = 2;
4458.             weightlist[cnt].unique = (objects[i].oc_unique != 0);
4459.             objects[i].oc_name_known = 1;
4460.             Strcpy(nmbufbase, simple_typename(i));
4461.             Snprintf(nmbuf, sizeof nmbuf, "%07u%s", wt,
4462.                      (weightlist[cnt].unique) ? the(nmbufbase)
4463.                                               : an(nmbufbase));
4464.             weightlist[cnt].nm = dupstr(nmbuf);
4465.             cnt++;
4466.         }
4467.     }
4468.     qsort((genericptr_t) weightlist, cnt,
4469.           sizeof (struct weight_table_entry), cmp_weights);
4470.     raw_printf("int all_weights[] = {");
4471.     for (i = 0; i < cnt; ++i) {
4472.         if (weightlist[i].nm) {
4473.             raw_printf("    %7u%s /* %*s */", weightlist[i].wt,
4474.                        (i == cnt - 1) ? " " : ",", -nmwidth,
4475.                        &weightlist[i].nm[7]);
4476.             free((genericptr_t) weightlist[i].nm), weightlist[i].nm = 0;
4477.         }
4478.     }
4479.     raw_print("};");
4480.     raw_print("");
4481.     free((genericptr_t) weightlist);
4482.     freedynamicdata();
4483. }
4484. 
4485. staticfn int QSORTCALLBACK
4486. cmp_weights(const void *p1, const void *p2)
4487. {
4488.     struct weight_table_entry *i1 = (struct weight_table_entry *) p1,
4489.                               *i2 = (struct weight_table_entry *) p2;
4490. 
4491.    /* return (i1->wt - i2->wt); */
4492.     return strcmp(i1->nm, i2->nm);
4493. }
4494. 
4495. int
4496. inv_cnt(boolean incl_gold)
4497. {
4498.     struct obj *otmp = gi.invent;
4499.     int ct = 0;
4500. 
4501.     while (otmp) {
4502.         if (incl_gold || otmp->invlet != GOLD_SYM)
4503.             ct++;
4504.         otmp = otmp->nobj;
4505.     }
4506.     return ct;
4507. }
4508. 
4509. /* Counts the money in an object chain. */
4510. /* Intended use is for your or some monster's inventory, */
4511. /* now that u.gold/m.gold is gone.*/
4512. /* Counting money in a container might be possible too. */
4513. long
4514. money_cnt(struct obj *otmp)
4515. {
4516.     while (otmp) {
4517.         if (otmp->oclass == COIN_CLASS)
4518.             return otmp->quan;
4519.         otmp = otmp->nobj;
4520.     }
4521.     return 0L;
4522. }
4523. 
4524. void
4525. spot_checks(coordxy x, coordxy y, schar old_typ)
4526. {
4527.     schar new_typ = levl[x][y].typ;
4528.     boolean db_ice_now = FALSE;
4529. 
4530.     switch (old_typ) {
4531.     case DRAWBRIDGE_UP:
4532.         db_ice_now = ((levl[x][y].drawbridgemask & DB_UNDER) == DB_ICE);
4533.         FALLTHROUGH;
4534.         /*FALLTHRU*/
4535.     case ICE:
4536.         if ((new_typ != old_typ)
4537.             || (old_typ == DRAWBRIDGE_UP && !db_ice_now)) {
4538.             /* make sure there's no MELT_ICE_AWAY timer */
4539.             if (spot_time_left(x, y, MELT_ICE_AWAY)) {
4540.                 spot_stop_timers(x, y, MELT_ICE_AWAY);
4541.             }
4542.             /* adjust things affected by the ice */
4543.             obj_ice_effects(x, y, FALSE);
4544.         }
4545.         break;
4546.     }
4547. }
4548. 
4549. /* calculate x/y, rounding as appropriate */
4550. int
4551. rounddiv(long x, int y)
4552. {
4553.     int r, m;
4554.     int divsgn = 1;
4555. 
4556.     if (y == 0)
4557.         panic("division by zero in rounddiv");
4558.     else if (y < 0) {
4559.         divsgn = -divsgn;
4560.         y = -y;
4561.     }
4562.     if (x < 0) {
4563.         divsgn = -divsgn;
4564.         x = -x;
4565.     }
4566.     r = (int) (x / y);
4567.     m = x % y;
4568.     if (2 * m >= y)
4569.         r++;
4570. 
4571.     return divsgn * r;
4572. }
4573. 
4574. 
4575. /*hack.c*/